diff --git a/CODEOWNERS b/CODEOWNERS index b2355ad1397df0b851c7d092315fb9c450cc9d46..9b63d1bbd03930ed56c660264086ffc1266a52f8 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -144,6 +144,8 @@ zh-cn/application-dev/telephony/ @zengyawen zh-cn/application-dev/dfx/ @zengyawen zh-cn/application-dev/database/ @ge-yafang zh-cn/application-dev/napi/drawing_guidelines.md @ge-yafang +zh-cn/application-dev/napi/native-window-guidelines.md @ge-yafang +zh-cn/application-dev/napi/mindspore-lite-guidelines.md @ge-yafang zh-cn/application-dev/napi/rawfile_guidelines.md @HelloCrease zh-cn/application-dev/background-agent-scheduled-reminder/ @RayShih zh-cn/application-dev/background-task-management/ @RayShih @@ -165,10 +167,9 @@ zh-cn/application-dev/reference/arkui-ts/ @HelloCrease zh-cn/application-dev/reference/native-apis @RayShih zh-cn/application-dev/reference/native-lib @RayShih zh-cn/application-dev/quick-start/start-overview.md @ge-yafang -zh-cn/application-dev/quick-start/start-with-ets.md @ge-yafang -zh-cn/application-dev/quick-start/start-with-ets-low-code.md @ge-yafang -zh-cn/application-dev/quick-start/start-with-js.md @ge-yafang -zh-cn/application-dev/quick-start/start-with-js-low-code.md @ge-yafang +zh-cn/application-dev/quick-start/start-with-ets-stage.md @ge-yafang +zh-cn/application-dev/quick-start/start-with-ets-fa.md @ge-yafang +zh-cn/application-dev/quick-start/start-with-js-fa.md @ge-yafang zh-cn/application-dev/quick-start/deveco-studio-user-guide-for-openharmony.md @ge-yafang zh-cn/application-dev/quick-start/package-structure.md @RayShih zh-cn/application-dev/quick-start/basic-resource-file-categories.md @RayShih diff --git a/en/application-dev/connectivity/http-request.md b/en/application-dev/connectivity/http-request.md index 6ddf26b87022c8bf098efc72de9ae4b4c0e28779..da1a7e1c517f284037a41a88e2167b6d1d2406aa 100644 --- a/en/application-dev/connectivity/http-request.md +++ b/en/application-dev/connectivity/http-request.md @@ -12,7 +12,7 @@ To use related APIs, you must declare the **ohos.permission.INTERNET** permissio For details about how to apply for permissions, see [Access Control Development](../security/accesstoken-guidelines.md). -The following table describes the related APIs. +The following table provides only a simple description of the related APIs. For details, see [API Reference](../reference/apis/js-apis-http.md). | API | Description | | ----------------------------------------- | --------------------------------------------------------- | diff --git a/en/application-dev/device/device-location-overview.md b/en/application-dev/device/device-location-overview.md index aa619c4549083521dd6ac5bcc05795074adc9af4..a26f0c5a7003a14c13cf4fc697e3a55a202f1eec 100644 --- a/en/application-dev/device/device-location-overview.md +++ b/en/application-dev/device/device-location-overview.md @@ -15,15 +15,18 @@ Your application can call location-specific APIs to obtain the location informat Location awareness helps determine where a mobile device locates. The system identifies the location of a mobile device with its coordinates, and uses location technologies such as Global Navigation Satellite System (GNSS) and network positioning (for example, base station positioning or WLAN/Bluetooth positioning) to provide diverse location-based services. These advanced location technologies make it possible to obtain the accurate location of the mobile device, regardless of whether it is indoors or outdoors. - **Coordinate** + A coordinate describes a location on the earth using the longitude and latitude in reference to the World Geodetic Coordinate System 1984. - **GNSS positioning** GNSS positioning locates a mobile device by using the location algorithm offered by the device chip to compute the location information provided by the Global Navigation Satellite System, for example, GPS, GLONASS, BeiDou, and Galileo. Whichever positioning system will be used during the location process depends on a hardware capability of the device. - **Base station positioning** + Base station positioning estimates the current location of a mobile device based on the location of the resident base station in reference to the neighboring base stations. This technology provides only a low accuracy and requires access to the cellular network. - **WLAN or Bluetooth positioning** + WLAN or Bluetooth positioning estimates the current location of a mobile device based on the locations of WLANs and Bluetooth devices that can be discovered by the device. The location accuracy of this technology depends on the distribution of fixed WLAN access points (APs) and Bluetooth devices around the device. A high density of WLAN APs and Bluetooth devices can produce a more accurate location result than base station positioning. This technology also requires access to the network. diff --git a/en/application-dev/device/usb-guidelines.md b/en/application-dev/device/usb-guidelines.md index d51625ccb9605fe2fb35b95f71eebc4e1607b753..eb023f7c782d8cb0e086819904b6def65da14214 100644 --- a/en/application-dev/device/usb-guidelines.md +++ b/en/application-dev/device/usb-guidelines.md @@ -38,7 +38,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat // Import the USB API package. import usb from '@ohos.usb'; // Obtain the USB device list. - var deviceList = usb.getDevices(); + let deviceList = usb.getDevices(); /* Example deviceList structure [ @@ -81,21 +81,21 @@ You can set a USB device as the USB host to connect to other USB devices for dat number: 1, type: 3, interfaceId: 0, - }, - ], - }, - ], - }, - ], - }, - ], + } + ] + } + ] + } + ] + } + ] */ ``` 2. Obtain the device operation permissions. ```js - var deviceName = deviceList[0].name; + let deviceName = deviceList[0].name; // Request the permissions to operate a specified device. usb.requestRight(deviceName).then(hasRight => { console.info("usb device request right result: " + hasRight); @@ -108,7 +108,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat ```js // Open the device, and obtain the USB device pipe for data transfer. - var pipe = usb.connectDevice(deviceList[0]); + let pipe = usb.connectDevice(deviceList[0]); /* Claim the corresponding interface from deviceList. interface1 must be one present in the device configuration. @@ -127,7 +127,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat usb.bulkTransfer(pipe, inEndpoint, dataUint8Array, 15000).then(dataLength => { if (dataLength >= 0) { console.info("usb readData result Length : " + dataLength); - var resultStr = this.ab2str(dataUint8Array); // Convert uint8 data into a string. + let resultStr = this.ab2str(dataUint8Array); // Convert uint8 data into a string. console.info("usb readData buffer : " + resultStr); } else { console.info("usb readData failed : " + dataLength); diff --git a/en/application-dev/dfx/hiappevent-guidelines.md b/en/application-dev/dfx/hiappevent-guidelines.md index 48f725e080441281cd2e88820eeacc6032a2dbab..afda67ee6fdf21b3d91d525d397c956d98167e82 100644 --- a/en/application-dev/dfx/hiappevent-guidelines.md +++ b/en/application-dev/dfx/hiappevent-guidelines.md @@ -12,12 +12,10 @@ The following table provides only a brief description of related APIs. For detai **Table 1** APIs for application event logging -| API | Description | -| ------------------------------------------------------------ | ------------------------------------------------------------ | -| write(string eventName, EventType type, object keyValues, AsyncCallback\ callback): void | Logs application events in asynchronous mode. This API uses an asynchronous callback to return the result. | -| write(string eventName, EventType type, object keyValues): Promise\ | Logs application events in asynchronous mode. This API uses a promise to return the result. | -| write(AppEventInfo info, AsyncCallback\ callback): void | Logs application events by domain in asynchronous mode. This API uses an asynchronous callback to return the result.| -| write(AppEventInfo info): Promise\ | Logs application events by domain in asynchronous mode. This API uses a promise to return the result.| +| API | Description | +| ------------------------------------------------------------ | ---------------------------------------------------- | +| write(AppEventInfo info, AsyncCallback\ callback): void | Logs application events in asynchronous mode. This API uses an asynchronous callback to return the result.| +| write(AppEventInfo info): Promise\ | Logs application events in asynchronous mode. This API uses a promise to return the result. | When an asynchronous callback is used, the return value can be processed directly in the callback. @@ -84,6 +82,7 @@ The following uses a one-time event watcher as an example to illustrate the deve .fontWeight(FontWeight.Bold) Button("1 writeTest").onClick(()=>{ + // Perform event logging based on the input event parameters. hiAppEvent.write({ domain: "test_domain", name: "test_event", @@ -100,6 +99,7 @@ The following uses a one-time event watcher as an example to illustrate the deve }) Button("2 addWatcherTest").onClick(()=>{ + // Add an event watcher based on the input subscription parameters. hiAppEvent.addWatcher({ name: "watcher1", appEventFilters: [{ domain: "test_domain" }], @@ -109,17 +109,23 @@ The following uses a one-time event watcher as an example to illustrate the deve timeOut: 2 }, onTrigger: function (curRow, curSize, holder) { + // If the holder object is null, return an error after recording it in the log. if (holder == null) { console.error("HiAppEvent holder is null"); return; } + // Set the size threshold to 1,000 bytes for obtaining an event package. + holder.setSize(1000); let eventPkg = null; + // Obtain the event package based on the configured size threshold. If returned event package is null, all event data has been obtained. while ((eventPkg = holder.takeNext()) != null) { - console.info("HiAppEvent eventPkg.packageId=" + eventPkg.packageId); - console.info("HiAppEvent eventPkg.row=" + eventPkg.row); - console.info("HiAppEvent eventPkg.size=" + eventPkg.size); + // Parse the obtained event package and display the result on the Log page. + console.info('HiAppEvent eventPkg.packageId=' + eventPkg.packageId); + console.info('HiAppEvent eventPkg.row=' + eventPkg.row); + console.info('HiAppEvent eventPkg.size=' + eventPkg.size); + // Traverse and parse event string arrays in the obtained event package. for (const eventInfo of eventPkg.data) { - console.info("HiAppEvent eventPkg.data=" + eventInfo); + console.info('HiAppEvent eventPkg.data=' + eventInfo); } } } @@ -127,6 +133,7 @@ The following uses a one-time event watcher as an example to illustrate the deve }) Button("3 removeWatcherTest").onClick(()=>{ + // Remove the specified event watcher. hiAppEvent.removeWatcher({ name: "watcher1" }) diff --git a/en/application-dev/faqs/Readme-EN.md b/en/application-dev/faqs/Readme-EN.md index dc45ed9db0eec504b1ff6f535babf11265f2df91..c0b69b85a868f8afd7a7f627fb0275f46cbc87fc 100644 --- a/en/application-dev/faqs/Readme-EN.md +++ b/en/application-dev/faqs/Readme-EN.md @@ -1,19 +1,15 @@ # FAQs - [Ability Framework Development](faqs-ability.md) -- [Data Management Development](faqs-data-management.md) -- [File Management Development](faqs-file-management.md) -- [Graphics and Image Development](faqs-graphics.md) -- [hdc_std Command Usage](faqs-ide.md) -- [IDE Usage](faqs-hdc-std.md) - [ArkUI (JavaScript) Development](faqs-ui-js.md) - [ArkUI (eTS) Development](faqs-ui-ets.md) - [Graphics and Image Development](faqs-graphics.md) - [File Management Development](faqs-file-management.md) +- [Network and Connection Development](faqs-connectivity.md) - [Data Management Development](faqs-data-management.md) - [Device Management Development](faqs-device-management.md) - [Native API Usage](faqs-native.md) -- [Network and Connection Development](faqs-connectivity.md) - [Usage of Third- and Fourth-Party Libraries](faqs-third-party-library.md) +- [hdc_std Command Usage](faqs-ide.md) +- [IDE Usage](faqs-hdc-std.md) - [Development Board](faqs-development-board.md) - diff --git a/en/application-dev/faqs/faqs-connectivity.md b/en/application-dev/faqs/faqs-connectivity.md index 3b8dea82129c03f0dc12c12296a28b9a0c46c99b..e3b02269e2de947fb4ab4069f1d7ba4812825ddc 100644 --- a/en/application-dev/faqs/faqs-connectivity.md +++ b/en/application-dev/faqs/faqs-connectivity.md @@ -19,7 +19,7 @@ Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9 Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9 -Error code 28 refers to **CURLE_OPERATION_TIMEDOUT**, which means a libcurl library operation timeout. For details, see any HTTP status code description available. +Error code 28 refers to **CURLE_OPERATION_TIMEDOUT**, which means a cURL operation timeout. For details, see any HTTP status code description available. Reference: [Development Guide](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-http.md#httpresponse) and [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html) diff --git a/en/application-dev/napi/Readme-EN.md b/en/application-dev/napi/Readme-EN.md index 280efd8afa5fa845dab0d607ed94b33e2a75e6d3..bf16d91435bf68ebd6f93a1a52b5f6da35e67169 100644 --- a/en/application-dev/napi/Readme-EN.md +++ b/en/application-dev/napi/Readme-EN.md @@ -4,5 +4,6 @@ - [Drawing Development](drawing-guidelines.md) - [Raw File Development](rawfile-guidelines.md) - [Native Window Development](native-window-guidelines.md) +- [Using MindSpore Lite for Model Inference](native-window-guidelines.md) diff --git a/en/application-dev/napi/figures/01.png b/en/application-dev/napi/figures/01.png new file mode 100644 index 0000000000000000000000000000000000000000..5293e5afe5a8637dbef3fd0b32c7bd43d60e4368 Binary files /dev/null and b/en/application-dev/napi/figures/01.png differ diff --git a/en/application-dev/napi/mindspore-lite-guidelines.md b/en/application-dev/napi/mindspore-lite-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..47ede475575484d60317e9ed7e2afe586fb12524 --- /dev/null +++ b/en/application-dev/napi/mindspore-lite-guidelines.md @@ -0,0 +1,216 @@ +# Using MindSpore Lite for Model Inference + +## When to Use + +MindSpore Lite is an AI engine that provides 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 MindSpore Lite model inference. + +## Basic Concepts + +Before getting started, you need to understand the following basic concepts: + +**Tensor**: a special data structure that is similar to arrays and matrices. It is a basic data structure used in MindSpore Lite network operations. + +**Float16 inference**: a mode in which Float16 is used for inference. Float16, also called half-precision, uses 16 bits to represent a number. + + + +## Available APIs +APIs involved in MindSpore Lite model inference are categorized into context APIs, model APIs, and tensor APIs. +### Context APIs + +| API | Description | +| ------------------ | ----------------- | +|OH_AI_ContextHandle OH_AI_ContextCreate()|Creates a context object.| +|void OH_AI_ContextSetThreadNum(OH_AI_ContextHandle context, int32_t thread_num)|Sets the number of runtime threads.| +| void OH_AI_ContextSetThreadAffinityMode(OH_AI_ContextHandle context, int mode)|Sets the affinity mode for binding runtime threads to CPU cores, which are categorized into little cores and big cores depending on the CPU frequency.| +|OH_AI_DeviceInfoHandle OH_AI_DeviceInfoCreate(OH_AI_DeviceType device_type)|Creates a runtime device information object.| +|void OH_AI_ContextDestroy(OH_AI_ContextHandle *context)|Destroys a context object.| +|void OH_AI_DeviceInfoSetEnableFP16(OH_AI_DeviceInfoHandle device_info, bool is_fp16)|Sets whether to enable float16 inference. This function is available only for CPU and GPU devices.| +|void OH_AI_ContextAddDeviceInfo(OH_AI_ContextHandle context, OH_AI_DeviceInfoHandle device_info)|Adds a runtime device information object.| + +### Model APIs + +| API | Description | +| ------------------ | ----------------- | +|OH_AI_ModelHandle OH_AI_ModelCreate()|Creates a model object.| +|OH_AI_Status OH_AI_ModelBuildFromFile(OH_AI_ModelHandle model, const char *model_path,OH_AI_ModelType odel_type, const OH_AI_ContextHandle model_context)|Loads and builds a MindSpore model from a model file.| +|void OH_AI_ModelDestroy(OH_AI_ModelHandle *model)|Destroys a model object.| + +### Tensor APIs + +| API | Description | +| ------------------ | ----------------- | +|OH_AI_TensorHandleArray OH_AI_ModelGetInputs(const OH_AI_ModelHandle model)|Obtains the input tensor array structure of a model.| +|int64_t OH_AI_TensorGetElementNum(const OH_AI_TensorHandle tensor)|Obtains the number of tensor elements.| +|const char *OH_AI_TensorGetName(const OH_AI_TensorHandle tensor)|Obtains the name of a tensor.| +|OH_AI_DataType OH_AI_TensorGetDataType(const OH_AI_TensorHandle tensor)|Obtains the tensor data type.| +|void *OH_AI_TensorGetMutableData(const OH_AI_TensorHandle tensor)|Obtains the pointer to variable tensor data.| + +## How to Develop +The following figure shows the development process for MindSpore Lite model inference. + +**Figure 1** Development process for MindSpore Lite model inference +![how-to-use-mindspore-lite](figures/01.png) + +The development process consists of the following main steps: + +1. Prepare the required model. + + The required model can be downloaded directly or obtained using the model conversion tool. + + - If the downloaded model is in the `.ms` format, you can use it directly for inference. The following uses the **mobilenetv2.ms** model 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/r1.5/use/benchmark_tool.html) to convert it to the `.ms` format. + +2. Create a context, and set parameters such as the number of runtime threads and device type. + + ```c + // Create a context, and set the number of runtime threads to 2 and the thread affinity mode to 1 (big cores first). + OH_AI_ContextHandle context = OH_AI_ContextCreate(); + if (context == NULL) { + printf("OH_AI_ContextCreate failed.\n"); + return OH_AI_STATUS_LITE_ERROR; + } + const int thread_num = 2; + OH_AI_ContextSetThreadNum(context, thread_num); + OH_AI_ContextSetThreadAffinityMode(context, 1); + // Set the device type to CPU, and disable Float16 inference. + OH_AI_DeviceInfoHandle cpu_device_info = OH_AI_DeviceInfoCreate(OH_AI_DEVICETYPE_CPU); + if (cpu_device_info == NULL) { + printf("OH_AI_DeviceInfoCreate failed.\n"); + OH_AI_ContextDestroy(&context); + return OH_AI_STATUS_LITE_ERROR; + } + OH_AI_DeviceInfoSetEnableFP16(cpu_device_info, false); + OH_AI_ContextAddDeviceInfo(context, cpu_device_info); + ``` + +3. Create, load, and build the model. + + Call **OH_AI_ModelBuildFromFile** to load and build the model. + + In this example, the **argv[1]** parameter passed to **OH_AI_ModelBuildFromFile** indicates the specified model file path. + + ```c + // Create a model. + OH_AI_ModelHandle model = OH_AI_ModelCreate(); + if (model == NULL) { + printf("OH_AI_ModelCreate failed.\n"); + OH_AI_ContextDestroy(&context); + return OH_AI_STATUS_LITE_ERROR; + } + + // Load and build the model. The model type is OH_AI_ModelTypeMindIR. + int ret = OH_AI_ModelBuildFromFile(model, argv[1], OH_AI_ModelTypeMindIR, context); + if (ret != OH_AI_STATUS_SUCCESS) { + printf("OH_AI_ModelBuildFromFile failed, ret: %d.\n", ret); + OH_AI_ModelDestroy(&model); + return ret; + } + ``` + +4. Input data. + + Before executing model inference, you need to populate data to the input tensor. In this example, random data is used to populate the model. + + ```c + // Obtain the input tensor. + OH_AI_TensorHandleArray inputs = OH_AI_ModelGetInputs(model); + if (inputs.handle_list == NULL) { + printf("OH_AI_ModelGetInputs failed, ret: %d.\n", ret); + OH_AI_ModelDestroy(&model); + return ret; + } + // Use random data to populate the tensor. + ret = GenerateInputDataWithRandom(inputs); + if (ret != OH_AI_STATUS_SUCCESS) { + printf("GenerateInputDataWithRandom failed, ret: %d.\n", ret); + OH_AI_ModelDestroy(&model); + return ret; + } + ``` + +5. Execute model inference. + + Call **OH_AI_ModelPredict** to perform model inference. + + ```c + // Execute model inference. + OH_AI_TensorHandleArray outputs; + ret = OH_AI_ModelPredict(model, inputs, &outputs, NULL, NULL); + if (ret != OH_AI_STATUS_SUCCESS) { + printf("OH_AI_ModelPredict failed, ret: %d.\n", ret); + OH_AI_ModelDestroy(&model); + return ret; + } + ``` + +6. Obtain the output. + + After model inference is complete, you can obtain the inference result through the output tensor. + + ```c + // Obtain the output tensor and print the information. + for (size_t i = 0; i < outputs.handle_num; ++i) { + OH_AI_TensorHandle tensor = outputs.handle_list[i]; + int64_t element_num = OH_AI_TensorGetElementNum(tensor); + printf("Tensor name: %s, tensor size is %zu ,elements num: %lld.\n", OH_AI_TensorGetName(tensor), + OH_AI_TensorGetDataSize(tensor), element_num); + const float *data = (const float *)OH_AI_TensorGetData(tensor); + printf("output data is:\n"); + const int max_print_num = 50; + for (int j = 0; j < element_num && j <= max_print_num; ++j) { + printf("%f ", data[j]); + } + printf("\n"); + } + ``` + +7. Destroy the model. + + If the MindSpore Lite inference framework is no longer needed, you need to destroy the created model. + + ```c + // Destroy the model. + OH_AI_ModelDestroy(&model); + ``` + +## Verification + +1. Compile **CMakeLists.txt**. + + ```cmake + cmake_minimum_required(VERSION 3.14) + project(Demo) + + add_executable(demo main.c) + + target_link_libraries( + demo + mindspore-lite.huawei + pthread + dl + ) + ``` + - To use ohos-sdk for cross compilation, you need to set the native toolchain path for the CMake tool as follows: `-DCMAKE_TOOLCHAIN_FILE="/xxx/ohos-sdk/linux/native/build/cmake/ohos.toolchain.cmake"`. + + - The toolchain builds a 64-bit application by default. To build a 32-bit application, add the following configuration: `-DOHOS_ARCH="armeabi-v7a"`. + +2. Run the CMake tool. + + - Use hdc_std to connect to the RK3568 development board and put **demo** and **mobilenetv2.ms** to the same directory on the board. + - Run the hdc_std shell command to access the development board, go to the directory where **demo** is located, and run the following command: + + ```shell + ./demo mobilenetv2.ms + ``` + + The inference is successful if the output is similar to the following: + + ```shell + # ./QuickStart ./mobilenetv2.ms + Tensor name: Softmax-65, tensor size is 4004 ,elements num: 1001. + output data is: + 0.000018 0.000012 0.000026 0.000194 0.000156 0.001501 0.000240 0.000825 0.000016 0.000006 0.000007 0.000004 0.000004 0.000004 0.000015 0.000099 0.000011 0.000013 0.000005 0.000023 0.000004 0.000008 0.000003 0.000003 0.000008 0.000014 0.000012 0.000006 0.000019 0.000006 0.000018 0.000024 0.000010 0.000002 0.000028 0.000372 0.000010 0.000017 0.000008 0.000004 0.000007 0.000010 0.000007 0.000012 0.000005 0.000015 0.000007 0.000040 0.000004 0.000085 0.000023 + ``` diff --git a/en/application-dev/notification/common-event.md b/en/application-dev/notification/common-event.md index 37d55ef434d0cec71eed60862e13f1de0d9e13fb..dfb611ea572b80486756faaa4b004513cd6858a7 100644 --- a/en/application-dev/notification/common-event.md +++ b/en/application-dev/notification/common-event.md @@ -32,7 +32,8 @@ import commonEvent from '@ohos.commonEvent'; 2. Create a **subscribeInfo** object. For details about the data types and parameters of the object, see [CommonEventSubscribeInfo](../reference/apis/js-apis-commonEvent.md#commoneventsubscribeinfo). ```js -private subscriber = null // Used to save the created subscriber object for subsequent subscription and unsubscription. +// Used to save the created subscriber object for subsequent subscription and unsubscription. +private subscriber = null // Subscriber information var subscribeInfo = { diff --git a/en/application-dev/notification/notification-brief.md b/en/application-dev/notification/notification-brief.md index b1df6ce3e2c022accb06bc1070740b7d7b3e7433..75237412fdf29d88843a9f23fa653f64f2de7c86 100644 --- a/en/application-dev/notification/notification-brief.md +++ b/en/application-dev/notification/notification-brief.md @@ -1,6 +1,6 @@ # Common Event and Notification Overview -The common event and notification module enables applications to publish messages to other applications, and receive messages from the system or other applications. These messages can be news push messages, advertisement notifications, or warning information. +The common event and notification module enables applications to publish messages to other applications, and receive messages from the system or other applications. These messages can be news push messages, advertisement notifications, warning information, and more. Common Event Service (CES) enables applications to publish, subscribe to, and unsubscribe from common events. Based on the sender type, common events are classified into system common events and custom common events. diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index beab6e2411714274074d3e0cbdfb13cc60ba574b..1446d4fcef22eb94e6c4796be4e55fd0968c8e69 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -86,6 +86,7 @@ - bundle/[PermissionDef](js-apis-bundle-PermissionDef.md) - bundle/[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md) - bundle/[ShortcutInfo(deprecated)](js-apis-bundle-ShortcutInfo.md) + - bundle/[PackInfo](js-apis-bundle-PackInfo.md) - UI Page - [@ohos.animator](js-apis-animator.md) - [@ohos.mediaquery](js-apis-mediaquery.md) @@ -133,7 +134,6 @@ - [@ohos.data.dataShare](js-apis-data-dataShare.md) - [@ohos.data.dataSharePredicates](js-apis-data-dataSharePredicates.md) - [@ohos.data.dataShareResultSet](js-apis-data-DataShareResultSet.md) - - [@ohos.data.distributedData](js-apis-distributed-data.md) - [@ohos.data.distributedDataObject](js-apis-data-distributedobject.md) - [@ohos.data.preferences](js-apis-data-preferences.md) - [@ohos.data.rdb](js-apis-data-rdb.md) @@ -160,9 +160,13 @@ - [@ohos.telephony.sms](js-apis-sms.md) - Network Management - [@ohos.net.connection](js-apis-net-connection.md) + - [@ohos.net.ethernet](js-apis-net-ethernet.md) - [@ohos.net.http](js-apis-http.md) + - [@ohos.net.policy](js-apis-net-policy.md) + - [@ohos.net.sharing](js-apis-net-sharing.md) - [@ohos.net.socket](js-apis-socket.md) - + - [@ohos.net.statistics](js-apis-net-statistics.md) + - [@ohos.net.tlsSocket](js-apis-tlsSocket.md) - [@ohos.net.webSocket](js-apis-webSocket.md) - [@ohos.request](js-apis-request.md) - Connectivity @@ -174,8 +178,8 @@ - [@ohos.rpc](js-apis-rpc.md) - [@ohos.wifi](js-apis-wifi.md) - [@ohos.wifiext](js-apis-wifiext.md) - - [@ohos.nfc.tag](js-apis-nfctech.md) - - [@ohos.nfc.tag](js-apis-tagSession.md) + - tag/[nfctech](js-apis-nfctech.md) + - tag/[tagSession](js-apis-tagSession.md) - Basic Features - [@ohos.accessibility](js-apis-accessibility.md) - [@ohos.accessibility.config](js-apis-accessibility-config.md) @@ -196,6 +200,7 @@ - [@ohos.systemTime](js-apis-system-time.md) - [@ohos.systemTimer](js-apis-system-timer.md) - [@ohos.wallpaper](js-apis-wallpaper.md) + - [console](js-apis-logs.md) - [Timer](js-apis-timer.md) - Device Management @@ -257,6 +262,7 @@ - APIs No Longer Maintained - [@ohos.bytrace](js-apis-bytrace.md) - [@ohos.data.storage](js-apis-data-storage.md) + - [@ohos.data.distributedData](js-apis-distributed-data.md) - [@ohos.prompt](js-apis-prompt.md) - [@ohos.reminderAgent](js-apis-reminderAgent.md) - [@system.app](js-apis-system-app.md) @@ -278,4 +284,3 @@ - [@system.sensor](js-apis-system-sensor.md) - [@system.storage](js-apis-system-storage.md) - [@system.vibrator](js-apis-system-vibrate.md) - - [console](js-apis-logs.md) \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-appmanager.md b/en/application-dev/reference/apis/js-apis-appmanager.md index 9dc3ec0c3c5f022d4aecd438f59ebc830a34ae63..3d93bdf33a527668c4c1c98ac4cfd8611ea9010a 100644 --- a/en/application-dev/reference/apis/js-apis-appmanager.md +++ b/en/application-dev/reference/apis/js-apis-appmanager.md @@ -294,6 +294,9 @@ Registers an observer to listen for the state changes of all applications. }, onProcessDied(processData) { console.log('------------ onProcessDied -----------', processData); + }, + onProcessStateChanged(processData) { + console.log('------------ onProcessStateChanged -----------', processData); } } const observerCode = app.registerApplicationStateObserver(applicationStateObserver); @@ -335,6 +338,9 @@ Registers an observer to listen for the state changes of a specified application }, onProcessDied(processData) { console.log('------------ onProcessDied -----------', processData); + }, + onProcessStateChanged(processData) { + console.log('------------ onProcessStateChanged -----------', processData); } } var bundleNameList = ['bundleName1', 'bundleName2']; @@ -707,6 +713,18 @@ Called when the application state changes. var applicationStateObserver = { onForegroundApplicationChanged(appStateData) { console.log('------------ onForegroundApplicationChanged -----------', appStateData); + }, + onAbilityStateChanged(abilityStateData) { + console.log('------------ onAbilityStateChanged -----------', abilityStateData); + }, + onProcessCreated(processData) { + console.log('------------ onProcessCreated -----------', processData); + }, + onProcessDied(processData) { + console.log('------------ onProcessDied -----------', processData); + }, + onProcessStateChanged(processData) { + console.log('------------ onProcessStateChanged -----------', processData); } } const observerCode = app.registerApplicationStateObserver(applicationStateObserver); @@ -734,8 +752,20 @@ Called when the ability state changes. ```js var applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log('------------ onForegroundApplicationChanged -----------', appStateData); + }, onAbilityStateChanged(abilityStateData) { console.log('------------ onAbilityStateChanged -----------', abilityStateData); + }, + onProcessCreated(processData) { + console.log('------------ onProcessCreated -----------', processData); + }, + onProcessDied(processData) { + console.log('------------ onProcessDied -----------', processData); + }, + onProcessStateChanged(processData) { + console.log('------------ onProcessStateChanged -----------', processData); } } const observerCode = app.registerApplicationStateObserver(applicationStateObserver); @@ -762,8 +792,20 @@ Called when a process is created. ```js var applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log('------------ onForegroundApplicationChanged -----------', appStateData); + }, + onAbilityStateChanged(abilityStateData) { + console.log('------------ onAbilityStateChanged -----------', abilityStateData); + }, onProcessCreated(processData) { console.log('------------ onProcessCreated -----------', processData); + }, + onProcessDied(processData) { + console.log('------------ onProcessDied -----------', processData); + }, + onProcessStateChanged(processData) { + console.log('------------ onProcessStateChanged -----------', processData); } } const observerCode = app.registerApplicationStateObserver(applicationStateObserver); @@ -790,8 +832,20 @@ Called when a process is terminated. ```js var applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log('------------ onForegroundApplicationChanged -----------', appStateData); + }, + onAbilityStateChanged(abilityStateData) { + console.log('------------ onAbilityStateChanged -----------', abilityStateData); + }, + onProcessCreated(processData) { + console.log('------------ onProcessCreated -----------', processData); + }, onProcessDied(processData) { console.log('------------ onProcessDied -----------', processData); + }, + onProcessStateChanged(processData) { + console.log('------------ onProcessStateChanged -----------', processData); } } const observerCode = app.registerApplicationStateObserver(applicationStateObserver); @@ -818,6 +872,18 @@ Called when the process state changes. ```js var applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log('------------ onForegroundApplicationChanged -----------', appStateData); + }, + onAbilityStateChanged(abilityStateData) { + console.log('------------ onAbilityStateChanged -----------', abilityStateData); + }, + onProcessCreated(processData) { + console.log('------------ onProcessCreated -----------', processData); + }, + onProcessDied(processData) { + console.log('------------ onProcessDied -----------', processData); + }, onProcessStateChanged(processData) { console.log('------------ onProcessStateChanged -----------', processData); } diff --git a/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md b/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md index eb85e5d52d50068b8147c1a4789389b2cf5506e1..d744a5ab3e1ef6770d0dee18d68c4a1512cd4183 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md @@ -1,40 +1,40 @@ # BundleInfo +The **BundleInfo** module provides bundle information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**. + > **NOTE** > > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -The **BundleInfo** module provides bundle information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**. - ## BundleInfo **System capability**: SystemCapability.BundleManager.BundleFramework | Name | Type | Readable| Writable| Description | | --------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | -| name | string | Yes | No | Bundle name. | -| type | string | Yes | No | Bundle type. | -| appId | string | Yes | No | ID of the application to which the bundle belongs. | -| uid | number | Yes | No | UID of the application to which the bundle belongs. | -| installTime | number | Yes | No | Time when the HAP file was installed. | -| updateTime | number | Yes | No | Time when the HAP file was updated. | -| appInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information. | +| name | string | Yes | No | Bundle name. | +| type | string | Yes | No | Bundle type. | +| appId | string | Yes | No | ID of the application to which the bundle belongs. | +| uid | number | Yes | No | UID of the application to which the bundle belongs. | +| installTime | number | Yes | No | Time when the HAP file was installed. | +| updateTime | number | Yes | No | Time when the HAP file was updated. | +| appInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information. | | abilityInfos | Array\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | No | Ability configuration information.
The value is obtained by passing **GET_BUNDLE_WITH_ABILITIES**.| | reqPermissions | Array\ | Yes | No | Permissions to request from the system for running the application.
The value is obtained by passing **GET_BUNDLE_WITH_REQUESTED_PERMISSION**.| | reqPermissionDetails | Array\<[ReqPermissionDetail](#reqpermissiondetail)> | Yes | No | Detailed information of the permissions to request from the system.
The value is obtained by passing **GET_BUNDLE_WITH_REQUESTED_PERMISSION**.| -| vendor | string | Yes | No | Vendor of the bundle. | -| versionCode | number | Yes | No | Version number of the bundle. | -| versionName | string | Yes | No | Version description of the bundle. | -| compatibleVersion | number | Yes | No | Earliest SDK version required for running the bundle. | -| targetVersion | number | Yes | No | Latest SDK version required for running the bundle. | -| isCompressNativeLibs | boolean | Yes | No | Whether to compress the native library of the bundle. The default value is **true**. | -| hapModuleInfos | Array\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | No | Module configuration information. | -| entryModuleName | string | Yes | No | Name of the entry module. | -| cpuAbi | string | Yes | No | CPU and ABI information of the bundle. | -| isSilentInstallation | string | Yes | No | Whether the application can be installed in silent mode. | -| minCompatibleVersionCode | number | Yes | No | Earliest version compatible with the bundle in the distributed scenario. | -| entryInstallationFree | boolean | Yes | No | Whether installation-free is supported for the entry module. | -| reqPermissionStates8+ | Array\ | Yes | No | Permission grant state. | +| vendor | string | Yes | No | Vendor of the bundle. | +| versionCode | number | Yes | No | Version number of the bundle. | +| versionName | string | Yes | No | Version description of the bundle. | +| compatibleVersion | number | Yes | No | Earliest SDK version required for running the bundle. | +| targetVersion | number | Yes | No | Latest SDK version required for running the bundle. | +| isCompressNativeLibs | boolean | Yes | No | Whether to compress the native library of the bundle. The default value is **true**. | +| hapModuleInfos | Array\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | No | Module configuration information. | +| entryModuleName | string | Yes | No | Name of the entry module. | +| cpuAbi | string | Yes | No | CPU and ABI information of the bundle. | +| isSilentInstallation | string | Yes | No | Whether the application can be installed in silent mode. | +| minCompatibleVersionCode | number | Yes | No | Earliest version compatible with the bundle in the distributed scenario. | +| entryInstallationFree | boolean | Yes | No | Whether installation-free is supported for the entry module. | +| reqPermissionStates8+ | Array\ | Yes | No | Permission grant state. | | extensionAbilityInfo9+ | Array\<[ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md)> | Yes | No | Extension ability information.
The value is obtained by passing **GET_BUNDLE_WITH_EXTENSION_ABILITY**.| @@ -45,8 +45,8 @@ Provides the detailed information of the permissions to request from the system. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type | Readable| Writable| Description | -| --------------------- | ----------------------- | ---- | ---- | -------------------- | +| Name | Type | Readable| Writable| Description | +| --------------------- | ----------------------- | ---- | ---- | ---------------------- | | name | string | Yes | Yes | Name of the permission to request. | | reason | string | Yes | Yes | Reason for requesting the permission. | | reasonId9+ | number | Yes | Yes | ID of the reason for requesting the permission.| @@ -60,7 +60,7 @@ Describes the application scenario and timing for using the permission. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type | Readable| Writable| Description | -| --------- | -------------- | ---- | ---- | ------------------------- | +| Name | Type | Readable| Writable| Description | +| --------- | -------------- | ---- | ---- | --------------------------- | | abilities | Array\ | Yes | Yes | Abilities that use the permission.| | when | string | Yes | Yes | Time when the permission is used. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-PackInfo.md b/en/application-dev/reference/apis/js-apis-bundle-PackInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..323d4d1f948d12193b38333a11f7954153fec97a --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bundle-PackInfo.md @@ -0,0 +1,157 @@ +# PackInfo + +The **PackInfo** module provides the bundle package information, which can be obtained using [bundle.getBundlePackInfo](js-apis-Bundle.md). + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## BundlePackFlag + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Value | Description | +| ------------------ | ---------- | ---------------------------------- | +| GET_PACK_INFO_ALL | 0x00000000 | All information about the package. | +| GET_PACKAGES | 0x00000001 | Package information about the package.| +| GET_BUNDLE_SUMMARY | 0x00000002 | Bundle summary of the package. | +| GET_MODULE_SUMMARY | 0x00000004 | Module summary of the package. | + +## BundlePackInfo + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| -------- | --------------------------------------- | ---- | ---- | ----------------------------- | +| packages | Array\<[PackageConfig](#packageconfig)> | Yes | No | Package configuration information. | +| summary | [PackageSummary](#packagesummary) | Yes | No | Package summary.| + +## PackageConfig + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------------------- | -------------- | ---- | ---- | ------------------------------------------------------------ | +| deviceType | Array\ | Yes | No | Device types supported. | +| name | string | Yes | No | Package name. | +| moduleType | string | Yes | No | Module type. | +| deliveryWithInstall | boolean | Yes | No | Whether the HAP file will be installed when the user installs the application. The value **true** means that the HAP file will be automatically installed when the user installs the application, and **false** means the opposite.| + +## PackageSummary + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------- | --------------------------------------------- | ---- | ---- | -------------------- | +| app | [BundleConfigInfo](#bundleconfiginfo) | Yes | No | Bundle configuration information. | +| modules | Array\<[ModuleConfigInfo](#moduleconfiginfo)> | Yes | No | Module configuration information.| + +## BundleConfigInfo + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ---------- | ------------------- | ---- | ---- | ---------------------------------- | +| bundleName | string | Yes | No | Bundle name of an application. It uniquely identifies the application.| +| version | [Version](#version) | Yes | No | Bundle version. | + +## ModuleConfigInfo + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------------------ | ------------------------------------------------- | ---- | ---- | ---------------------------------- | +| apiVersion | [ApiVersion](#apiversion) | Yes | No | API version of the module. | +| deviceType | Array\ | Yes | No | Device type of the module. | +| distro | [ModuleDistroInfo](#moduledistroinfo) | Yes | No | Distribution information of the module. | +| abilities | Array\<[ModuleAbilityInfo](#moduleabilityinfo)> | Yes | No | Ability information of the module. | +| extensionAbilities | Array\<[ExtensionAbilities](#extensionabilities)> | Yes | No | Extension ability information of the module.| + +## ModuleDistroInfo + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------------------- | ------- | ---- | ---- | ------------------------------------------------------------ | +| mainAbility | string | Yes | No | Name of the main ability. | +| deliveryWithInstall | boolean | Yes | No | Whether the HAP file will be installed when the user installs the application. The value **true** means that the HAP file will be automatically installed when the user installs the application, and **false** means the opposite.| +| installationFree | boolean | Yes | No | Whether the HAP file supports the installation-free feature. The value **true** means that the HAP file supports the installation-free feature and meets installation-free constraints, and **false** means the opposite.| +| moduleName | string | Yes | No | Module name. | +| moduleType | string | Yes | No | Module type. | + +## ModuleAbilityInfo + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------------------------------------------- | ---- | ---- | ------------------------------------------------------------ | +| name | string | Yes | No | Logical name of the ability. The name must be unique in the application. | +| label | string | Yes | No | Name of the ability displayed to users. The value is a resource index to names in multiple languages.| +| visible | boolean | Yes | No | Whether the ability can be called by other applications. The value **true** means that the ability can be called by other applications, and **false** means the opposite.| +| forms | Array\<[AbilityFormInfo](#abilityforminfo)> | Yes | No | Widget information. | + +## ExtensionAbilities + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ----- | ------------------------------------------- | ---- | ---- | ------------------------------------------------------------ | +| forms | Array\<[AbilityFormInfo](#abilityforminfo)> | Yes | No | Specification of the widget. A widget is a brief view of an application that is embedded on the home screen to receive periodical updates.| + +## AbilityFormInfo + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------------------- | -------------- | ---- | ---- | ------------------------------------------------------------ | +| name | string | Yes | No | Widget name. | +| type | string | Yes | No | Widget type. | +| updateEnabled | boolean | Yes | No | Whether the widget supports periodical update. The value **true** means that the widget supports periodical update, and **false** means the opposite.| +| scheduledUpdateTime | string | Yes | No | Scheduled time to update the widget. The value is in 24-hour format and accurate to the minute. | +| updateDuration | number | Yes | No | Interval to update the widget. The unit is 30 minutes. The value is a multiple of 30. A widget can be updated periodically, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). If both are configured, **updateDuration** takes precedence.| +| supportDimensions | Array\ | Yes | No | Dimensions of the widget. The value can be **1\*2**, **2\*2**, **2\*4**, **4\*4**, or a combination of these options. At least one option must be specified when defining the widget.| +| defaultDimension | number | Yes | No | Default dimensions of the widget. The value must be available in the **supportDimensions** array of the widget.| + +## ApiVersion + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ----------- | ------ | ---- | ---- | -------------------- | +| releaseType | string | Yes | No | Name of the API version. | +| compatible | number | Yes | No | Minimum API version.| +| target | numbe | Yes | No | Target API version. | + +## Version + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------------------------ | ------ | ---- | ---- | ------------------------------------------------------------ | +| minCompatibleVersionCode | number | Yes | No | Minimum compatible version of the application. It is used to check whether the application is compatible with a version on other devices in the cross-device scenario. The value is a 32-bit non-negative integer.| +| name | string | Yes | No | Application version number visible to users. | +| code | number | Yes | No | Application version number used only for application management. The value is a 32-bit non-negative integer. It is used only to determine whether a version is later than another version. A larger value indicates a later version.| diff --git a/en/application-dev/reference/apis/js-apis-call.md b/en/application-dev/reference/apis/js-apis-call.md index 5ea820e6160af090dbaf1e784970adfcb01ba013..ab561f552758ed5af3c79bc2c4406d84ceb56f2b 100644 --- a/en/application-dev/reference/apis/js-apis-call.md +++ b/en/application-dev/reference/apis/js-apis-call.md @@ -827,7 +827,7 @@ call.reject(1, (error, data) => { ## call.reject7+ -reject\(callId: number, options: RejectMessageOption, callback: AsyncCallback\): void +reject\(callId: number, options: RejectMessageOptions, callback: AsyncCallback\): void Rejects a call based on the specified call ID and options. This API uses an asynchronous callback to return the result. diff --git a/en/application-dev/reference/apis/js-apis-cardEmulation.md b/en/application-dev/reference/apis/js-apis-cardEmulation.md index 9168a42e978c20caaface2523337d8c413a2296e..b4f3906b02b1dea7dabd558173010a37e65c2c19 100644 --- a/en/application-dev/reference/apis/js-apis-cardEmulation.md +++ b/en/application-dev/reference/apis/js-apis-cardEmulation.md @@ -1,6 +1,6 @@ # Standard NFC Card Emulation -The **cardEmulation** module implements Near-Field Communication (NFC) card emulation. +The **cardEmulation** module implements Near-Field Communication (NFC) card emulation. You can use the APIs provided by this module to determine the card emulation type supported and implement Host-based Card Emulation (HCE). > **NOTE**
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -12,6 +12,17 @@ The **cardEmulation** module implements Near-Field Communication (NFC) card emul import cardEmulation from '@ohos.nfc.cardEmulation'; ``` +## FeatureType + +Enumerates the NFC card emulation types. + +**System capability**: SystemCapability.Communication.NFC.Core + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| HCE | 0 | HCE.| +| UICC | 1 | Subscriber identity module (SIM) card emulation.| +| ESE | 2 | embedded Secure Element (eSE) emulation.| ## cardEmulation.isSupported @@ -19,23 +30,31 @@ isSupported(feature: number): boolean Checks whether a certain type of card emulation is supported. +**Required permissions**: ohos.permission.NFC_CARD_EMULATION + **System capability**: SystemCapability.Communication.NFC.Core +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | -------- | ---- | ----------------------- | +| feature | number | Yes | Card emulation type. For details, see [FeatureType](#featuretype).| + **Return value** | **Type**| **Description**| | -------- | -------- | - | boolean | Returns **true** if the card emulation is supported; returns **false** otherwise.| + | boolean | Returns **true** if the card emulation type is supported; returns **false** otherwise.| ## HceService8+ -Implements Host-based Card Emulation (HCE). Before calling any API in **HceService**, you must use **new cardEmulation.HceService()** to create an **HceService** instance. +Implements HCE, including receiving Application Protocol Data Units (APDUs) from the peer card reader and sending a response. Before using HCE-related APIs, check whether the device supports HCE. ### startHCE8+ startHCE(aidList: string[]): boolean -Starts HCE. +Starts HCE, including setting the application to be foreground preferred and dynamically registering the application identifier (AID) list. **Required permissions**: ohos.permission.NFC_CARD_EMULATION @@ -45,13 +64,13 @@ Starts HCE. | Name | Type | Mandatory| Description | | ------- | -------- | ---- | ----------------------- | -| aidList | string[] | Yes | Application ID (AID) list to be registered for card emulation.| +| aidList | string[] | Yes | AID list to register.| ### stopHCE8+ stopHCE(): boolean -Stops HCE. +Stops HCE, including removing the foreground preferred attribute and releasing the dynamically registered AID list. **Required permissions**: ohos.permission.NFC_CARD_EMULATION @@ -61,7 +80,7 @@ Stops HCE. on(type: "hceCmd", callback: AsyncCallback): void; -Subscribes to messages from the peer device after **startHCE()**. +Registers a callback to receive APDUs from the peer card reader. **Required permissions**: ohos.permission.NFC_CARD_EMULATION @@ -72,13 +91,13 @@ Subscribes to messages from the peer device after **startHCE()**. | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------------- | | type | string | Yes | Event type to subscribe to. The value is **hceCmd**. | -| callback | AsyncCallback | Yes | Callback invoked to return the subscribed event. The input parameter is a data array that complies with the Application Protocol Data Unit (APDU).| +| callback | AsyncCallback | Yes | Callback invoked to return the APDU. Each number in the callback is a hexadecimal number ranging from **0x00** to **0xFF**.| ### sendResponse8+ sendResponse(responseApdu: number[]): void; -Sends a response to the peer device. +Sends a response to the peer card reader. **Required permissions**: ohos.permission.NFC_CARD_EMULATION @@ -88,16 +107,25 @@ Sends a response to the peer device. | Name | Type | Mandatory| Description | | ------------ | -------- | ---- | -------------------------------------------------- | -| responseApdu | number[] | Yes | Data to send, which is an array that complies with the APDU.| +| responseApdu | number[] | Yes | Response APDU sent to the peer card reader. Each number of the APDU is a hexadecimal number ranging from **0x00** to **0xFF**.| **Example** ```js +import cardEmulation from '@ohos.nfc.cardEmulation'; + +var isHceSupported = cardEmulation.isSupported(cardEmulation.FeatureType.HCE); +if (!isHceSupported) { + console.log('this device is not supported for HCE, ignore it.'); + return; +} + +// The device supports HCE and transimits APDUs with the remote NFC reader. var hceService = new cardEmulation.HceService(); hceService.startHCE([ "F0010203040506", "A0000000041010" -]) -hceService.stopHCE(); +]); + hceService.on("hceCmd", (err, res) => { if(err.data === 0) { console.log('callback => Operation hceCmd succeeded. Data: ' + JSON.stringify(res)); @@ -108,4 +136,7 @@ hceService.on("hceCmd", (err, res) => { console.log('callback => Operation hceCmd failed. Cause: ' + err.data); } }) + +// Stop HCE when the application exits the NFC card emulation. +hceService.stopHCE(); ``` diff --git a/en/application-dev/reference/apis/js-apis-commonEvent.md b/en/application-dev/reference/apis/js-apis-commonEvent.md index 50fad38058530104fda01f09d5745c0f8051000a..4cb3ef3bc5f1672b883ae42d722e593aabf03d24 100644 --- a/en/application-dev/reference/apis/js-apis-commonEvent.md +++ b/en/application-dev/reference/apis/js-apis-commonEvent.md @@ -18,7 +18,7 @@ Provides the event types supported by the **CommonEvent** module. The name and v **System capability**: SystemCapability.Notification.CommonEvent -| Name | Value | Subscriber Permission | Description | +| Name | Value | Subscriber Permission | Description | | ------------ | ------------------ | ---------------------- | -------------------- | | COMMON_EVENT_BOOT_COMPLETED | usual.event.BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the user has finished booting and the system has been loaded. | | COMMON_EVENT_LOCKED_BOOT_COMPLETED | usual.event.LOCKED_BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the user has finished booting and the system has been loaded but the screen is still locked. | @@ -152,17 +152,17 @@ Provides the event types supported by the **CommonEvent** module. The name and v | COMMON_EVENT_USB_DEVICE_DETACHED | usual.event.hardware.usb.action.USB_DEVICE_DETACHED | - | Indicates the common event that a USB device has been detached when the user device functions as a USB host. | | COMMON_EVENT_USB_ACCESSORY_ATTACHED | usual.event.hardware.usb.action.USB_ACCESSORY_ATTACHED | - | Indicates the common event that a USB accessory was attached. | | COMMON_EVENT_USB_ACCESSORY_DETACHED | usual.event.hardware.usb.action.USB_ACCESSORY_DETACHED | - | Indicates the common event that a USB accessory was detached. | -| COMMON_EVENT_DISK_REMOVED | usual.event.data.DISK_REMOVED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was removed. | -| COMMON_EVENT_DISK_UNMOUNTED | usual.event.data.DISK_UNMOUNTED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was unmounted. | -| COMMON_EVENT_DISK_MOUNTED | usual.event.data.DISK_MOUNTED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was mounted. | -| COMMON_EVENT_DISK_BAD_REMOVAL | usual.event.data.DISK_BAD_REMOVAL | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was removed without being unmounted. | -| COMMON_EVENT_DISK_UNMOUNTABLE | usual.event.data.DISK_UNMOUNTABLE | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device becomes unmountable. | -| COMMON_EVENT_DISK_EJECT | usual.event.data.DISK_EJECT | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was ejected. | -| COMMON_EVENT_VOLUME_REMOVED9+ | usual.event.data.VOLUME_REMOVED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was removed. | -| COMMON_EVENT_VOLUME_UNMOUNTED9+ | usual.event.data.VOLUME_UNMOUNTED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was unmounted. | -| COMMON_EVENT_VOLUME_MOUNTED9+ | usual.event.data.VOLUME_MOUNTED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was mounted. | -| COMMON_EVENT_VOLUME_BAD_REMOVAL9+ | usual.event.data.VOLUME_BAD_REMOVAL | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was removed without being unmounted. | -| COMMON_EVENT_VOLUME_EJECT9+ | usual.event.data.VOLUME_EJECT | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was ejected. | +| COMMON_EVENT_DISK_REMOVED | usual.event.data.DISK_REMOVED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed. | +| COMMON_EVENT_DISK_UNMOUNTED | usual.event.data.DISK_UNMOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was unmounted. | +| COMMON_EVENT_DISK_MOUNTED | usual.event.data.DISK_MOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was mounted. | +| COMMON_EVENT_DISK_BAD_REMOVAL | usual.event.data.DISK_BAD_REMOVAL | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed without being unmounted. | +| COMMON_EVENT_DISK_UNMOUNTABLE | usual.event.data.DISK_UNMOUNTABLE | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device becomes unmountable. | +| COMMON_EVENT_DISK_EJECT | usual.event.data.DISK_EJECT | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was ejected. | +| COMMON_EVENT_VOLUME_REMOVED9+ | usual.event.data.VOLUME_REMOVED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed. | +| COMMON_EVENT_VOLUME_UNMOUNTED9+ | usual.event.data.VOLUME_UNMOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was unmounted. | +| COMMON_EVENT_VOLUME_MOUNTED9+ | usual.event.data.VOLUME_MOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was mounted. | +| COMMON_EVENT_VOLUME_BAD_REMOVAL9+ | usual.event.data.VOLUME_BAD_REMOVAL | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed without being unmounted. | +| COMMON_EVENT_VOLUME_EJECT9+ | usual.event.data.VOLUME_EJECT | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was ejected. | | COMMON_EVENT_VISIBLE_ACCOUNTS_UPDATED | usual.event.data.VISIBLE_ACCOUNTS_UPDATED | ohos.permission.GET_APP_ACCOUNTS | Indicates the common event that the account visibility changed. | | COMMON_EVENT_ACCOUNT_DELETED | usual.event.data.ACCOUNT_DELETED | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | Indicates the common event that the account was deleted. | | COMMON_EVENT_FOUNDATION_READY | usual.event.data.FOUNDATION_READY | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the foundation is ready. | @@ -170,13 +170,14 @@ Provides the event types supported by the **CommonEvent** module. The name and v | COMMON_EVENT_SPLIT_SCREEN8+ | usual.event.SPLIT_SCREEN | ohos.permission.RECEIVER_SPLIT_SCREEN | Indicates the common event of screen splitting. | | COMMON_EVENT_SLOT_CHANGE9+ | usual.event.SLOT_CHANGE | ohos.permission.NOTIFICATION_CONTROLLER | Indicates the common event that the notification slot has changed. | | COMMON_EVENT_SPN_INFO_CHANGED 9+ | usual.event.SPN_INFO_CHANGED | - | Indicates the common event that the SPN displayed has been updated. | +| COMMON_EVENT_QUICK_FIX_APPLY_RESULT 9+ | usual.event.QUICK_FIX_APPLY_RESULT | - | Indicates the common event that a quick fix is applied to the application. | ## CommonEvent.publish publish(event: string, callback: AsyncCallback\): void -Publishes a common event. This API uses a callback to return the result. +Publishes a common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -209,7 +210,7 @@ CommonEvent.publish("event", PublishCallBack); publish(event: string, options: CommonEventPublishData, callback: AsyncCallback\): void -Publishes a common event with given attributes. This API uses a callback to return the result. +Publishes a common event with given attributes. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -226,7 +227,7 @@ Publishes a common event with given attributes. This API uses a callback to retu ```js // Attributes of a common event. -var options = { +let options = { code: 0, // Result code of the common event. data: "initial data";// Result data of the common event. isOrdered: true // The common event is an ordered one. @@ -251,7 +252,7 @@ CommonEvent.publish("event", options, PublishCallBack); publishAsUser(event: string, userId: number, callback: AsyncCallback\): void -Publishes a common event to a specific user. This API uses a callback to return the result. +Publishes a common event to a specific user. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -278,7 +279,7 @@ function PublishAsUserCallBack(err) { } // Specify the user to whom the common event will be published. -var userId = 100; +let userId = 100; // Publish a common event. CommonEvent.publishAsUser("event", userId, PublishAsUserCallBack); @@ -290,7 +291,7 @@ CommonEvent.publishAsUser("event", userId, PublishAsUserCallBack); publishAsUser(event: string, userId: number, options: CommonEventPublishData, callback: AsyncCallback\): void -Publishes a common event with given attributes to a specific user. This API uses a callback to return the result. +Publishes a common event with given attributes to a specific user. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -310,9 +311,9 @@ Publishes a common event with given attributes to a specific user. This API uses ```js // Attributes of a common event. -var options = { +let options = { code: 0, // Result code of the common event. - data: "initial data";// Result data of the common event + data: "initial data";// Result data of the common event. } // Callback for common event publication @@ -325,7 +326,7 @@ function PublishAsUserCallBack(err) { } // Specify the user to whom the common event will be published. -var userId = 100; +let userId = 100; // Publish a common event. CommonEvent.publishAsUser("event", userId, options, PublishAsUserCallBack); @@ -337,7 +338,7 @@ CommonEvent.publishAsUser("event", userId, options, PublishAsUserCallBack); createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback\): void -Creates a subscriber. This API uses a callback to return the result. +Creates a subscriber. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -352,10 +353,10 @@ Creates a subscriber. This API uses a callback to return the result. ```js -var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -var subscribeInfo = { +let subscribeInfo = { events: ["event"] }; @@ -397,10 +398,10 @@ Creates a subscriber. This API uses a promise to return the result. **Example** ```js -var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -var subscribeInfo = { +let subscribeInfo = { events: ["event"] }; @@ -419,7 +420,7 @@ CommonEvent.createSubscriber(subscribeInfo).then((commonEventSubscriber) => { subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback\): void -Subscribes to common events. This API uses a callback to return the result. +Subscribes to common events. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -433,10 +434,10 @@ Subscribes to common events. This API uses a callback to return the result. **Example** ```js -var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -var subscribeInfo = { +let subscribeInfo = { events: ["event"] }; @@ -471,7 +472,7 @@ CommonEvent.createSubscriber(subscribeInfo, CreateSubscriberCallBack); unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback\): void -Unsubscribes from common events. This API uses a callback to return the result. +Unsubscribes from common events. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -485,10 +486,10 @@ Unsubscribes from common events. This API uses a callback to return the result. **Example** ```js -var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -var subscribeInfo = { +let subscribeInfo = { events: ["event"] }; @@ -535,7 +536,7 @@ CommonEvent.unsubscribe(subscriber, UnsubscribeCallBack); getCode(callback: AsyncCallback\): void -Obtains the result code of this common event. This API uses a callback to return the result. +Obtains the result code of this common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -548,7 +549,7 @@ Obtains the result code of this common event. This API uses a callback to return **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for result code obtaining of an ordered common event. function getCodeCallback(err, Code) { @@ -578,7 +579,7 @@ Obtains the result code of this common event. This API uses a promise to return **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.getCode().then((Code) => { console.info("getCode " + JSON.stringify(Code)); @@ -591,7 +592,7 @@ subscriber.getCode().then((Code) => { setCode(code: number, callback: AsyncCallback\): void -Sets the result code for this common event. This API uses a callback to return the result. +Sets the result code for this common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -605,7 +606,7 @@ Sets the result code for this common event. This API uses a callback to return t **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for result code setting of an ordered common event. function setCodeCallback(err) { @@ -641,7 +642,7 @@ Sets the result code for this common event. This API uses a promise to return th **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.setCode(1).then(() => { console.info("setCode"); @@ -654,7 +655,7 @@ subscriber.setCode(1).then(() => { getData(callback: AsyncCallback\): void -Obtains the result data of this common event. This API uses a callback to return the result. +Obtains the result data of this common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -667,7 +668,7 @@ Obtains the result data of this common event. This API uses a callback to return **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for result data obtaining of an ordered common event. function getDataCallback(err, Data) { @@ -697,7 +698,7 @@ Obtains the result data of this common event. This API uses a promise to return **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.getData().then((Data) => { console.info("getData " + JSON.stringify(Data)); @@ -710,7 +711,7 @@ subscriber.getData().then((Data) => { setData(data: string, callback: AsyncCallback\): void -Sets the result data for this common event. This API uses a callback to return the result. +Sets the result data for this common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -724,7 +725,7 @@ Sets the result data for this common event. This API uses a callback to return t **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for result data setting of an ordered common event function setDataCallback(err) { @@ -760,7 +761,7 @@ Sets the result data for this common event. This API uses a promise to return th **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.setData("publish_data_changed").then(() => { console.info("setData"); @@ -773,7 +774,7 @@ subscriber.setData("publish_data_changed").then(() => { setCodeAndData(code: number, data: string, callback:AsyncCallback\): void -Sets the result code and result data for this common event. This API uses a callback to return the result. +Sets the result code and result data for this common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -788,7 +789,7 @@ Sets the result code and result data for this common event. This API uses a call **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for result code and result data setting of an ordered common event. function setCodeDataCallback(err) { @@ -825,7 +826,7 @@ Sets the result code and result data for this common event. This API uses a prom **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.setCodeAndData(1, "publish_data_changed").then(() => { console.info("setCodeAndData"); @@ -838,7 +839,8 @@ subscriber.setCodeAndData(1, "publish_data_changed").then(() => { isOrderedCommonEvent(callback: AsyncCallback\): void -Checks whether this common event is an ordered one. This API uses a callback to return the result. +Checks whether this common event is an ordered one. This API uses an asynchronous callback to return the result. + **System capability**: SystemCapability.Notification.CommonEvent @@ -851,7 +853,7 @@ Checks whether this common event is an ordered one. This API uses a callback to **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for checking whether the current common event is an ordered one. function isOrderedCallback(err, isOrdered) { @@ -870,6 +872,7 @@ isOrderedCommonEvent(): Promise\ Checks whether this common event is an ordered one. This API uses a promise to return the result. + **System capability**: SystemCapability.Notification.CommonEvent **Return value** @@ -881,7 +884,7 @@ Checks whether this common event is an ordered one. This API uses a promise to r **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.isOrderedCommonEvent().then((isOrdered) => { console.info("isOrdered " + JSON.stringify(isOrdered)); @@ -894,7 +897,8 @@ subscriber.isOrderedCommonEvent().then((isOrdered) => { isStickyCommonEvent(callback: AsyncCallback\): void -Checks whether this common event is a sticky one. This API uses a callback to return the result. +Checks whether this common event is a sticky one. This API uses an asynchronous callback to return the result. + **System capability**: SystemCapability.Notification.CommonEvent @@ -907,7 +911,7 @@ Checks whether this common event is a sticky one. This API uses a callback to re **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for checking whether the current common event is a sticky one. function isStickyCallback(err, isSticky) { @@ -926,6 +930,7 @@ isStickyCommonEvent(): Promise\ Checks whether this common event is a sticky one. This API uses a promise to return the result. + **System capability**: SystemCapability.Notification.CommonEvent **Return value** @@ -937,7 +942,7 @@ Checks whether this common event is a sticky one. This API uses a promise to ret **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.isStickyCommonEvent().then((isSticky) => { console.info("isSticky " + JSON.stringify(isSticky)); @@ -950,7 +955,7 @@ subscriber.isStickyCommonEvent().then((isSticky) => { abortCommonEvent(callback: AsyncCallback\): void -Aborts this common event. After the abort, the common event is not sent to the next subscriber. This API takes effect only for ordered common events. It uses a callback to return the result. +Aborts this common event. After the abort, the common event is not sent to the next subscriber. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -963,7 +968,7 @@ Aborts this common event. After the abort, the common event is not sent to the n **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for common event aborting. function abortCallback(err) { @@ -993,7 +998,7 @@ Aborts this common event. After the abort, the common event is not sent to the n **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.abortCommonEvent().then(() => { console.info("abortCommonEvent"); @@ -1006,7 +1011,7 @@ subscriber.abortCommonEvent().then(() => { clearAbortCommonEvent(callback: AsyncCallback\): void -Clears the aborted state of this common event. This API takes effect only for ordered common events. It uses a callback to return the result. +Clears the aborted state of this common event. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -1019,7 +1024,7 @@ Clears the aborted state of this common event. This API takes effect only for or **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for clearing the aborted state of the current common event. function clearAbortCallback(err) { @@ -1049,7 +1054,7 @@ Clears the aborted state of this common event. This API takes effect only for or **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.clearAbortCommonEvent().then(() => { console.info("clearAbortCommonEvent"); @@ -1062,7 +1067,7 @@ subscriber.clearAbortCommonEvent().then(() => { getAbortCommonEvent(callback: AsyncCallback\): void -Checks whether this common event is in the aborted state. This API takes effect only for ordered common events. It uses a callback to return the result. +Checks whether this common event is in the aborted state. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -1075,7 +1080,7 @@ Checks whether this common event is in the aborted state. This API takes effect **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for checking whether the current common event is in the aborted state. function getAbortCallback(err, AbortCommonEvent) { @@ -1105,7 +1110,7 @@ Checks whether this common event is in the aborted state. This API takes effect **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.getAbortCommonEvent().then((AbortCommonEvent) => { console.info("AbortCommonEvent " + JSON.stringify(AbortCommonEvent)); @@ -1118,7 +1123,7 @@ subscriber.getAbortCommonEvent().then((AbortCommonEvent) => { getSubscribeInfo(callback: AsyncCallback\): void -Obtains the subscriber information. This API uses a callback to return the result. +Obtains the subscriber information. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -1131,7 +1136,7 @@ Obtains the subscriber information. This API uses a callback to return the resul **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for subscriber information obtaining. function getSubscribeInfoCallback(err, SubscribeInfo) { @@ -1161,7 +1166,7 @@ Obtains the subscriber information. This API uses a promise to return the result **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.getSubscribeInfo().then((SubscribeInfo) => { console.info("SubscribeInfo " + JSON.stringify(SubscribeInfo)); @@ -1174,7 +1179,7 @@ subscriber.getSubscribeInfo().then((SubscribeInfo) => { finishCommonEvent(callback: AsyncCallback\): void -Finishes this ordered common event. This API uses a callback to return the result. +Finishes this ordered common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -1187,7 +1192,7 @@ Finishes this ordered common event. This API uses a callback to return the resul **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for ordered common event finishing. function finishCommonEventCallback(err) { @@ -1217,7 +1222,7 @@ Finishes this ordered common event. This API uses a promise to return the result **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.finishCommonEvent().then(() => { console.info("FinishCommonEvent"); diff --git a/en/application-dev/reference/apis/js-apis-contact.md b/en/application-dev/reference/apis/js-apis-contact.md index 67b846c17b94a6acee894da72ae28cedefd2532c..a166781108683f6b6fb53673da4deacd99882b26 100644 --- a/en/application-dev/reference/apis/js-apis-contact.md +++ b/en/application-dev/reference/apis/js-apis-contact.md @@ -202,8 +202,8 @@ Updates a contact based on the specified contact information and attributes. Thi contact.updateContact({ name: {fullName: 'xxx'}, phoneNumbers: [{phoneNumber: '138xxxxxxxx'}] - },{ - attributes:[contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] + }, { + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }, (err) => { if (err) { console.log('updateContact callback: err->${JSON.stringify(err)}'); @@ -432,7 +432,7 @@ Queries my card based on the specified contact attributes. This API uses an asyn ```js contact.queryMyCard({ - attributes:['ATTR_EMAIL', 'ATTR_NAME'] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }, (err, data) => { if (err) { console.log(`queryMyCard callback: err->${JSON.stringify(err)}`); @@ -469,7 +469,7 @@ Queries my card based on the specified contact attributes. This API uses a promi ```js let promise = contact.queryMyCard({ - attributes:['ATTR_EMAIL', 'ATTR_NAME'] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }); promise.then((data) => { console.log(`queryMyCard success: data->${JSON.stringify(data)}`); @@ -487,7 +487,7 @@ Selects a contact. This API uses an asynchronous callback to return the result. **Permission required**: ohos.permission.READ_CONTACTS -**System capability**: SystemCapability.Applications.ContactsData +**System capability**: SystemCapability.Applications.Contacts **Parameters** @@ -516,7 +516,7 @@ Selects a contact. This API uses a promise to return the result. **Permission required**: ohos.permission.READ_CONTACTS -**System capability**: SystemCapability.Applications.ContactsData +**System capability**: SystemCapability.Applications.Contacts **Return Value** diff --git a/en/application-dev/reference/apis/js-apis-emitter.md b/en/application-dev/reference/apis/js-apis-emitter.md index 6398b87f685e5f91c59dacb1da97b4ad993e5afa..0bc6f9c6a4c156cfa2d604885572fcbe4bdc41bc 100644 --- a/en/application-dev/reference/apis/js-apis-emitter.md +++ b/en/application-dev/reference/apis/js-apis-emitter.md @@ -16,19 +16,6 @@ import emitter from '@ohos.events.emitter' None -## EventPriority - -Enumerates the event emit priority levels. - -**System capability**: SystemCapability.Notification.Emitter - -| Name | Value | Description | -| --------- | ---- | ------------------------------------------------- | -| IMMEDIATE | 0 | The event will be emitted immediately. | -| HIGH | 1 | The event will be emitted before low-priority events. | -| LOW | 2 | The event will be emitted before idle-priority events. By default, an event is in LOW priority. | -| IDLE | 3 | The event will be emitted after all the other events. | - ## emitter.on on(event: [InnerEvent](#innerevent), callback: Callback\<[EventData](#eventdata)\>): void @@ -39,21 +26,21 @@ Subscribes to an event in persistent manner. This API uses a callback to return **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------- | ---- | ------------------------ | -| event | [InnerEvent](#innerevent) | Yes | Event to subscribe to in persistent manner. | -| callback | Callback\<[EventData](#eventdata)\> | Yes | Callback used to return the event.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | --------------------------------------- | +| event | [InnerEvent](#innerevent) | Yes | Event to subscribe to in persistent manner. The **EventPriority** settings do not take effect.| +| callback | Callback\<[EventData](#eventdata)\> | Yes | Callback used to return the event. | **Example** ```javascript -var innerEvent = { +let innerEvent = { eventId: 1 }; -var callback = (eventData) => { +function EmitterCallback(eventData) { console.info('callback'); -}; -emitter.on(innerEvent, callback); +} +emitter.on(innerEvent, EmitterCallback); ``` ## emitter.once @@ -66,21 +53,21 @@ Subscribes to an event in one-shot manner and unsubscribes from it after the eve **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------- | ---- | ------------------------ | -| event | [InnerEvent](#innerevent) | Yes | Event to subscribe to in one-shot manner. | -| callback | Callback\<[EventData](#eventdata)\> | Yes | Callback used to return the event.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | --------------------------------------- | +| event | [InnerEvent](#innerevent) | Yes | Event to subscribe to in one-shot manner. The **EventPriority** settings do not take effect.| +| callback | Callback\<[EventData](#eventdata)\> | Yes | Callback used to return the event. | **Example** ```javascript -var innerEvent = { +let innerEvent = { eventId: 1 }; -var callback = (eventData) => { +function EmitterCallback(eventData) { console.info('once callback'); }; -emitter.once(innerEvent, callback); +emitter.once(innerEvent, EmitterCallback); ``` ## emitter.off @@ -121,18 +108,31 @@ Emits an event to the event queue. **Example** ```javascript -var eventData = { +let eventData = { data: { "content": "c", "id": 1, }}; -var innerEvent = { +let innerEvent = { eventId: 1, priority: emitter.EventPriority.HIGH }; emitter.emit(innerEvent, eventData); ``` +## EventPriority + +Enumerates the event emit priority levels. + +**System capability**: SystemCapability.Notification.Emitter + +| Name | Value | Description | +| --------- | ---- | --------------------------------------------------- | +| IMMEDIATE | 0 | The event will be emitted immediately. | +| HIGH | 1 | The event will be emitted before low-priority events. | +| LOW | 2 | The event will be emitted before idle-priority events. By default, an event is in LOW priority.| +| IDLE | 3 | The event will be emitted after all the other events. | + ## InnerEvent Describes an in-process event. @@ -141,7 +141,7 @@ Describes an in-process event. | Name | Type | Readable| Writable| Description | | -------- | ------------------------------- | ---- | ---- | ---------------------------------- | -| eventId | number | Yes | Yes | Event ID, which is used to identify an event.| +| eventId | number | Yes | Yes | Event ID.| | priority | [EventPriority](#eventpriority) | Yes | Yes | Emit priority of the event. | ## EventData diff --git a/en/application-dev/reference/apis/js-apis-hiappevent.md b/en/application-dev/reference/apis/js-apis-hiappevent.md index cc7d684666b28555597b406fddfc7b4c5cd7e130..aefc93a933ecdf42a0d270134d81f17c8a5788af 100644 --- a/en/application-dev/reference/apis/js-apis-hiappevent.md +++ b/en/application-dev/reference/apis/js-apis-hiappevent.md @@ -3,6 +3,7 @@ This module provides the application event logging functions, such as writing application events to the event file and managing the event logging configuration. > **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -18,11 +19,11 @@ Before using application event logging, you need to understand the requirements **Event Domain** -An event domain is a string that contains a maximum of 32 characters, including digits (0 to 9), letters (a to z), and underscores (_). It cannot start with an underscore (_). +An event domain is a string that contains a maximum of 32 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It cannot start with an underscore (\_). **Event Name** -An event name is a string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (_). It cannot start with an underscore (_). +An event name is a string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It cannot start with an underscore (\_). **Event Type** @@ -32,7 +33,7 @@ An event type is an enumerated value of [EventType](#eventtype). An event parameter is an object in key-value pair format, where the key is the parameter name and the value is the parameter value. The requirements are as follows: -- The parameter name is a string that contains a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (_). It cannot start or end with an underscore (_). +- The parameter name is a string that contains a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It cannot start or end with an underscore (\_). - The parameter value is a string, number, boolean, or array. - When the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be truncated. - When the parameter value is an array, the elements in the array must be of the same type, which can only be string, number, or boolean. In addition, the number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded. @@ -404,12 +405,30 @@ Defines a subscription data holder for processing subscription events. **System capability**: SystemCapability.HiviewDFX.HiAppEvent +### constructor9+ + +constructor(watcherName: string); + +A constructor used to create a **holder** object. It is called automatically when a **Watcher** object is added. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +**Example** + +```js +let holder = hiAppEvent.addWatcher({ + name: "watcher", +}); +``` + ### setSize9+ setSize(size: number): void Sets the data size threshold for fetching an application event package. The default value is **512*1024**, in bytes. +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + **Example** ```js @@ -425,6 +444,8 @@ takeNext(): [AppEventPackage](#appeventpackage9) Extracts subscription event data based on the configured data size threshold. If all subscription event data has been extracted, **null** will be returned. +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + **Example** ```js diff --git a/en/application-dev/reference/apis/js-apis-hidebug.md b/en/application-dev/reference/apis/js-apis-hidebug.md index 469fcae6f1c0f82f0894422b3e2a4416fabc7a60..53af9c42a3aa2d8cddf8d38290f7a29c30f8f9d6 100644 --- a/en/application-dev/reference/apis/js-apis-hidebug.md +++ b/en/application-dev/reference/apis/js-apis-hidebug.md @@ -1,6 +1,7 @@ # HiDebug -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. You can run the hidebug command to obtain the memory usage of an application, including the static heap memory (native heap) and proportional set size (PSS) occupied by the application process. You can also export VM memory slices and collect VM CPU profiling data. @@ -16,7 +17,7 @@ import hidebug from '@ohos.hidebug'; getNativeHeapSize(): bigint -Obtains the total size of the native heap memory. +Obtains the total size of the heap memory of this application. This API is defined but not implemented in OpenHarmony 3.1 Release. @@ -26,84 +27,80 @@ This API is defined but not implemented in OpenHarmony 3.1 Release. | Type | Description | | ------ | --------------------------- | -| bigint | Total size of the native heap memory, in kB.| +| bigint | Total size of the heap memory of this application, in kB.| **Example** - -```js -let nativeHeapSize = hidebug.getNativeHeapSize(); -``` + ```js + let nativeHeapSize = hidebug.getNativeHeapSize(); + ``` ## hidebug.getNativeHeapAllocatedSize getNativeHeapAllocatedSize(): bigint -Obtains the size of the allocated native heap memory. +Obtains the size of the allocated heap memory of this application. This API is defined but not implemented in OpenHarmony 3.1 Release. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug -**Return value** +**Return value** | Type | Description | | ------ | --------------------------------- | -| bigint | Size of the allocated native heap memory, in kB.| +| bigint | Size of the allocated heap memory of this application, in kB.| **Example** - -```js -let nativeHeapAllocatedSize = hidebug.getNativeHeapAllocatedSize(); -``` + ```js + let nativeHeapAllocatedSize = hidebug.getNativeHeapAllocatedSize(); + ``` ## hidebug.getNativeHeapFreeSize getNativeHeapFreeSize(): bigint -Obtains the size of the free native heap memory. +Obtains the size of the free heap memory of this application. This API is defined but not implemented in OpenHarmony 3.1 Release. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug -**Return value** +**Return value** | Type | Description | | ------ | ------------------------------- | -| bigint | Size of the free native heap memory, in kB.| +| bigint | Size of the free heap memory of this application, in kB.| **Example** - -```js -let nativeHeapFreeSize = hidebug.getNativeHeapFreeSize(); -``` + ```js + let nativeHeapFreeSize = hidebug.getNativeHeapFreeSize(); + ``` ## hidebug.getPss getPss(): bigint -Obtains the PSS of this process. +Obtains the size of the used physical memory of this process. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug -**Return value** +**Return value** | Type | Description | | ------ | ------------------------- | -| bigint | PSS of the process, in kB.| +| bigint | Used physical memory of this process, in kB.| **Example** - -```js -let pss = hidebug.getPss(); -``` + ```js + let pss = hidebug.getPss(); + ``` ## hidebug.getSharedDirty @@ -114,18 +111,17 @@ Obtains the size of the shared dirty memory of this process. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug -**Return value** +**Return value** | Type | Description | | ------ | -------------------------- | -| bigint | Size of the shared dirty memory of the process, in kB.| +| bigint | Size of the shared dirty memory of this process, in kB.| **Example** - -```js -let sharedDirty = hidebug.getSharedDirty(); -``` + ```js + let sharedDirty = hidebug.getSharedDirty(); + ``` ## hidebug.getPrivateDirty9+ @@ -135,11 +131,11 @@ Obtains the size of the private dirty memory of this process. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug -**Return value** +**Return value** | Type | Description | | ------ | -------------------------- | -| bigint | Size of the private dirty memory of the process, in kB.| +| bigint | Size of the private dirty memory of this process, in kB.| **Example** @@ -157,18 +153,17 @@ For example, if the CPU usage is **50%**, **0.5** is returned. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug -**Return value** +**Return value** | Type | Description | | ------ | -------------------------- | -| number | CPU usage of the process.| +| number | CPU usage of this process.| **Example** - -```js -let cpuUsage = hidebug.getCpuUsage(); -``` + ```js + let cpuUsage = hidebug.getCpuUsage(); + ``` ## hidebug.startProfiling @@ -195,6 +190,7 @@ hidebug.stopProfiling(); ``` + ## hidebug.stopProfiling stopProfiling() : void @@ -225,7 +221,7 @@ Exports data from the specified heap file. | Name | Type | Mandatory | Description | | -------- | ------ | ---- | ------------------------------------------------------------ | -| filename | string | Yes | User-defined heap file name. The `filename.heapsnapshot` file is generated in the `files` directory of the app based on the specified `filename`.| +| filename | string | Yes | User-defined heap file name. The `filename.heapsnapshot` file is generated in the `files` directory of the application based on the specified `filename`.| **Example** @@ -250,7 +246,6 @@ This is a system API and cannot be called by third-party applications. | serviceid | number | Yes | ID of the system service. | **Return value** - | Type | Description | | ------ | -------------------------- | | string | Absolute path of the file that contains the service information to dump. | diff --git a/en/application-dev/reference/apis/js-apis-hisysevent.md b/en/application-dev/reference/apis/js-apis-hisysevent.md index 65952c0b23946b02582d74e5be9fbc5f8c33b42d..553ff5a9925a30f262acb49bb69cd4e95c7bd95b 100644 --- a/en/application-dev/reference/apis/js-apis-hisysevent.md +++ b/en/application-dev/reference/apis/js-apis-hisysevent.md @@ -2,7 +2,7 @@ Provides system event logging APIs for system HAP applications. -> **NOTE**
+> **NOTE** > - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The APIs of this module are system APIs. @@ -19,7 +19,7 @@ Enumerates event types. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Default Value| Description| +| Name | Default Value | Description | | -------- | -------- | -------- | | FAULT | 1 | Error event.| | STATISTIC | 2 | Statistic event.| @@ -32,7 +32,7 @@ Defines a system event. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | domain | string | Yes| Event domain.| | name | string | Yes| Event name.| @@ -50,7 +50,7 @@ Writes event information to the event file. This API uses an asynchronous callba **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory | Description | | --------- | ------------------------- | ---- | ------------------------------------------------------------ | | info | [SysEventInfo](#syseventinfo) | Yes| System event information.| | callback | AsyncCallback<void> | Yes| Callback used to process the received return value.
- Value **0**: The event verification is successful, and the event will be written to the event file asynchronously.
- A value greater than **0**: Invalid parameters are present in the event, and the event will be written to the event file asynchronously after the invalid parameters are ignored.
- A value smaller than **0**: The event parameter verification fails, and the event will not be written to the event file.| @@ -91,13 +91,13 @@ Writes event information to the event file. This API uses a promise to return th **Parameters** -| Name | Type | Mandatory| Description| +| Name | Type | Mandatory | Description| | --------- | ----------------------- | ---- | --------------- | | info | [SysEventInfo](#syseventinfo) | Yes | System event information.| **Return value** -| Type | Description | +| Type | Description | | ------------------- | ------------------------------------------------------------ | | Promise<void> | Promise used to return the result. Depending on whether event writing is successful, you can use the **then()** or **catch()** method to process the callback.| @@ -138,7 +138,7 @@ Enumerates matching rule types. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Default Value| Description| +| Name | Default Value | Description | | -------- | -------- | -------- | | WHOLE_WORD | 1 | Whole word matching.| | PREFIX | 2 | Prefix matching.| @@ -150,7 +150,7 @@ Defines rules for event subscription. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | domain | string | Yes| Event domain.| | name | string | Yes| Event name.| @@ -163,7 +163,7 @@ Defines a watcher for event subscription. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | rules | [WatchRule](#watchrule)[] | Yes| Array of matching rules for event subscription.| | onEvent | function | Yes| Callback for event subscription: (info: [SysEventInfo](#syseventinfo)) => void| @@ -181,7 +181,7 @@ Adds a watcher for event subscription. **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | ------ | ----------------------------- | ---- | ------------------------ | | watcher | [Watcher](#watcher) | Yes| Watcher for event subscription.| @@ -223,7 +223,7 @@ Removes a watcher used for event subscription. **Parameters** -| Name| Type | Mandatory| Description | +| Name| Type | Mandatory | Description | | ------ | ------------- | ---- | ------------------------ | | watcher | [Watcher](#watcher) | Yes| Watcher for event subscription.| @@ -260,7 +260,7 @@ Defines arguments for event query. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | beginTime | number | Yes| Start time (13-digit timestamp) for event query.| | endTime | number | Yes| End time (13-digit timestamp) for event query.| @@ -272,7 +272,7 @@ Defines rules for event query. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | domain | string | Yes| Event domain.| | names | string[] | Yes| Array of event names.| @@ -283,7 +283,7 @@ Defines an event query instance. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | onQuery | function | Yes| Callback of queried events: (infos: [SysEventInfo](#syseventinfo)[]) => void| | onComplete | function | Yes| Callback of query result statistics: (reason: number, total: number) => void| @@ -300,7 +300,7 @@ Queries system events. **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | ------ | ----------------------------- | ---- | ------------------------ | | queryArg | [QueryArg](#queryarg) | Yes | Arguments for event query.| | rules | [QueryRule](#queryrule)[] | Yes | Array of event query rules.| diff --git a/en/application-dev/reference/apis/js-apis-http.md b/en/application-dev/reference/apis/js-apis-http.md index 9e0e0bf5160d01596d0c6e0969c3cc783712f45a..294ed0fa79032d4e47e6c9c999183811d272acd3 100644 --- a/en/application-dev/reference/apis/js-apis-http.md +++ b/en/application-dev/reference/apis/js-apis-http.md @@ -358,7 +358,7 @@ Specifies the type and value range of the optional parameters in the HTTP reques | Name | Type | Mandatory| Description | | -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | | method | [RequestMethod](#requestmethod) | No | Request method. | -| extraData | string \| Object \| ArrayBuffer8+ | No | Additional data of the request.
- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.
- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter is a supplement to the HTTP request parameters and will be added to the URL when the request is sent.8+
- To pass in a string object, you first need to encode the object on your own.8+ | +| extraData | string \| Object \| ArrayBuffer6+ | No | Additional data of the request.
- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.
- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter is a supplement to the HTTP request parameters and will be added to the URL when the request is sent.6+
- To pass in a string object, you first need to encode the object on your own.8+ | | header | Object | No | HTTP request header. The default value is **{'Content-Type': 'application/json'}**. | | readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. | | connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. | @@ -432,7 +432,7 @@ Defines the response to an HTTP request. | Name | Type | Mandatory| Description | | -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | -| result | string \| Object \| ArrayBuffer8+ | Yes | Response content returned based on **Content-type** in the response header:
- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.
- application/octet-stream: ArrayBuffer
- Others: string| +| result | string \| Object \| ArrayBuffer6+ | Yes | Response content returned based on **Content-type** in the response header:
- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.
- application/octet-stream: ArrayBuffer
- Others: string| | responseCode | [ResponseCode](#responsecode) \| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**. For details, see [Error Codes](#error-codes).| | header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:
- Content-Type: header['Content-Type'];
- Status-Line: header['Status-Line'];
- Date: header.Date/header['Date'];
- Server: header.Server/header['Server'];| | cookies8+ | Array\ | Yes | Cookies returned by the server. | diff --git a/en/application-dev/reference/apis/js-apis-huks.md b/en/application-dev/reference/apis/js-apis-huks.md index 2d66bc9c61a54f3bfa88d6e7f27aa93fabd49a2d..a886b6c643be1295bd49f0bf166d1e244d82f9af 100644 --- a/en/application-dev/reference/apis/js-apis-huks.md +++ b/en/application-dev/reference/apis/js-apis-huks.md @@ -12,1218 +12,2277 @@ The keys managed by OpenHarmony Universal KeyStore (HUKS) can be imported by app ```js import huks from '@ohos.security.huks' ``` -## HuksErrorCode -Enumerates the error codes. +## HuksParam -**System capability**: SystemCapability.Security.Huks +Defines the **param** in the **properties** array of **options** used in the APIs. -| Name | Value | Description| -| -------------------------- | ----- | ---- | -| HUKS_SUCCESS | 0 |Success.| -| HUKS_FAILURE | -1 |Failure.| -| HUKS_ERROR_BAD_STATE | -2 |Incorrect state.| -| HUKS_ERROR_INVALID_ARGUMENT | -3 |Invalid argument.| -| HUKS_ERROR_NOT_SUPPORTED | -4 |Not supported.| -| HUKS_ERROR_NO_PERMISSION | -5 |No permission.| -| HUKS_ERROR_INSUFFICIENT_DATA | -6 |Insufficient data.| -| HUKS_ERROR_BUFFER_TOO_SMALL | -7 |Insufficient buffer.| -| HUKS_ERROR_INSUFFICIENT_MEMORY | -8 |Insufficient memory.| -| HUKS_ERROR_COMMUNICATION_FAILURE | -9 |Communication failure.| -| HUKS_ERROR_STORAGE_FAILURE | -10 |Storage failure.| -| HUKS_ERROR_HARDWARE_FAILURE | -11 |Hardware fault.| -| HUKS_ERROR_ALREADY_EXISTS | -12 |The object already exists.| -| HUKS_ERROR_NOT_EXIST | -13 |The object does not exist.| -| HUKS_ERROR_NULL_POINTER | -14 |Null pointer.| -| HUKS_ERROR_FILE_SIZE_FAIL | -15 |Incorrect file size.| -| HUKS_ERROR_READ_FILE_FAIL | -16 |Failed to read the file.| -| HUKS_ERROR_INVALID_PUBLIC_KEY | -17 |Invalid public key.| -| HUKS_ERROR_INVALID_PRIVATE_KEY | -18 |Invalid private key.| -| HUKS_ERROR_INVALID_KEY_INFO | -19 |Invalid key information.| -| HUKS_ERROR_HASH_NOT_EQUAL | -20 |The hash values are not equal.| -| HUKS_ERROR_MALLOC_FAIL | -21 |MALLOC failed.| -| HUKS_ERROR_WRITE_FILE_FAIL | -22 |Failed to write the file.| -| HUKS_ERROR_REMOVE_FILE_FAIL | -23 |Failed to delete the file.| -| HUKS_ERROR_OPEN_FILE_FAIL | -24 |Failed to open the file.| -| HUKS_ERROR_CLOSE_FILE_FAIL | -25 |Failed to close the file.| -| HUKS_ERROR_MAKE_DIR_FAIL | -26 |Failed to create the directory.| -| HUKS_ERROR_INVALID_KEY_FILE | -27 |Invalid key file.| -| HUKS_ERROR_IPC_MSG_FAIL | -28 |Incorrect IPC information.| -| HUKS_ERROR_REQUEST_OVERFLOWS | -29 |Request overflows.| -| HUKS_ERROR_PARAM_NOT_EXIST | -30 |The parameter does not exist.| -| HUKS_ERROR_CRYPTO_ENGINE_ERROR | -31 |CRYPTO ENGINE error.| -| HUKS_ERROR_COMMUNICATION_TIMEOUT | -32 |Communication timed out.| -| HUKS_ERROR_IPC_INIT_FAIL | -33 |IPC initialization failed.| -| HUKS_ERROR_IPC_DLOPEN_FAIL | -34 |IPC DLOPEN failed.| -| HUKS_ERROR_EFUSE_READ_FAIL | -35 |Failed to read eFUSE.| -| HUKS_ERROR_NEW_ROOT_KEY_MATERIAL_EXIST | -36 |New root key material exists.| -| HUKS_ERROR_UPDATE_ROOT_KEY_MATERIAL_FAIL | -37 |Failed to update the root key material.| -| HUKS_ERROR_VERIFICATION_FAILED | -38 |Failed to verify the certificate chain.| -| HUKS_ERROR_GET_USERIAM_SECINFO_FAILED9+ | -40 |Failed to obtain the security attribute information of the user.| -| HUKS_ERROR_GET_USERIAM_AUTHINFO_FAILED9+ | -41 |Failed to obtain the authentication information of the user.| -| HUKS_ERROR_USER_AUTH_TYPE_NOT_SUPPORT9+ | -42 |The access control of the current authentication type is not supported.| -| HUKS_ERROR_KEY_AUTH_FAILED9+ | -43 |The access control authentication has failed.| -| HUKS_ERROR_DEVICE_NO_CREDENTIAL9+ | -44 |No credential has been enrolled for the device.| -| HUKS_ERROR_CHECK_GET_ALG_FAIL | -100 |Failed to check whether the ALG is obtained. | -| HUKS_ERROR_CHECK_GET_KEY_SIZE_FAIL | -101 |Failed to check whether the key size is obtained.| -| HUKS_ERROR_CHECK_GET_PADDING_FAIL | -102 |Failed to check whether padding is obtained.| -| HUKS_ERROR_CHECK_GET_PURPOSE_FAIL | -103 |Failed to check whether the purpose is obtained.| -| HUKS_ERROR_CHECK_GET_DIGEST_FAIL | -104 |Failed to check whether digest is obtained.| -| HUKS_ERROR_CHECK_GET_MODE_FAIL | -105 |Failed to check whether the mode is obtained.| -| HUKS_ERROR_CHECK_GET_NONCE_FAIL | -106 |Failed to check whether the nonce is obtained.| -| HUKS_ERROR_CHECK_GET_AAD_FAIL | -107 |Failed to check whether the AAD is obtained.| -| HUKS_ERROR_CHECK_GET_IV_FAIL | -108 |Failed to check whether the initialization vector (IV) is obtained.| -| HUKS_ERROR_CHECK_GET_AE_TAG_FAIL | -109 |Failed to check whether the AE flag is obtained.| -| HUKS_ERROR_CHECK_GET_SALT_FAIL | -110 |Failed to check whether the SALT is obtained.| -| HUKS_ERROR_CHECK_GET_ITERATION_FAIL | -111 |Failed to check whether the iteration is obtained.| -| HUKS_ERROR_INVALID_ALGORITHM | -112 |Invalid algorithm.| -| HUKS_ERROR_INVALID_KEY_SIZE | -113 |Invalid key size.| -| HUKS_ERROR_INVALID_PADDING | -114 |Invalid padding.| -| HUKS_ERROR_INVALID_PURPOSE | -115 |Invalid purpose.| -| HUKS_ERROR_INVALID_MODE | -116 |Invalid mode.| -| HUKS_ERROR_INVALID_DIGEST | -117 |Invalid digest.| -| HUKS_ERROR_INVALID_SIGNATURE_SIZE | -118 |Invalid signature size.| -| HUKS_ERROR_INVALID_IV | -119 |Invalid IV.| -| HUKS_ERROR_INVALID_AAD | -120 |Invalid AAD.| -| HUKS_ERROR_INVALID_NONCE | -121 |Invalid nonce.| -| HUKS_ERROR_INVALID_AE_TAG | -122 |Invalid AE tag.| -| HUKS_ERROR_INVALID_SALT | -123 |Invalid SALT.| -| HUKS_ERROR_INVALID_ITERATION | -124 |Invalid iteration.| -| HUKS_ERROR_INVALID_OPERATION | -125 |Invalid operation.| -| HUKS_ERROR_INVALID_WRAPPED_FORMAT9+ | -126 |Incorrect format of the wrapped key being imported.| -| HUKS_ERROR_INVALID_USAGE_OF_KEY9+ | -127 |Incorrect purpose of the wrapped key being imported.| -| HUKS_ERROR_INTERNAL_ERROR | -999 |Internal error.| -| HUKS_ERROR_UNKNOWN_ERROR | -1000 |Unknown error.| +**System capability**: SystemCapability.Security.Huks +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------- | ---- | ------------ | +| tag | [HuksTag](#hukstag) | Yes | Tag. | +| value | boolean\|number\|bigint\|Uint8Array | Yes | Value of the tag.| -## HuksKeyPurpose +## HuksOptions -Enumerates the key purposes. +Defines the **options** used in the APIs. **System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ------------------------ | ---- | -------------------------------- | -| HUKS_KEY_PURPOSE_ENCRYPT | 1 | Used to encrypt plaintext.| -| HUKS_KEY_PURPOSE_DECRYPT | 2 | Used to decrypt the cipher text.| -| HUKS_KEY_PURPOSE_SIGN | 4 | Used to sign data. | -| HUKS_KEY_PURPOSE_VERIFY | 8 | Used to verify the signed data. | -| HUKS_KEY_PURPOSE_DERIVE | 16 | Used to derive a key. | -| HUKS_KEY_PURPOSE_WRAP | 32 | Used to wrap a key. | -| HUKS_KEY_PURPOSE_UNWRAP | 64 | Used to unwrap a key. | -| HUKS_KEY_PURPOSE_MAC | 128 | Used to generate a message authentication code (MAC). | -| HUKS_KEY_PURPOSE_AGREE | 256 | Used for key agreement. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------- | ---- | ------------------------ | +| properties | Array\<[HuksParam](#huksparam)> | No | Properties used to hold the **HuksParam** array.| +| inData | Uint8Array | No | Input data. | -## HuksKeyDigest +## HuksSessionHandle9+ -Enumerates the digest algorithms. +Defines the HUKS handle structure. **System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ---------------------- | ---- | ---------------------------------------- | -| HUKS_DIGEST_NONE | 0 | No digest algorithm| -| HUKS_DIGEST_MD5 | 1 | MD5| -| HUKS_DIGEST_SM39+ | 2 | SM3| -| HUKS_DIGEST_SHA1 | 10 | SHA1| -| HUKS_DIGEST_SHA224 | 11 | SHA-224| -| HUKS_DIGEST_SHA256 | 12 | SHA-256| -| HUKS_DIGEST_SHA384 | 13 | SHA-384| -| HUKS_DIGEST_SHA512 | 14 | SHA-512| +| Name | Type | Mandatory| Description | +| --------- | ---------- | ---- | ---------------------------------------------------- | +| handle | number | Yes | Value of the handle. | +| challenge | Uint8Array | No | Challenge obtained after the [init](#huksinit) operation.| -## HuksKeyPadding +## HuksReturnResult9+ -Enumerates the padding algorithms. +Defines the **HuksResult** structure. **System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ---------------------- | ---- | ---------------------------------------- | -| HUKS_PADDING_NONE | 0 | No padding algorithm| -| HUKS_PADDING_OAEP | 1 | Optimal Asymmetric Encryption Padding (OAEP)| -| HUKS_PADDING_PSS | 2 | Probabilistic Signature Scheme (PSS)| -| HUKS_PADDING_PKCS1_V1_5 | 3 | PKCS1_V1_5| -| HUKS_PADDING_PKCS5 | 4 | Public Key Cryptography Standards (PKCS) #5| -| HUKS_PADDING_PKCS7 | 5 | PKCS #7| -## HuksCipherMode -Enumerates the cipher modes. +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------- | ---- | ---------------- | +| outData | Uint8Array | No | Output data. | +| properties | Array\<[HuksParam](#huksparam)> | No | Property information. | +| certChains | Array\ | No | Certificate chain information.| -**System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ------------- | ---- | --------------------- | -| HUKS_MODE_ECB | 1 | Electronic Code BLock (ECB) mode| -| HUKS_MODE_CBC | 2 | Cipher Block Chaining (CBC) mode| -| HUKS_MODE_CTR | 3 | Counter (CTR) mode| -| HUKS_MODE_OFB | 4 | Output Feedback (OFB) mode| -| HUKS_MODE_CCM | 31 | Counter with CBC-MAC (CCM) mode| -| HUKS_MODE_GCM | 32 | Galois/Counter (GCM) mode| +## huks.generateKeyItem9+ -## HuksKeySize +generateKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void -Enumerates the key sizes. +Generates a key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ---------------------------------- | ---- | ------------------------------------------ | -| HUKS_RSA_KEY_SIZE_512 | 512 | Rivest-Shamir-Adleman (RSA) key of 512 bits | -| HUKS_RSA_KEY_SIZE_768 | 768 | RSA key of 768 bits | -| HUKS_RSA_KEY_SIZE_1024 | 1024 | RSA key of 1024 bits | -| HUKS_RSA_KEY_SIZE_2048 | 2048 | RSA key of 2048 bits | -| HUKS_RSA_KEY_SIZE_3072 | 3072 | RSA key of 3072 bits | -| HUKS_RSA_KEY_SIZE_4096 | 4096 | RSA key of 4096 bits | -| HUKS_ECC_KEY_SIZE_224 | 224 | ECC key of 224 bits | -| HUKS_ECC_KEY_SIZE_256 | 256 | ECC key of 256 bits | -| HUKS_ECC_KEY_SIZE_384 | 384 | ECC key of 384 bits | -| HUKS_ECC_KEY_SIZE_521 | 521 | ECC key of 521 bits | -| HUKS_AES_KEY_SIZE_128 | 128 | AES key of 128 bits | -| HUKS_AES_KEY_SIZE_192 | 196 | AES key of 196 bits | -| HUKS_AES_KEY_SIZE_256 | 256 | AES key of 256 bits | -| HUKS_AES_KEY_SIZE_512 | 512 | AES key of 512 bits | -| HUKS_CURVE25519_KEY_SIZE_256 | 256 | Curve25519 key of 256 bits| -| HUKS_DH_KEY_SIZE_2048 | 2048 | DH key of 2048 bits | -| HUKS_DH_KEY_SIZE_3072 | 3072 | DH key of 3072 bits | -| HUKS_DH_KEY_SIZE_4096 | 4096 | DH key of 4096 bits | -| HUKS_SM2_KEY_SIZE_2569+ | 256 | SM2 key of 256 bits | -| HUKS_SM4_KEY_SIZE_1289+ | 128 | SM4 key of 128 bits | +**Parameters** -## HuksKeyAlg +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | --------------------------------------------- | +| keyAlias | string | Yes | Alias of the key. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| -Enumerates the key algorithms. +**Example** -**System capability**: SystemCapability.Security.Huks +```js +/* Generate an ECC key of 256 bits. */ +let keyAlias = 'keyAlias'; +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_ECC +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 +}; +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 +}; +let options = { + properties: properties +}; +try { + huks.generateKeyItem(keyAlias, options, function (error, data) { + if (error) { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: generateKeyItem key success`); + } + }); +} catch (error) { + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} +``` -| Name | Value | Description | -| ------------------------- | ---- | --------------------- | -| HUKS_ALG_RSA | 1 | RSA | -| HUKS_ALG_ECC | 2 | ECC | -| HUKS_ALG_DSA | 3 | DSA | -| HUKS_ALG_AES | 20 | AES | -| HUKS_ALG_HMAC | 50 | HMAC | -| HUKS_ALG_HKDF | 51 | HKDF | -| HUKS_ALG_PBKDF2 | 52 | PBKDF2 | -| HUKS_ALG_ECDH | 100 | ECDH | -| HUKS_ALG_X25519 | 101 | X25519 | -| HUKS_ALG_ED25519 | 102 | ED25519| -| HUKS_ALG_DH | 103 | DH | -| HUKS_ALG_SM29+ | 150 | SM2 | -| HUKS_ALG_SM39+ | 151 | SM3 | -| HUKS_ALG_SM49+ | 152 | SM4 | +## huks.generateKeyItem9+ -## HuksKeyGenerateType +generateKeyItem(keyAlias: string, options: HuksOptions) : Promise\ -Enumerates the key generation types. +Generates a key. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ------------------------------ | ---- | ---------------- | -| HUKS_KEY_GENERATE_TYPE_DEFAULT | 0 | Key generated by default.| -| HUKS_KEY_GENERATE_TYPE_DERIVE | 1 | Derived key.| -| HUKS_KEY_GENERATE_TYPE_AGREE | 2 | Key generated by agreement.| +**Parameters** -## HuksKeyFlag +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------ | +| keyAlias | string | Yes | Alias of the key. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key.| -Enumerates the key generation modes. +**Example** -**System capability**: SystemCapability.Security.Huks +```js +/* Generate an ECC key of 256 bits. */ +let keyAlias = 'keyAlias'; +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_ECC +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 +}; +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 +}; +let options = { + properties: properties +}; +try { + huks.generateKeyItem(keyAlias, options) + .then((data) => { + console.info(`promise: generateKeyItem success`); + }) + .catch(error => { + console.error(`promise: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); +} catch (error) { + console.error(`promise: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} +``` -| Name | Value | Description | -| -------------------------- | ---- | ------------------------------------ | -| HUKS_KEY_FLAG_IMPORT_KEY | 1 | The key is imported by using an API. | -| HUKS_KEY_FLAG_GENERATE_KEY | 2 | The key is generated by using an API. | -| HUKS_KEY_FLAG_AGREE_KEY | 3 | The key is generated by using a key agreement API.| -| HUKS_KEY_FLAG_DERIVE_KEY | 4 | The key is derived by using an API.| +## huks.deleteKeyItem9+ -## HuksKeyStorageType +deleteKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void -Enumerates the key storage modes. +Deletes a key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ----------------------- | ---- | ------------------------------ | -| HUKS_STORAGE_TEMP | 0 | The key is managed locally. | -| HUKS_STORAGE_PERSISTENT | 1 | The key is managed by the HUKS service.| +**Parameters** -## HuksSendType +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | --------------------------------------------- | +| keyAlias | string | Yes | Key alias passed in when the key was generated. | +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| -Enumerates the tag transfer modes. +**Example** -**System capability**: SystemCapability.Security.Huks +```js +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +try { + huks.deleteKeyItem(keyAlias, emptyOptions, function (error, data) { + if (error) { + console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: deleteKeyItem key success`); + } + }); +} catch (error) { + console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} +``` -| Name | Value | Description | -| -------------------- | ---- | ----------------- | -| HUKS_SEND_TYPE_ASYNC | 0 | The tag is sent asynchronously.| -| HUKS_SEND_TYPE_SYNC | 1 | The tag is sent synchronously.| +## huks.deleteKeyItem9+ -## HuksUnwrapSuite9+ +deleteKeyItem(keyAlias: string, options: HuksOptions) : Promise\ -Enumerates the algorithm suites used when a wrapped key is imported. +Deletes a key. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ---------------------------------------------- | ---- | ----------------------------------------------------- | -| HUKS_UNWRAP_SUITE_X25519_AES_256_GCM_NOPADDING | 1 | Use X25519 for key agreement and then use AES-256 GCM to encrypt the key.| -| HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING | 2 | Use ECDH for key agreement and then use AES-256 GCM to encrypt the key. | - -## HuksImportKeyType9+ +**Parameters** -Enumerates the types of keys to import. By default, a public key is imported. This field is not required when a symmetric key is imported. +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ----------------------------------- | +| keyAlias | string | Yes | Key alias passed in when the key was generated.| +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | -**System capability**: SystemCapability.Security.Huks +**Example** -| Name | Value | Description | -| ------------------------- | ---- | ------------------------------ | -| HUKS_KEY_TYPE_PUBLIC_KEY | 0 | Public key | -| HUKS_KEY_TYPE_PRIVATE_KEY | 1 | Private key | -| HUKS_KEY_TYPE_KEY_PAIR | 2 | Public and private key pair| - -## HuksUserAuthType9+ - -Enumerates the user authentication types. - -**System capability**: SystemCapability.Security.Huks - -| Name | Value | Description | -| ------------------------------- | ---- | ------------------------- | -| HUKS_USER_AUTH_TYPE_FINGERPRINT | 1 | Fingerprint authentication. | -| HUKS_USER_AUTH_TYPE_FACE | 2 | Facial authentication.| -| HUKS_USER_AUTH_TYPE_PIN | 4 | PIN authentication.| - -## HuksAuthAccessType9+ - -Enumerates the access control types. - -**System capability**: SystemCapability.Security.Huks - -| Name | Value | Description | -| --------------------------------------- | ---- | ------------------------------------------------ | -| HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | 1 | The key is invalid after the password is cleared. | -| HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | 2 | The key is invalid after a new biometric feature is added.| - -## HuksChallengeType9+ - -Enumerates the types of the challenges generated when a key is used. - -**System capability**: SystemCapability.Security.Huks - -| Name | Value | Description | -| ------------------------------- | ---- | ------------------------------ | -| HUKS_CHALLENGE_TYPE_NORMAL | 0 | Normal challenge, which is of 32 bytes by default.| -| HUKS_CHALLENGE_TYPE_CUSTOM | 1 | Custom challenge, which supports only one authentication for multiple keys.| -| HUKS_CHALLENGE_TYPE_NONE | 2 | Challenge is not required.| - -## HuksChallengePosition9+ - -Enumerates the positions of the 8-byte valid value in a custom challenge generated. - -**System capability**: SystemCapability.Security.Huks - -| Name | Value | Description | -| ------------------------------- | ---- | ------------------------------ | -| HUKS_CHALLENGE_POS_0 | 0 | Bytes 0 to 7 indicate the valid challenge of the key.| -| HUKS_CHALLENGE_POS_1 | 1 | Bytes 8 to 15 indicate the valid challenge of the key.| -| HUKS_CHALLENGE_POS_2 | 2 | Bytes 16 to 23 indicate the valid challenge of the key.| -| HUKS_CHALLENGE_POS_3 | 3 | Bytes 24 to 31 indicate the valid challenge of the key.| - -## HuksSecureSignType9+ - -Defines the signature type of the key generated or imported. - -**System capability**: SystemCapability.Security.Huks +```js +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +try { + huks.deleteKeyItem(keyAlias, emptyOptions) + .then ((data) => { + console.info(`promise: deleteKeyItem key success`); + }) + .catch(error => { + console.error(`promise: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); +} catch (error) { + console.error(`promise: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} +``` -| Name | Value | Description | -| ------------------------------ | ---- | ------------------------------------------------------------ | -| HUKS_SECURE_SIGN_WITH_AUTHINFO | 1 | The signature carries authentication information. This field is specified when a key is generated or imported. When the key is used to sign data, the data will be added with the authentication information and then be signed.| +## huks.getSdkVersion -## HuksTagType +getSdkVersion(options: HuksOptions) : string -Enumerates the tag data types. +Obtains the SDK version of the current system. **System capability**: SystemCapability.Security.Huks +**Parameters** -| Name | Value | Description | -| --------------------- | ------- | --------------------------------------- | -| HUKS_TAG_TYPE_INVALID | 0 << 28 | Invalid tag type. | -| HUKS_TAG_TYPE_INT | 1 << 28 | Number of the int type. | -| HUKS_TAG_TYPE_UINT | 2 << 28 | Number of the uint type.| -| HUKS_TAG_TYPE_ULONG | 3 << 28 | BigInt. | -| HUKS_TAG_TYPE_BOOL | 4 << 28 | Boolean. | -| HUKS_TAG_TYPE_BYTES | 5 << 28 | Uint8Array. | +| Name | Type | Mandatory| Description | +| ------- | ---------- | ---- | ------------------------- | +| options | [HuksOptions](#huksoptions) | Yes | Empty object, which is used to hold the SDK version.| -## HuksTag +**Return value** -Enumerates the tags used to invoke parameters. +| Type | Description | +| ------ | ------------- | +| string | SDK version obtained.| -**System capability**: SystemCapability.Security.Huks +**Example** -| Name | Value | Description | -| -------------------------------------------- | ---------------------------------------- | -------------------------------------- | -| HUKS_TAG_INVALID | HuksTagType.HUKS_TAG_TYPE_INVALID \| 0 | Invalid tag. | -| HUKS_TAG_ALGORITHM | HUKS_TAG_TYPE_UINT \| 1 | Algorithm. | -| HUKS_TAG_PURPOSE | HuksTagType.HUKS_TAG_TYPE_UINT \| 2 | Purpose of a key. | -| HUKS_TAG_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 3 | Key size. | -| HUKS_TAG_DIGEST | HuksTagType.HUKS_TAG_TYPE_UINT \| 4 | Digest algorithm. | -| HUKS_TAG_PADDING | HuksTagType.HUKS_TAG_TYPE_UINT \| 5 | Padding algorithm. | -| HUKS_TAG_BLOCK_MODE | HuksTagType.HUKS_TAG_TYPE_UINT \| 6 | Cipher mode. | -| HUKS_TAG_KEY_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 7 | Key type. | -| HUKS_TAG_ASSOCIATED_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 8 | Associated authentication data. | -| HUKS_TAG_NONCE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 9 | Field for key encryption and decryption. | -| HUKS_TAG_IV | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10 | IV. | -| HUKS_TAG_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 11 | Information generated during key derivation. | -| HUKS_TAG_SALT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 12 | Salt value used for key derivation. | -| HUKS_TAG_PWD | HuksTagType.HUKS_TAG_TYPE_BYTES \| 13 | Password used for key derivation. | -| HUKS_TAG_ITERATION | HuksTagType.HUKS_TAG_TYPE_UINT \| 14 | Number of iterations for key derivation. | -| HUKS_TAG_KEY_GENERATE_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 15 | Key generation type. | -| HUKS_TAG_DERIVE_MAIN_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 16 | Main key for key derivation. | -| HUKS_TAG_DERIVE_FACTOR | HuksTagType.HUKS_TAG_TYPE_BYTES \| 17 | Factor for key derivation. | -| HUKS_TAG_DERIVE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 18 | Type of the algorithm used for key derivation. | -| HUKS_TAG_AGREE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 19 | Type of the algorithm used for key agreement. | -| HUKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 20 | Public key alias used in key agreement. | -| HUKS_TAG_AGREE_PRIVATE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 21 | Private key alias used in key agreement. | -| HUKS_TAG_AGREE_PUBLIC_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 22 | Public key used in key agreement. | -| HUKS_TAG_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 23 | Key alias. | -| HUKS_TAG_DERIVE_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 24 | Size of the derived key. | -| HUKS_TAG_IMPORT_KEY_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 25 | Type of the imported key. | -| HUKS_TAG_UNWRAP_ALGORITHM_SUITE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 26 | Algorithm suite used when a wrapped key is imported. | -| HUKS_TAG_ACTIVE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 201 | Reserved. | -| HUKS_TAG_ORIGINATION_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 202 | Reserved. | -| HUKS_TAG_USAGE_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 203 | Reserved. | -| HUKS_TAG_CREATION_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 204 | Reserved. | -| HUKS_TAG_ALL_USERS | ksTagType.HUKS_TAG_TYPE_BOOL \| 301 | Reserved. | -| HUKS_TAG_USER_ID | HuksTagType.HUKS_TAG_TYPE_UINT \| 302 | Reserved. | -| HUKS_TAG_NO_AUTH_REQUIRED | HuksTagType.HUKS_TAG_TYPE_BOOL \| 303 | Reserved. | -| HUKS_TAG_USER_AUTH_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 304 | User authentication type. For details, see [HuksUserAuthType](#huksuserauthtype9). This parameter must be set together with [HuksAuthAccessType](#huksauthaccesstype9). You can set a maximum of two user authentication types at a time. For example, if **HuksAuthAccessType** is **HKS_SECURE_ACCESS_INVALID_NEW_BIO_ENROLL**, you can set the authentication type to **HKS_USER_AUTH_TYPE_FACE**, **HKS_USER_AUTH_TYPE_FINGERPRINT**, or their combination.| -| HUKS_TAG_AUTH_TIMEOUT | HuksTagType.HUKS_TAG_TYPE_UINT \| 305 | Reserved. | -| HUKS_TAG_AUTH_TOKEN | HuksTagType.HUKS_TAG_TYPE_BYTES \| 306 | Reserved. | -| HUKS_TAG_KEY_AUTH_ACCESS_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 307 | Access control type. For details, see [HuksAuthAccessType](#huksauthaccesstype9). This parameter must be set together with [HuksUserAuthType](#huksuserauthtype9).| -| HUKS_TAG_KEY_SECURE_SIGN_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 308 | Signature type of the key generated or imported.| -| HUKS_TAG_CHALLENGE_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 309 | Type of the challenge generated for a key. For details, see [HuksChallengeType](#hukschallengetype9).| -| HUKS_TAG_CHALLENGE_POS9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 310 | Position of the 8-byte valid value in a custom challenge. For details, see [HuksChallengePosition](#hukschallengeposition9).| -| HUKS_TAG_ATTESTATION_CHALLENGE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 501 | Challenge value used in the attestation. | -| HUKS_TAG_ATTESTATION_APPLICATION_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 502 | Application ID used in the attestation. | -| HUKS_TAG_ATTESTATION_ID_BRAND | HuksTagType.HUKS_TAG_TYPE_BYTES \| 503 | Brand of the device. | -| HUKS_TAG_ATTESTATION_ID_DEVICE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 504 | Device ID. | -| HUKS_TAG_ATTESTATION_ID_PRODUCT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 505 | Product name of the device. | -| HUKS_TAG_ATTESTATION_ID_SERIAL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 506 | Device SN. | -| HUKS_TAG_ATTESTATION_ID_IMEI | HuksTagType.HUKS_TAG_TYPE_BYTES \| 507 | Device IMEI. | -| HUKS_TAG_ATTESTATION_ID_MEID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 508 | Device MEID. | -| HUKS_TAG_ATTESTATION_ID_MANUFACTURER | HuksTagType.HUKS_TAG_TYPE_BYTES \| 509 | Device manufacturer. | -| HUKS_TAG_ATTESTATION_ID_MODEL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 510 | Device model. | -| HUKS_TAG_ATTESTATION_ID_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 511 | Key alias used in the attestation. | -| HUKS_TAG_ATTESTATION_ID_SOCID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 512 | Device SOCID. | -| HUKS_TAG_ATTESTATION_ID_UDID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 513 | Device UDID. | -| HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 514 | Security credential used in the attestation. | -| HUKS_TAG_ATTESTATION_ID_VERSION_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 515 | Version information used in the attestation. | -| HUKS_TAG_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1001 | Whether to use the alias passed in during key generation.| -| HUKS_TAG_KEY_STORAGE_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1002 | Key storage mode. | -| HUKS_TAG_IS_ALLOWED_WRAP | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1003 | Reserved. | -| HUKS_TAG_KEY_WRAP_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1004 | Reserved. | -| HUKS_TAG_KEY_AUTH_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1005 | Reserved. | -| HUKS_TAG_KEY_ROLE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1006 | Reserved. | -| HUKS_TAG_KEY_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1007 | Flag of the key. | -| HUKS_TAG_IS_ASYNCHRONIZED | HuksTagType.HUKS_TAG_TYPE_UINT \| 1008 | Reserved. | -| HUKS_TAG_SECURE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1009 | Reserved. | -| HUKS_TAG_SECURE_KEY_UUID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1010 | Reserved. | -| HUKS_TAG_KEY_DOMAIN | HuksTagType.HUKS_TAG_TYPE_UINT \| 1011 | Reserved. | -| HUKS_TAG_PROCESS_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10001 | Process name. | -| HUKS_TAG_PACKAGE_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10002 | Reserved. | -| HUKS_TAG_ACCESS_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10003 | Reserved. | -| HUKS_TAG_USES_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10004 | Reserved. | -| HUKS_TAG_CRYPTO_CTX | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10005 | Reserved. | -| HUKS_TAG_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10006 | Reserved. | -| HUKS_TAG_KEY_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10007 | Key version. | -| HUKS_TAG_PAYLOAD_LEN | HuksTagType.HUKS_TAG_TYPE_UINT \| 10008 | Reserved. | -| HUKS_TAG_AE_TAG | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10009 | Reserved. | -| HUKS_TAG_IS_KEY_HANDLE | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10010 | Reserved. | -| HUKS_TAG_OS_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10101 | OS version. | -| HUKS_TAG_OS_PATCHLEVEL | HuksTagType.HUKS_TAG_TYPE_UINT \| 10102 | OS patch level. | -| HUKS_TAG_SYMMETRIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20001 | Reserved. | -| HUKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20002 | Reserved. | -| HUKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20003 | Reserved. | +```js +/* Set options to emptyOptions. */ +let emptyOptions = { + properties: [] +}; +let result = huks.getSdkVersion(emptyOptions); +``` -## huks.generateKey +## huks.importKeyItem9+ -generateKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void +importKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void -Generates a key. This API uses an asynchronous callback to return the result. +Imports a key in plaintext. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | -| keyAlias | string | Yes | Alias of the key. | -| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code defined in **HuksResult** will be returned.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | --------------------------------------------- | +| keyAlias | string | Yes | Alias of the key. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| **Example** ```js -/* Generate an RSA key of 512 bits. */ -var keyAlias = 'keyAlias'; -var properties = new Array(); +/* Import an AES key of 256 bits. */ +let plainTextSize32 = makeRandomArr(32); +function makeRandomArr(size) { + let arr = new Uint8Array(size); + for (let i = 0; i < size; i++) { + arr[i] = Math.floor(Math.random() * 10); + } + return arr; +}; +let keyAlias = 'keyAlias'; +let properties = new Array(); properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_RSA + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES }; properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512 + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 }; properties[2] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: -huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | -huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT }; properties[3] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_OAEP + tag: huks.HuksTag.HUKS_TAG_PADDING, + value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7 }; properties[4] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB }; -var options = { - properties: properties +let options = { + properties: properties, + inData: plainTextSize32 }; -huks.generateKey(keyAlias, options, function (err, data){}); +try { + huks.importKeyItem(keyAlias, options, function (error, data) { + if (error) { + console.error(`callback: importKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: importKeyItem success`); + } + }); +} catch (error) { + console.error(`callback: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} ``` -## huks.generateKey +## huks.importKeyItem9+ -generateKey(keyAlias: string, options: HuksOptions) : Promise\ +importKeyItem(keyAlias: string, options: HuksOptions) : Promise\ -Generates a key. This API uses a promise to return the result. +Imports a key in plaintext. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | ------------------------ | -| keyAlias | string | Yes | Alias of the key. | -| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key.| - -**Return value** - -| Type | Description | -| ----------------------------------- | -------------------------------------------------- | -| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ----------------------------------- | +| keyAlias | string | Yes | Alias of the key. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.| **Example** ```js -/* Generate an ECC key of 256 bits. */ -var keyAlias = 'keyAlias'; -var properties = new Array(); +/* Import an AES key of 128 bits. */ +let plainTextSize32 = makeRandomArr(32); + +function makeRandomArr(size) { + let arr = new Uint8Array(size); + for (let i = 0; i < size; i++) { + arr[i] = Math.floor(Math.random() * 10); + } + return arr; +}; + +/* Step 1 Generate a key. */ +let keyAlias = 'keyAlias'; +let properties = new Array(); properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_ECC + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES }; properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128 }; properties[2] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: -huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | -huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT }; properties[3] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + tag: huks.HuksTag.HUKS_TAG_PADDING, + value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7 }; -var options = { - properties: properties +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB }; -var result = huks.generateKey(keyAlias, options); +let huksoptions = { + properties: properties, + inData: plainTextSize32 +}; +try { + huks.importKeyItem(keyAlias, huksoptions) + .then ((data) => { + console.info(`promise: importKeyItem success`); + }) + .catch(error => { + console.error(`promise: importKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); +} catch (error) { + console.error(`promise: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} ``` -## huks.deleteKey +## huks.attestKeyItem9+ -deleteKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void +attestKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void -Deletes a key. This API uses an asynchronous callback to return the result. +Obtains the certificate used to verify a key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------- | ---- | -------------------------------------------------- | -| keyAlias | string | Yes | Key alias passed in when the key was generated. | -| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | --------------------------------------------- | +| keyAlias | string | Yes | Alias of the key. The certificate to be obtained stores the key. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters and data required for obtaining the certificate. | +| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| **Example** ```js -/* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { - properties: [] -}; -huks.deleteKey(keyAlias, emptyOptions, function (err, data) {}); +let securityLevel = stringToUint8Array('sec_level'); +let challenge = stringToUint8Array('challenge_data'); +let versionInfo = stringToUint8Array('version_info'); +let keyAliasString = "key attest"; + +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + let tmpUint8Array = new Uint8Array(arr); + return tmpUint8Array; +} + +async function generateKey(alias) { + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_RSA + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, + value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048 + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY + }; + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + }; + properties[5] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_PSS + }; + properties[6] = { + tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE, + value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT + }; + properties[7] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB + }; + let options = { + properties: properties + }; + + try { + huks.generateKeyItem(alias, options, function (error, data) { + if (error) { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: generateKeyItem success`); + } + }); + } catch (error) { + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +async function attestKey() { + let aliasString = keyAliasString; + let aliasUint8 = stringToUint8Array(aliasString); + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, + value: securityLevel + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE, + value: challenge + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, + value: versionInfo + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS, + value: aliasUint8 + }; + let options = { + properties: properties + }; + await generateKey(aliasString); + try { + huks.attestKeyItem(aliasString, options, function (error, data) { + if (error) { + console.error(`callback: attestKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: attestKeyItem success`); + } + }); + } catch (error) { + console.error(`callback: attestKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} ``` -## huks.deleteKey +## huks.attestKeyItem9+ -deleteKey(keyAlias: string, options: HuksOptions) : Promise\ +attestKeyItem(keyAlias: string, options: HuksOptions) : Promise\ -Deletes a key. This API uses a promise to return the result. +Obtains the certificate used to verify a key. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------- | ---- | ----------------------------------------------------- | -| keyAlias | string | Yes | Key alias passed in when the key was generated.| -| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------ | +| keyAlias | string | Yes | Alias of the key. The certificate to be obtained stores the key.| +| options | [HuksOptions](#huksoptions) | Yes | Parameters and data required for obtaining the certificate. | **Return value** -| Type | Description | -| ----------------------------------- | -------------------------------------------------- | -| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Type | Description | +| ---------------------------------------------- | --------------------------------------------- | +| Promise<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result. If **err** is not returned, the operation is successful. Otherwise, an error occurs.| **Example** ```js -/* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { - properties: [] -}; -var result = huks.deleteKey(keyAlias, emptyOptions); +let securityLevel = stringToUint8Array('sec_level'); +let challenge = stringToUint8Array('challenge_data'); +let versionInfo = stringToUint8Array('version_info'); +let keyAliasString = "key attest"; + +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + let tmpUint8Array = new Uint8Array(arr); + return tmpUint8Array; +} + +async function generateKey(alias) { + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_RSA + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, + value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048 + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY + }; + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + }; + properties[5] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_PSS + }; + properties[6] = { + tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE, + value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT + }; + properties[7] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB + }; + let options = { + properties: properties + }; + + try { + await huks.generateKeyItem(alias, options) + .then((data) => { + console.info(`promise: generateKeyItem success`); + }) + .catch(error => { + console.error(`promise: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +async function attestKey() { + let aliasString = keyAliasString; + let aliasUint8 = stringToUint8Array(aliasString); + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, + value: securityLevel + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE, + value: challenge + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, + value: versionInfo + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS, + value: aliasUint8 + }; + let options = { + properties: properties + }; + await generateKey(aliasString); + try { + await huks.attestKeyItem(aliasString, options) + .then ((data) => { + console.info(`promise: attestKeyItem success`); + }) + .catch(error => { + console.error(`promise: attestKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: attestKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} ``` -## huks.getSdkVersion +## huks.importWrappedKeyItem9+ -getSdkVersion(options: HuksOptions) : string +importWrappedKeyItem(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void -Obtains the SDK version of the current system. +Imports a wrapped key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ---------- | ---- | ------------------------- | -| options | [HuksOptions](#huksoptions) | Yes | Empty object, which is used to hold the SDK version.| - -**Return value** - -| Type | Description | -| ------ | ------------- | -| string | SDK version obtained.| +| Name | Type | Mandatory| Description | +| ---------------- | --------------------------- | ---- | --------------------------------------------- | +| keyAlias | string | Yes | Alias of the wrapped key to import. | +| wrappingKeyAlias | string | Yes | Alias of the data used to unwrap the key imported. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| **Example** ```js -/* Set options to emptyOptions. */ -var emptyOptions = { - properties: [] +import huks from '@ohos.security.huks'; + +let exportWrappingKey; +let alias1 = "importAlias"; +let alias2 = "wrappingKeyAlias"; + +async function TestGenFunc(alias, options) { + try { + await genKey(alias, options) + .then((data) => { + console.info(`callback: generateKeyItem success`); + }) + .catch(error => { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +function genKey(alias, options) { + return new Promise((resolve, reject) => { + try { + huks.generateKeyItem(alias, options, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throw(error); + } + }); +} + +async function TestExportFunc(alias, options) { + try { + await exportKey(alias, options) + .then ((data) => { + console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`); + exportWrappingKey = data.outData; + }) + .catch(error => { + console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +function exportKey(alias, options) : Promise { + return new Promise((resolve, reject) => { + try { + huks.exportKeyItem(alias, options, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throw(error); + } + }); +} + +async function TestImportWrappedFunc(alias, wrappingAlias, options) { + try { + await importWrappedKey(alias, wrappingAlias, options) + .then ((data) => { + console.info(`callback: importWrappedKeyItem success`); + }) + .catch(error => { + console.error(`callback: importWrappedKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`callback: importWrappedKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +function importWrappedKey(alias, wrappingAlias, options) { + return new Promise((resolve, reject) => { + try { + huks.importWrappedKeyItem(alias, wrappingAlias, options, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throw(error); + } + }); +} + +async function TestImportWrappedKeyFunc( + alias, + wrappingAlias, + genOptions, + importOptions +) { + await TestGenFunc(wrappingAlias, genOptions); + await TestExportFunc(wrappingAlias, genOptions); + + /*The following operations do not invoke the HUKS APIs, and the specific implementation is not provided here. + * For example, import **keyA**. + * 1. Use ECC to generate a public and private key pair **keyB**. The public key is **keyB_pub**, and the private key is **keyB_pri**. + * 2. Use **keyB_pri** and the public key obtained from **wrappingAlias** to negotiate the shared key **share_key**. + * 3. Randomly generate a key **kek** and use it to encrypt **keyA** with AES-GCM. During the encryption, record **nonce1**, **aad1**, ciphertext **keyA_enc**, and encrypted **tag1**. + * 4. Use **share_key** to encrypt **kek** with AES-GCM. During the encryption, record **nonce2**, **aad2**, ciphertext **kek_enc**, and encrypted **tag2**. + * 5. Generate the **importOptions.inData** field in the following format: + * keyB_pub length (4 bytes) + keyB_pub + aad2 length (4 bytes) + aad2 + + * nonce2 length (4 bytes) + nonce2 + tag2 length (4 bytes) + tag2 + + * kek_enc length (4 bytes) + kek_enc + aad1 length (4 bytes) + aad1 + + * nonce1 length (4 bytes) + nonce1 + tag1 length (4 bytes) + tag1 + + * Memory occupied by the keyA length (4 bytes) + keyA length + keyA_enc length (4 bytes) + keyA_enc + */ + let inputKey = new Uint8Array([0x02, 0x00, 0x00, 0x00]); + importOptions.inData = inputKey; + await TestImportWrappedFunc(alias, wrappingAlias, importOptions); +} + +function makeGenerateOptions() { + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_ECC + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + }; + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE, + value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR, + }; + let options = { + properties: properties + }; + return options; }; -var result = huks.getSdkVersion(emptyOptions); + +function makeImportOptions() { + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC + }; + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE + }; + properties[5] = { + tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE, + value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING + }; + let options = { + properties: properties + }; + return options; +}; + +function huksImportWrappedKey() { + let genOptions = makeGenerateOptions(); + let importOptions = makeImportOptions(); + TestImportWrappedKeyFunc( + alias1, + alias2, + genOptions, + importOptions + ); +} ``` -## huks.importKey +## huks.importWrappedKeyItem9+ -importKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void +importWrappedKeyItem(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions) : Promise\ -Imports a key in plaintext. This API uses an asynchronous callback to return the result. +Imports a wrapped key. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------ | ---- | ------------------------------------------------- | -| keyAlias | string | Yes | Alias of the key to import.| -| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.| -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Name | Type | Mandatory| Description | +| ---------------- | --------------------------- | ---- | --------------------------------------------- | +| keyAlias | string | Yes | Alias of the wrapped key to import. | +| wrappingKeyAlias | string | Yes | Alias of the data used to unwrap the key imported. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import.| **Example** ```js -/* Import an AES key of 256 bits. */ -var plainTextSize32 = makeRandomArr(32); -function makeRandomArr(size) { - var arr = new Uint8Array(size); - for (var i = 0; i < size; i++) { - arr[i] = Math.floor(Math.random() * 10); +/* The process is similar as if a callback is used, except the following:*/ +async function TestImportWrappedFunc(alias, wrappingAlias, options) { + try { + await huks.importWrappedKeyItem(alias, wrappingAlias, options) + .then ((data) => { + console.info(`promise: importWrappedKeyItem success`); + }) + .catch(error => { + console.error(`promise: importWrappedKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: importWrappedKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } - return arr; -}; -var keyAlias = 'keyAlias'; -var properties = new Array(); -properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_AES -}; -properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 -}; -properties[2] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: -huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT -}; -properties[3] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7 -}; -properties[4] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_ECB -}; -var options = { - properties: properties, - inData: plainTextSize32 +} +``` + +## huks.exportKeyItem9+ + +exportKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Exports a key. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | +| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | +| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs. **outData** contains the public key exported.| + +**Example** + +```js +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] }; -huks.importKey(keyAlias, options, function (err, data){}); +try { + huks.exportKeyItem(keyAlias, emptyOptions, function (error, data) { + if (error) { + console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`); + } + }); +} catch (error) { + console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} ``` -## huks.importKey +## huks.exportKeyItem9+ -importKey(keyAlias: string, options: HuksOptions) : Promise\ +exportKeyItem(keyAlias: string, options: HuksOptions) : Promise\ -Imports a key in plaintext. This API uses a promise to return the result. +Exports a key. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------- | ---- | ------------------------------------ | -| keyAlias | string | Yes | Alias of the key to import.| -| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | -------------------------------------------- | +| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated.| +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | **Return value** -| Type | Description | -| ----------------------------------- | -------------------------------------------------- | -| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Type | Description | +| ---------------------------------------------- | ------------------------------------------------------------ | +| Promise<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result. If **err** is not returned, the operation is successful. Otherwise, an error occurs. **outData** contains the public key exported.| **Example** ```js -/* Import an AES key of 128 bits. */ -var plainTextSize32 = makeRandomArr(32); - -function makeRandomArr(size) { - var arr = new Uint8Array(size); - for (var i = 0; i < size; i++) { - arr[i] = Math.floor(Math.random() * 10); - } - return arr; -}; - -/* Step 1 Generate a key. */ -var keyAlias = 'keyAlias'; -var properties = new Array(); -properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_AES -}; -properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128 -}; -properties[2] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT -}; -properties[3] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7 -}; -properties[4] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_ECB -}; -var huksoptions = { - properties: properties, - inData: plainTextSize32 +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] }; -var result = huks.importKey(keyAlias, huksoptions); +try { + huks.exportKeyItem(keyAlias, emptyOptions) + .then ((data) => { + console.info(`promise: exportKeyItem success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + console.error(`promise: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); +} catch (error) { + console.error(`promise: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} ``` -## huks.attestkey9+ +## huks.getKeyItemProperties9+ -attestKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void +getKeyItemProperties(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void -Obtains the certificate used to verify a key. This API uses an asynchronous callback to return the result. +Obtains key properties. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| ---------------- | ----------------------------------------- | ---- | -------------------------------------------------- | -| keyAlias | string | Yes | Alias of the key. The certificate to be obtained stores the key. | -| options | [HuksOptions](#huksoptions) | Yes | Parameters and data required for obtaining the certificate. | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | +| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | +| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result. If **errorCode** is **HUKS_SUCCESS**, the operation is successful. Otherwise, an error occurs.| **Example** ```js -let securityLevel = stringToUint8Array('sec_level'); -let challenge = stringToUint8Array('challenge_data'); -let versionInfo = stringToUint8Array('version_info'); -let keyAliasString = "key attest"; - -function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - var tmpUint8Array = new Uint8Array(arr); - return tmpUint8Array; +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +try { + huks.getKeyItemProperties(keyAlias, emptyOptions, function (error, data) { + if (error) { + console.error(`callback: getKeyItemProperties failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: getKeyItemProperties success, data = ${JSON.stringify(data)}`); + } + }); +} catch (error) { + console.error(`callback: getKeyItemProperties input arg invalid, code: ${error.code}, msg: ${error.message}`); } +``` -function printLog(...data) { - console.error(data.toString()); -} +## huks.getKeyItemProperties9+ -async function generateKey(alias) { - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_RSA - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, - value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048 - }; - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY - }; - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 - }; - properties[5] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_PSS - }; - properties[6] = { - tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE, - value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT - }; - properties[7] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_ECB - }; - let options = { - properties: properties - }; +getKeyItemProperties(keyAlias: string, options: HuksOptions) : Promise\ - await huks.generateKey(alias, options).then(async (data) => { - console.error(`generateKey data ${JSON.stringify(data)}`); - }).catch((err) => { - console.error(`generateKey err: " + ${JSON.stringify(err)}`); - });; +Obtains key properties. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | -------------------------------------------- | +| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated.| +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | + +**Return value** + +| Type | Description | +| ----------------------------------------------- | ------------------------------------------------------------ | +| Promise\<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result. If **err** is not returned, the operation is successful. Otherwise, an error occurs. **properties** returns the parameters required for generating the key.| + +**Example** + +```js +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +try { + huks.getKeyItemProperties(keyAlias, emptyOptions) + .then ((data) => { + console.info(`promise: getKeyItemProperties success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + console.error(`promise: getKeyItemProperties failed, code: ${error.code}, msg: ${error.message}`); + }); +} catch (error) { + console.error(`promise: getKeyItemProperties input arg invalid, code: ${error.code}, msg: ${error.message}`); } +``` -async function attestKey() { - let aliasString = keyAliasString; - let aliasUint8 = stringToUint8Array(aliasString); - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, - value: securityLevel - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE, - value: challenge - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, - value: versionInfo - }; - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS, - value: aliasUint8 - }; - let options = { - properties: properties - }; - await generateKey(aliasString); - huks.attestKey(aliasString, options, function (err, data) { - printLog(`key attest result : ${JSON.stringify(data)}`); - }); +## huks.isKeyItemExist9+ + +isKeyItemExist(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Checks whether a key exists. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | --------------------------------------- | +| keyAlias | string | Yes | Alias of the key to check. | +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. The value **TRUE** means that the key exists, and **FALSE** means the opposite.| + +**Example** + +```js +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +try { + huks.isKeyItemExist(keyAlias, emptyOptions, function (error, data) { + if (error) { + console.info(`callback: isKeyItemExist success, data = ${JSON.stringify(data)}`); + } else { + console.error(`callback: isKeyItemExist failed, code: ${error.code}, msg: ${error.message}`); + } + }); +} catch (error) { + console.error(`promise: isKeyItemExist input arg invalid, code: ${error.code}, msg: ${error.message}`); } ``` -## huks.attestkey9+ +## huks.isKeyItemExist9+ -attestKey(keyAlias: string, options: HuksOptions) : Promise\ +isKeyItemExist(keyAlias: string, options: HuksOptions) : Promise\ -Obtains the certificate used to verify a key. This API uses a promise to return the result. +Checks whether a key exists. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| ---------------- | ----------------------------------------- | ---- | -------------------------------------------------- | -| keyAlias | string | Yes | Alias of the key. The certificate to be obtained stores the key. | -| options | [HuksOptions](#huksoptions) | Yes | Parameters and data required for obtaining the certificate. | +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------ | +| keyAlias | string | Yes | Alias of the key to check. | +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).| **Return value** -| Type | Description | -| ----------------------------------- | -------------------------------------------------- | -| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Type | Description | +| ----------------- | --------------------------------------- | +| Promise\ | Promise used to return the result. The value **TRUE** means that the key exists, and **FALSE** means the opposite.| **Example** ```js -let securityLevel = stringToUint8Array('sec_level'); -let challenge = stringToUint8Array('challenge_data'); -let versionInfo = stringToUint8Array('version_info'); -let keyAliasString = "key attest"; - -function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - var tmpUint8Array = new Uint8Array(arr); - return tmpUint8Array; +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +try { + huks.isKeyItemExist(keyAlias, emptyOptions) + .then ((data) => { + console.info(`promise: isKeyItemExist success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + console.error(`promise: isKeyItemExist failed, code: ${error.code}, msg: ${error.message}`); + }); +} catch (error) { + console.error(`promise: isKeyItemExist input arg invalid, code: ${error.code}, msg: ${error.message}`); } +``` -function printLog(...data) { - console.error(data.toString()); -} +## huks.initSession9+ -async function generateKey(alias) { - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_RSA - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, - value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048 - }; - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY - }; - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 - }; - properties[5] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_PSS - }; - properties[6] = { - tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE, - value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT - }; - properties[7] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_ECB - }; - let options = { - properties: properties - }; +initSession(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void - await huks.generateKey(alias, options).then(async (data) => { - console.error(`generateKey data ${JSON.stringify(data)}`); - }).catch((err) => { - console.error(`generateKey err: " + ${JSON.stringify(err)}`); - });; -} +Initializes the data for a key operation. This API uses an asynchronous callback to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. -async function attestKey() { - let aliasString = keyAliasString; - let aliasUint8 = stringToUint8Array(aliasString); - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, - value: securityLevel - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE, - value: challenge - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, - value: versionInfo - }; - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS, - value: aliasUint8 - }; - let options = { - properties: properties - }; - await generateKey(aliasString); - huks.attestKey(aliasString, options) - .then((data) => { - console.log(`test attestKey data: ${JSON.stringify(data)}`); - }) - .catch((err) => { - console.log('test attestKey information: ' + JSON.stringify(err)); - }); -} -``` +**System capability**: SystemCapability.Security.Huks -## huks.importWrappedKey9+ +**Parameters** -importWrappedKey(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ---------------------------------------------------- | +| keyAlias | string | Yes | Alias of the target key. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters used for initialization. | +| callback | AsyncCallback\<[HuksSessionHandle](#hukssessionhandle)> | Yes | Callback invoked to return the key operation handle.| -Imports a wrapped key. This API uses an asynchronous callback to return the result. + +## huks.initSession9+ + +initSession(keyAlias: string, options: HuksOptions) : Promise\ + +Initializes the data for a key operation. This API uses a promise to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------- | ---- | ------------------------------------------------ | +| keyAlias | string | Yes | Alias of the target key. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters used for initialization. | + +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksSessionHandle](#hukssessionhandle)> | Promise used to return the key operation handle.| + +## huks.updateSession9+ + +updateSession(handle: number, options: HuksOptions, callback: AsyncCallback\) : void + +Updates the key operation by segment. This API uses an asynchronous callback to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | -------------------------------------------- | +| handle | number | Yes | Handle of the **Update** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | +| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result.| + + +## huks.updateSession9+ + +updateSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void + +Updates the key operation by segment. This API uses an asynchronous callback to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | -------------------------------------------- | +| handle | number | Yes | Handle of the **Update** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | +| token | Uint8Array | Yes | Token of the **Update** operation. | +| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result.| + +## huks.updateSession9+ + +updateSession(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\ + +Updates the key operation data by segment. This API uses a promise to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------------- | ---- | -------------------------------------------- | +| handle | number | Yes | Handle of the **Update** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | +| token | Uint8Array | No | Token of the **Update** operation. | + +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result.| + +## huks.finishSession9+ + +finishSession(handle: number, options: HuksOptions, callback: AsyncCallback\) : void + +Completes the key operation and releases resources. This API uses an asynchronous callback to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | -------------------------------------------- | +| handle | number | Yes | Handle of the **Finish** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation. | +| token | Uint8Array | Yes | Token for the **Finish** operation. | +| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result.| + +## huks.finishSession9+ + +finishSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void + +Completes the key operation and releases resources. This API uses an asynchronous callback to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------- | ---- | -------------------------------------------- | +| handle | number | Yes | Handle of the **Finish** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation. | +| token | Uint8Array | Yes | Token for the **Finish** operation. | +| callback | AsyncCallback\<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result.| + + +## huks.finishSession9+ + +finishSession(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\ + +Completes the key operation and releases resources. This API uses a promise to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ----------------------------------------------- | ---- | ----------------------------------- | +| handle | number | Yes | Handle of the **Finish** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation. | +| token | Uint8Array | No | Token for the **Finish** operation. | + +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result.| + + +## huks.abortSession9+ + +abortSession(handle: number, options: HuksOptions, callback: AsyncCallback\) : void + +Aborts the use of the key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| ---------------- | ----------------------------------------- | ---- | -------------------------------------------------- | -| keyAlias | string | Yes | Alias of the wrapped key to import. | -| wrappingKeyAlias | string | Yes | Alias of the data used to unwrap the key imported. | -| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import. | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------- | +| handle | number | Yes | Handle of the **Abort** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Abort** operation. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| **Example** ```js -var exportWrappingKey; -var alias1 = "importAlias"; -var alias2 = "wrappingKeyAlias"; - -async function TestGenFunc(alias, options) { - await genKey(alias, options) - .then((data) => { - console.log(`test genKey data: ${JSON.stringify(data)}`); - }) - .catch((err) => { - console.log('test genKey err information: ' + JSON.stringify(err)); - }); +/* huks.initSession, huks.updateSession, and huks.finishSession must be used together. + * If an error occurs in any of huks.initSession, huks.updateSession, + * and huks.finishSession operation, + * huks.abortSession must be called to terminate the use of the key. + * + * The following uses the callback of an RSA1024 key as an example. + */ +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + let tmpUint8Array = new Uint8Array(arr); + return tmpUint8Array; } -function genKey(alias, options) { - return new Promise((resolve, reject) => { - huks.generateKey(alias, options, function (err, data) { - console.log(`test genKey data: ${JSON.stringify(data)}`); - if (err.code !== 0) { - console.log('test genKey err information: ' + JSON.stringify(err)); - reject(err); - } else { - resolve(data); - } - }); - }); +let keyAlias = "HuksDemoRSA"; +let properties = new Array(); +let options = { + properties: properties, + inData: new Uint8Array(0) +}; +let handle; +async function generateKey() { + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_RSA + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_1024 + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5 + }; + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + }; + properties[5] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB, + } + + try { + await huks.generateKeyItem(keyAlias, options, function (error, data) { + if (error) { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: generateKeyItem success`); + } + }); + } catch (error) { + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } } -async function TestExportFunc(alias, options) { - await exportKey(alias, options) - .then((data) => { - console.log(`test exportKey data: ${JSON.stringify(data)}`); - }) - .catch((err) => { - console.log('test exportKey err information: ' + JSON.stringify(err)); - }); +async function huksInit() { + console.log('enter huksInit'); + try { + huks.initSession(keyAlias, options, function (error, data) { + if (error) { + console.error(`callback: initSession failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: initSession success, data = ${JSON.stringify(data)}`); + handle = data.handle; + } + }); + } catch (error) { + console.error(`callback: initSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } } -function exportKey(alias, options) { - return new Promise((resolve, reject) => { - huks.exportKey(alias, options, function (err, data) { - console.log(`test exportKey data: ${JSON.stringify(data)}`); - if (err.code !== 0) { - console.log('test exportKey err information: ' + JSON.stringify(err)); - reject(err); - } else { - exportWrappingKey = data.outData; - resolve(data); - } - }); - }); +async function huksUpdate() { + console.log('enter huksUpdate'); + options.inData = stringToUint8Array("huksHmacTest"); + try { + huks.updateSession(handle, options, function (error, data) { + if (error) { + console.error(`callback: updateSession failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: updateSession success, data = ${JSON.stringify(data)}`); + } + }); + } catch (error) { + console.error(`callback: updateSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } } -async function TestImportWrappedFunc(alias, wrappingAlias, options) { - await importWrappedKey(alias, wrappingAlias, options) - .then((data) => { - console.log(`TestImportWrappedFunc data: ${JSON.stringify(data)}`); - }) - .catch((err) => { - console.log('test importWrappedKey err information: ' + JSON.stringify(err)); - }); +async function huksFinish() { + console.log('enter huksFinish'); + options.inData = new Uint8Array(0); + try { + huks.finishSession(handle, options, function (error, data) { + if (error) { + console.error(`callback: finishSession failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: finishSession success, data = ${JSON.stringify(data)}`); + } + }); + } catch (error) { + console.error(`callback: finishSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } } -function importWrappedKey(alias, wrappingAlias, options) { - return new Promise((resolve, reject) => { - huks.importWrappedKey(alias, wrappingAlias, options, function (err, data) { - console.log(`importWrappedKey data: ${JSON.stringify(data)}`); - if (err.code !== 0) { - console.log('importWrappedKey err information: ' + JSON.stringify(err)); - reject(err); - } else { - resolve(data); - } - }); - }); +async function huksAbort() { + console.log('enter huksAbort'); + try { + huks.abortSession(handle, options, function (error, data) { + if (error) { + console.error(`callback: abortSession failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: abortSession success`); + } + }); + } catch (error) { + console.error(`callback: abortSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } } +``` -async function TestImportWrappedKeyFunc( - alias, - wrappingAlias, - genOptions, - importOptions -) { - await TestGenFunc(wrappingAlias, genOptions); - await TestExportFunc(wrappingAlias, genOptions); +## huks.abortSession9+ - /*The following operations do not invoke the HUKS APIs, and the specific implementation is not provided here. - * For example, import **keyA**. - * 1. Use ECC to generate a public and private key pair **keyB**. The public key is **keyB_pub**, and the private key is **keyB_pri**. - * 2. Use **keyB_pri** and the public key obtained from **wrappingAlias** to negotiate the shared key **share_key**. - * 3. Randomly generate a key **kek** and use it to encrypt **keyA** with AES-GCM. During the encryption, record **nonce1**, **aad1**, ciphertext **keyA_enc**, and encrypted **tag1**. - * 4. Use **share_key** to encrypt **kek** with AES-GCM. During the encryption, record **nonce2**, ** aad2**, ciphertext **kek_enc**, and encrypted **tag2**. - * 5. Generate the **importOptions.inData** field in the following format: - * keyB_pub length (4 bytes) + keyB_pub + aad2 length (4 bytes) + aad2 + - * nonce2 length (4 bytes) + nonce2 + tag2 length (4 bytes) + tag2 + - * kek_enc length (4 bytes) + kek_enc + aad1 length (4 bytes) + aad1 + - * nonce1 length (4 bytes) + nonce1 + tag1 length (4 bytes) + tag1 + - * Memory occupied by the keyA length (4 bytes) + keyA length + keyA_enc length (4 bytes) + keyA_enc - */ - var inputKey = new Uint8Array([0x02, 0x00, 0x00, 0x00]); - importOptions.inData = inputKey; - await TestImportWrappedFunc(alias, wrappingAlias, importOptions); +abortSession(handle: number, options: HuksOptions) : Promise\; + +Aborts the use of the key. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | --------------------------- | ---- | ------------------------------------------- | +| handle | number | Yes | Handle of the **Abort** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Abort** operation. | + +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +/* huks.initSession, huks.updateSession, and huks.finishSession must be used together. + * If an error occurs in any of huks.initSession, huks.updateSession, + * and huks.finishSession operation, + * huks.abortSession must be called to terminate the use of the key. + * + * The following uses the callback of an RSA1024 key as an example. + */ +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + let tmpUint8Array = new Uint8Array(arr); + return tmpUint8Array; } -function makeGenerateOptions() { - var properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_ECC - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP - }; - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 - }; - var options = { - properties: properties - }; - return options; +let keyAlias = "HuksDemoRSA"; +let properties = new Array(); +let options = { + properties: properties, + inData: new Uint8Array(0) }; +let handle; +async function generateKey() { + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_RSA + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_1024 + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5 + }; + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + }; + properties[5] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB, + } -function makeImportOptions() { - var properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_AES - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT - }; - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_CBC - }; - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE, - value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING - }; - var options = { - properties: properties - }; - return options; + try { + await huks.generateKeyItem(keyAlias, options) + .then((data) => { + console.info(`promise: generateKeyItem success`); + }) + .catch(error => { + console.error(`promise: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +async function huksInit() { + console.log('enter huksInit'); + try { + await huks.initSession(keyAlias, options) + .then ((data) => { + console.info(`promise: initSession success, data = ${JSON.stringify(data)}`); + handle = data.handle; + }) + .catch(error => { + console.error(`promise: initSession key failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: initSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +async function huksUpdate() { + console.log('enter huksUpdate'); + options.inData = stringToUint8Array("huksHmacTest"); + try { + await huks.updateSession(handle, options) + .then ((data) => { + console.info(`promise: updateSession success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + console.error(`promise: updateSession failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: updateSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +async function huksFinish() { + console.log('enter huksFinish'); + options.inData = new Uint8Array(0); + try { + await huks.finishSession(handle, options) + .then ((data) => { + console.info(`promise: finishSession success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + console.error(`promise: finishSession failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: finishSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +async function huksAbort() { + console.log('enter huksAbort'); + try { + await huks.abortSession(keyAlias, options) + .then ((data) => { + console.info(`promise: abortSession success`); + }) + .catch(error => { + console.error(`promise: abortSession failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: abortSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} +``` + + +## HuksExceptionErrCode9+ + +Enumerates the error codes. + +For details about the error codes, see [KUKS Error Codes](../errorcodes/errorcode-huks.md). + +**System capability**: SystemCapability.Security.Huks + +| Name | Description | Error Code | +| ---------------------------------------------- | --------------------------- | -------- | +| HUKS_ERR_CODE_PERMISSION_FAIL | Permission verification failed. | 201 | +| HUKS_ERR_CODE_ILLEGAL_ARGUMENT | Invalid parameters are detected. | 401 | +| HUKS_ERR_CODE_NOT_SUPPORTED_API | The API is not supported. | 801 | +| HUKS_ERR_CODE_FEATURE_NOT_SUPPORTED | The feature is not supported. | 12000001 | +| HUKS_ERR_CODE_MISSING_CRYPTO_ALG_ARGUMENT | Key algorithm parameters are missing. | 12000002 | +| HUKS_ERR_CODE_INVALID_CRYPTO_ALG_ARGUMENT | Invalid key algorithm parameters are detected. | 12000003 | +| HUKS_ERR_CODE_FILE_OPERATION_FAIL | The file operation failed. | 12000004 | +| HUKS_ERR_CODE_COMMUNICATION_FAIL | The communication failed. | 12000005 | +| HUKS_ERR_CODE_CRYPTO_FAIL | Failed to operate the algorithm library. | 12000006 | +| HUKS_ERR_CODE_KEY_AUTH_PERMANENTLY_INVALIDATED | Failed to access the key because the key has expired.| 12000007 | +| HUKS_ERR_CODE_KEY_AUTH_VERIFY_FAILED | Failed to access the key because the authentication has failed.| 12000008 | +| HUKS_ERR_CODE_KEY_AUTH_TIME_OUT | Key access timed out.| 12000009 | +| HUKS_ERR_CODE_SESSION_LIMIT | The number of key operation sessions has reached the limit. | 12000010 | +| HUKS_ERR_CODE_ITEM_NOT_EXIST | The target object does not exist. | 12000011 | +| HUKS_ERR_CODE_EXTERNAL_ERROR | An external error occurs. | 12000012 | +| HUKS_ERR_CODE_CREDENTIAL_NOT_EXIST | The credential does not exist. | 12000013 | +| HUKS_ERR_CODE_INSUFFICIENT_MEMORY | The memory is insufficient. | 12000014 | +| HUKS_ERR_CODE_CALL_SERVICE_FAILED | Failed to call other system services. | 12000015 | + +## HuksKeyPurpose + +Enumerates the key purposes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------ | ---- | -------------------------------- | +| HUKS_KEY_PURPOSE_ENCRYPT | 1 | Used to encrypt the plaintext.| +| HUKS_KEY_PURPOSE_DECRYPT | 2 | Used to decrypt the cipher text.| +| HUKS_KEY_PURPOSE_SIGN | 4 | Used for signing. | +| HUKS_KEY_PURPOSE_VERIFY | 8 | Used to verify the signature. | +| HUKS_KEY_PURPOSE_DERIVE | 16 | Used to derive a key. | +| HUKS_KEY_PURPOSE_WRAP | 32 | Used for an encrypted export. | +| HUKS_KEY_PURPOSE_UNWRAP | 64 | Used for an encrypted import. | +| HUKS_KEY_PURPOSE_MAC | 128 | Used to generate a message authentication code (MAC). | +| HUKS_KEY_PURPOSE_AGREE | 256 | Used for key agreement. | + +## HuksKeyDigest + +Enumerates the digest algorithms. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ---------------------- | ---- | ---------------------------------------- | +| HUKS_DIGEST_NONE | 0 | No digest algorithm| +| HUKS_DIGEST_MD5 | 1 | MD5| +| HUKS_DIGEST_SM39+ | 2 | SM3| +| HUKS_DIGEST_SHA1 | 10 | SHA-1| +| HUKS_DIGEST_SHA224 | 11 | SHA-224| +| HUKS_DIGEST_SHA256 | 12 | SHA-256| +| HUKS_DIGEST_SHA384 | 13 | SHA-384| +| HUKS_DIGEST_SHA512 | 14 | SHA-512| + +## HuksKeyPadding + +Enumerates the padding algorithms. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ---------------------- | ---- | ---------------------------------------- | +| HUKS_PADDING_NONE | 0 | No padding algorithm| +| HUKS_PADDING_OAEP | 1 | Optimal Asymmetric Encryption Padding (OAEP)| +| HUKS_PADDING_PSS | 2 | Probabilistic Signature Scheme (PSS)| +| HUKS_PADDING_PKCS1_V1_5 | 3 | Public Key Cryptography Standards (PKCS) #1 v1.5| +| HUKS_PADDING_PKCS5 | 4 | PKCS #5| +| HUKS_PADDING_PKCS7 | 5 | PKCS #7| + +## HuksCipherMode + +Enumerates the cipher modes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------- | ---- | --------------------- | +| HUKS_MODE_ECB | 1 | Electronic Code Block (ECB) mode| +| HUKS_MODE_CBC | 2 | Cipher Block Chaining (CBC) mode| +| HUKS_MODE_CTR | 3 | Counter (CTR) mode| +| HUKS_MODE_OFB | 4 | Output Feedback (OFB) mode| +| HUKS_MODE_CCM | 31 | Counter with CBC-MAC (CCM) mode| +| HUKS_MODE_GCM | 32 | Galois/Counter (GCM) mode| + +## HuksKeySize + +Enumerates the key sizes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ---------------------------------- | ---- | ------------------------------------------ | +| HUKS_RSA_KEY_SIZE_512 | 512 | Rivest-Shamir-Adleman (RSA) key of 512 bits | +| HUKS_RSA_KEY_SIZE_768 | 768 | RSA key of 768 bits | +| HUKS_RSA_KEY_SIZE_1024 | 1024 | RSA key of 1024 bits | +| HUKS_RSA_KEY_SIZE_2048 | 2048 | RSA key of 2048 bits | +| HUKS_RSA_KEY_SIZE_3072 | 3072 | RSA key of 3072 bits | +| HUKS_RSA_KEY_SIZE_4096 | 4096 | RSA key of 4096 bits | +| HUKS_ECC_KEY_SIZE_224 | 224 | Elliptic Curve Cryptography (ECC) key of 224 bits | +| HUKS_ECC_KEY_SIZE_256 | 256 | ECC key of 256 bits | +| HUKS_ECC_KEY_SIZE_384 | 384 | ECC key of 384 bits | +| HUKS_ECC_KEY_SIZE_521 | 521 | ECC key of 521 bits | +| HUKS_AES_KEY_SIZE_128 | 128 | Advanced Encryption Standard (AES) key of 128 bits | +| HUKS_AES_KEY_SIZE_192 | 196 | AES key of 196 bits | +| HUKS_AES_KEY_SIZE_256 | 256 | AES key of 256 bits | +| HUKS_AES_KEY_SIZE_512 | 512 | AES key of 512 bits | +| HUKS_CURVE25519_KEY_SIZE_256 | 256 | Curve25519 key of 256 bits| +| HUKS_DH_KEY_SIZE_2048 | 2048 | Diffie-Hellman (DH) key of 2048 bits | +| HUKS_DH_KEY_SIZE_3072 | 3072 | DH key of 3072 bits | +| HUKS_DH_KEY_SIZE_4096 | 4096 | DH key of 4096 bits | +| HUKS_SM2_KEY_SIZE_2569+ | 256 | ShangMi2 (SM2) key of 256 bits | +| HUKS_SM4_KEY_SIZE_1289+ | 128 | ShangMi4 (SM4) key of 128 bits | + +## HuksKeyAlg + +Enumerates the key algorithms. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------- | ---- | --------------------- | +| HUKS_ALG_RSA | 1 | RSA | +| HUKS_ALG_ECC | 2 | ECC | +| HUKS_ALG_DSA | 3 | DSA | +| HUKS_ALG_AES | 20 | AES | +| HUKS_ALG_HMAC | 50 | HMAC | +| HUKS_ALG_HKDF | 51 | HKDF | +| HUKS_ALG_PBKDF2 | 52 | PBKDF2 | +| HUKS_ALG_ECDH | 100 | ECDH | +| HUKS_ALG_X25519 | 101 | X25519 | +| HUKS_ALG_ED25519 | 102 | ED25519| +| HUKS_ALG_DH | 103 | DH | +| HUKS_ALG_SM29+ | 150 | SM2 | +| HUKS_ALG_SM39+ | 151 | SM3 | +| HUKS_ALG_SM49+ | 152 | SM4 | + +## HuksKeyGenerateType + +Enumerates the key generation types. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------------ | ---- | ---------------- | +| HUKS_KEY_GENERATE_TYPE_DEFAULT | 0 | Key generated by default.| +| HUKS_KEY_GENERATE_TYPE_DERIVE | 1 | Derived key.| +| HUKS_KEY_GENERATE_TYPE_AGREE | 2 | Key generated by agreement.| + +## HuksKeyFlag + +Enumerates the key generation modes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| -------------------------- | ---- | ------------------------------------ | +| HUKS_KEY_FLAG_IMPORT_KEY | 1 | Import a key using an API. | +| HUKS_KEY_FLAG_GENERATE_KEY | 2 | Generate a key by using an API. | +| HUKS_KEY_FLAG_AGREE_KEY | 3 | Generate a key by using a key agreement API.| +| HUKS_KEY_FLAG_DERIVE_KEY | 4 | Derive a key by using an API.| + +## HuksKeyStorageType + +Enumerates the key storage modes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ----------------------- | ---- | ------------------------------ | +| HUKS_STORAGE_TEMP | 0 | The key is managed locally. | +| HUKS_STORAGE_PERSISTENT | 1 | The key is managed by the HUKS service.| + +## HuksSendType + +Enumerates the tag transfer modes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| -------------------- | ---- | ----------------- | +| HUKS_SEND_TYPE_ASYNC | 0 | The tag is sent asynchronously.| +| HUKS_SEND_TYPE_SYNC | 1 | The tag is sent synchronously.| + +## HuksUnwrapSuite9+ + +Enumerates the algorithm suites required for encrypted imports. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ---------------------------------------------- | ---- | ----------------------------------------------------- | +| HUKS_UNWRAP_SUITE_X25519_AES_256_GCM_NOPADDING | 1 | Use X25519 for key agreement and then use AES-256 GCM to encrypt the key.| +| HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING | 2 | Use ECDH for key agreement and then use AES-256 GCM to encrypt the key. | + +## HuksImportKeyType9+ + +Enumerates the types of keys to import. By default, a public key is imported. This field is not required when a symmetric key is imported. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------- | ---- | ------------------------------ | +| HUKS_KEY_TYPE_PUBLIC_KEY | 0 | Public key | +| HUKS_KEY_TYPE_PRIVATE_KEY | 1 | Private key | +| HUKS_KEY_TYPE_KEY_PAIR | 2 | Public and private key pair| + +## HuksUserAuthType9+ + +Enumerates the user authentication types. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------------- | ---- | ------------------------- | +| HUKS_USER_AUTH_TYPE_FINGERPRINT | 1 | Fingerprint authentication. | +| HUKS_USER_AUTH_TYPE_FACE | 2 | Facial authentication.| +| HUKS_USER_AUTH_TYPE_PIN | 4 | PIN authentication.| + +## HuksAuthAccessType9+ + +Enumerates the access control types. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| --------------------------------------- | ---- | ------------------------------------------------ | +| HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | 1 | The key becomes invalid after the password is cleared. | +| HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | 2 | The key becomes invalid after a new biometric feature is added.| + +## HuksChallengeType9+ + +Enumerates the types of the challenges generated when a key is used. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------------- | ---- | ------------------------------ | +| HUKS_CHALLENGE_TYPE_NORMAL | 0 | Normal challenge, which is of 32 bytes by default.| +| HUKS_CHALLENGE_TYPE_CUSTOM | 1 | Custom challenge, which supports only one authentication for multiple keys.| +| HUKS_CHALLENGE_TYPE_NONE | 2 | Challenge is not required.| + +## HuksChallengePosition9+ + +Enumerates the positions of the 8-byte valid value in a custom challenge generated. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------------- | ---- | ------------------------------ | +| HUKS_CHALLENGE_POS_0 | 0 | Bytes 0 to 7.| +| HUKS_CHALLENGE_POS_1 | 1 | Bytes 8 to 15.| +| HUKS_CHALLENGE_POS_2 | 2 | Bytes 16 to 23.| +| HUKS_CHALLENGE_POS_3 | 3 | Bytes 24 to 31.| + +## HuksSecureSignType9+ + +Defines the signature type of the key generated or imported. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------------ | ---- | ------------------------------------------------------------ | +| HUKS_SECURE_SIGN_WITH_AUTHINFO | 1 | The signature carries authentication information. This field is specified when a key is generated or imported. When the key is used for signing, the data will be added with the authentication information and then be signed.| + +## HuksTagType + +Enumerates the tag data types. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| --------------------- | ------- | --------------------------------------- | +| HUKS_TAG_TYPE_INVALID | 0 << 28 | Invalid tag type. | +| HUKS_TAG_TYPE_INT | 1 << 28 | Number of the int type. | +| HUKS_TAG_TYPE_UINT | 2 << 28 | Number of the uint type.| +| HUKS_TAG_TYPE_ULONG | 3 << 28 | BigInt. | +| HUKS_TAG_TYPE_BOOL | 4 << 28 | Boolean. | +| HUKS_TAG_TYPE_BYTES | 5 << 28 | Uint8Array. | + +## HuksTag + +Enumerates the tags used to invoke parameters. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| -------------------------------------------- | ---------------------------------------- | -------------------------------------- | +| HUKS_TAG_INVALID | HuksTagType.HUKS_TAG_TYPE_INVALID \| 0 | Invalid tag. | +| HUKS_TAG_ALGORITHM | HUKS_TAG_TYPE_UINT \| 1 | Algorithm. | +| HUKS_TAG_PURPOSE | HuksTagType.HUKS_TAG_TYPE_UINT \| 2 | Purpose of the key. | +| HUKS_TAG_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 3 | Key size. | +| HUKS_TAG_DIGEST | HuksTagType.HUKS_TAG_TYPE_UINT \| 4 | Digest algorithm. | +| HUKS_TAG_PADDING | HuksTagType.HUKS_TAG_TYPE_UINT \| 5 | Padding algorithm. | +| HUKS_TAG_BLOCK_MODE | HuksTagType.HUKS_TAG_TYPE_UINT \| 6 | Cipher mode. | +| HUKS_TAG_KEY_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 7 | Key type. | +| HUKS_TAG_ASSOCIATED_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 8 | Associated authentication data. | +| HUKS_TAG_NONCE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 9 | Field for key encryption and decryption. | +| HUKS_TAG_IV | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10 | IV. | +| HUKS_TAG_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 11 | Information generated during key derivation. | +| HUKS_TAG_SALT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 12 | Salt value used for key derivation. | +| HUKS_TAG_PWD | HuksTagType.HUKS_TAG_TYPE_BYTES \| 13 | Password used for key derivation. | +| HUKS_TAG_ITERATION | HuksTagType.HUKS_TAG_TYPE_UINT \| 14 | Number of iterations for key derivation. | +| HUKS_TAG_KEY_GENERATE_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 15 | Key generation type. | +| HUKS_TAG_DERIVE_MAIN_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 16 | Main key for key derivation. | +| HUKS_TAG_DERIVE_FACTOR | HuksTagType.HUKS_TAG_TYPE_BYTES \| 17 | Factor for key derivation. | +| HUKS_TAG_DERIVE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 18 | Type of the algorithm used for key derivation. | +| HUKS_TAG_AGREE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 19 | Type of the algorithm used for key agreement. | +| HUKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 20 | Public key alias used in key agreement. | +| HUKS_TAG_AGREE_PRIVATE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 21 | Private key alias used in key agreement. | +| HUKS_TAG_AGREE_PUBLIC_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 22 | Public key used in key agreement. | +| HUKS_TAG_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 23 | Key alias. | +| HUKS_TAG_DERIVE_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 24 | Size of the derived key. | +| HUKS_TAG_IMPORT_KEY_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 25 | Type of the imported key. | +| HUKS_TAG_UNWRAP_ALGORITHM_SUITE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 26 | Algorithm suite required for encrypted imports. | +| HUKS_TAG_ACTIVE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 201 | Reserved. | +| HUKS_TAG_ORIGINATION_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 202 | Reserved. | +| HUKS_TAG_USAGE_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 203 | Reserved. | +| HUKS_TAG_CREATION_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 204 | Reserved. | +| HUKS_TAG_ALL_USERS | ksTagType.HUKS_TAG_TYPE_BOOL \| 301 | Reserved. | +| HUKS_TAG_USER_ID | HuksTagType.HUKS_TAG_TYPE_UINT \| 302 | Reserved. | +| HUKS_TAG_NO_AUTH_REQUIRED | HuksTagType.HUKS_TAG_TYPE_BOOL \| 303 | Reserved. | +| HUKS_TAG_USER_AUTH_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 304 | User authentication type. For details, see [HuksUserAuthType](#huksuserauthtype9). This parameter must be set together with [HuksAuthAccessType](#huksauthaccesstype9). You can set a maximum of two user authentication types at a time. For example, if **HuksAuthAccessType** is **HKS_SECURE_ACCESS_INVALID_NEW_BIO_ENROLL**, you can set two of **HKS_USER_AUTH_TYPE_FACE**, **HKS_USER_AUTH_TYPE_FINGERPRINT**, and **HKS_USER_AUTH_TYPE_FACE\**.| HKS_USER_AUTH_TYPE_FINGERPRINT | +| HUKS_TAG_AUTH_TIMEOUT | HuksTagType.HUKS_TAG_TYPE_UINT \| 305 | Reserved. | +| HUKS_TAG_AUTH_TOKEN | HuksTagType.HUKS_TAG_TYPE_BYTES \| 306 | Reserved. | +| HUKS_TAG_KEY_AUTH_ACCESS_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 307 | Access control type. For details, see [HuksAuthAccessType](#huksauthaccesstype9). This parameter must be set together with [HuksUserAuthType](#huksuserauthtype9).| +| HUKS_TAG_KEY_SECURE_SIGN_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 308 | Signature type of the key generated or imported.| +| HUKS_TAG_CHALLENGE_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 309 | Type of the challenge generated for a key. For details, see [HuksChallengeType](#hukschallengetype9).| +| HUKS_TAG_CHALLENGE_POS9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 310 | Position of the 8-byte valid value in a custom challenge. For details, see [HuksChallengePosition](#hukschallengeposition9).| +| HUKS_TAG_ATTESTATION_CHALLENGE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 501 | Challenge value used in the attestation. | +| HUKS_TAG_ATTESTATION_APPLICATION_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 502 | Application ID used in the attestation. | +| HUKS_TAG_ATTESTATION_ID_BRAND | HuksTagType.HUKS_TAG_TYPE_BYTES \| 503 | Brand of the device. | +| HUKS_TAG_ATTESTATION_ID_DEVICE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 504 | ID of the device. | +| HUKS_TAG_ATTESTATION_ID_PRODUCT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 505 | Product name of the device. | +| HUKS_TAG_ATTESTATION_ID_SERIAL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 506 | SN of the device. | +| HUKS_TAG_ATTESTATION_ID_IMEI | HuksTagType.HUKS_TAG_TYPE_BYTES \| 507 | International mobile equipment identity (IMEI) of the device. | +| HUKS_TAG_ATTESTATION_ID_MEID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 508 | Mobile equipment identity (MEID) of the device. | +| HUKS_TAG_ATTESTATION_ID_MANUFACTURER | HuksTagType.HUKS_TAG_TYPE_BYTES \| 509 | Manufacturer of the device. | +| HUKS_TAG_ATTESTATION_ID_MODEL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 510 | Device model. | +| HUKS_TAG_ATTESTATION_ID_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 511 | Key alias used in the attestation. | +| HUKS_TAG_ATTESTATION_ID_SOCID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 512 | System-on-a-chip (SoCID) of the device. | +| HUKS_TAG_ATTESTATION_ID_UDID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 513 | Unique device identifier (UDID) of the device. | +| HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 514 | Security level used in the attestation. | +| HUKS_TAG_ATTESTATION_ID_VERSION_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 515 | Version information used in the attestation. | +| HUKS_TAG_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1001 | Whether to use the alias passed in during key generation.| +| HUKS_TAG_KEY_STORAGE_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1002 | Key storage mode. | +| HUKS_TAG_IS_ALLOWED_WRAP | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1003 | Reserved. | +| HUKS_TAG_KEY_WRAP_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1004 | Reserved. | +| HUKS_TAG_KEY_AUTH_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1005 | Reserved. | +| HUKS_TAG_KEY_ROLE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1006 | Reserved. | +| HUKS_TAG_KEY_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1007 | Flag of the key. | +| HUKS_TAG_IS_ASYNCHRONIZED | HuksTagType.HUKS_TAG_TYPE_UINT \| 1008 | Reserved. | +| HUKS_TAG_SECURE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1009 | Reserved. | +| HUKS_TAG_SECURE_KEY_UUID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1010 | Reserved. | +| HUKS_TAG_KEY_DOMAIN | HuksTagType.HUKS_TAG_TYPE_UINT \| 1011 | Reserved. | +| HUKS_TAG_PROCESS_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10001 | Process name. | +| HUKS_TAG_PACKAGE_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10002 | Reserved. | +| HUKS_TAG_ACCESS_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10003 | Reserved. | +| HUKS_TAG_USES_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10004 | Reserved. | +| HUKS_TAG_CRYPTO_CTX | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10005 | Reserved. | +| HUKS_TAG_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10006 | Reserved. | +| HUKS_TAG_KEY_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10007 | Key version. | +| HUKS_TAG_PAYLOAD_LEN | HuksTagType.HUKS_TAG_TYPE_UINT \| 10008 | Reserved. | +| HUKS_TAG_AE_TAG | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10009 | Reserved. | +| HUKS_TAG_IS_KEY_HANDLE | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10010 | Reserved. | +| HUKS_TAG_OS_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10101 | OS version. | +| HUKS_TAG_OS_PATCHLEVEL | HuksTagType.HUKS_TAG_TYPE_UINT \| 10102 | OS patch level. | +| HUKS_TAG_SYMMETRIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20001 | Reserved. | +| HUKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20002 | Reserved. | +| HUKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20003 | Reserved. | + +## huks.generateKey(deprecated) + +generateKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Generates a key. This API uses an asynchronous callback to return the result. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.generateKeyItem9+](#huksgeneratekeyitem9). + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | +| keyAlias | string | Yes | Alias of the key. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. | +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. For details about other results, see HuksResult.| + +**Example** + +```js +/* Generate an RSA key of 512 bits. */ +let keyAlias = 'keyAlias'; +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_RSA +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512 +}; +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: +huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | +huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_OAEP +}; +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 +}; +let options = { + properties: properties +}; +huks.generateKey(keyAlias, options, function (err, data){}); +``` + +## huks.generateKey(deprecated) + +generateKey(keyAlias: string, options: HuksOptions) : Promise\ + +Generates a key. This API uses a promise to return the result. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.generateKeyItem9+](#huksgeneratekeyitem9-1). + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------ | +| keyAlias | string | Yes | Alias of the key. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key.| + +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs.| + +**Example** + +```js +/* Generate an ECC key of 256 bits. */ +let keyAlias = 'keyAlias'; +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_ECC +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 +}; +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: +huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | +huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 +}; +let options = { + properties: properties +}; +let result = huks.generateKey(keyAlias, options); +``` + + +## huks.deleteKey(deprecated) + +deleteKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Deletes a key. This API uses an asynchronous callback to return the result. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.deleteKeyItem9+](#huksdeletekeyitem9). + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | -------------------------------------------------- | +| keyAlias | string | Yes | Key alias passed in when the key was generated. | +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs.| + +**Example** + +```js +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +huks.deleteKey(keyAlias, emptyOptions, function (err, data) {}); +``` + +## huks.deleteKey(deprecated) + +deleteKey(keyAlias: string, options: HuksOptions) : Promise\ + +Deletes a key. This API uses a promise to return the result. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.deleteKeyItem9+](#huksdeletekeyitem9-1). + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------- | ---- | ----------------------------------------------------- | +| keyAlias | string | Yes | Key alias passed in when the key was generated.| +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).| + +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs.| + +**Example** + +```js +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +let result = huks.deleteKey(keyAlias, emptyOptions); +``` + + +## huks.importKey(deprecated) + +importKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Imports a key in plaintext. This API uses an asynchronous callback to return the result. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.importKeyItem9+](#huksimportkeyitem9). + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------------------------------- | +| keyAlias | string | Yes | Alias of the key.| +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs.| + +**Example** + +```js +/* Import an AES key of 256 bits. */ +let plainTextSize32 = makeRandomArr(32); +function makeRandomArr(size) { + let arr = new Uint8Array(size); + for (let i = 0; i < size; i++) { + arr[i] = Math.floor(Math.random() * 10); + } + return arr; +}; +let keyAlias = 'keyAlias'; +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 }; - -function huksImportWrappedKey() { - var genOptions = makeGenerateOptions(); - var importOptions = makeImportOptions(); - TestImportWrappedKeyFunc( - alias1, - alias2, - genOptions, - importOptions - ); -} +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: +huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7 +}; +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB +}; +let options = { + properties: properties, + inData: plainTextSize32 +}; +huks.importKey(keyAlias, options, function (err, data){}); ``` -## huks.importWrappedKey9+ +## huks.importKey(deprecated) -importWrappedKey(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions) : Promise\ +importKey(keyAlias: string, options: HuksOptions) : Promise\ -Imports a wrapped key. This API uses a promise to return the result. +Imports a key in plaintext. This API uses a promise to return the result. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.importKeyItem9+](#huksimportkeyitem9-1). **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| ---------------- | --------------------------- | ---- | --------------------------------------------- | -| keyAlias | string | Yes | Alias of the wrapped key to import. | -| wrappingKeyAlias | string | Yes | Alias of the data used to unwrap the key imported. | -| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import.| +| Name | Type | Mandatory| Description | +| -------- | ----------- | ---- | ------------------------------------ | +| keyAlias | string | Yes | Alias of the key.| +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.| **Return value** | Type | Description | | ----------------------------------- | -------------------------------------------------- | -| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs.| **Example** ```js -/* The process is similar as if a callback is used, except the following:*/ -async function TestImportWrappedFunc(alias, wrappingAlias, options) { - var result = await huks.importWrappedKey(alias, wrappingAlias, options); - if (result.errorCode === 0) { - console.log('test importWrappedKey success'); - } else { - console.log('test importWrappedKey fail'); - } -} +/* Import an AES key of 128 bits. */ +let plainTextSize32 = makeRandomArr(32); + +function makeRandomArr(size) { + let arr = new Uint8Array(size); + for (let i = 0; i < size; i++) { + arr[i] = Math.floor(Math.random() * 10); + } + return arr; +}; + +/* Step 1 Generate a key. */ +let keyAlias = 'keyAlias'; +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128 +}; +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7 +}; +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB +}; +let huksoptions = { + properties: properties, + inData: plainTextSize32 +}; +let result = huks.importKey(keyAlias, huksoptions); ``` -## huks.exportKey + +## huks.exportKey(deprecated) exportKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void Exports a key. This API uses an asynchronous callback to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.exportKeyItem9+](#huksexportkeyitem9). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1232,25 +2291,27 @@ Exports a key. This API uses an asynchronous callback to return the result. | -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned. **outData** contains the public key exported.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs. **outData** contains the public key exported.| **Example** ```js /* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { +let keyAlias = 'keyAlias'; +let emptyOptions = { properties: [] }; huks.exportKey(keyAlias, emptyOptions, function (err, data){}); ``` -## huks.exportKey +## huks.exportKey(deprecated) exportKey(keyAlias: string, options: HuksOptions) : Promise\ Exports a key. This API uses a promise to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.exportKeyItem9+](#huksexportkeyitem9-1). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1264,25 +2325,28 @@ Exports a key. This API uses a promise to return the result. | Type | Description | | ----------------------------------- | ------------------------------------------------------------ | -| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned. **outData** contains the public key exported.| +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs. **outData** contains the public key exported.| **Example** ```js /* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { +let keyAlias = 'keyAlias'; +let emptyOptions = { properties: [] }; -var result = huks.exportKey(keyAlias, emptyOptions); +let result = huks.exportKey(keyAlias, emptyOptions); ``` -## huks.getKeyProperties + +## huks.getKeyProperties(deprecated) getKeyProperties(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void Obtains key properties. This API uses an asynchronous callback to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.getKeyItemProperties9+](#huksgetkeyitemproperties9). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1291,25 +2355,27 @@ Obtains key properties. This API uses an asynchronous callback to return the res | -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **errorCode** is **HUKS_SUCCESS**; otherwise, an error code will be returned.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If **errorCode** is **HUKS_SUCCESS**, the operation is successful. Otherwise, an error occurs.| **Example** ```js /* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { +let keyAlias = 'keyAlias'; +let emptyOptions = { properties: [] }; huks.getKeyProperties(keyAlias, emptyOptions, function (err, data){}); ``` -## huks.getKeyProperties +## huks.getKeyProperties(deprecated) getKeyProperties(keyAlias: string, options: HuksOptions) : Promise\ Obtains key properties. This API uses a promise to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.getKeyItemProperties9+](#huksgetkeyitemproperties9-1). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1323,25 +2389,28 @@ Obtains key properties. This API uses a promise to return the result. | Type | Description | | ------------------ | ------------------------------------------------------------ | -| Promise\<[HuksResult](#huksoptions)> | Promise used to return the result. If the operation is successful, **errorCode** is **HUKS_SUCCESS**; otherwise, an error code will be returned. **properties** returns the parameters required for generating the key.| +| Promise\<[HuksResult](#huksoptions)> | Promise used to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs. **properties** returns the parameters required for generating the key.| **Example** ```js /* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { +let keyAlias = 'keyAlias'; +let emptyOptions = { properties: [] }; -var result = huks.getKeyProperties(keyAlias, emptyOptions); +let result = huks.getKeyProperties(keyAlias, emptyOptions); ``` -## huks.isKeyExist + +## huks.isKeyExist(deprecated) isKeyExist(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void Checks whether a key exists. This API uses an asynchronous callback to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.isKeyItemExist9+](#huksiskeyitemexist9). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1350,25 +2419,27 @@ Checks whether a key exists. This API uses an asynchronous callback to return th | -------- | ---------------------- | ---- | ------------------------------------- | | keyAlias | string | Yes | Alias of the key to check.| | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).| -| callback | AsyncCallback\ | Yes | Callback used to return the result. **TRUE** means that the key exists; **FALSE** means the opposite.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. The value **TRUE** means that the key exists, and **FALSE** means the opposite.| **Example** ```js /* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { +let keyAlias = 'keyAlias'; +let emptyOptions = { properties: [] }; huks.isKeyExist(keyAlias, emptyOptions, function (err, data){}); ``` -## huks.isKeyExist +## huks.isKeyExist(deprecated) isKeyExist(keyAlias: string, options: HuksOptions) : Promise\ Checks whether a key exists. This API uses a promise to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.isKeyItemExist9+](#huksiskeyitemexist9-1). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1382,26 +2453,26 @@ Checks whether a key exists. This API uses a promise to return the result. | Type | Description | | ----------------- | --------------------------------------- | -| Promise\ | Promise used to return the result. **TRUE** means that the key exists; **FALSE** means the opposite.| +| Promise\ | Promise used to return the result. The value **TRUE** means that the key exists, and **FALSE** means the opposite.| **Example** ```js /* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { +let keyAlias = 'keyAlias'; +let emptyOptions = { properties: [] }; -var result = huks.isKeyExist(keyAlias, emptyOptions); +let result = huks.isKeyExist(keyAlias, emptyOptions); ``` - - -## huks.init +## huks.init(deprecated) init(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void -Initializes the data for a key operation. This API uses an asynchronous callback to return the result. +Initializes the data for a key operation. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.initSession9+](#huksinitsession9-1). **System capability**: SystemCapability.Security.Huks @@ -1411,14 +2482,16 @@ Initializes the data for a key operation. This API uses an asynchronous callback | -------- | ---------------------- | ---- | ------------------------------------- | | keyAlias | string | Yes | Alias of the target key.| | options | [HuksOptions](#huksoptions) | Yes | Parameters used for initialization.| -| callback | AsyncCallback\<[HuksHandle](#hukshandle)> | Yes | Callback used to return the handle of the initialization operation.| +| callback | AsyncCallback\<[HuksHandle](#hukshandle)> | Yes | Callback invoked to return the key operation handle.| -## huks.init +## huks.init(deprecated) init(keyAlias: string, options: HuksOptions) : Promise\ -Initializes the data for a key operation. This API uses a promise to return the result. +Initializes the data for a key operation. This API uses a promise to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.initSession9+](#huksinitsession9-1). **System capability**: SystemCapability.Security.Huks @@ -1428,52 +2501,21 @@ Initializes the data for a key operation. This API uses a promise to return the | -------- | ---------------------- | ---- | ------------------------------------- | | keyAlias | string | Yes | Alias of the target key.| | options | [HuksOptions](#huksoptions) | Yes | Parameters used for initialization.| -| promise | Promise\<[HuksHandle](#hukshandle)> | Yes | Promise used to return the handle of the initialization operation.| - - -## huks.update(deprecated) - -update(handle: number, token?: Uint8Array, options: HuksOptions, callback: AsyncCallback\) : void - -Updates the key operation data by segment. This API uses an asynchronous callback to return the result. -> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.update9+](#huksupdate9-1). - -**System capability**: SystemCapability.Security.Huks +**Return value** -**Parameters** +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksHandle](#hukshandle)> | Promise used to return the key operation handle.| -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------- | ---- | -------------------------------------------- | -| handle | number | Yes | Handle of the **Update** operation. | -| token | Uint8Array | No | Token of the **Update** operation. | -| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the operation result.| ## huks.update(deprecated) -update(handle: number, token?: Uint8Array, options: HuksOptions) : Promise\ - -Updates the key operation data by segment. This API uses a promise to return the result. - -> **NOTE**
This API is discarded since API version 9. You are advised to use [huks.update9+](#huksupdate9-2). - -**System capability**: SystemCapability.Security.Huks - -**Parameters** - -| Name | Type | Mandatory| Description | -| ------- | ----------------------------------- | ---- | -------------------------------------------- | -| handle | number | Yes | Handle of the **Update** operation. | -| token | Uint8Array | No | Token of the **Update** operation. | -| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | -| promise | Promise\<[HuksResult](#huksresult)> | Yes | Callback used to return the operation result.| - -## huks.update9+ - update(handle: number, options: HuksOptions, callback: AsyncCallback\) : void -Updates the key operation by segment. This API uses an asynchronous callback to return the result. +Updates the key operation by segment. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.updateSession9+](#huksupdatesession9). **System capability**: SystemCapability.Security.Huks @@ -1483,14 +2525,15 @@ Updates the key operation by segment. This API uses an asynchronous callback to | -------- | ----------------------------------------- | ---- | -------------------------------------------- | | handle | number | Yes | Handle of the **Update** operation. | | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the operation result.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result.| +## huks.update(deprecated) -## huks.update9+ +update(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void -update(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void +Updates the key operation by segment. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. -Updates the key operation by segment. This API uses an asynchronous callback to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.updateSession9+](#huksupdatesession9-1). **System capability**: SystemCapability.Security.Huks @@ -1499,15 +2542,17 @@ Updates the key operation by segment. This API uses an asynchronous callback to | Name | Type | Mandatory| Description | | -------- | ----------------------------------------- | ---- | -------------------------------------------- | | handle | number | Yes | Handle of the **Update** operation. | +| token | Uint8Array | No | Token of the **Update** operation. | | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | -| token | Uint8Array | Yes | Token of the **Update** operation. | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the operation result.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result.| -## huks.update9+ +## huks.update(deprecated) update(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\ -Updates the key operation by segment. This API uses a promise to return the result. +Updates the key operation by segment. This API uses a promise to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.updateSession9+](#huksupdatesession9-2). **System capability**: SystemCapability.Security.Huks @@ -1516,15 +2561,23 @@ Updates the key operation by segment. This API uses a promise to return the resu | Name | Type | Mandatory| Description | | ------- | ----------------------------------- | ---- | -------------------------------------------- | | handle | number | Yes | Handle of the **Update** operation. | -| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | | token | Uint8Array | No | Token of the **Update** operation. | -| promise | Promise\<[HuksResult](#huksresult)> | Yes | Promise used to return the operation result.| +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | -## huks.finish +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result.| + + +## huks.finish(deprecated) finish(handle: number, options: HuksOptions, callback: AsyncCallback\) : void -Completes the key operation and releases resources. This API uses an asynchronous callback to return the result. +Completes the key operation and releases resources. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.finishSession9+](#huksfinishsession9). **System capability**: SystemCapability.Security.Huks @@ -1534,14 +2587,16 @@ Completes the key operation and releases resources. This API uses an asynchronou | -------- | ---------------------- | ---- | ------------------------------------- | | handle | number | Yes | Handle of the **Finish** operation.| | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation.| -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback used to return the operation result.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback invoked to return the result.| -## huks.finish +## huks.finish(deprecated) finish(handle: number, options: HuksOptions) : Promise\ -Completes the key operation and releases resources. This API uses a promise to return the result. +Completes the key operation and releases resources. This API uses a promise to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.finishSession9+](#huksfinishsession9-1). **System capability**: SystemCapability.Security.Huks @@ -1551,49 +2606,22 @@ Completes the key operation and releases resources. This API uses a promise to r | -------- | ---------------------- | ---- | ------------------------------------- | | handle | number | Yes | Handle of the **Finish** operation.| | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation.| -| promise | Promise\<[HuksResult](#huksresult)> | Yes| Promise used to return the operation result.| -## huks.finish9+ - -finish(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void - -Completes the key operation and releases resources. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Security.Huks - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------- | ---- | -------------------------------------------- | -| handle | number | Yes | Handle of the **Finish** operation. | -| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation. | -| token | Uint8Array | Yes | Token for the **Finish** operation. | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the operation result.| - - -## huks.finish9+ - -finish(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\ - -Completes the key operation and releases resources. This API uses a promise to return the result. - -**System capability**: SystemCapability.Security.Huks +**Return value** -**Parameters** +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result.| -| Name | Type | Mandatory| Description | -| ------- | ----------------------------------- | ---- | ----------------------------------- | -| handle | number | Yes | Handle of the **Finish** operation. | -| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation. | -| token | Uint8Array | No | Token for the **Finish** operation. | -| promise | Promise\<[HuksResult](#huksresult)> | Yes | Promise used to return the operation result.| -## huks.abort +## huks.abort(deprecated) abort(handle: number, options: HuksOptions, callback: AsyncCallback\) : void Aborts the use of the key. This API uses an asynchronous callback to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.abortSession9+](#huksabortsession9). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1602,7 +2630,7 @@ Aborts the use of the key. This API uses an asynchronous callback to return the | -------- | ---------------------- | ---- | ------------------------------------- | | handle | number | Yes | Handle of the **Abort** operation.| | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Abort** operation.| -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback used to return the operation result.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback invoked to return the result.| **Example** @@ -1612,27 +2640,14 @@ Aborts the use of the key. This API uses an asynchronous callback to return the * * The following uses the callback of an RSA 1024-bit key as an example. */ -import router from '@system.router'; -import huks from '@ohos.security.huks'; - -async function routePage() { - let options = { - uri: 'pages/second' - } - try { - await router.push(options) - } catch (err) { - console.error(`fail callback, code: ${err.code}, msg: ${err.msg}`) - } -} -var keyalias = "HuksDemoRSA"; -var properties = new Array(); -var options = { +let keyalias = "HuksDemoRSA"; +let properties = new Array(); +let options = { properties: properties, inData: new Uint8Array(0) }; -var handle; -var resultMessage = ""; +let handle; +let resultMessage = ""; async function generateKey() { properties[0] = { tag: huks.HuksTag.HUKS_TAG_ALGORITHM, @@ -1657,11 +2672,11 @@ async function generateKey() { huks.generateKey(keyalias, options); } function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { arr.push(str.charCodeAt(i)); } - var tmpUint8Array = new Uint8Array(arr); + let tmpUint8Array = new Uint8Array(arr); return tmpUint8Array; } async function huksInit() { @@ -1708,112 +2723,16 @@ async function huksAbort() { }); console.log(resultMessage); } - -@Entry -@Component -struct Index { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Text('Hello World') - .fontSize(50) - .fontWeight(FontWeight.Bold) - Button() { - Text('Tocallback') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - routePage() - }) - Button() { - Text('generateKey') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - generateKey() - }) - Button() { - Text('Init') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksInit() - }) - Button() { - Text('Update') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksUpdate() - }) - Button() { - Text('Finish') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksFinish() - }) - Button() { - Text('Abort') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksAbort() - }) - } - .width('100%') - .height('100%') - } -} ``` -## huks.abort +## huks.abort(deprecated) abort(handle: number, options: HuksOptions) : Promise\; Aborts the use of the key. This API uses a promise to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.abortSession9+](#huksabortsession9-1). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1822,7 +2741,12 @@ Aborts the use of the key. This API uses a promise to return the result. | -------- | ---------------------- | ---- | ------------------------------------- | | handle | number | Yes | Handle of the **Abort** operation.| | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Abort** operation.| -| promise | Promise\<[HuksResult](#huksresult)> | Yes| Promise used to return the operation result.| + +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result.| **Example** @@ -1832,34 +2756,20 @@ Aborts the use of the key. This API uses a promise to return the result. * * The following uses the promise of an RSA 1024-bit key as an example. */ -import router from '@system.router'; -import huks from '@ohos.security.huks'; - -async function routePage() { - let options = { - uri: 'pages/second' - } - try { - await router.push(options) - } catch (err) { - console.error(`fail callback, code: ${err.code}, msg: ${err.msg}`) - } -} - -var keyalias = "HuksDemoRSA"; -var properties = new Array(); -var options = { +let keyalias = "HuksDemoRSA"; +let properties = new Array(); +let options = { properties: properties, inData: new Uint8Array(0) }; -var handle; -var resultMessage = ""; +let handle; +let resultMessage = ""; function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { arr.push(str.charCodeAt(i)); } - var tmpUint8Array = new Uint8Array(arr); + let tmpUint8Array = new Uint8Array(arr); return tmpUint8Array; } @@ -1890,7 +2800,7 @@ async function huksInit() { return new Promise((resolve, reject) => { huks.init(keyalias, options, async function (err, data) { if (data.errorCode === 0) { - resultMessage = "Initialization successful!" + resultMessage = "init success!" handle = data.handle; } else { resultMessage = "init fail errorCode: " + data.errorCode @@ -1935,128 +2845,10 @@ function huksAbort() { }); }); } -@Entry -@Component -struct Index { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Text('Hello World') - .fontSize(50) - .fontWeight(FontWeight.Bold) - Button() { - Text('to Promise') - .fontSize(20) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - router.back() - }) - Button() { - Text('generateKey') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - generateKey() - }) - Button() { - Text('Init') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksInit() - }) - Button() { - Text('Update') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksUpdate() - }) - Button() { - Text('Finish') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksFinish() - }) - Button() { - Text('Abort') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksAbort() - }) - } - .width('100%') - .height('100%') - } -} ``` -## HuksParam - -Defines the **param** in the **properties** array of **options** used in the APIs. - -**System capability**: SystemCapability.Security.Huks - -| Name| Type | Mandatory| Description | -| ------ | ----------------------------------- | ---- | ------------ | -| tag | [HuksTag](#hukstag) | Yes | Tag. | -| value | boolean\|number\|bigint\|Uint8Array | Yes | Value of the tag.| - -## HuksOptions - -Defines the **options** used in the APIs. - -**System capability**: SystemCapability.Security.Huks - -| Name | Type | Mandatory| Description | -| ---------- | ----------------- | ---- | ------------------------ | -| properties | Array\<[HuksParam](#huksparam)> | No | Array used to hold **HuksParam**.| -| inData | Uint8Array | No | Input data. | -## HuksHandle +## HuksHandle(deprecated) Defines the HUKS handle structure. @@ -2069,7 +2861,7 @@ Defines the HUKS handle structure. | token | Uint8Array | No| Challenge obtained after the [init](#huksinit) operation.| -## HuksResult +## HuksResult(deprecated) Defines the **HuksResult** structure. @@ -2083,3 +2875,87 @@ Defines the **HuksResult** structure. | outData | Uint8Array | No | Output data. | | properties | Array\<[HuksParam](#huksparam)> | No | Property information. | | certChains | Array\ | No | Certificate chain information.| + + +## HuksErrorCode(deprecated) + +Enumerates the error codes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description| +| -------------------------- | ----- | ---- | +| HUKS_SUCCESS | 0 |Success.| +| HUKS_FAILURE | -1 |Failure.| +| HUKS_ERROR_BAD_STATE | -2 |Incorrect state.| +| HUKS_ERROR_INVALID_ARGUMENT | -3 |Invalid argument.| +| HUKS_ERROR_NOT_SUPPORTED | -4 |Not supported.| +| HUKS_ERROR_NO_PERMISSION | -5 |No permission.| +| HUKS_ERROR_INSUFFICIENT_DATA | -6 |Insufficient data.| +| HUKS_ERROR_BUFFER_TOO_SMALL | -7 |Insufficient buffer.| +| HUKS_ERROR_INSUFFICIENT_MEMORY | -8 |Insufficient memory.| +| HUKS_ERROR_COMMUNICATION_FAILURE | -9 |Communication failure.| +| HUKS_ERROR_STORAGE_FAILURE | -10 |Insufficient storage space.| +| HUKS_ERROR_HARDWARE_FAILURE | -11 |Hardware fault.| +| HUKS_ERROR_ALREADY_EXISTS | -12 |The object already exists.| +| HUKS_ERROR_NOT_EXIST | -13 |The object does not exist.| +| HUKS_ERROR_NULL_POINTER | -14 |Null pointer.| +| HUKS_ERROR_FILE_SIZE_FAIL | -15 |Incorrect file size.| +| HUKS_ERROR_READ_FILE_FAIL | -16 |Failed to read the file.| +| HUKS_ERROR_INVALID_PUBLIC_KEY | -17 |Invalid public key.| +| HUKS_ERROR_INVALID_PRIVATE_KEY | -18 |Invalid private key.| +| HUKS_ERROR_INVALID_KEY_INFO | -19 |Invalid key information.| +| HUKS_ERROR_HASH_NOT_EQUAL | -20 |The hash values are not equal.| +| HUKS_ERROR_MALLOC_FAIL | -21 |MALLOC failed.| +| HUKS_ERROR_WRITE_FILE_FAIL | -22 |Failed to write the file.| +| HUKS_ERROR_REMOVE_FILE_FAIL | -23 |Failed to delete the file.| +| HUKS_ERROR_OPEN_FILE_FAIL | -24 |Failed to open the file.| +| HUKS_ERROR_CLOSE_FILE_FAIL | -25 |Failed to close the file.| +| HUKS_ERROR_MAKE_DIR_FAIL | -26 |Failed to create the directory.| +| HUKS_ERROR_INVALID_KEY_FILE | -27 |Invalid key file.| +| HUKS_ERROR_IPC_MSG_FAIL | -28 |Incorrect IPC information.| +| HUKS_ERROR_REQUEST_OVERFLOWS | -29 |Request overflows.| +| HUKS_ERROR_PARAM_NOT_EXIST | -30 |The parameter does not exist.| +| HUKS_ERROR_CRYPTO_ENGINE_ERROR | -31 |CRYPTO ENGINE error.| +| HUKS_ERROR_COMMUNICATION_TIMEOUT | -32 |Communication timed out.| +| HUKS_ERROR_IPC_INIT_FAIL | -33 |IPC initialization failed.| +| HUKS_ERROR_IPC_DLOPEN_FAIL | -34 |IPC DLOPEN failed.| +| HUKS_ERROR_EFUSE_READ_FAIL | -35 |Failed to read eFUSE.| +| HUKS_ERROR_NEW_ROOT_KEY_MATERIAL_EXIST | -36 |New root key material exists.| +| HUKS_ERROR_UPDATE_ROOT_KEY_MATERIAL_FAIL | -37 |Failed to update the root key material.| +| HUKS_ERROR_VERIFICATION_FAILED | -38 |Failed to verify the certificate chain.| +| HUKS_ERROR_GET_USERIAM_SECINFO_FAILED9+ | -40 |Failed to obtain the security attribute information of the user.| +| HUKS_ERROR_GET_USERIAM_AUTHINFO_FAILED9+ | -41 |Failed to obtain the authentication information of the user.| +| HUKS_ERROR_USER_AUTH_TYPE_NOT_SUPPORT9+ | -42 |The access control of the current authentication type is not supported.| +| HUKS_ERROR_KEY_AUTH_FAILED9+ | -43 |The access control authentication has failed.| +| HUKS_ERROR_DEVICE_NO_CREDENTIAL9+ | -44 |No credential has been enrolled for the device.| +| HUKS_ERROR_CHECK_GET_ALG_FAIL | -100 |Failed to obtain the ALG. | +| HUKS_ERROR_CHECK_GET_KEY_SIZE_FAIL | -101 |Failed to obtain the key size.| +| HUKS_ERROR_CHECK_GET_PADDING_FAIL | -102 |Failed to obtain the padding algorithm.| +| HUKS_ERROR_CHECK_GET_PURPOSE_FAIL | -103 |Failed to obtain the key purpose.| +| HUKS_ERROR_CHECK_GET_DIGEST_FAIL | -104 |Failed to obtain the digest algorithm.| +| HUKS_ERROR_CHECK_GET_MODE_FAIL | -105 |Failed to obtain the cipher mode.| +| HUKS_ERROR_CHECK_GET_NONCE_FAIL | -106 |Failed to obtain the nonce.| +| HUKS_ERROR_CHECK_GET_AAD_FAIL | -107 |Failed to obtain the AAD.| +| HUKS_ERROR_CHECK_GET_IV_FAIL | -108 |Failed to obtain the initialization vector (IV).| +| HUKS_ERROR_CHECK_GET_AE_TAG_FAIL | -109 |Failed to obtain the AE flag.| +| HUKS_ERROR_CHECK_GET_SALT_FAIL | -110 |Failed to obtain the salt value.| +| HUKS_ERROR_CHECK_GET_ITERATION_FAIL | -111 |Failed to obtain the number of iterations.| +| HUKS_ERROR_INVALID_ALGORITHM | -112 |Invalid algorithm.| +| HUKS_ERROR_INVALID_KEY_SIZE | -113 |Invalid key size.| +| HUKS_ERROR_INVALID_PADDING | -114 |Invalid padding algorithm.| +| HUKS_ERROR_INVALID_PURPOSE | -115 |Invalid key purpose.| +| HUKS_ERROR_INVALID_MODE | -116 |Invalid cipher mode.| +| HUKS_ERROR_INVALID_DIGEST | -117 |Invalid digest algorithm.| +| HUKS_ERROR_INVALID_SIGNATURE_SIZE | -118 |Invalid signature size.| +| HUKS_ERROR_INVALID_IV | -119 |Invalid IV.| +| HUKS_ERROR_INVALID_AAD | -120 |Invalid AAD.| +| HUKS_ERROR_INVALID_NONCE | -121 |Invalid nonce.| +| HUKS_ERROR_INVALID_AE_TAG | -122 |Invalid AE tag.| +| HUKS_ERROR_INVALID_SALT | -123 |Invalid salt value.| +| HUKS_ERROR_INVALID_ITERATION | -124 |Invalid iteration count.| +| HUKS_ERROR_INVALID_OPERATION | -125 |Invalid operation.| +| HUKS_ERROR_INVALID_WRAPPED_FORMAT9+ | -126 |Incorrect format of the wrapped key being imported.| +| HUKS_ERROR_INVALID_USAGE_OF_KEY9+ | -127 |Incorrect purpose of the wrapped key being imported.| +| HUKS_ERROR_INTERNAL_ERROR | -999 |Internal error.| +| HUKS_ERROR_UNKNOWN_ERROR | -1000 |Unknown error.| diff --git a/en/application-dev/reference/apis/js-apis-image.md b/en/application-dev/reference/apis/js-apis-image.md index 866a5833b69feb01da451f2464fbdd7915f06172..6b7463a11b96f468bd275b0fd0fd841fe690713c 100644 --- a/en/application-dev/reference/apis/js-apis-image.md +++ b/en/application-dev/reference/apis/js-apis-image.md @@ -40,9 +40,11 @@ Creates a **PixelMap** object with the default BGRA_8888 format and pixel proper const color = new ArrayBuffer(96); let bufferArr = new Uint8Array(color); let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } -image.createPixelMap(color, opts) - .then((pixelmap) => { - }) +image.createPixelMap(color, opts).then((pixelmap) => { + console.log('Succeeded in creating pixelmap.'); +}).catch(error => { + console.log('Failed to create pixelmap.'); +}) ``` ## image.createPixelMap8+ @@ -115,7 +117,7 @@ const readBuffer = new ArrayBuffer(96); pixelmap.readPixelsToBuffer(readBuffer).then(() => { console.log('Succeeded in reading image pixel data.'); // Called if the condition is met. }).catch(error => { - console.log('Failed to read image pixel data.'); // Called if no condition is met. + console.log('Failed to read image pixel data.'); // Called if no condition is met. }) ``` @@ -392,7 +394,6 @@ Obtains pixel map information of this image. This API uses a promise to return t const color = new ArrayBuffer(96); let opts = { editable: true, pixelFormat: 2, size: { height: 6, width: 8 } } image.createPixelMap(color, opts).then(pixelmap => { - globalpixelmap = pixelmap; if (pixelmap == undefined) { console.error("Failed to obtain the image pixel map information."); } @@ -428,7 +429,6 @@ const color = new ArrayBuffer(96); let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } image.createPixelMap(color, opts, (err, pixelmap) => { if (pixelmap == undefined) { - globalpixelmap = pixelmap; console.error("Failed to obtain the image pixel map information."); } pixelmap.getImageInfo((err, imageInfo) => { @@ -559,9 +559,8 @@ Sets an opacity rate for this image pixel map. This API uses a promise to return **Example** ```js -async function () { - var rate = 0.5; - await pixelmap.opacity(rate); +async function Demo() { + await pixelmap.opacity(0.5); } ``` @@ -582,9 +581,9 @@ Creates a **PixelMap** object that contains only the alpha channel information. **Example** ```js -async function () { - await pixelmap.createAlphaPixelmap(); -}) +async function Demo() { + await pixelmap.createAlphaPixelmap(); +} ``` ### createAlphaPixelmap9+ @@ -632,7 +631,7 @@ Scales this image based on the input width and height. This API uses an asynchro **Example** ```js -async function () { +async function Demo() { await pixelmap.scale(2.0, 1.0); } ``` @@ -661,7 +660,7 @@ Scales this image based on the input width and height. This API uses a promise t **Example** ```js -async function () { +async function Demo() { await pixelmap.scale(2.0, 1.0); } ``` @@ -685,7 +684,7 @@ Translates this image based on the input coordinates. This API uses an asynchron **Example** ```js -async function () { +async function Demo() { await pixelmap.translate(3.0, 1.0); } ``` @@ -714,7 +713,7 @@ Translates this image based on the input coordinates. This API uses a promise to **Example** ```js -async function () { +async function Demo() { await pixelmap.translate(3.0, 1.0); } ``` @@ -737,7 +736,7 @@ Rotates this image based on the input angle. This API uses an asynchronous callb **Example** ```js -async function () { +async function Demo() { await pixelmap.rotate(90.0); } ``` @@ -765,7 +764,7 @@ Rotates this image based on the input angle. This API uses a promise to return t **Example** ```js -async function () { +async function Demo() { await pixelmap.rotate(90.0); } ``` @@ -789,7 +788,7 @@ Flips this image horizontally or vertically, or both. This API uses an asynchron **Example** ```js -async function () { +async function Demo() { await pixelmap.flip(false, true); } ``` @@ -818,7 +817,7 @@ Flips this image horizontally or vertically, or both. This API uses a promise to **Example** ```js -async function () { +async function Demo() { await pixelmap.flip(false, true); } ``` @@ -841,7 +840,7 @@ Crops this image based on the input size. This API uses an asynchronous callback **Example** ```js -async function () { +async function Demo() { await pixelmap.crop({ x: 0, y: 0, size: { height: 100, width: 100 } }); } ``` @@ -869,7 +868,7 @@ Crops this image based on the input size. This API uses a promise to return the **Example** ```js -async function () { +async function Demo() { await pixelmap.crop({ x: 0, y: 0, size: { height: 100, width: 100 } }); } ``` @@ -891,15 +890,10 @@ Releases this **PixelMap** object. This API uses a promise to return the result. **Example** ```js -const color = new ArrayBuffer(96); -let bufferArr = new Uint8Array(color); -let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } -image.createPixelMap(color, opts, (pixelmap) => { - pixelmap.release().then(() => { - console.log('Succeeded in releasing pixelmap object.'); - }).catch(error => { - console.log('Failed to release pixelmap object.'); - }) +pixelmap.release().then(() => { + console.log('Succeeded in releasing pixelmap object.'); +}).catch(error => { + console.log('Failed to release pixelmap object.'); }) ``` @@ -920,13 +914,8 @@ Releases this **PixelMap** object. This API uses an asynchronous callback to ret **Example** ```js -const color = new ArrayBuffer(96); -let bufferArr = new Uint8Array(color); -let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } -image.createPixelMap(color, opts, (pixelmap) => { - pixelmap.release().then(() => { - console.log('Succeeded in releasing pixelmap object.'); - }) +pixelmap.release(() => { + console.log('Succeeded in releasing pixelmap object.'); }) ``` @@ -1345,11 +1334,10 @@ Modifies the value of a property in this image. This API uses a promise to retur **Example** ```js -imageSourceApi.modifyImageProperty("ImageWidth", "120") - .then(() => { - const w = imageSourceApi.getImageProperty("ImageWidth") - console.info('w', w); - }) +imageSourceApi.modifyImageProperty("ImageWidth", "120").then(() => { + const w = imageSourceApi.getImageProperty("ImageWidth") + console.info('w', w); +}) ``` ### modifyImageProperty9+ @@ -1401,9 +1389,9 @@ Updates incremental data. This API uses a promise to return the result. ```js const array = new ArrayBuffer(100); -imageSourceIncrementalSApi.updateData(array, false, 0, 10).then(data => { - console.info('Succeeded in updating data.'); - }) +imageSourceApi.updateData(array, false, 0, 10).then(data => { + console.info('Succeeded in updating data.'); +}) ``` @@ -1429,11 +1417,11 @@ Updates incremental data. This API uses an asynchronous callback to return the r ```js const array = new ArrayBuffer(100); -imageSourceIncrementalSApi.updateData(array, false, 0, 10,(error,data )=> { - if(data !== undefined){ - console.info('Succeeded in updating data.'); - } - }) +imageSourceApi.updateData(array, false, 0, 10,(error,data )=> { + if(data !== undefined){ + console.info('Succeeded in updating data.'); + } +}) ``` ### createPixelMap7+ @@ -1617,6 +1605,7 @@ Packs an image. This API uses an asynchronous callback to return the result. **Example** ```js +const imageSourceApi = image.createImageSource(0); let packOpts = { format:"image/jpeg", quality:98 }; imagePackerApi.packing(imageSourceApi, packOpts, data => {}) ``` @@ -1645,6 +1634,7 @@ Packs an image. This API uses a promise to return the result. **Example** ```js +const imageSourceApi = image.createImageSource(0); let packOpts = { format:"image/jpeg", quality:98 } imagePackerApi.packing(imageSourceApi, packOpts) .then( data => { @@ -1673,10 +1663,14 @@ Packs an image. This API uses an asynchronous callback to return the result. **Example** ```js -let packOpts = { format:"image/jpeg", quality:98 } -const pixelMapApi = new ArrayBuffer(400); -imagePackerApi.packing(pixelMapApi, packOpts, data => { - console.log('Succeeded in packing the image.'); +const color = new ArrayBuffer(96); +let bufferArr = new Uint8Array(color); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts).then((pixelmap) => { + let packOpts = { format:"image/jpeg", quality:98 } + imagePackerApi.packing(pixelmap, packOpts, data => { + console.log('Succeeded in packing the image.'); + }) }) ``` @@ -1704,14 +1698,18 @@ Packs an image. This API uses a promise to return the result. **Example** ```js -let packOpts = { format:"image/jpeg", quality:98 } -const pixelMapApi = new ArrayBuffer(400); -imagePackerApi.packing(pixelMapApi, packOpts) - .then( data => { - console.log('Succeeded in packing the image.'); - }).catch(error => { - console.log('Failed to pack the image..'); - }) +const color = new ArrayBuffer(96); +let bufferArr = new Uint8Array(color); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts).then((pixelmap) => { + let packOpts = { format:"image/jpeg", quality:98 } + imagePackerApi.packing(pixelmap, packOpts) + .then( data => { + console.log('Succeeded in packing the image.'); + }).catch(error => { + console.log('Failed to pack the image..'); + }) +}) ``` ### release @@ -1764,7 +1762,7 @@ imagePackerApi.release().then(()=>{ createImageReceiver(width: number, height: number, format: number, capacity: number): ImageReceiver -Create an **ImageReceiver** instance by specifying the image width, height, format, and capacity. +Creates an **ImageReceiver** instance by specifying the image width, height, format, and capacity. **System capability**: SystemCapability.Multimedia.Image.ImageReceiver @@ -1774,7 +1772,7 @@ Create an **ImageReceiver** instance by specifying the image width, height, form | -------- | ------ | ---- | ---------------------- | | width | number | Yes | Default image width. | | height | number | Yes | Default image height. | -| format | number | Yes | Image format. | +| format | number | Yes | Image format, which is a constant of [ImageFormat](#imageformat9). | | capacity | number | Yes | Maximum number of images that can be accessed at the same time.| **Return value** @@ -1955,7 +1953,7 @@ receiver.readNextImage().then(img => { }) ``` -### on('imageArrival')9+ +### on9+ on(type: 'imageArrival', callback: AsyncCallback\): void @@ -2020,6 +2018,228 @@ receiver.release().then(() => { }) ``` +## image.createImageCreator9+ + +createImageCreator(width: number, height: number, format: number, capacity: number): ImageCreator + +Creates an **ImageCreator** instance by specifying the image width, height, format, and capacity. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ---------------------- | +| width | number | Yes | Default image width. | +| height | number | Yes | Default image height. | +| format | number | Yes | Image format, for example, YCBCR_422_SP or JPEG. | +| capacity | number | Yes | Maximum number of images that can be accessed at the same time.| + +**Return value** + +| Type | Description | +| ------------------------------ | --------------------------------------- | +| [ImageCreator](#imagecreator9) | Returns an **ImageCreator** instance if the operation is successful.| + +**Example** + +```js +var creator = image.createImageCreator(8192, 8, 4, 8); +``` + +## ImageCreator9+ + +Requests an image native data area, and provides APIs for applications to compile native image data. +Before calling any APIs in **ImageCreator**, you must create an **ImageCreator** instance. + +### Attributes + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +| Name | Type | Readable| Writable| Description | +| -------- | ---------------------------- | ---- | ---- | ------------------ | +| capacity | number | Yes | No | Maximum number of images that can be accessed at the same time.| +| format | [ImageFormat](#imageformat9) | Yes | No | Image format. | + +### dequeueImage9+ + +dequeueImage(callback: AsyncCallback\): void + +Obtains an image buffer from the idle queue and writes image data into it. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | ---------------------------------------| ---- | -------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the drawn image.| + +**Example** + +```js +creator.dequeueImage((err, img) => { + if (err) { + console.info('dequeueImage succeeded.'); + } + console.info('dequeueImage failed.')); +}); +``` + +### dequeueImage9+ + +dequeueImage(): Promise\ + +Obtains an image buffer from the idle queue and writes image data into it. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Return value** + +| Type | Description | +| --------------- | ------------- | +| Promise\ | Promise used to return the drawn image.| + +**Example** + +```js +creator.dequeueImage().then(img => { + console.info('dequeueImage succeeded.'); +}).catch(error => { + console.log('dequeueImage failed: ' + error); +}) +``` + +### queueImage9+ + +queueImage(interface: Image, callback: AsyncCallback\): void + +Places the drawn image in the dirty queue. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | -------------------------| ---- | -------------------- | +| interface | Image | Yes | Drawn image.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| + +**Example** + +```js +creator.queueImage(img, (err) => { + if (err) { + console.info('dequeueImage failed: ' + err); + } + console.info('dequeueImage succeeded'); +}) +``` + +### queueImage9+ + +queueImage(interface: Image): Promise\ + +Places the drawn image in the dirty queue. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | --------| ---- | ------------------- | +| interface | Image | Yes | Drawn image.| + +**Return value** + +| Type | Description | +| -------------- | ------------- | +| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| + +**Example** + +```js +creator.queueImage(img).then(() => { + console.info('dequeueImage succeeded.'); +}).catch(error => { + console.info('dequeueImage failed: ' + error); +}) +``` + +### on9+ + +on(type: 'imageRelease', callback: AsyncCallback\): void + +Listens for image release events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | -------------------------| ---- | -------------------- | +| type | string | Yes | Type of event, which is **'imageRelease'**.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| + +**Example** + +```js +creator.on('imageRelease', (err) => { + if (err) { + console.info('on faild' + err); + } + console.info('on succeeded'); +}) +``` + +### release9+ + +release(callback: AsyncCallback\): void + +Releases this **ImageCreator** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | -------------------------| ---- | -------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| + +**Example** + +```js +creator.release((err) => { + if (err) { + console.info('release failed: ' + err); + } + console.info('release succeeded'); +}); +``` +### release9+ + +release(): Promise\ + +Releases this **ImageCreator** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Return value** + +| Type | Description | +| -------------- | ------------- | +| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| + +**Example** + +```js +creator.release().then(() => { + console.info('release succeeded'); +}).catch(error => { + console.info('release failed'); +}) +``` + ## Image9+ Provides APIs for basic image operations, including obtaining image information and reading and writing image data. An **Image** instance is returned when [readNextImage](#readnextimage9) and [readLatestImage](#readlatestimage9) are called. @@ -2147,7 +2367,7 @@ Describes area information in an image. | ------ | ------------------ | ---- | ---- | ------------------------------------------------------------ | | pixels | ArrayBuffer | Yes | No | Pixels of the image. | | offset | number | Yes | No | Offset for data reading. | -| stride | number | Yes | No | Number of bytes from one row of pixels in memory to the next row of pixels in memory. The value of **stride** must be greater than or equal to the value of **region.size.width** multiplied by 4. | +| stride | number | Yes | No | Number of bytes from one row of pixels in memory to the next row of pixels in memory. The value of **stride** must be greater than or equal to the value of **region.size.width** multiplied by 4. | | region | [Region](#region7) | Yes | No | Region to read or write. The width of the region to write plus the X coordinate cannot be greater than the width of the original image. The height of the region to write plus the Y coordinate cannot be greater than the height of the original image.| ## ImageInfo @@ -2159,6 +2379,7 @@ Describes image information. | Name| Type | Readable| Writable| Description | | ---- | ------------- | ---- | ---- | ---------- | | size | [Size](#size) | Yes | Yes | Image size.| +| density9+ | number | Yes | Yes | Pixel density, in ppi.| ## Size @@ -2181,8 +2402,13 @@ Enumerates the pixel formats of images. | ---------------------- | ------ | ----------------- | | UNKNOWN | 0 | Unknown format. | | RGB_565 | 2 | RGB_565. | -| RGBA_8888 | 3 | RGBA_8888. | -| BGRA_88889+ | 4 | BGRA_8888. | +| RGBA_8888 | 3 | RGBA_8888.| +| BGRA_88889+ | 4 | BGRA_8888.| +| RGB_8889+ | 5 | RGB_888. | +| ALPHA_89+ | 6 | ALPHA_8. | +| RGBA_F169+ | 7 | RGBA_F16. | +| NV219+ | 8 | NV21. | +| NV129+ | 9 | NV12. | ## AlphaType9+ @@ -2194,8 +2420,8 @@ Enumerates the alpha types of images. | -------- | ------ | ----------------------- | | UNKNOWN | 0 | Unknown alpha type. | | OPAQUE | 1 | There is no alpha or the image is opaque.| -| PREMUL | 2 | Premultiplied alpha. | -| UNPREMUL | 3 | Unpremultiplied alpha, that is, straight alpha. | +| PREMUL | 2 | Premultiplied alpha. | +| UNPREMUL | 3 | Unpremultiplied alpha, that is, straight alpha. | ## ScaleMode9+ @@ -2250,6 +2476,7 @@ Defines image decoding options. | desiredRegion | [Region](#region7) | Yes | Yes | Region to decode. | | desiredPixelFormat | [PixelMapFormat](#pixelmapformat7) | Yes | Yes | Pixel map format for decoding.| | index | number | Yes | Yes | Index of the image to decode. | +| fitDensity9+ | number | Yes | Yes | Image pixel density, in ppi. | ## Region7+ @@ -2260,7 +2487,7 @@ Describes region information. | Name| Type | Readable| Writable| Description | | ---- | ------------- | ---- | ---- | ------------ | | size | [Size](#size) | Yes | Yes | Region size. | -| x | number | Yes | Yes | X coordinate of the region.| +| x | number | Yes | Yes | X coordinate to translate.| | y | number | Yes | Yes | Y coordinate of the region.| ## PackingOption @@ -2271,8 +2498,9 @@ Defines the option for image packing. | Name | Type | Readable| Writable| Description | | ------- | ------ | ---- | ---- | --------------------------------------------------- | -| format | string | Yes | Yes | Format of the packed image.
Currently, the JPEG and WebP formats are supported. | +| format | string | Yes | Yes | Format of the packed image.
Currently, the following raw formats are supported: .jpg, .png, .gif, .bmp, and .webp.| | quality | number | Yes | Yes | Quality of the output image during JPEG encoding. The value ranges from 1 to 100.| +| bufferSize9+ | number | Yes | Yes | Buffer size, which is used to set the image size. The default value is 10 MB.| ## GetImagePropertyOptions7+ @@ -2299,8 +2527,14 @@ Describes the exchangeable image file format (EXIF) information of an image. | IMAGE_WIDTH | "ImageWidth" | Image width. | | GPS_LATITUDE | "GPSLatitude" | Image latitude. | | GPS_LONGITUDE | "GPSLongitude" | Image longitude. | -| GPS_LATITUDE_REF | "GPSLatitudeRef" | Latitude reference, for example, N or S. | -| GPS_LONGITUDE_REF | "GPSLongitudeRef" | Longitude reference, for example, W or E. | +| GPS_LATITUDE_REF | "GPSLatitudeRef" | Latitude reference, for example, N or S. | +| GPS_LONGITUDE_REF | "GPSLongitudeRef" | Longitude reference, for example, W or E. | +| DATE_TIME_ORIGINAL9+ | "DateTimeOriginal" | Shooting time, for example, 2022:09:06 15:48:00. | +| EXPOSURE_TIME9+ | "ExposureTime" | Exposure time, for example, 1/33 sec.| +| SCENE_TYPE9+ | "SceneType" | Shooting scene mode, for example, portrait, scenery, motion, and night sight. | +| ISO_SPEED_RATINGS9+ | "ISOSpeedRatings" | ISO sensitivity or ISO speed, for example, 400. | +| F_NUMBER9+ | "FNumber" | Aperture, for example, f/1.8. | + ## ImageFormat9+ diff --git a/en/application-dev/reference/apis/js-apis-intl.md b/en/application-dev/reference/apis/js-apis-intl.md index b998d06bc0ca9900249144012f30e1230a0598f1..79cdf3ac5627984eba2f03e7eb37b9cc7137de4a 100644 --- a/en/application-dev/reference/apis/js-apis-intl.md +++ b/en/application-dev/reference/apis/js-apis-intl.md @@ -64,7 +64,7 @@ Creates a Locale object. | Name | Type | Mandatory | Description | | ------- | ------------- | ---- | ---------------------------- | | locale | string | Yes | A string containing locale information, including the language, optional script, and region.| -| options | LocaleOptions | No | Options for creating the **Locale** object. | +| options9+ | [LocaleOptions](#localeoptions9) | No | Options for creating the **Locale** object. | **Example** ``` @@ -181,7 +181,7 @@ Creates a **DateTimeOptions** object for the specified locale. | Name | Type | Mandatory | Description | | ------- | ----------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options | [DateTimeOptions](#datetimeoptions) | No | Options for creating a **DateTimeFormat** object. | +| options9+ | [DateTimeOptions](#datetimeoptions9) | No | Options for creating a **DateTimeFormat** object. | **Example** ``` @@ -265,7 +265,7 @@ Obtains the formatting options for **DateTimeFormat** object. | Type | Description | | ----------------------------------- | ----------------------------- | -| [DateTimeOptions](#datetimeoptions) | Formatting options for **DateTimeFormat** objects.| +| [DateTimeOptions](#datetimeoptions9) | Formatting options for **DateTimeFormat** objects.| **Example** ``` @@ -332,7 +332,7 @@ Parameters | Name | Type | Mandatory | Description | | ------- | ------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options | [NumberOptions](#numberoptions) | No | Options for creating a **NumberFormat** object. | +| options9+ | [NumberOptions](#numberoptions9) | No | Options for creating a **NumberFormat** object. | **Example** ``` @@ -380,7 +380,7 @@ Obtains the options of the **NumberFormat** object. | Type | Description | | ------------------------------- | --------------------------- | -| [NumberOptions](#numberoptions) | Formatting options for **NumberFormat** objects.| +| [NumberOptions](#numberoptions9) | Formatting options for **NumberFormat** objects.| **Example** @@ -449,7 +449,7 @@ Creates a Collator object. | Name | Type | Mandatory | Description | | ------- | ----------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options | [CollatorOptions](#collatoroptions) | No | Options for creating a **Collator** object. | +| options9+ | [CollatorOptions](#collatoroptions9) | No | Options for creating a **Collator** object. | **Example** ``` @@ -497,7 +497,7 @@ Returns properties reflecting the locale and collation options of a **Collator** | Type | Description | | ----------------------------------- | ----------------- | -| [CollatorOptions](#collatoroptions) | Properties of the **Collator** object.| +| [CollatorOptions](#collatoroptions9) | Properties of the **Collator** object.| **Example** @@ -553,7 +553,7 @@ Parameters | Name | Type | Mandatory | Description | | ------- | ---------------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options | [PluralRulesOptions](#pluralrulesoptions) | No | Options for creating a **PluralRules** object. | +| options9+ | [PluralRulesOptions](#pluralrulesoptions9) | No | Options for creating a **PluralRules** object. | **Example** ``` @@ -635,7 +635,7 @@ Creates a **RelativeTimeFormat** object. | Name | Type | Mandatory | Description | | ------- | ---------------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions) | No | Options for creating a **RelativeTimeFormat** object. | +| options9+ | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions9) | No | Options for creating a **RelativeTimeFormat** object. | **Example** ``` @@ -711,7 +711,7 @@ Obtains the formatting options for **RelativeTimeFormat** objects. | Type | Description | | ---------------------------------------- | --------------------------------- | -| [RelativeTimeFormatResolvedOptions](#relativetimeformatresolvedoptions) | Formatting options for **RelativeTimeFormat** objects.| +| [RelativeTimeFormatResolvedOptions](#relativetimeformatresolvedoptions8) | Formatting options for **RelativeTimeFormat** objects.| **Example** ``` diff --git a/en/application-dev/reference/apis/js-apis-missionManager.md b/en/application-dev/reference/apis/js-apis-missionManager.md index 50057062701f1ddbe0b058dc79e957c1a47e63a3..189042b1f1df1727423c65c0a226b11ae473db2a 100644 --- a/en/application-dev/reference/apis/js-apis-missionManager.md +++ b/en/application-dev/reference/apis/js-apis-missionManager.md @@ -42,18 +42,18 @@ Registers a listener to observe the mission status. **Example** - ```js - var listener = { - onMissionCreated: function(mission){"--------onMissionCreated-------"}, - onMissionDestroyed: function(mission){"--------onMissionDestroyed-------"}, - onMissionSnapshotChanged: function(mission){"--------onMissionSnapshotChanged-------"}, - onMissionMovedToFront: function(mission){"--------onMissionMovedToFront-------"}, - onMissionIconUpdated: function(mission,icon){"--------onMissionIconUpdated-------"} +```js + var listener = { + onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, + onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, + onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, + onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, + onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, + onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")} }; console.log("registerMissionListener") var listenerid = missionManager.registerMissionListener(listener); - - ``` +``` ## missionManager.unregisterMissionListener @@ -77,21 +77,22 @@ Deregisters a mission status listener. This API uses an asynchronous callback to **Example** - ```js - var listener = { - onMissionCreated: function(mission){"--------onMissionCreated-------"}, - onMissionDestroyed: function(mission){"--------onMissionDestroyed-------"}, - onMissionSnapshotChanged: function(mission){"--------onMissionSnapshotChanged-------"}, - onMissionMovedToFront: function(mission){"--------onMissionMovedToFront-------"}, - onMissionIconUpdated: function(mission,icon){"--------onMissionIconUpdated-------"} +```js + var listener = { + onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, + onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, + onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, + onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, + onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, + onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")} }; console.log("registerMissionListener") var listenerid = missionManager.registerMissionListener(listener); missionManager.unregisterMissionListener(listenerid, (error) => { - console.log("unregisterMissionListener"); + console.log("unregisterMissionListener"); }) - ``` +``` ## missionManager.unregisterMissionListener @@ -120,21 +121,22 @@ Deregisters a mission status listener. This API uses a promise to return the res **Example** - ```js - var listener = { - onMissionCreated: function(mission){"--------onMissionCreated-------"}, - onMissionDestroyed: function(mission){"--------onMissionDestroyed-------"}, - onMissionSnapshotChanged: function(mission){"--------onMissionSnapshotChanged-------"}, - onMissionMovedToFront: function(mission){"--------onMissionMovedToFront-------"}, - onMissionIconUpdated: function(mission,icon){"--------onMissionIconUpdated-------"} - }; - console.log("registerMissionListener") - var listenerid = missionManager.registerMissionListener(listener); - - missionManager.unregisterMissionListener(listenerid).catch(function (err){ - console.log(err); - }); - ``` +```js + var listener = { + onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, + onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, + onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, + onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, + onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, + onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")} + }; + console.log("registerMissionListener") + var listenerid = missionManager.registerMissionListener(listener); + + missionManager.unregisterMissionListener(listenerid).catch(function (err) { + console.log(err); + }); +``` ## missionManager.getMissionInfo diff --git a/en/application-dev/reference/apis/js-apis-net-connection.md b/en/application-dev/reference/apis/js-apis-net-connection.md index 1d272e9f03c4956e141456324b1eb1f05293cea8..da2443a7c87c363ae79085a9b0dfeda4f7f5af99 100644 --- a/en/application-dev/reference/apis/js-apis-net-connection.md +++ b/en/application-dev/reference/apis/js-apis-net-connection.md @@ -61,11 +61,37 @@ connection.getDefaultNet().then(function (netHandle) { }) ``` +## connection.getDefaultNetSync + +getDefaultNetSync(): NetHandle; + +Obtains the default active data network in synchronous mode. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------- | ---------------------------------- | +| NetHandle | Handle of the default active data network.| + +**Example** + +```js +let netHandle = connection.getDefaultNetSync(); +``` + + ## connection.hasDefaultNet hasDefaultNet(callback: AsyncCallback\): void Checks whether the default data network is activated. This API uses an asynchronous callback to return the result. +The default network priority is as follows: Ethernet > Wi-Fi > cellular. When only one network is connected, it is treated as the default data network. + +**Required permission**: ohos.permission.GET_NETWORK_INFO **System capability**: SystemCapability.Communication.NetManager.Core @@ -89,6 +115,9 @@ connection.hasDefaultNet(function (error, has) { hasDefaultNet(): Promise\ Checks whether the default data network is activated. This API uses a promise to return the result. +The default network priority is as follows: Ethernet > Wi-Fi > cellular. When only one network is connected, it is treated as the default data network. + +**Required permission**: ohos.permission.GET_NETWORK_INFO **System capability**: SystemCapability.Communication.NetManager.Core @@ -160,7 +189,7 @@ connection.getAllNets().then(function (nets) { getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback\): void -Obtains connection properties of the network corresponding to given network handle. This API uses an asynchronous callback to return the result. +Obtains connection properties of the network corresponding to the given network handle. This API uses an asynchronous callback to return the result. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -792,6 +821,108 @@ Before invoking NetHandle APIs, call **getNetHandle** to obtain a **NetHandle** | ------ | ------ | ------------------------- | | netId | number | Network ID. The value must be greater than or equal to 100.| +### bindSocket + +bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\): void; + +Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------------------------ | ---- | -------------------------------| +| socketParam | [TCPSocket](js-apis-socket.md#tcpsocket) \| [UDPSocket](js-apis-socket.md#udpsocket) | Yes| **TCPSocket** or **UDPSocket** object.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +connection.getDefaultNet().then(function (netHandle) { + var tcp = socket.constructTCPSocketInstance(); + var udp = socket.constructUDPSocketInstance(); + let socketType = "xxxx"; + if (socketType == "TCPSocket") { + tcp.bind({ + address: "xxxx", port: xxxx, family: xxxx + }, err => { + netHandle.bindSocket(tcp, function (error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) + }) + } else { + udp.on('message', callback); + udp.bind({ + address: "xxxx", port: xxxx, family: xxxx + }, err => { + udp.on('message', (data) => { + console.log(JSON.stringify(data)) + }); + netHandle.bindSocket(udp, function (error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) + }); + }) + } +} +``` + +### bindSocket + +bindSocket(socketParam: TCPSocket \| UDPSocket): Promise\; + +Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses a promise to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------------- | --------------------- | ---- | ------------------------------ | +| socketParam | [TCPSocket](js-apis-socket.md#tcpsocket) \| [UDPSocket](js-apis-socket.md#udpsocket) | Yes | **TCPSocket** or **UDPSocket** object.| + +**Return value** + +| Type | Description | +| -------------- | ---------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +connection.getDefaultNet().then(function (netHandle) { + var tcp = socket.constructTCPSocketInstance(); + var udp = socket.constructUDPSocketInstance(); + let socketType = "xxxx"; + if(socketType == "TCPSocket") { + tcp.bind({ + address: "xxxx", port: xxxx, family: xxxx + }, err => { + netHandle.bindSocket(tcp).then(err, data) { + console.log(JSON.stringify(data)) + }) + } else { + udp.on('message', callback); + udp.bind({ + address: "xxxx", port: xxxx, family: xxxx + }, err => { + udp.on('message', (data) => { + console.log(JSON.stringify(data)) + }); + netHandle.bindSocket(tcp).then(err, data) { + console.log(JSON.stringify(data)) + }); + }) + } +} +``` + + ### getAddressesByName getAddressesByName(host: string, callback: AsyncCallback\>): void diff --git a/en/application-dev/reference/apis/js-apis-net-ethernet.md b/en/application-dev/reference/apis/js-apis-net-ethernet.md new file mode 100644 index 0000000000000000000000000000000000000000..bf132f3c63710fc83b04a3411eb2477f2fe8b855 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-net-ethernet.md @@ -0,0 +1,301 @@ +# Ethernet Connection Management + +The Ethernet Connection Management module provides wired network capabilities, which allow users to set the IP address, subnet mask, gateway, and Domain Name System (DNS) server of a wired network. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import ethernet from '@ohos.net.ethernet' +``` + +## ethernet.setIfaceConfig + +setIfaceConfig(iface: string, ic: InterfaceConfiguration, callback: AsyncCallback\): void; + +Sets the network interface configuration. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------- | ---- | ------------------------------------------ | +| iface | string | Yes | Name of the network interface. | +| ic | [InterfaceConfiguration](#interfaceconfiguration) | Yes | Network interface configuration to set. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, the return result is empty. If the operation fails, an error code is returned.| + +**Example** + +```js +ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.1.123", routeAddr:"192.168.1.1", + gateAddr:"192.168.1.1", maskAddr:"255.255.255.0", dnsAddr0:"1.1.1.1", dnsAddr1:"2.2.2.2"}, + (error) => { + if (error) { + console.log("setIfaceConfig callback error = " + error); + } else { + console.log("setIfaceConfig callback ok "); + } + }); +``` + +## ethernet.setIfaceConfig + +setIfaceConfig(iface: string, ic: InterfaceConfiguration): Promise\; + +Sets the network interface configuration. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------- | ---- | ------------------------ | +| iface | string | Yes | Name of the network interface. | +| ic | [InterfaceConfiguration](#interfaceconfiguration) | Yes | Network interface configuration to set.| + +**Return value** + +| Type | Description | +| ------------------- | ----------------------------------------------------------- | +| Promise\ | Promise that returns no value.| + +**Example** + +```js +ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.1.123", routeAddr:"192.168.1.1", + gateAddr:"192.168.1.1", maskAddr:"255.255.255.0", dnsAddr0:"1.1.1.1", dnsAddr1:"2.2.2.2"}).then(() => { + console.log("setIfaceConfig promiss ok "); +}).catch((error) => { + console.log("setIfaceConfig promiss error = " + error); +}); +``` + +## ethernet.getIfaceConfig + +getIfaceConfig(iface: string, callback: AsyncCallback\): void; + +Obtains the configuration of a network interface. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------------- | ----- | ------------ | +| iface | string | Yes | Name of the network interface.| +| callback | AsyncCallback\<[InterfaceConfiguration](#interfaceconfiguration)> | Yes | Callback used to return the configuration. | + +**Example** + +```js +ethernet.getIfaceConfig("eth0", (error, value) => { + if (error) { + console.log("getIfaceConfig callback error = " + error); + } else { + console.log("getIfaceConfig callback mode = " + value.mode); + console.log("getIfaceConfig callback ipAddr = " + value.ipAddr); + console.log("getIfaceConfig callback routeAddr = " + value.routeAddr); + console.log("getIfaceConfig callback gateAddr = " + value.gateAddr); + console.log("getIfaceConfig callback maskAddr = " + value.maskAddr); + console.log("getIfaceConfig callback dns0Addr = " + value.dns0Addr); + console.log("getIfaceConfig callback dns1Addr = " + value.dns1Addr); + } +}); +``` + +## ethernet.getIfaceConfig + +getIfaceConfig(iface: string): Promise\; + +Obtains the configuration of a network interface. This API uses a promise to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ------------ | +| iface | string | Yes | Name of the network interface.| + +**Return value** + +| Type | Description | +| --------------------------------- | ---------------------------------- | +| Promise\<[InterfaceConfiguration](#interfaceconfiguration)> | Promise used to return the configuration. | + +**Example** + +```js +ethernet.getIfaceConfig("eth0").then((data) => { + console.log("getIfaceConfig promiss mode = " + data.mode); + console.log("getIfaceConfig promiss ipAddr = " + data.ipAddr); + console.log("getIfaceConfig promiss routeAddr = " + data.routeAddr); + console.log("getIfaceConfig promiss gateAddr = " + data.gateAddr); + console.log("getIfaceConfig promiss maskAddr = " + data.maskAddr); + console.log("getIfaceConfig promiss dns0Addr = " + data.dns0Addr); + console.log("getIfaceConfig promiss dns1Addr = " + data.dns1Addr); +}).catch((error) => { + console.log("getIfaceConfig promiss error = " + error); +}); +``` + +## ethernet.isIfaceActive + +isIfaceActive(iface?: string, callback: AsyncCallback\): void; + +Checks whether a network interface is active. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | -------------------------------------------------- | +| iface | string | No | Name of the network interface. If this parameter is left empty, the API checks for any active network interface. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **1** means that the network interface is active, **0** means that the network interface is inactive, and any other value means that an error has occurred.| + +**Example** + +```js +ethernet.isIfaceActive("eth0", (error, value) => { + if (error) { + console.log("whether2Activate callback error = " + error); + } else { + console.log("whether2Activate callback = " + value); + } +}); +``` + +## ethernet.isIfaceActive + +isIfaceActive(iface?: string): Promise\; + +Checks whether a network interface is active. This API uses a promise to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| iface | string | No | Name of the network interface. If this parameter is left empty, the API checks for any active network interface.| + +**Return value** + +| Type | Description | +| ----------------| ------------------------------------------------------------------ | +| Promise\ | Promise used to return the result. The value **1** means that the network interface is active, **0** means that the network interface is inactive, and any other value means that an error has occurred.| + +**Example** + +```js +ethernet.isIfaceActive("eth0").then((data) => { + console.log("isIfaceActive promiss = " + data); +}).catch((error) => { + console.log("isIfaceActive promiss error = " + error); +}); +``` + +## ethernet.getAllActiveIfaces + +getAllActiveIfaces(callback: AsyncCallback\>): void; + +Obtains all active network interfaces. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | ------------------------------ | +| callback | AsyncCallback\> | Yes | Callback used to return all the active network interface names obtained.| + +**Example** + +```js +ethernet.getAllActiveIfaces((error, value) => { + if (error) { + console.log("getAllActiveIfaces callback error = " + error); + } else { + console.log("getAllActiveIfaces callback value.length = " + value.length); + for (let i = 0; i < value.length; i++) { + console.log("getAllActiveIfaces callback = " + value[i]); + } + } +}); +``` + +## ethernet.getAllActiveIfaces + +getAllActiveIfaces(): Promise\>; + +Obtains all active network interfaces. This API uses a promise to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +**Return value** + +| Type | Description | +| ------------------------------ | ----------------------------------------------- | +| Promise\> | Promise used to return all the active network interface names obtained.| + +**Example** + +```js +ethernet.getAllActiveIfaces().then((data) => { + console.log("getAllActiveIfaces promiss data.length = " + data.length); + for (let i = 0; i < data.length; i++) { + console.log("getAllActiveIfaces promiss = " + data[i]); + } +}).catch((error) => { + console.log("getAllActiveIfaces promiss error = " + error); +}); +``` + +## InterfaceConfiguration + +Defines the network configuration for the Ethernet connection. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Type | Description | +| ----------------------- | ----------------------------------- | ------------------------------------------------------------ | +| mode | [IPSetMode](#ipsetmode) | Configuration mode of the Ethernet connection.| +| ipAddr | string | Static IP address of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in Dynamic Host Configuration Protocol (DHCP) mode.| +| route | string | Route of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.| +| gateway | string | Gateway of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.| +| netMask | string | Subnet mask of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.| +| dnsServers | string | DNS server addresses of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode. Multiple addresses are separated by commas (,).| + +## IPSetMode + +Defines the configuration mode of the Ethernet connection. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value | Description | +| ------------------------ | ---- | ---------------------- | +| STATIC | 0 | Static configuration.| +| DHCP | 1 | Dynamic configuration.| diff --git a/en/application-dev/reference/apis/js-apis-net-policy.md b/en/application-dev/reference/apis/js-apis-net-policy.md new file mode 100644 index 0000000000000000000000000000000000000000..4537266a60faa11243140aee10a7f9d9a36bfa7b --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-net-policy.md @@ -0,0 +1,1120 @@ +# Network Policy Management + +The Network Policy Management module provides APIs for managing network policies, through which you can control and manage the data volume used. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import policy from '@ohos.net.policy' +``` + +## policy.setBackgroundPolicy + +setBackgroundPolicy(isAllowed: boolean, callback: AsyncCallback\): void + +Sets a background network policy. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| isAllowed | boolean | Yes | Whether applications running in the background are allowed to use mobile data.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))), (err, data) => { + this.callBack(err, data); + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}); +``` + +## policy.setBackgroundPolicy + +setBackgroundPolicy(isAllowed: boolean): Promise\ + +Sets a background network policy. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| isAllowed | boolean | Yes | Whether applications running in the background are allowed to use mobile data.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## policy.getBackgroundPolicy + +getBackgroundPolicy(callback: AsyncCallback\): void; + +Obtains the background network policy. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If **true** is returned, applications running in the background are allowed to use mobile data.| + +**Example** + +```js +policy.getBackgroundPolicy((err, data) => { + this.callBack(err, data); + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}); +``` + +## policy.getBackgroundPolicy + +getBackgroundPolicy(): Promise\; + +Obtains the background network policy. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +policy.getBackgroundPolicy().then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.setPolicyByUid + +setPolicyByUid(uid: number, policy: NetUidPolicy, callback: AsyncCallback\): void; + +Sets an application-specific network policy. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes | Unique ID of the application.| +| policy | [NetUidPolicy](#netuidpolicy) | Yes| Application-specific network policy to set.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +let param = { + uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy) +} +policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy), (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.setPolicyByUid + +setPolicyByUid(uid: number, policy: NetUidPolicy): Promise\; + +Sets an application-specific network policy. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes | Unique ID of the application.| +| policy | [NetUidPolicy](#netuidpolicy) | Yes| Application-specific network policy to set.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let param = { + uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy) +} +policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy)).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.getPolicyByUid + +getPolicyByUid(uid: number, callback: AsyncCallback\): void; + +Obtains an application-specific network policy by **uid**. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| callback | AsyncCallback\<[NetUidPolicy](#netuidpolicy)> | Yes | Callback used to return the result.| + +**Example** + +```js +policy.getPolicyByUid(Number.parseInt(this.firstParam), (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.getPolicyByUid + +getPolicyByUid(uid: number): Promise\; + +Obtains an application-specific network policy by **uid**. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\<[NetUidPolicy](#netuidpolicy)> | Promise used to return the result.| + +**Example** + +```js +policy.getPolicyByUid(Number.parseInt(this.firstParam)).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.getUidsByPolicy + +getUidsByPolicy(policy: NetUidPolicy, callback: AsyncCallback\>): void; + +Obtains the UID array of applications configured with a certain application-specific network policy. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| policy | [NetUidPolicy](#netuidpolicy) | Yes| Target application-specific network policy.| +| callback | AsyncCallback\> | Yes | Callback used to return the result.| + +**Example** + +```js +policy.getUidsByPolicy(Number.parseInt(this.currentNetUidPolicy), (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.getUidsByPolicy + +function getUidsByPolicy(policy: NetUidPolicy): Promise\>; + +Obtains the UID array of applications configured with a certain application-specific network policy. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| policy | [NetUidPolicy](#netuidpolicy) | Yes| Target application-specific network policy.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\> | Promise used to return the result.| + +**Example** + +```js +policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.getNetQuotaPolicies + +getNetQuotaPolicies(callback: AsyncCallback\>): void; + +Obtains the network quota policies. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\> | Yes | Callback used to return the result.| + +**Example** + +```js +policy.getNetQuotaPolicies((err, data) => { + this.callBack(err, data); +}); +``` + +## policy.getNetQuotaPolicies + +getNetQuotaPolicies(): Promise\>; + +Obtains the network quota policies. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\> | Promise used to return the result.| + +**Example** + +```js +policy.getNetQuotaPolicies().then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.setNetQuotaPolicies + +setNetQuotaPolicies(quotaPolicies: Array\, callback: AsyncCallback\): void; + +Sets an array of network quota policies. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| quotaPolicies | Array\<[NetQuotaPolicy](#netquotapolicy)> | Yes| An array of network quota policies to set.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +let param = {netType:Number.parseInt(this.netType), iccid:this.iccid, ident:this.ident, periodDuration:this.periodDuration, warningBytes:Number.parseInt(this.warningBytes), + limitBytes:Number.parseInt(this.limitBytes), lastWarningRemind:this.lastWarningRemind, lastLimitRemind:this.lastLimitRemind, metered:Boolean(Number.parseInt(this.metered)), limitAction:this.limitAction}; +this.netQuotaPolicyList.push(param); + +policy.setNetQuotaPolicies(this.netQuotaPolicyList, (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.setNetQuotaPolicies + +setNetQuotaPolicies(quotaPolicies: Array\): Promise\; + +Sets an array of network quota policies. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| quotaPolicies | Array\<[NetQuotaPolicy](#netquotapolicy)> | Yes| An array of network quota policies to set.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let param = {netType:Number.parseInt(this.netType), iccid:this.iccid, ident:this.ident, periodDuration:this.periodDuration, warningBytes:Number.parseInt(this.warningBytes), + limitBytes:Number.parseInt(this.limitBytes), lastWarningRemind:this.lastWarningRemind, lastLimitRemind:this.lastLimitRemind, metered:Boolean(Number.parseInt(this.metered)), limitAction:this.limitAction}; +this.netQuotaPolicyList.push(param); + +policy.setNetQuotaPolicies(this.netQuotaPolicyList).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## policy.restoreAllPolicies + +restoreAllPolicies(iccid: string, callback: AsyncCallback\): void; + +Restores all the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| iccid | string | Yes| SIM card ID.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +this.firstParam = iccid; +policy.restoreAllPolicies(this.firstParam, (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.restoreAllPolicies + +restoreAllPolicies(iccid: string): Promise\; + +Restores all the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| iccid | string | Yes| SIM card ID.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +this.firstParam = iccid; +policy.restoreAllPolicies(this.firstParam).then((err, data){ + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.isUidNetAllowed + +isUidNetAllowed(uid: number, isMetered: boolean, callback: AsyncCallback\): void; + +Checks whether an application is allowed to access metered networks. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| isMetered | boolean | Yes| Whether the network is a metered network.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that the application is allowed to access metered networks, and **false** means the opposite.| + +**Example** + +```js + +let param = { + uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean)) +} +policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.isUidNetAllowed + +isUidNetAllowed(uid: number, isMetered: boolean): Promise\; + +Checks whether an application is allowed to access metered networks. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| isMetered | boolean | Yes| Whether the network is a metered network.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js + +let param = { + uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean)) +} +policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.isUidNetAllowed + +isUidNetAllowed(uid: number, iface: string, callback: AsyncCallback\): void; + +Checks whether an application is allowed to access the given network. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| iface | string | Yes| Name of the target network.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that the application is allowed to access the given network, and **false** means the opposite.| + +**Example** + +```js + +let param = { + uid: Number.parseInt(this.firstParam), iface: this.secondParam +} +policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam, (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.isUidNetAllowed + +isUidNetAllowed(uid: number, iface: string): Promise\; + +Checks whether an application is allowed to access the given network. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| iface | string | Yes| Name of the target network.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let param = { + uid: Number.parseInt(this.firstParam), iface: this.secondParam +} +policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.setDeviceIdleAllowlist + +setDeviceIdleAllowList(uid: number, isAllowed: boolean, callback: AsyncCallback\): void; + +Sets whether to add an application to the device idle allowlist. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| isAllowed | boolean | Yes| Whether to add the application to the allowlist.| +| callback | callback: AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +let param = { + uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) +} +policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.setDeviceIdleAllowlist + +setDeviceIdleAllowList(uid: number, isAllowed: boolean): Promise\; + +Sets whether to add an application to the device idle allowlist. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| isAllowed | boolean | Yes| Whether to add the application to the allowlist.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let param = { + uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) +} +policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.getDeviceIdleAllowlist + +getDeviceIdleAllowList(callback: AsyncCallback\>): void; + +Obtains the UID array of applications that are on the device idle allowlist. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\> | Yes | Callback used to return the result.| + +**Example** + +```js +policy.getDeviceIdleAllowList((err, data) => { + this.callBack(err, data); +}); +``` + +## policy.getDeviceIdleAllowlist + +getDeviceIdleAllowList(): Promise\>; + +Obtains the UID array of applications that are on the device idle allowlist. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\> | Promise used to return the result.| + +**Example** + +```js +policy.getDeviceIdleAllowList().then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## policy.getBackgroundPolicyByUid + +getBackgroundPolicyByUid(uid: number, callback: AsyncCallback\): void; + +Obtains the background network policies configured for the given application. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| callback | AsyncCallback\<[NetBackgroundPolicy](#netbackgroundpolicy)> | Yes | Callback used to return the result.| + +**Example** + +```js +this.firstParam = uid +policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam), (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.getBackgroundPolicyByUid + +getBackgroundPolicyByUid(uid: number): Promise\; + +Obtains the background network policies configured for the given application. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\<[NetBackgroundPolicy](#netbackgroundpolicy)> | Promise used to return the result.| + +**Example** + +```js +this.firstParam = uid +policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam)).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## policy.resetPolicies + +resetPolicies(iccid: string, callback: AsyncCallback\): void; + +Resets the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| iccid | string | Yes| SIM card ID.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +this.firstParam = iccid +policy.resetPolicies(this.firstParam, (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.resetPolicies + +resetPolicies(iccid: string): Promise\; + +Resets the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| iccid | string | Yes| SIM card ID.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then((err, data) { + +}) +this.firstParam = iccid +policy.resetPolicies(this.firstParam).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.updateRemindPolicy + +updateRemindPolicy(netType: NetBearType, iccid: string, remindType: RemindType, callback: AsyncCallback\): void; + +Updates a reminder policy. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| netType | [NetBearType](js-apis-net-connection.md#netbeartype) | Yes| Network type.| +| iccid | string | Yes| SIM card ID.| +| remindType | [RemindType](#remindtype) | Yes| Reminder type.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +let param = { + netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType +} +policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType), (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.updateRemindPolicy + +updateRemindPolicy(netType: NetBearType, iccid: string, remindType: RemindType): Promise\; + +Updates a reminder policy. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| netType | [NetBearType](js-apis-net-connection.md#netbeartype) | Yes| Network type.| +| iccid | string | Yes| SIM card ID.| +| remindType | [RemindType](#remindtype) | Yes| Reminder type.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let param = { + netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType +} +policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType)).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.on + +Functions as the handle to a network policy. + +### on('netUidPolicyChange') + +on(type: "netUidPolicyChange", callback: Callback\<{ uid: number, policy: NetUidPolicy }>): void; + +Subscribes to policy changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | netUidPolicyChange | Yes| Event type. The value **netUidPolicyChange** indicates a policy change event.| +| callback | Callback\<{ uid: number, policy: [NetUidPolicy](#netuidpolicy) }> | Yes | Callback used to return the result.| + +**Example** + +```js +policy.on('netUidPolicyChange', (data) => { + this.log('on netUidPolicyChange: ' + JSON.stringify(data)); +}) +``` + +### on('netUidRuleChange') + +on(type: "netUidRuleChange", callback: Callback\<{ uid: number, rule: NetUidRule }>): void; + +Subscribes to rule changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | netUidRuleChange | Yes| Event type. The value **netUidRuleChange** indicates a rule change event.| +| callback | Callback\<{ uid: number, rule: [NetUidRule](#netuidrule) }> | Yes | Callback used to return the result.| + +**Example** + +```js +policy.on('netUidRuleChange', (data) => { + this.log('on netUidRuleChange: ' + JSON.stringify(data)); +}) +``` + +### on('netMeteredIfacesChange') + +on(type: "netMeteredIfacesChange", callback: Callback\>): void; + +Subscribes to metered network name (specified by **iface**) changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | netMeteredIfacesChange | Yes| Event type. The value **netMeteredIfacesChange** indicates a metered network name change event.| +| callback | Callback\> | Yes | Callback used to return the result.| + +**Example** + +```js +policy.on('netMeteredIfacesChange', (data) => { + this.log('on netMeteredIfacesChange: ' + JSON.stringify(data)); +}) +``` + +### on('netQuotaPolicyChange') + +on(type: "netQuotaPolicyChange", callback: Callback\>): void; + +Subscribes to network quota policy changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | netQuotaPolicyChange | Yes| Event type. The value **netQuotaPolicyChange** indicates a network quota policy change event.| +| callback | Callback\> | Yes | Callback used to return the result.| + +**Example** + +```js +policy.on('netQuotaPolicyChange', (data) => { + this.log('on netQuotaPolicyChange: ' + JSON.stringify(data)); +}) +``` + +### on('netBackgroundPolicyChange') + +on(type: "netBackgroundPolicyChange", callback: Callback\): void; + +Subscribes to background network policy changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | netBackgroundPolicyChange | Yes| Event type. The value **netBackgroundPolicyChange** indicates a background network policy change event.| +| callback | Callback\ | Yes | Callback used to return the result.| + +**Example** + +```js +policy.on('netBackgroundPolicyChange', (data) => { + this.log('on netBackgroundPolicyChange: ' + JSON.stringify(data)); +}) +``` + +## NetBackgroundPolicy + +Enumerates the background network policies. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value | Description | +| ------------------------ | ---- | ---------------------- | +| NET_BACKGROUND_POLICY_NONE | 0 | Default policy.| +| NET_BACKGROUND_POLICY_ENABLE | 1 | Applications running in the background are allowed to access metered networks.| +| NET_BACKGROUND_POLICY_DISABLE | 2 | Applications running in the background are not allowed to access metered networks.| +| NET_BACKGROUND_POLICY_ALLOW_LIST | 3 | Only applications on the device idle allowlist are allowed to access metered networks when they are running in the background.| + +## NetQuotaPolicy + +Defines a network quota policy. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Type | Description | +| ----------------------- | ----------------------------------- | ------------------------------------------------------------ | +| netType | [NetBearType](js-apis-net-connection.md#netbeartype) | Network type.| +| iccid | string | Identifier of the SIM card on the metered cellular network. It is not used for Wi-Fi networks.| +| ident | string | Identifier of the SIM card on the metered cellular network. It is used for Wi-Fi networks. It is used together with **iccid**.| +| periodDuration | string | Start time of metering.| +| warningBytes | number | Data volume threshold for generating an alarm.| +| limitBytes | number | Data volume quota.| +| lastWarningRemind | string | Last time when an alarm was generated.| +| lastLimitRemind | string | Last time when the quota was exhausted.| +| metered | string | Whether the network is a metered network.| +| limitAction | [LimitAction](#limitaction) | Action to take when the data volume quota is reached.| + +## LimitAction + +Enumerates the actions that can be taken when the data volume quota is reached. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value| Description | +| ---------------------- | ----- | ------------ | +| LIMIT_ACTION_NONE | -1 | Default action.| +| LIMIT_ACTION_DISABLE | 0 | Internet access is disabled.| +| LIMIT_ACTION_AUTO_BILL| 1 | Users will be automatically charged for the data volume they use.| + +## NetUidRule + +Enumerates the metered network rules. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value| Description | +| ---------------------- | ----- | ------------ | +| NET_RULE_NONE | 0 | Default rule.| +| NET_RULE_ALLOW_METERED_FOREGROUND | 1 | Applications running in the foreground are allowed to access metered networks.| +| NET_RULE_ALLOW_METERED | 2 | Applications are allowed to access metered networks.| +| NET_RULE_REJECT_METERED | 4 | Applications are not allowed to access metered networks.| +| NET_RULE_ALLOW_ALL | 32 | Applications are allowed to access all networks (metered or non-metered).| +| NET_RULE_REJECT_ALL | 64 | Applications are not allowed to access any networks (metered or non-metered).| + +## RemindType + +Enumerates the reminder types. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value| Description | +| ---------------------- | - | ------- | +| REMIND_TYPE_WARNING | 1 | Warning.| +| REMIND_TYPE_LIMIT | 2 | Limit.| + +## NetUidPolicy + +Enumerates the application-specific network policies. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value| Description | +| ---------------------- | ----- | ------------ | +| NET_POLICY_NONE | 0 | Default network policy.| +| NET_POLICY_ALLOW_METERED_BACKGROUND | 1 | Applications running in the background are allowed to access metered networks.| +| NET_POLICY_REJECT_METERED_BACKGROUND | 2 | Applications running in the background are not allowed to access metered networks.| diff --git a/en/application-dev/reference/apis/js-apis-net-sharing.md b/en/application-dev/reference/apis/js-apis-net-sharing.md new file mode 100644 index 0000000000000000000000000000000000000000..23284aeb1715a3f8aed9ec7b2d79ad55d1408319 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-net-sharing.md @@ -0,0 +1,746 @@ +# Network Sharing Management + +The Network Sharing Management module allows you to share your device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing. It also allows you to query the network sharing state and shared mobile data volume. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import sharing from '@ohos.net.sharing' +``` + +## sharing.isSharingSupported + +isSharingSupported(callback: AsyncCallback\): void + +Checks whether network sharing is supported. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that network sharing is supported, and **false** means the opposite.| + +**Example** + +```js +sharing.isSharingSupported((error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## sharing.isSharingSupported + +isSharingSupported(): Promise\ + +Checks whether network sharing is supported. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result. The value **true** means that network sharing is supported, and **false** means the opposite.| + +**Example** + +```js +sharing.isSharingSupported().then(data => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); +``` + +## sharing.isSharing + +isSharing(callback: AsyncCallback\): void + +Checks whether network sharing is in progress. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that network sharing is in progress, and **false** means the opposite.| + +**Example** + +```js +sharing.isSharing((error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## sharing.isSharing + +isSharing(): Promise\ + +Checks whether network sharing is in progress. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result. The value **true** means that network sharing is in progress, and **false** means the opposite.| + +**Example** + +```js +sharing.isSharing().then(data => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); +``` + +## sharing.startSharing + +startSharing(type: SharingIfaceType, callback: AsyncCallback\): void + +Starts network sharing of a specified type. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +import SharingIfaceType from '@ohos.net.sharing' +sharing.startSharing(SharingIfaceType.SHARING_WIFI, (error) => { + console.log(JSON.stringify(error)); +}); +``` + +## sharing.startSharing + +startSharing(type: SharingIfaceType): Promise\ + +Starts network sharing of a specified type. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +import SharingIfaceType from '@ohos.net.sharing' +sharing.startSharing(SharingIfaceType.SHARING_WIFI).then(() => { + console.log("start wifi sharing successful"); +}).catch(error => { + console.log("start wifi sharing failed"); +}); +``` + +## sharing.stopSharing + +stopSharing(type: SharingIfaceType, callback: AsyncCallback\): void + +Stops network sharing of a specified type. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +import SharingIfaceType from '@ohos.net.sharing' +sharing.stopSharing(SharingIfaceType.SHARING_WIFI, (error) => { + console.log(JSON.stringify(error)); +}); +``` + +## sharing.stopSharing + +stopSharing(type: SharingIfaceType): Promise\ + +Stops network sharing of a specified type. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +import SharingIfaceType from '@ohos.net.sharing' +sharing.stopSharing(SharingIfaceType.SHARING_WIFI).then(() => { + console.log("stop wifi sharing successful"); +}).catch(error => { + console.log("stop wifi sharing failed"); +}); +``` + +## sharing.getStatsRxBytes + +getStatsRxBytes(callback: AsyncCallback\): void + +Obtains the volume of mobile data traffic received via network sharing. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in KB.| + +**Example** + +```js +sharing.getStatsRxBytes((error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## sharing.getStatsRxBytes + +getStatsRxBytes(): Promise\ + +Obtains the volume of mobile data traffic received via network sharing. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in KB.| + +**Example** + +```js +sharing.getStatsRxBytes().then(data => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); +``` + +## sharing.getStatsTxBytes + +getStatsTxBytes(callback: AsyncCallback\): void + +Obtains the volume of mobile data traffic sent via network sharing. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in KB.| + +**Example** + +```js +sharing.getStatsTxBytes((error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## sharing.getStatsTxBytes + +getStatsTxBytes(): Promise\ + +Obtains the volume of mobile data traffic sent via network sharing. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in KB.| + +**Example** + +```js +sharing.getStatsTxBytes().then(data => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); +``` + +## sharing.getStatsTotalBytes + +getStatsTotalBytes(callback: AsyncCallback\): void + +Obtains the volume of mobile data traffic sent and received via network sharing. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in KB.| + +**Example** + +```js +sharing.getStatsTotalBytes((error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## sharing.getStatsTotalBytes + +getStatsTotalBytes(): Promise\ + +Obtains the volume of mobile data traffic sent and received via network sharing. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in KB.| + +**Example** + +```js +sharing.getStatsTotalBytes().then(data => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); +``` + +## sharing.getSharingIfaces + +getSharingIfaces(state: SharingIfaceState, callback: AsyncCallback\>): void + +Obtains the names of NICs in the specified network sharing state. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| state | state: [SharingIfaceState](#sharingifacestate) | Yes | Network sharing state.| +| callback | AsyncCallback\> | Yes | Callback used to return an array of NIC names.| + +**Example** + +```js +import SharingIfaceState from '@ohos.net.sharing' +sharing.getSharingIfaces(SharingIfaceState.SHARING_NIC_CAN_SERVER, (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## sharing.getSharingIfaces + +getSharingIfaces(state: SharingIfaceState): Promise\> + +Obtains the names of NICs in the specified network sharing state. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| state | state: [SharingIfaceState](#sharingifacestate) | Yes | Network sharing state.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\> | Promise used to return an array of NIC names.| + +**Example** + +```js +import SharingIfaceState from '@ohos.net.sharing' +sharing.getSharingIfaces(SharingIfaceState.SHARING_NIC_CAN_SERVER).then(data => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); +``` + +## sharing.getSharingState + +getSharingState(type: SharingIfaceType, callback: AsyncCallback\): void + +Obtains the network sharing state of the specified type. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| +| callback | AsyncCallback\<[SharingIfaceState](#sharingifacestate)> | Yes | Callback used to return the network sharing state.| + +**Example** + +```js +import SharingIfaceState from '@ohos.net.sharing' +sharing.getSharingState(SharingIfaceType.SHARING_WIFI, (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## sharing.getSharingState + +getSharingState(type: SharingIfaceType): Promise\ + +Obtains the network sharing state of the specified type. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\<[SharingIfaceState](#sharingifacestate)> | Promise used to return the network sharing state.| + +**Example** + +```js +import SharingIfaceType from '@ohos.net.sharing' +sharing.getSharingIfaces(SharingIfaceType.SHARING_WIFI).then(data => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); +``` + +## sharing.getSharableRegexes + +getSharableRegexes(type: SharingIfaceType, callback: AsyncCallback\>): void + +Obtains regular expressions of NICs of a specified type. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| +| callback | AsyncCallback\> | Yes | Callback used to return an array of regular expressions.| + +**Example** + +```js +import SharingIfaceState from '@ohos.net.sharing' +sharing.getSharingState(SharingIfaceType.SHARING_WIFI, (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## sharing.getSharableRegexes + +getSharableRegexes(type: SharingIfaceType): Promise\> + +Obtains regular expressions of NICs of a specified type. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\> | Promise used to return an array of regular expressions.| + +**Example** + +```js +import SharingIfaceType from '@ohos.net.sharing' +sharing.getSharableRegexes(SharingIfaceType.SHARING_WIFI).then(data => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); +``` + +## on('sharingStateChange') + +on(type: 'sharingStateChange', callback: Callback\): void + +Subscribes to network sharing state changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | string | Yes | Event name.| +| callback | AsyncCallback\ | Yes | Callback used to return the network sharing state.| + +**Example** + +```js +sharing.on('sharingStateChange', (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## off('sharingStateChange') + +off(type: 'sharingStateChange', callback?: Callback\): void + +Unsubscribes from network sharing state changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | string | Yes | Event name.| +| callback | AsyncCallback\ | No | Callback used for unsubscription.| + +**Example** + +```js +sharing.off('sharingStateChange', (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## on('interfaceSharingStateChange') + +on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void + +Subscribes to network sharing state changes of a specified NIC. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | string | Yes | Event name.| +| callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | Yes | Callback invoked when the network sharing state of the specified NIC changes.| + +**Example** + +```js +sharing.on('interfaceSharingStateChange', (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## off('interfaceSharingStateChange') + +off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void + +Unsubscribes from network sharing status changes of a specified NIC. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | string | No | Event name.| +| callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | No | Callback used for unsubscription.| + +**Example** + +```js +sharing.off('interfaceSharingStateChange', (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## on('sharingUpstreamChange') + +on(type: 'sharingUpstreamChange', callback: Callback\): void + +Subscribes to upstream network changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | string | Yes | Event name.| +| callback | AsyncCallback\ | Yes | Callback invoked when the upstream network changes.| + +**Example** + +```js +sharing.on('sharingUpstreamChange', (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## off('sharingUpstreamChange') + +off(type: 'sharingUpstreamChange', callback?: Callback\): void + +Unsubscribes from upstream network changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | string | Yes | Event name.| +| callback | AsyncCallback\ | No | Callback used for unsubscription.| + +**Example** + +```js +sharing.off('sharingUpstreamChange', (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## SharingIfaceState + +Enumerates the network sharing states of an NIC. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value | Description | +| ------------------------ | ---- | ---------------------- | +| SHARING_NIC_SERVING | 1 | Network sharing is in progress.| +| SHARING_NIC_CAN_SERVER | 2 | Network sharing is supported.| +| SHARING_NIC_ERROR | 3 | An error occurred during network sharing.| + +## SharingIfaceType + +Enumerates the network sharing types of an NIC. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value | Description | +| ------------------------ | ---- | ---------------------- | +| SHARING_WIFI | 0 | Wi-Fi hotspot sharing.| +| SHARING_USB | 1 | USB sharing.| +| SHARING_BLUETOOTH | 2 | Bluetooth sharing.| diff --git a/en/application-dev/reference/apis/js-apis-net-statistics.md b/en/application-dev/reference/apis/js-apis-net-statistics.md new file mode 100644 index 0000000000000000000000000000000000000000..37d470deb661f185c4d87aa0259d67f38324651e --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-net-statistics.md @@ -0,0 +1,409 @@ +# Network Traffic Management + +The Network Traffic Management module collects statistics on the mobile data traffic and allows you to query the data volume by network interface (cellular or Wi-Fi) or application. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import statistics from '@ohos.net.statistics' +``` + +## statistics.getIfaceRxBytes + +getIfaceRxBytes(nic: string, callback: AsyncCallback\): void + +Obtains the volume of mobile data traffic received by a specified NIC. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| nic | string | Yes | NIC name.| +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getIfaceRxBytes(this.nic, (err, data) => { + this.callBack(err, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getIfaceRxBytes + +getIfaceRxBytes(nic: string): Promise\; + +Obtains the volume of mobile data traffic received by a specified NIC. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| nic | string | Yes | NIC name.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getIfaceRxBytes(this.nic).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getIfaceTxBytes + +getIfaceTxBytes(nic: string, callback: AsyncCallback\): void + +Obtains the volume of mobile data traffic sent by a specified NIC. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| nic | string | Yes | NIC name.| +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getIfaceTxBytes(this.nic, (err, data) => { + this.callBack(err, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getIfaceTxBytes + +getIfaceTxBytes(nic: string): Promise\; + +Obtains the volume of mobile data traffic sent by a specified NIC. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| nic | string | Yes | NIC name.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getIfaceTxBytes(this.nic).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getCellularRxBytes + +getCellularRxBytes(callback: AsyncCallback\): void; + +Obtains the volume of mobile data traffic received by the cellular network. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getCellularRxBytes((err, data) => { + this.callBack(err, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getCellularRxBytes + +getCellularRxBytes(): Promise\; + +Obtains the volume of mobile data traffic received by the cellular network. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getCellularRxBytes().then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getCellularTxBytes + +getCellularTxBytes(callback: AsyncCallback\): void; + +Obtains the volume of mobile data traffic sent by the cellular network. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getCellularTxBytes((err, data) => { + this.callBack(err, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getCellularTxBytes + +getCellularTxBytes(): Promise\; + +Obtains the volume of mobile data traffic sent by the cellular network. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getCellularTxBytes().then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getAllRxBytes + +getAllRxBytes(callback: AsyncCallback\): void; + +Obtains the volume of mobile data traffic received by all NICs. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getAllRxBytes(err, data) => { + this.callBack(err, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getAllRxBytes + +getAllRxBytes(): Promise\; + +Obtains the volume of mobile data traffic received by all NICs. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getAllRxBytes().then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getAllTxBytes + +getAllTxBytes(callback: AsyncCallback\): void; + +Obtains the volume of mobile data traffic sent by all NICs. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getAllTxBytes((err, data) => { + this.callBack(err, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getAllTxBytes + +getAllTxBytes(): Promise\; + +Obtains the volume of mobile data traffic sent by all NICs. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getAllTxBytes().then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getUidRxBytes + +getUidRxBytes(uid: number, callback: AsyncCallback\): void; + +Obtains the volume of mobile data traffic received by a specified application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes | Application ID.| +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getUidRxBytes(this.uid, (err, data) => { + this.callBack(err, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getUidRxBytes + +getUidRxBytes(uid: number): Promise\; + +Obtains the volume of mobile data traffic received by a specified application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes | Application ID.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getUidRxBytes(this.uid).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getUidTxBytes + +getUidTxBytes(uid: number, callback: AsyncCallback\): void; + +Obtains the volume of mobile data traffic sent by a specified application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes | Application ID.| +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getUidTxBytes(this.uid, (err, data) => { + this.callBack(err, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getUidTxBytes + +getUidTxBytes(uid: number): Promise\; + +Obtains the volume of mobile data traffic sent by a specified application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes | Application ID.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getUidTxBytes(this.uid).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` diff --git a/en/application-dev/reference/apis/js-apis-nfcController.md b/en/application-dev/reference/apis/js-apis-nfcController.md index c8a9d7cf699963e494c5f04c1d5e887e8795eb0f..105af3cf95ca3a052faddbb6fe632940169fbcd1 100644 --- a/en/application-dev/reference/apis/js-apis-nfcController.md +++ b/en/application-dev/reference/apis/js-apis-nfcController.md @@ -1,6 +1,6 @@ # Standard NFC -The **nfcController** module implements Near-Field Communication (NFC). +The **nfcController** module provides APIs for opening and closing Near-Field Communication (NFC) and reading the NFC state. > **NOTE**
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -12,12 +12,24 @@ The **nfcController** module implements Near-Field Communication (NFC). import controller from '@ohos.nfc.controller'; ``` +## NfcState + +Enumerates the NFC states. + +**System capability**: SystemCapability.Communication.NFC.Core + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| STATE_OFF | 1 | NFC is closed (OFF).| +| STATE_TURNING_ON | 2 | NFC is turning on.| +| STATE_ON | 3 | NFC is open (ON).| +| STATE_TURNING_OFF | 4 | NFC is turning off.| ## controller.isNfcAvailable isNfcAvailable(): boolean -Checks whether NFC is available. +Checks whether the device supports NFC. **System capability**: SystemCapability.Communication.NFC.Core @@ -25,7 +37,7 @@ Checks whether NFC is available. | **Type**| **Description**| | -------- | -------- | -| boolean | Returns **true** if NFC is available; returns **false** otherwise.| +| boolean | Returns **true** if the device supports NFC; returns **false** otherwise.| ## controller.openNfc @@ -42,7 +54,7 @@ Opens NFC. | **Type**| **Description**| | -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise. | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## controller.closeNfc @@ -76,7 +88,7 @@ Checks whether NFC is open. ## controller.getNfcState -getNfcState(): NfcState +getNfcState(): [NfcState](#nfcstate) Obtains the NFC state. @@ -86,13 +98,13 @@ Obtains the NFC state. | **Type**| **Description** | | -------- | ---------------------- | -| NfcState | NFC state obtained. For details, see [NfcState](#nfcstate).| +| [NfcState](#nfcstate) | NFC state obtained. For details, see [NfcState](#nfcstate).| ## controller.on('nfcStateChange') -on(type: "nfcStateChange", callback: Callback<NfcState>): void +on(type: "nfcStateChange", callback: Callback<[NfcState](#nfcstate)>): void -Subscribes to NFC state changes. +Subscribes to NFC state changes. A callback will be invoked to return the NFC state when the NFC state changes. **System capability**: SystemCapability.Communication.NFC.Core @@ -101,15 +113,15 @@ Subscribes to NFC state changes. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type to subscribe to. The value is **nfcStateChange**.| - | callback | Callback<NfcState> | Yes| Callback invoked to return the NFC state changes.| + | callback | Callback<[NfcState](#nfcstate)> | Yes| Callback invoked to return the NFC state.| ## controller.off('nfcStateChange') -off(type: "nfcStateChange", callback?: Callback<NfcState>): void +off(type: "nfcStateChange", callback?: Callback<[NfcState](#nfcstate)>): void -Unsubscribes from the NFC state changes. +Unsubscribes from the NFC state changes. The subscriber will not receive NFC state change notifications. **System capability**: SystemCapability.Communication.NFC.Core @@ -118,35 +130,37 @@ Unsubscribes from the NFC state changes. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type to unsubscribe from. The value is **nfcStateChange**.| -| callback | Callback<NfcState> | No| Callback used to return the NFC state changes. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<[NfcState](#nfcstate)> | No| Callback for the NFC state changes. This parameter can be left blank.| **Example** ```js - import nfcController from '@ohos.nfcController'; - - var NFC_STATE_NOTIFY = "nfcStateChange"; - - var recvNfcStateNotifyFunc = result => { - console.info("nfc state receive state: " + result); + import controller from '@ohos.nfc.controller'; + + // Define a callback key. + var NFC_STATE_CALLBACK_KEY = "nfcStateChange"; + + // Register the callback to receive NFC state change notifications. + controller.on(NFC_STATE_CALLBACK_KEY, (err, nfcState)=> { + if (err) { + console.log("controller on callback err: " + err); + } else { + console.log("controller on callback nfcState: " + nfcState); + } + }); + + // Open NFC. Require permission: ohos.permission.MANAGE_SECURE_SETTINGS. + if (!controller.isNfcOpen()) { + var ret = controller.openNfc(); + console.log("controller openNfc ret: " + ret); } - - // Subscribe to the NFC state changes. - nfcController.on(NFC_STATE_NOTIFY, recvNfcStateNotifyFunc); - - // Unsubscribe from the NFC state changes. - nfcController.off(NFC_STATE_NOTIFY, recvNfcStateNotifyFunc); - ``` - -## NfcState - -Enumerates the NFC states. -**System capability**: SystemCapability.Communication.NFC.Core + // Close NFC. Require permission: ohos.permission.MANAGE_SECURE_SETTINGS. + if (controller.isNfcOpen()) { + var ret = controller.closeNfc(); + console.log("controller closeNfc ret: " + ret); + } -| Name| Default Value| Description| -| -------- | -------- | -------- | -| STATE_OFF | 1 | Off| -| STATE_TURNING_ON | 2 | Turning on| -| STATE_ON | 3 | On| -| STATE_TURNING_OFF | 4 | Turning off| + // Unregister the callback. + controller.off(NFC_STATE_CALLBACK_KEY); + ``` diff --git a/en/application-dev/reference/apis/js-apis-notification.md b/en/application-dev/reference/apis/js-apis-notification.md index 2f6cd9a66dcd1a5dcd1d92e126461e307643814f..ff80fc8564758868ec979ff6bf033b7084fea561 100644 --- a/en/application-dev/reference/apis/js-apis-notification.md +++ b/en/application-dev/reference/apis/js-apis-notification.md @@ -34,7 +34,11 @@ Publishes a notification. This API uses an asynchronous callback to return the r ```js // publish callback function publishCallback(err) { - console.info("==========================>publishCallback=======================>"); + if (err.code) { + console.info("publish failed " + JSON.stringify(err)); + } else { + console.info("publish success"); + } } // NotificationRequest object var notificationRequest = { @@ -83,7 +87,7 @@ var notificationRequest = { } } Notification.publish(notificationRequest).then(() => { - console.info("==========================>publishCallback=======================>"); + console.info("publish sucess"); }); ``` @@ -113,7 +117,11 @@ Publishes a notification. This API uses an asynchronous callback to return the r ```js // publish callback function publishCallback(err) { - console.info("==========================>publishCallback=======================>"); + if (err.code) { + console.info("publish failed " + JSON.stringify(err)); + } else { + console.info("publish success"); + } } // ID of the user who receives the notification var userId = 1 @@ -169,7 +177,7 @@ var notificationRequest = { var userId = 1 Notification.publish(notificationRequest, userId).then(() => { - console.info("==========================>publishCallback=======================>"); + console.info("publish sucess"); }); ``` @@ -195,7 +203,11 @@ Cancels a notification with the specified ID and label. This API uses an asynchr ```js // cancel callback function cancelCallback(err) { - console.info("==========================>cancelCallback=======================>"); + if (err.code) { + console.info("cancel failed " + JSON.stringify(err)); + } else { + console.info("cancel success"); + } } Notification.cancel(0, "label", cancelCallback) ``` @@ -221,7 +233,7 @@ Cancels a notification with the specified ID and label. This API uses a promise ```js Notification.cancel(0).then(() => { - console.info("==========================>cancelCallback=======================>"); + console.info("cancel sucess"); }); ``` @@ -247,7 +259,11 @@ Cancels a notification with the specified ID. This API uses an asynchronous call ```js // cancel callback function cancelCallback(err) { - console.info("==========================>cancelCallback=======================>"); + if (err.code) { + console.info("cancel failed " + JSON.stringify(err)); + } else { + console.info("cancel success"); + } } Notification.cancel(0, cancelCallback) ``` @@ -273,7 +289,11 @@ Cancels all notifications. This API uses an asynchronous callback to return the ```js // cancel callback function cancelAllCallback(err) { - console.info("==========================>cancelAllCallback=======================>"); + if (err.code) { + console.info("cancelAll failed " + JSON.stringify(err)); + } else { + console.info("cancelAll success"); + } } Notification.cancelAll(cancelAllCallback) ``` @@ -292,7 +312,7 @@ Cancels all notifications. This API uses a promise to return the result. ```js Notification.cancelAll().then(() => { - console.info("==========================>cancelAllCallback=======================>"); + console.info("cancelAll sucess"); }); ``` @@ -322,7 +342,11 @@ Adds a notification slot. This API uses an asynchronous callback to return the r ```js // addSlot callback function addSlotCallBack(err) { - console.info("==========================>addSlotCallBack=======================>"); + if (err.code) { + console.info("addSlot failed " + JSON.stringify(err)); + } else { + console.info("addSlot success"); + } } // NotificationSlot object var notificationSlot = { @@ -359,7 +383,7 @@ var notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION } Notification.addSlot(notificationSlot).then(() => { - console.info("==========================>addSlotCallback=======================>"); + console.info("addSlot sucess"); }); ``` @@ -385,7 +409,11 @@ Adds a notification slot. This API uses an asynchronous callback to return the r ```js // addSlot callback function addSlotCallBack(err) { - console.info("==========================>addSlotCallBack=======================>"); + if (err.code) { + console.info("addSlot failed " + JSON.stringify(err)); + } else { + console.info("addSlot success"); + } } Notification.addSlot(Notification.SlotType.SOCIAL_COMMUNICATION, addSlotCallBack) ``` @@ -410,7 +438,7 @@ Adds a notification slot. This API uses a promise to return the result. ```js Notification.addSlot(Notification.SlotType.SOCIAL_COMMUNICATION).then(() => { - console.info("==========================>addSlotCallback=======================>"); + console.info("addSlot sucess"); }); ``` @@ -440,7 +468,11 @@ Adds multiple notification slots. This API uses an asynchronous callback to retu ```js // addSlots callback function addSlotsCallBack(err) { - console.info("==========================>addSlotsCallBack=======================>"); + if (err.code) { + console.info("addSlots failed " + JSON.stringify(err)); + } else { + console.info("addSlots success"); + } } // NotificationSlot object var notificationSlot = { @@ -485,7 +517,7 @@ var notificationSlotArray = new Array(); notificationSlotArray[0] = notificationSlot; Notification.addSlots(notificationSlotArray).then(() => { - console.info("==========================>addSlotCallback=======================>"); + console.info("addSlots sucess"); }); ``` @@ -511,7 +543,11 @@ Obtains a notification slot of the specified type. This API uses an asynchronous ```js // getSlot callback function getSlotCallback(err,data) { - console.info("==========================>getSlotCallback=======================>"); + if (err.code) { + console.info("getSlot failed " + JSON.stringify(err)); + } else { + console.info("getSlot success"); + } } var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; Notification.getSlot(slotType, getSlotCallback) @@ -544,7 +580,7 @@ Obtains a notification slot of the specified type. This API uses a promise to re ```js var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; Notification.getSlot(slotType).then((data) => { - console.info("==========================>getSlotCallback=======================>"); + console.info("getSlot sucess, data: " + JSON.stringify(data)); }); ``` @@ -569,7 +605,11 @@ Obtains all notification slots. This API uses an asynchronous callback to return ```js // getSlots callback function getSlotsCallback(err,data) { - console.info("==========================>getSlotsCallback=======================>"); + if (err.code) { + console.info("getSlots failed " + JSON.stringify(err)); + } else { + console.info("getSlots success"); + } } Notification.getSlots(getSlotsCallback) ``` @@ -594,7 +634,7 @@ Obtains all notification slots of this application. This API uses a promise to r ```js Notification.getSlots().then((data) => { - console.info("==========================>getSlotsCallback=======================>"); + console.info("getSlots sucess, data: " + JSON.stringify(data)); }); ``` @@ -620,7 +660,11 @@ Removes a notification slot of the specified type. This API uses an asynchronous ```js // removeSlot callback function removeSlotCallback(err) { - console.info("==========================>removeSlotCallback=======================>"); + if (err.code) { + console.info("removeSlot failed " + JSON.stringify(err)); + } else { + console.info("removeSlot success"); + } } var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; Notification.removeSlot(slotType,removeSlotCallback) @@ -647,7 +691,7 @@ Removes a notification slot of the specified type. This API uses a promise to re ```js var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; Notification.removeSlot(slotType).then(() => { - console.info("==========================>removeSlotCallback=======================>"); + console.info("removeSlot sucess"); }); ``` @@ -671,7 +715,11 @@ Removes all notification slots. This API uses an asynchronous callback to return ```js function removeAllCallBack(err) { - console.info("================>removeAllCallBack=======================>"); + if (err.code) { + console.info("removeAllSlots failed " + JSON.stringify(err)); + } else { + console.info("removeAllSlots success"); + } } Notification.removeAllSlots(removeAllCallBack) ``` @@ -690,7 +738,7 @@ Removes all notification slots. This API uses a promise to return the result. ```js Notification.removeAllSlots().then(() => { - console.info("==========================>removeAllCallBack=======================>"); + console.info("removeAllSlots sucess"); }); ``` @@ -721,10 +769,14 @@ Subscribes to a notification with the subscription information specified. This A ```js // subscribe callback function subscribeCallback(err) { - console.info("==========================>subscribeCallback=======================>"); + if (err.code) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribe success"); + } } function onConsumeCallback(data) { - console.info("==========================>onConsumeCallback=======================>"); + console.info("Consume callback: " + JSON.stringify(data)); } var subscriber = { onConsume: onConsumeCallback @@ -760,10 +812,14 @@ Subscribes to a notification with the subscription information specified. This A ```js function subscribeCallback(err) { - console.info("==========================>subscribeCallback=======================>"); + if (err.code) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribe success"); + } } function onConsumeCallback(data) { - console.info("==========================>onConsumeCallback=======================>"); + console.info("Consume callback: " + JSON.stringify(data)); } var subscriber = { onConsume: onConsumeCallback @@ -796,13 +852,17 @@ Subscribes to a notification with the subscription information specified. This A ```js function onConsumeCallback(data) { - console.info("==========================>onConsumeCallback=======================>"); + if (err.code) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribe success"); + } } var subscriber = { onConsume: onConsumeCallback }; Notification.subscribe(subscriber).then(() => { - console.info("==========================>subscribeCallback=======================>"); + console.info("subscribe sucess"); }); ``` @@ -831,13 +891,17 @@ Unsubscribes from a notification. This API uses an asynchronous callback to retu ```js function unsubscribeCallback(err) { - console.info("==========================>unsubscribeCallback=======================>"); + if (err.code) { + console.info("unsubscribe failed " + JSON.stringify(err)); + } else { + console.info("unsubscribe success"); + } } -function onConsumeCallback(data) { - console.info("==========================>onConsumeCallback=======================>"); +function onCancelCallback(data) { + console.info("Cancel callback: " + JSON.stringify(data)); } var subscriber = { - onConsume: onConsumeCallback + onCancel: onCancelCallback } Notification.unsubscribe(subscriber, unsubscribeCallback); ``` @@ -865,14 +929,14 @@ Unsubscribes from a notification. This API uses a promise to return the result. **Example** ```js -function onConsumeCallback(data) { - console.info("==========================>onConsumeCallback=======================>"); +function onCancelCallback(data) { + console.info("Cancel callback: " + JSON.stringify(data)); } var subscriber = { - onConsume: onConsumeCallback + onCancel: onCancelCallback }; Notification.unsubscribe(subscriber).then(() => { - console.info("==========================>unsubscribeCallback=======================>"); + console.info("unsubscribe sucess"); }); ``` @@ -902,7 +966,11 @@ Sets whether to enable notification for a specified bundle. This API uses an asy ```js function enableNotificationCallback(err) { - console.info("==========================>enableNotificationCallback=======================>"); + if (err.code) { + console.info("enableNotification failed " + JSON.stringify(err)); + } else { + console.info("enableNotification success"); + } } var bundle = { bundle: "bundleName1", @@ -938,7 +1006,7 @@ var bundle = { bundle: "bundleName1", } Notification.enableNotification(bundle, false).then(() => { - console.info("==========================>enableNotificationCallback=======================>"); + console.info("enableNotification sucess"); }); ``` @@ -967,7 +1035,11 @@ Checks whether notification is enabled for a specified bundle. This API uses an ```js function isNotificationEnabledCallback(err, data) { - console.info("==========================>isNotificationEnabledCallback=======================>"); + if (err.code) { + console.info("isNotificationEnabled failed " + JSON.stringify(err)); + } else { + console.info("isNotificationEnabled success"); + } } var bundle = { bundle: "bundleName1", @@ -1008,7 +1080,7 @@ var bundle = { bundle: "bundleName1", } Notification.isNotificationEnabled(bundle).then((data) => { - console.info("==========================>isNotificationEnabledCallback=======================>"); + console.info("isNotificationEnabled sucess, data: " + JSON.stringify(data)); }); ``` @@ -1036,7 +1108,11 @@ Checks whether notification is enabled for this application. This API uses an as ```js function isNotificationEnabledCallback(err, data) { - console.info("==========================>isNotificationEnabledCallback=======================>"); + if (err.code) { + console.info("isNotificationEnabled failed " + JSON.stringify(err)); + } else { + console.info("isNotificationEnabled success"); + } } Notification.isNotificationEnabled(isNotificationEnabledCallback); @@ -1072,7 +1148,7 @@ Checks whether notification is enabled for this application. This API uses a pro ```js Notification.isNotificationEnabled().then((data) => { - console.info("==========================>isNotificationEnabledCallback=======================>"); + console.info("isNotificationEnabled sucess, data: " + JSON.stringify(data)); }); ``` @@ -1102,7 +1178,11 @@ Sets whether to enable the notification badge for a specified bundle. This API u ```js function displayBadgeCallback(err) { - console.info("==========================>displayBadgeCallback=======================>"); + if (err.code) { + console.info("displayBadge failed " + JSON.stringify(err)); + } else { + console.info("displayBadge success"); + } } var bundle = { bundle: "bundleName1", @@ -1138,7 +1218,7 @@ var bundle = { bundle: "bundleName1", } Notification.displayBadge(bundle, false).then(() => { - console.info("==========================>displayBadgeCallback=======================>"); + console.info("displayBadge sucess"); }); ``` @@ -1167,7 +1247,11 @@ Checks whether the notification badge is enabled for a specified bundle. This AP ```js function isBadgeDisplayedCallback(err, data) { - console.info("==========================>isBadgeDisplayedCallback=======================>"); + if (err.code) { + console.info("isBadgeDisplayed failed " + JSON.stringify(err)); + } else { + console.info("isBadgeDisplayed success"); + } } var bundle = { bundle: "bundleName1", @@ -1208,7 +1292,7 @@ var bundle = { bundle: "bundleName1", } Notification.isBadgeDisplayed(bundle).then((data) => { - console.info("==========================>isBadgeDisplayedCallback=======================>"); + console.info("isBadgeDisplayed sucess, data: " + JSON.stringify(data)); }); ``` @@ -1238,7 +1322,11 @@ Sets the notification slot for a specified bundle. This API uses an asynchronous ```js function setSlotByBundleCallback(err) { - console.info("==========================>setSlotByBundleCallback=======================>"); + if (err.code) { + console.info("setSlotByBundle failed " + JSON.stringify(err)); + } else { + console.info("setSlotByBundle success"); + } } var bundle = { bundle: "bundleName1", @@ -1280,7 +1368,7 @@ var notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION } Notification.setSlotByBundle(bundle, notificationSlot).then(() => { - console.info("==========================>setSlotByBundleCallback=======================>"); + console.info("setSlotByBundle sucess"); }); ``` @@ -1309,7 +1397,11 @@ Obtains the notification slots of a specified bundle. This API uses an asynchron ```js function getSlotsByBundleCallback(err, data) { - console.info("==========================>getSlotsByBundleCallback=======================>"); + if (err.code) { + console.info("getSlotsByBundle failed " + JSON.stringify(err)); + } else { + console.info("getSlotsByBundle success"); + } } var bundle = { bundle: "bundleName1", @@ -1350,7 +1442,7 @@ var bundle = { bundle: "bundleName1", } Notification.getSlotsByBundle(bundle).then((data) => { - console.info("==========================>getSlotsByBundleCallback=======================>"); + console.info("getSlotsByBundle sucess, data: " + JSON.stringify(data)); }); ``` @@ -1379,7 +1471,11 @@ Obtains the number of notification slots of a specified bundle. This API uses an ```js function getSlotNumByBundleCallback(err, data) { - console.info("==========================>getSlotNumByBundleCallback=======================>"); + if (err.code) { + console.info("getSlotNumByBundle failed " + JSON.stringify(err)); + } else { + console.info("getSlotNumByBundle success"); + } } var bundle = { bundle: "bundleName1", @@ -1420,7 +1516,7 @@ var bundle = { bundle: "bundleName1", } Notification.getSlotNumByBundle(bundle).then((data) => { - console.info("==========================>getSlotNumByBundleCallback=======================>"); + console.info("getSlotNumByBundle sucess, data: " + JSON.stringify(data)); }); ``` @@ -1428,7 +1524,7 @@ Notification.getSlotNumByBundle(bundle).then((data) => { ## Notification.remove -remove(bundle: BundleOption, notificationKey: NotificationKey, callback: AsyncCallback\): void +remove(bundle: BundleOption, notificationKey: NotificationKey, reason: RemoveReason, callback: AsyncCallback\): void Removes a notification for a specified bundle. This API uses an asynchronous callback to return the result. @@ -1441,16 +1537,21 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal **Parameters** | Name | Type | Mandatory| Description | -| --------------- | ----------------------------------- | ---- | -------------------- | +| --------------- | ----------------------------------| ---- | -------------------- | | bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | | notificationKey | [NotificationKey](#notificationkey) | Yes | Notification key. | +| reason | [RemoveReason](#removereason9) | Yes | Indicates the reason for deleting a notification. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** ```js function removeCallback(err) { - console.info("==========================>removeCallback=======================>"); + if (err.code) { + console.info("remove failed " + JSON.stringify(err)); + } else { + console.info("remove success"); + } } var bundle = { bundle: "bundleName1", @@ -1459,14 +1560,15 @@ var notificationKey = { id: 0, label: "label", } -Notification.remove(bundle, notificationKey, removeCallback); +var reason = Notification.RemoveReason.CLICK_REASON_REMOVE; +Notification.remove(bundle, notificationKey, reason, removeCallback); ``` ## Notification.remove -remove(bundle: BundleOption, notificationKey: NotificationKey): Promise\ +remove(bundle: BundleOption, notificationKey: NotificationKey, reason: RemoveReason): Promise\ Removes a notification for a specified bundle. This API uses a promise to return the result. @@ -1482,6 +1584,7 @@ Removes a notification for a specified bundle. This API uses a promise to return | --------------- | --------------- | ---- | ---------- | | bundle | [BundleOption](#bundleoption) | Yes | Bundle information.| | notificationKey | [NotificationKey](#notificationkey) | Yes | Notification key. | +| reason | [RemoveReason](#removereason9) | Yes | Reason for deleting the notification. | **Example** @@ -1493,8 +1596,9 @@ var notificationKey = { id: 0, label: "label", } -Notification.remove(bundle, notificationKey).then(() => { - console.info("==========================>removeCallback=======================>"); +var reason = Notification.RemoveReason.CLICK_REASON_REMOVE; +Notification.remove(bundle, notificationKey, reason).then(() => { + console.info("remove sucess"); }); ``` @@ -1502,7 +1606,7 @@ Notification.remove(bundle, notificationKey).then(() => { ## Notification.remove -remove(hashCode: string, callback: AsyncCallback\): void +remove(hashCode: string, reason: RemoveReason, callback: AsyncCallback\): void Removes a notification for a specified bundle. This API uses an asynchronous callback to return the result. @@ -1517,6 +1621,7 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | -------------------- | | hashCode | string | Yes | Unique notification ID. | +| reason | [RemoveReason](#removereason9) | Yes | Reason for removing the notification. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1525,17 +1630,21 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal var hashCode = 'hashCode' function removeCallback(err) { - console.info("==========================>removeCallback=======================>"); + if (err.code) { + console.info("remove failed " + JSON.stringify(err)); + } else { + console.info("remove success"); + } } - -Notification.remove(hashCode, removeCallback); +var reason = Notification.RemoveReason.CANCEL_REASON_REMOVE; +Notification.remove(hashCode, reason, removeCallback); ``` ## Notification.remove -remove(hashCode: string): Promise\ +remove(hashCode: string, reason: RemoveReason): Promise\ Removes a notification for a specified bundle. This API uses a promise to return the result. @@ -1550,14 +1659,15 @@ Removes a notification for a specified bundle. This API uses a promise to return | Name | Type | Mandatory| Description | | -------- | ---------- | ---- | ---------- | | hashCode | string | Yes | Unique notification ID.| +| reason | [RemoveReason](#removereason9) | Yes | Reason for removing the notification. | **Example** ```js var hashCode = 'hashCode' - -Notification.remove(hashCode).then(() => { - console.info("==========================>removeCallback=======================>"); +var reason = Notification.RemoveReason.CLICK_REASON_REMOVE; +Notification.remove(hashCode, reason).then(() => { + console.info("remove sucess"); }); ``` @@ -1586,7 +1696,11 @@ Removes all notifications for a specified bundle. This API uses an asynchronous ```js function removeAllCallback(err) { - console.info("==========================>removeAllCallback=======================>"); + if (err.code) { + console.info("removeAll failed " + JSON.stringify(err)); + } else { + console.info("removeAll success"); + } } var bundle = { bundle: "bundleName1", @@ -1618,7 +1732,11 @@ Removes all notifications. This API uses an asynchronous callback to return the ```js function removeAllCallback(err) { - console.info("==========================>removeAllCallback=======================>"); + if (err.code) { + console.info("removeAll failed " + JSON.stringify(err)); + } else { + console.info("removeAll success"); + } } Notification.removeAll(removeAllCallback); @@ -1648,7 +1766,7 @@ Removes all notifications for a specified user. This API uses a promise to retur ```js Notification.removeAll().then(() => { - console.info("==========================>removeAllCallback=======================>"); + console.info("removeAll sucess"); }); ``` @@ -1675,7 +1793,11 @@ Removes all notifications for a specified user. This API uses an asynchronous ca ```js function removeAllCallback(err) { - console.info("==========================>removeAllCallback=======================>"); + if (err.code) { + console.info("removeAll failed " + JSON.stringify(err)); + } else { + console.info("removeAll success"); + } } var userId = 1 @@ -1705,7 +1827,11 @@ Removes all notifications for a specified user. This API uses a promise to retur ```js function removeAllCallback(err) { - console.info("==========================>removeAllCallback=======================>"); + if (err.code) { + console.info("removeAll failed " + JSON.stringify(err)); + } else { + console.info("removeAll success"); + } } var userId = 1 @@ -1736,7 +1862,11 @@ Obtains all active notifications. This API uses an asynchronous callback to retu ```js function getAllActiveNotificationsCallback(err, data) { - console.info("==========================>getAllActiveNotificationsCallback=======================>"); + if (err.code) { + console.info("getAllActiveNotifications failed " + JSON.stringify(err)); + } else { + console.info("getAllActiveNotifications success"); + } } Notification.getAllActiveNotifications(getAllActiveNotificationsCallback); @@ -1766,7 +1896,7 @@ Obtains all active notifications. This API uses a promise to return the result. ```js Notification.getAllActiveNotifications().then((data) => { - console.info("==========================>getAllActiveNotificationsCallback=======================>"); + console.info("getAllActiveNotifications sucess, data: " + JSON.stringify(data)); }); ``` @@ -1790,7 +1920,11 @@ Obtains the number of active notifications. This API uses an asynchronous callba ```js function getActiveNotificationCountCallback(err, data) { - console.info("==========================>getActiveNotificationCountCallback=======================>"); + if (err.code) { + console.info("getActiveNotificationCount failed " + JSON.stringify(err)); + } else { + console.info("getActiveNotificationCount success"); + } } Notification.getActiveNotificationCount(getActiveNotificationCountCallback); @@ -1816,7 +1950,7 @@ Obtains the number of active notifications. This API uses a promise to return th ```js Notification.getActiveNotificationCount().then((data) => { - console.info("==========================>getActiveNotificationCountCallback=======================>"); + console.info("getActiveNotificationCount sucess, data: " + JSON.stringify(data)); }); ``` @@ -1840,7 +1974,11 @@ Obtains active notifications of this application. This API uses an asynchronous ```js function getActiveNotificationsCallback(err, data) { - console.info("==========================>getActiveNotificationsCallback=======================>"); + if (err.code) { + console.info("getActiveNotifications failed " + JSON.stringify(err)); + } else { + console.info("getActiveNotifications success"); + } } Notification.getActiveNotifications(getActiveNotificationsCallback); @@ -1866,7 +2004,7 @@ Obtains active notifications of this application. This API uses a promise to ret ```js Notification.getActiveNotifications().then((data) => { - console.info("==========================>getActiveNotificationsCallback=======================>"); + console.info("removeGroupByBundle sucess, data: " + JSON.stringify(data)); }); ``` @@ -1891,7 +2029,11 @@ Cancels a notification group of this application. This API uses an asynchronous ```js function cancelGroupCallback(err) { - console.info("==========================>cancelGroupCallback=======================>"); + if (err.code) { + console.info("cancelGroup failed " + JSON.stringify(err)); + } else { + console.info("cancelGroup success"); + } } var groupName = "GroupName"; @@ -1920,7 +2062,7 @@ Cancels a notification group of this application. This API uses a promise to ret ```js var groupName = "GroupName"; Notification.cancelGroup(groupName).then(() => { - console.info("==========================>cancelGroupPromise=======================>"); + console.info("cancelGroup sucess"); }); ``` @@ -1950,7 +2092,11 @@ Removes a notification group for a specified bundle. This API uses an asynchrono ```js function removeGroupByBundleCallback(err) { - console.info("==========================>removeGroupByBundleCallback=======================>"); + if (err.code) { + console.info("removeGroupByBundle failed " + JSON.stringify(err)); + } else { + console.info("removeGroupByBundle success"); + } } var bundleOption = {bundle: "Bundle"}; @@ -1986,7 +2132,7 @@ Removes a notification group for a specified bundle. This API uses a promise to var bundleOption = {bundle: "Bundle"}; var groupName = "GroupName"; Notification.removeGroupByBundle(bundleOption, groupName).then(() => { - console.info("==========================>removeGroupByBundlePromise=======================>"); + console.info("removeGroupByBundle sucess"); }); ``` @@ -2015,7 +2161,11 @@ Sets the DND time. This API uses an asynchronous callback to return the result. ```js function setDoNotDisturbDateCallback(err) { - console.info("==========================>setDoNotDisturbDateCallback=======================>"); + if (err.code) { + console.info("setDoNotDisturbDate failed " + JSON.stringify(err)); + } else { + console.info("setDoNotDisturbDate success"); + } } var doNotDisturbDate = { @@ -2056,7 +2206,7 @@ var doNotDisturbDate = { end: new Date(2021, 11, 15, 18, 0) } Notification.setDoNotDisturbDate(doNotDisturbDate).then(() => { - console.info("==========================>setDoNotDisturbDatePromise=======================>"); + console.info("setDoNotDisturbDate sucess"); }); ``` @@ -2085,7 +2235,11 @@ Sets the DND time for a specified user. This API uses an asynchronous callback t ```js function setDoNotDisturbDateCallback(err) { - console.info("==========================>setDoNotDisturbDateCallback=======================>"); + if (err.code) { + console.info("setDoNotDisturbDate failed " + JSON.stringify(err)); + } else { + console.info("setDoNotDisturbDate success"); + } } var doNotDisturbDate = { @@ -2132,7 +2286,7 @@ var doNotDisturbDate = { var userId = 1 Notification.setDoNotDisturbDate(doNotDisturbDate, userId).then(() => { - console.info("==========================>setDoNotDisturbDatePromise=======================>"); + console.info("setDoNotDisturbDate sucess"); }); ``` @@ -2159,7 +2313,11 @@ Obtains the DND time. This API uses an asynchronous callback to return the resul ```js function getDoNotDisturbDateCallback(err,data) { - console.info("==========================>getDoNotDisturbDateCallback=======================>"); + if (err.code) { + console.info("getDoNotDisturbDate failed " + JSON.stringify(err)); + } else { + console.info("getDoNotDisturbDate success"); + } } Notification.getDoNotDisturbDate(getDoNotDisturbDateCallback); @@ -2189,7 +2347,7 @@ Obtains the DND time. This API uses a promise to return the result. ```js Notification.getDoNotDisturbDate().then((data) => { - console.info("==========================>getDoNotDisturbDatePromise=======================>"); + console.info("getDoNotDisturbDate sucess, data: " + JSON.stringify(data)); }); ``` @@ -2217,7 +2375,11 @@ Obtains the DND time of a specified user. This API uses an asynchronous callback ```js function getDoNotDisturbDateCallback(err,data) { - console.info("==========================>getDoNotDisturbDateCallback=======================>"); + if (err.code) { + console.info("getDoNotDisturbDate failed " + JSON.stringify(err)); + } else { + console.info("getDoNotDisturbDate success"); + } } var userId = 1 @@ -2257,7 +2419,7 @@ Obtains the DND time of a specified user. This API uses a promise to return the var userId = 1 Notification.getDoNotDisturbDate(userId).then((data) => { - console.info("==========================>getDoNotDisturbDatePromise=======================>"); + console.info("getDoNotDisturbDate sucess, data: " + JSON.stringify(data)); }); ``` @@ -2284,7 +2446,11 @@ Checks whether the DND mode is supported. This API uses an asynchronous callback ```js function supportDoNotDisturbModeCallback(err,data) { - console.info("==========================>supportDoNotDisturbModeCallback=======================>"); + if (err.code) { + console.info("supportDoNotDisturbMode failed " + JSON.stringify(err)); + } else { + console.info("supportDoNotDisturbMode success"); + } } Notification.supportDoNotDisturbMode(supportDoNotDisturbModeCallback); @@ -2314,7 +2480,7 @@ Checks whether the DND mode is supported. This API uses a promise to return the ```js Notification.supportDoNotDisturbMode().then((data) => { - console.info("==========================>supportDoNotDisturbModePromise=======================>"); + console.info("supportDoNotDisturbMode sucess, data: " + JSON.stringify(data)); }); ``` @@ -2340,7 +2506,11 @@ Checks whether a specified template exists. This API uses an asynchronous callba ```javascript var templateName = 'process'; function isSupportTemplateCallback(err, data) { - console.info("isSupportTemplateCallback"); + if (err.code) { + console.info("isSupportTemplate failed " + JSON.stringify(err)); + } else { + console.info("isSupportTemplate success"); + } } Notification.isSupportTemplate(templateName, isSupportTemplateCallback); @@ -2374,7 +2544,7 @@ Checks whether a specified template exists. This API uses a promise to return th var templateName = 'process'; Notification.isSupportTemplate(templateName).then((data) => { - console.info("isSupportTemplateCallback"); + console.info("isSupportTemplate success, data: " + JSON.stringify(data)); }); ``` @@ -2398,7 +2568,11 @@ Requests notification to be enabled for this application. This API uses an async ```javascript function requestEnableNotificationCallback() { - console.log('------------- requestEnabledNotification --------------'); + if (err.code) { + console.info("requestEnableNotification failed " + JSON.stringify(err)); + } else { + console.info("requestEnableNotification success"); + } }; Notification.requestEnableNotification(requestEnableNotificationCallback); @@ -2419,7 +2593,7 @@ Requests notification to be enabled for this application. This API uses a promis ```javascript Notification.requestEnableNotification() .then(() => { - console.info("requestEnableNotification "); + console.info("requestEnableNotification sucess"); }); ``` @@ -2447,7 +2621,11 @@ Sets whether this device supports distributed notifications. This API uses an as ```javascript function enabledNotificationCallback() { - console.log('----------- enableDistributed ------------'); + if (err.code) { + console.info("enableDistributed failed " + JSON.stringify(err)); + } else { + console.info("enableDistributed success"); + } }; var enable = true @@ -2482,7 +2660,7 @@ var enable = true Notification.enableDistributed(enable) .then(() => { - console.log('-------- enableDistributed ----------'); + console.info("enableDistributed sucess"); }); ``` @@ -2505,7 +2683,11 @@ Obtains whether this device supports distributed notifications. This API uses an ```javascript function isDistributedEnabledCallback() { - console.log('----------- isDistributedEnabled ------------'); + if (err.code) { + console.info("isDistributedEnabled failed " + JSON.stringify(err)); + } else { + console.info("isDistributedEnabled success"); + } }; Notification.isDistributedEnabled(isDistributedEnabledCallback); @@ -2532,7 +2714,7 @@ Obtains whether this device supports distributed notifications. This API uses a ```javascript Notification.isDistributedEnabled() .then((data) => { - console.log('-------- isDistributedEnabled ----------'); + console.info("isDistributedEnabled sucess, data: " + JSON.stringify(data)); }); ``` @@ -2561,7 +2743,11 @@ Sets whether an application supports distributed notifications based on the bund ```javascript function enableDistributedByBundleCallback() { - console.log('----------- enableDistributedByBundle ------------'); + if (err.code) { + console.info("enableDistributedByBundle failed " + JSON.stringify(err)); + } else { + console.info("enableDistributedByBundle success"); + } }; var bundle = { @@ -2605,7 +2791,7 @@ var enable = true Notification.enableDistributedByBundle(bundle, enable) .then(() => { - console.log('-------- enableDistributedByBundle ----------'); + console.info("enableDistributedByBundle sucess"); }); ``` @@ -2632,7 +2818,11 @@ Obtains whether an application supports distributed notifications based on the b ```javascript function isDistributedEnabledByBundleCallback(data) { - console.log('----------- isDistributedEnabledByBundle ------------', data); + if (err.code) { + console.info("isDistributedEnabledByBundle failed " + JSON.stringify(err)); + } else { + console.info("isDistributedEnabledByBundle success"); + } }; var bundle = { @@ -2677,7 +2867,7 @@ var bundle = { Notification.isDistributedEnabledByBundle(bundle) .then((data) => { - console.log('-------- isDistributedEnabledByBundle ----------', data); + console.info("isDistributedEnabledByBundle sucess, data: " + JSON.stringify(data)); }); ``` @@ -2704,7 +2894,11 @@ Obtains the notification reminder type. This API uses an asynchronous callback t ```javascript function getDeviceRemindTypeCallback(data) { - console.log('----------- getDeviceRemindType ------------', data); + if (err.code) { + console.info("getDeviceRemindType failed " + JSON.stringify(err)); + } else { + console.info("getDeviceRemindType success"); + } }; Notification.getDeviceRemindType(getDeviceRemindTypeCallback); @@ -2735,7 +2929,7 @@ Obtains the notification reminder type. This API uses a promise to return the re ```javascript Notification.getDeviceRemindType() .then((data) => { - console.log('-------- getDeviceRemindType ----------', data); + console.info("getDeviceRemindType sucess, data: " + JSON.stringify(data)); }); ``` @@ -2766,7 +2960,11 @@ Publishes an agent-powered notification. This API uses an asynchronous callback ```js // Callback for publishAsBundle function publishAsBundleCallback(err) { - console.info("==========================>publishAsBundleCallback=======================>"); + if (err.code) { + console.info("publishAsBundle failed " + JSON.stringify(err)); + } else { + console.info("publishAsBundle success"); + } } // Bundle name of the application whose notification function is taken over by the reminder agent let representativeBundle = "com.example.demo" @@ -2830,7 +3028,7 @@ var notificationRequest = { } Notification.publishAsBundle(notificationRequest, representativeBundle, userId).then(() => { - console.info("==========================>publishAsBundleCallback=======================>"); + console.info("publishAsBundle sucess"); }); ``` @@ -2862,7 +3060,11 @@ Cancels a notification published by the reminder agent. This API uses an asynchr ```js //cancelAsBundle function cancelAsBundleCallback(err) { - console.info("==========================>cancelAsBundleCallback=======================>"); + if (err.code) { + console.info("cancelAsBundle failed " + JSON.stringify(err)); + } else { + console.info("cancelAsBundle success"); + } } // Bundle name of the application whose notification function is taken over by the reminder agent let representativeBundle = "com.example.demo" @@ -2903,7 +3105,7 @@ let representativeBundle = "com.example.demo" let userId = 100 Notification.cancelAsBundle(0, representativeBundle, userId).then(() => { - console.info("==========================>cancelAsBundleCallback=======================>"); + console.info("cancelAsBundle success"); }); ``` @@ -2933,7 +3135,11 @@ Sets the enabled status for a notification slot of a specified type. This API us ```js //enableNotificationSlot function enableSlotCallback(err) { - console.log('===================>enableSlotCallback==================>'); + if (err.code) { + console.info("enableNotificationSlot failed " + JSON.stringify(err)); + } else { + console.info("enableNotificationSlot success"); + } }; Notification.enableNotificationSlot( @@ -2971,7 +3177,7 @@ Notification.enableNotificationSlot( { bundle: "ohos.samples.notification", }, Notification.SlotType.SOCIAL_COMMUNICATION, true).then(() => { - console.log('====================>enableNotificationSlot====================>'); + console.info("enableNotificationSlot sucess"); }); ``` @@ -3000,7 +3206,11 @@ Obtains the enabled status of the notification slot of a specified type. This AP ```js //isNotificationSlotEnabled function getEnableSlotCallback(err, data) { - console.log('===================>getEnableSlotCallback=================='); + if (err.code) { + console.info("isNotificationSlotEnabled failed " + JSON.stringify(err)); + } else { + console.info("isNotificationSlotEnabled success"); + } }; Notification.isNotificationSlotEnabled( @@ -3042,7 +3252,7 @@ Notification.isNotificationSlotEnabled( { bundle: "ohos.samples.notification", }, Notification.SlotType.SOCIAL_COMMUNICATION ).then((data) => { - console.log('====================>isNotificationSlotEnabled====================>'); + console.info("isNotificationSlotEnabled success, data: " + JSON.stringify(data)); }); ``` @@ -3074,7 +3284,11 @@ let userId = 100; let enable = true; function setSyncNotificationEnabledWithoutAppCallback(err) { - console.log('setSyncNotificationEnabledWithoutAppCallback'); + if (err.code) { + console.info("setSyncNotificationEnabledWithoutApp failed " + JSON.stringify(err)); + } else { + console.info("setSyncNotificationEnabledWithoutApp success"); + } } Notification.setSyncNotificationEnabledWithoutApp(userId, enable, setSyncNotificationEnabledWithoutAppCallback); @@ -3113,11 +3327,11 @@ let userId = 100; let enable = true; Notification.setSyncNotificationEnabledWithoutApp(userId, enable) - .then((data) => { - console.log('setSyncNotificationEnabledWithoutApp'); + .then(() => { + console.info('setSyncNotificationEnabledWithoutApp'); }) .catch((err) => { - console.log('setSyncNotificationEnabledWithoutApp, err:', err); + console.info('setSyncNotificationEnabledWithoutApp, err:', err); }); ``` @@ -3148,9 +3362,9 @@ let userId = 100; function getSyncNotificationEnabledWithoutAppCallback(data, err) { if (err) { - console.log('getSyncNotificationEnabledWithoutAppCallback, err' + err); + console.info('getSyncNotificationEnabledWithoutAppCallback, err' + err); } else { - console.log('getSyncNotificationEnabledWithoutAppCallback, data' + data); + console.info('getSyncNotificationEnabledWithoutAppCallback, data' + data); } } @@ -3189,10 +3403,10 @@ let userId = 100; Notification.getSyncNotificationEnabledWithoutApp(userId) .then((data) => { - console.log('getSyncNotificationEnabledWithoutApp, data:', data); + console.info('getSyncNotificationEnabledWithoutApp, data:', data); }) .catch((err) => { - console.log('getSyncNotificationEnabledWithoutApp, err:', err); + console.info('getSyncNotificationEnabledWithoutApp, err:', err); }); ``` @@ -3236,7 +3450,7 @@ function onConsumeCallback(data) { let wantAgent = data.wantAgent; wantAgent .getWant(wantAgent) .then((data1) => { - console.log('===> getWant success want:' + JSON.stringify(data1)); + console.info('===> getWant success want:' + JSON.stringify(data1)); }) .catch((err) => { console.error('===> getWant failed because' + JSON.stringify(err)); @@ -3877,3 +4091,14 @@ Notification.subscribe(subscriber, subscribeCallback); | TYPE_NORMAL | 0 | Normal notification. | | TYPE_CONTINUOUS | 1 | Continuous notification. | | TYPE_TIMER | 2 | Timed notification. | + +## RemoveReason9+ + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Value | Description | +| -------------------- | --- | -------------------- | +| CLICK_REASON_REMOVE | 1 | The notification is removed due to a click on it. | +| CANCEL_REASON_REMOVE | 2 | The notification is removed by the user. | diff --git a/en/application-dev/reference/apis/js-apis-permissionrequestresult.md b/en/application-dev/reference/apis/js-apis-permissionrequestresult.md index d133b1b37776187ac1120f42ead17e98273f0db4..b397ba221d3d570e3b5eca2f551ecee228bdfc35 100644 --- a/en/application-dev/reference/apis/js-apis-permissionrequestresult.md +++ b/en/application-dev/reference/apis/js-apis-permissionrequestresult.md @@ -37,4 +37,4 @@ export default class MainAbility extends Ability { | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | permissions | Array<string> | Yes| No| Permissions requested.| -| authResults | Array<number> | Yes| No| Whether the requested permissions are granted or denied. The value **0** means that the requests permissions are granted, and **-1** means the opposite. | +| authResults | Array<number> | Yes| No| Whether the requested permissions are granted or denied. The value **0** means that the requests permissions are granted, and a non-zero value means the opposite. | diff --git a/en/application-dev/reference/apis/js-apis-radio.md b/en/application-dev/reference/apis/js-apis-radio.md index 26d35ffeca4fe9c60ae46d8a8794fe46cb3d1748..ec920f58cab6825ce1dd286f42d1eb24e759f10b 100644 --- a/en/application-dev/reference/apis/js-apis-radio.md +++ b/en/application-dev/reference/apis/js-apis-radio.md @@ -384,6 +384,27 @@ promise.then(data => { }); ``` +## radio.isNrSupported7+ + +isNrSupported\(\): boolean + +Checks whether the current device supports 5G \(NR\). + +**System capability**: SystemCapability.Telephony.CoreService + +**Return value** + +| Type | Description | +| ------- | -------------------------------- | +| boolean | - **true**: The current device supports 5G \(NR\).
- **false**: The current device does not support 5G \(NR\).| + +**Example** + +```js +let result = radio.isNrSupported(); +console.log("Result: "+ result); +``` + ## radio.isNrSupported8+ diff --git a/en/application-dev/reference/apis/js-apis-sim.md b/en/application-dev/reference/apis/js-apis-sim.md index ae9a1ece9c9b419ea23162f354d7a428bd104a6c..6622b4b719e95f2c87af19653fbf8a89905239f2 100644 --- a/en/application-dev/reference/apis/js-apis-sim.md +++ b/en/application-dev/reference/apis/js-apis-sim.md @@ -2683,8 +2683,6 @@ getOpKey(slotId: number): Promise Obtains the opkey of the SIM card in the specified slot. This API uses a promise to return the result. -**System API**: This is a system API. - **System capability**: SystemCapability.Telephony.CoreService **Parameters** @@ -2716,8 +2714,6 @@ getOpName(slotId: number, callback: AsyncCallback): void Obtains the OpName of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -**System API**: This is a system API. - **System capability**: SystemCapability.Telephony.CoreService **Parameters** @@ -2742,8 +2738,6 @@ getOpName(slotId: number): Promise Obtains the OpName of the SIM card in the specified slot. This API uses a promise to return the result. -**System API**: This is a system API. - **System capability**: SystemCapability.Telephony.CoreService **Parameters** diff --git a/en/application-dev/reference/apis/js-apis-socket.md b/en/application-dev/reference/apis/js-apis-socket.md index 77dd0bc0560d11837a5cfbb68f38fd3f39075310..cd0995948cc8354d05845c7156abcdfdfb558bda 100644 --- a/en/application-dev/reference/apis/js-apis-socket.md +++ b/en/application-dev/reference/apis/js-apis-socket.md @@ -316,7 +316,7 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { return; } console.log('bind success'); - let promise = udp.getState({}); + let promise = udp.getState(); promise.then(data => { console.log('getState success:' + JSON.stringify(data)); }).catch(err => { @@ -626,7 +626,7 @@ Defines the parameters for sending data over the UDPSocket connection. | Name | Type | Mandatory| Description | | ------- | ---------------------------------- | ---- | -------------- | -| data | string | Yes | Data to send. | +| data | string \| ArrayBuffer7+ | Yes | Data to send. | | address | [NetAddress](#netaddress) | Yes | Destination address.| ## UDPExtraOptions @@ -1434,7 +1434,7 @@ Defines the parameters for sending data over the TCPSocket connection. | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | -| data | string | Yes | Data to send. | +| data | string\| ArrayBuffer7+ | Yes | Data to send. | | encoding | string | No | Character encoding format. The options are as follows: **UTF-8**, **UTF-16BE**, **UTF-16LE**, **UTF-16**, **US-AECII**, and **ISO-8859-1**. The default value is **UTF-8**.| ## TCPExtraOptions diff --git a/en/application-dev/reference/apis/js-apis-system-notification.md b/en/application-dev/reference/apis/js-apis-system-notification.md index daa6d4aac0d3ea39560a13de07b37c51c8b9226a..0a46cec929810e8f485a66b26445f1e3042b7672 100644 --- a/en/application-dev/reference/apis/js-apis-system-notification.md +++ b/en/application-dev/reference/apis/js-apis-system-notification.md @@ -1,6 +1,7 @@ # Notification -> ![icon-note.gif]public_sys-resources/icon-note.gif) **NOTE**
+> **NOTE** +> > - The APIs of this module are no longer maintained since API version 7. You are advised to use [`@ohos.notification`](js-apis-notification.md). > > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -51,18 +52,17 @@ Displays a notification. **Example** ```javascript -export default { - show() { - notification.show({ - contentTitle: 'title info', - contentText: 'text', - clickAction: { - bundleName: 'com.example.testapp', - abilityName: 'notificationDemo', - uri: '/path/to/notification', - }, - }); - }, +export default { + show() { + notification.show({ + contentTitle: 'title info', + contentText: 'text', + clickAction: { + bundleName: 'com.example.testapp', + abilityName: 'notificationDemo', + uri: '/path/to/notification', + }, + }); + }, } -; ``` diff --git a/en/application-dev/reference/apis/js-apis-telephony-data.md b/en/application-dev/reference/apis/js-apis-telephony-data.md index 7d8018a4e82916df0c218a10ca7d5e8fdb9e6364..f3a29a9cc683fecc38b4c935af7607bd2a5415b8 100644 --- a/en/application-dev/reference/apis/js-apis-telephony-data.md +++ b/en/application-dev/reference/apis/js-apis-telephony-data.md @@ -63,6 +63,29 @@ promise.then((data) => { }); ``` +## data.getDefaultCellularDataSlotIdSync + +getDefaultCellularDataSlotIdSync(): number + +Obtains the default SIM card used for mobile data synchronously. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Telephony.CellularData + +**Return value** + +| Type | Description | +| ------ | -------------------------------------------------- | +| number | Card slot ID.
**0**: card slot 1
**1**: card slot 2| + +**Example** + +```js +console.log("Result: "+ data.getDefaultCellularDataSlotIdSync()) +``` + + ## data.setDefaultCellularDataSlotId setDefaultCellularDataSlotId(slotId: number,callback: AsyncCallback\): void diff --git a/en/application-dev/reference/apis/js-apis-tlsSocket.md b/en/application-dev/reference/apis/js-apis-tlsSocket.md new file mode 100644 index 0000000000000000000000000000000000000000..d734a1c4bbc6ec59e76bb2fbf47afcedf83ab30d --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-tlsSocket.md @@ -0,0 +1,486 @@ +# TLSSocket + +The Transport Layer Security (TLS) protocol is designed to help protect the privacy of information at the transport layer. TLSSocket is an extension to socket communication. It provides higher security than socket communication by adding a security protection layer, which consists of the following submodules: key, certificate, and communication. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import socket from '@ohos.net.tlssocket' +``` + +## socket.constructTLSSocketInstance + +constructTLSSocketInstance(): TLSSocket + +Creates a **TLSSocket** object. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Example** + +```js +let tlssocket = socket.constructTLSSocketInstance(); +``` + +## tlssocket.connect + +connect(options: TLSConnectOptions, callback: AsyncCallback\): void + +Sets up a TLSSocket connection, and creates and initializes a TLS session. During this process, a TLS/SSL handshake is performed between the application and the server to implement data transmission. This API uses an asynchronous callback to return the result. + +**Parameters** + +| Name | Type | Mandatory| Description| +| -------- | ---------------------------------------| ----| --------------- | +| options | [TLSConnectOptions](#tlsconnectoptions) | Yes | Parameters required for the connection.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, the return result is empty. If the operation fails, an error code is returned.| + +**Example** + +```js +let options = { + ALPNProtocols: ["spdy/1", "http/1.1"], + address: { + address: "xxx", + port: "xxxx", + family: 1, + }, + secureOptions: { + key: "xxxx", + cert: "xxxx", + ca: ["xxxx"], + passwd: "xxxx", + protocols: "TlsV1_2", + useRemoteCipherPrefer: true, + signatureAlgorithms: SHA256, + cipherSuites: AES256-SHA256, + }, +}; + +tlssocket.connect(options, (err, data) => { + console.info(err); + console.info(data); +}); +``` + +## tlssocket.connect + +connect(options: TLSConnectOptions): Promise\; + +Sets up a TLSSocket connection, and creates and initializes a TLS session. During this process, a TLS/SSL handshake is performed between the application and the server to implement data transmission. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description| +| -------- | --------------------------------------| ----| --------------- | +| options | [TLSConnectOptions](#tlsconnectoptions) | Yes | Parameters required for the connection.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | ----------------------------- | +| Promise\ | Promise used to return the result. If the operation is successful, the return result is empty. If the operation fails, an error code is returned.| + +**Example** + +```js +let options = { + ALPNProtocols: ["spdy/1", "http/1.1"], + address: { + address: "xxxx", + port: "xxxx", + family: 1, + }, + secureOptions: { + key: "xxxx", + cert: "xxxx", + ca: ["xxxx"], + passwd: "xxxx", + protocols: "TlsV1_2", + useRemoteCipherPrefer: true, + signatureAlgorithms: SHA256, + cipherSuites: AES256-SHA256, + }, +}; + +tlssocket.connect(options).then(data => { + console.info(data); +}).catch(err => { + console.error(err); +}); +``` + +## tlssocket.getCertificate + +getCertificate(callback: AsyncCallback\): void; + +Obtains the local digital certificate after a TLSSocket connection is established. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description| +| -------- | ----------------------------------------| ---- | ---------------| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +tlssocket.getCertificate((err, data) => { + if (err) { + console.log("getCertificate callback error = " + err); + } else { + console.log("getCertificate callback = " + data); + } +}); +``` + +## tlssocket.getCertificate + +getCertificate():Promise\; + +Obtains the local digital certificate after a TLSSocket connection is established. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Return value** + +| Type | Description | +| -------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +tlssocket.getCertificate().then(data => { + console.info(data); +}).catch(err => { + console.error(err); +}); +``` + +## tlssocket.getRemoteCertificate + +getRemoteCertificate(callback: AsyncCallback\): void; + +Obtains the remote digital certificate after a TLSSocket connection is established. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------| ---- | ---------------| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +tlssocket.getRemoteCertificate((err, data) => { + if (err) { + console.log("getRemoteCertificate callback error = " + err); + } else { + console.log("getRemoteCertificate callback = " + data); + } +}); +``` + +## tlssocket.getRemoteCertificate + +getRemoteCertificate():Promise\; + +Obtains the remote digital certificate after a TLSSocket connection is established. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Return value** + +| Type | Description | +| -------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +tlssocket.getRemoteCertificate().then(data => { + console.info(data); +}).catch(err => { + console.error(err); +}); +``` + +## tlssocket.getProtocol + +getProtocol(callback: AsyncCallback\): void; + +Obtains the communication protocol after a TLSSocket connection is established. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------| ---- | ---------------| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +tlssocket.getProtocol((err, data) => { + if (err) { + console.log("getProtocol callback error = " + err); + } else { + console.log("getProtocol callback = " + data); + } +}); +``` + +## tlssocket.getProtocol + +getProtocol():Promise\; + +Obtains the communication protocol after a TLSSocket connection is established. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Return value** + +| Type | Description | +| -------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +tlssocket.getProtocol().then(data => { + console.info(data); +}).catch(err => { + console.error(err); +}); +``` + +## tlssocket.getCipherSuites + +getCipherSuites(callback: AsyncCallback\>): void; + +Obtains the cipher suites supported by both parties after a TLSSocket connection is established. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description| +| -------- | ----------------------------------------| ---- | ---------------| +| callback | AsyncCallback\> | Yes | Callback used to return the result. | + +**Example** + +```js +tlssocket.getCipherSuites((err, data) => { + if (err) { + console.log("getCipherSuites callback error = " + err); + } else { + console.log("getCipherSuites callback = " + data); + } +}); +``` + +## tlssocket.getCipherSuites + +getCipherSuites(): Promise\>; + +Obtains the cipher suites supported by both parties after a TLSSocket connection is established. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Return value** + +| Type | Description | +| ---------------------- | --------------------- | +| Promise\> | Promise used to return the result.| + +**Example** + +```js +tlssocket.getCipherSuites().then(data => { + console.info(data); +}).catch(err => { + console.error(err); +}); +``` + +## tlssocket.getSignatureAlgorithms + +getSignatureAlgorithms(callback: AsyncCallback\>): void; + +Obtains the signing algorithms supported by both parties after a TLSSocket connection is established. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------| ---- | ---------------| +| callback | AsyncCallback\> | Yes | Callback used to return the result. | + +**Example** + +```js +tlssocket.getSignatureAlgorithms((err, data) => { + if (err) { + console.log("getSignatureAlgorithms callback error = " + err); + } else { + console.log("getSignatureAlgorithms callback = " + data); + } +}); +``` + +## tlssocket.getSignatureAlgorithms + +getSignatureAlgorithms(): Promise\>; + +Obtains the signing algorithms supported by both parties after a TLSSocket connection is established. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Return value** + +| Type | Description | +| ---------------------- | -------------------- | +| Promise\> | Promise used to return the result.| + +**Example** + +```js +tlssocket.getSignatureAlgorithms().then(data => { + console.info(data); +}).catch(err => { + console.error(err); +}); +``` + +## tlssocket.close + +close(callback: AsyncCallback\): void; + +Closes a TLSSocket connection. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -----------------------------| ---- | ---------------| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +tlssocket.close((err) => { + if (err) { + console.log("close callback error = " + err); + } else { + console.log("close success"); + } +}); +``` + +## tlssocket.close + +close(): Promise\; + +Closes a TLSSocket connection. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Return value** + +| Type | Description | +| -------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +tlssocket.close().then(() => + console.log("close success"); +}).catch(err => { + console.error(err); +}); +``` + +## TLSConnectOptions + +Defines a TLSSocket connection. + +**System capability**: SystemCapability.Communication.NetStack + +| Name | Type | Description | +| -------------- | ------------------------------------- | -------------- | +| address | [NetAddress](#netaddress) | Gateway address. | +| secureOptions | [TLSSecureOptions](#tlssecureoptions) | TLS security options.| +| ALPNProtocols | Array\ | Application Layer Protocol Negotiation (ALPN) protocols. | + +## NetAddress + +Defines a network address. + +**System capability**: SystemCapability.Communication.NetStack + +| Name | Type | Description | +| ------- | ------ | ---------------------------- | +| address | string | Network address. | +| family | number | Address family identifier. The value is **1** for IPv4 and **2** for IPv6. The default value is **1**.| +| port | number | Port number. The value ranges from **0** to **65535**. | + +## TLSSecureOptions + +Defines TLS security options. + +**System capability**: SystemCapability.Communication.NetStack + +| Name | Type | Description | +| --------------------- | ---------------------- | ---------------------- | +| ca | string \| Array\ | CA certificate. | +| cert | string | Local digital certificate. | +| key | string | Private key of the local digital certificate. | +| passwd | string | Password. | +| protocols | string | Protocols. | +| useRemoteCipherPrefer | boolean | Whether to use the remote cipher suite preferentially.| +| signatureAlgorithms | string | Signing algorithms. | +| cipherSuites | string | Cipher suites. | diff --git a/en/application-dev/reference/apis/js-apis-update.md b/en/application-dev/reference/apis/js-apis-update.md index 91013f97245cf0b63073b88c51af91705324038a..bcbac5414055dfb654ab1264ab04f92e629cb3f3 100644 --- a/en/application-dev/reference/apis/js-apis-update.md +++ b/en/application-dev/reference/apis/js-apis-update.md @@ -43,13 +43,13 @@ Obtains an **OnlineUpdater** object. ```ts try { - var upgradeInfo = { + const upgradeInfo = { upgradeApp: "com.ohos.ota.updateclient", businessType: { vendor: update.BusinessVendor.PUBLIC, subType: update.BusinessSubType.FIRMWARE } - } + }; let updater = update.getOnlineUpdater(upgradeInfo); } catch(error) { console.error(`Fail to get updater error: ${error}`); @@ -233,15 +233,15 @@ Obtains the description file of the new version. This API uses an asynchronous c ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Options of the description file -var descriptionOptions = { +const descriptionOptions = { format: update.DescriptionFormat.STANDARD, // Standard format language: "zh-cn" // Chinese -} +}; updater.getNewVersionDescription(versionDigestInfo, descriptionOptions, (err, info) => { console.log(`getNewVersionDescription info ${JSON.stringify(info)}`); @@ -276,15 +276,15 @@ Obtains the description file of the new version. This API uses a promise to retu ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Options of the description file -var descriptionOptions = { +const descriptionOptions = { format: update.DescriptionFormat.STANDARD, // Standard format language: "zh-cn" // Chinese -} +}; updater.getNewVersionDescription(versionDigestInfo, descriptionOptions).then(info => { console.log(`getNewVersionDescription promise info ${JSON.stringify(info)}`); @@ -368,10 +368,10 @@ Obtains the description file of the current version. This API uses an asynchrono ```ts // Options of the description file -var descriptionOptions = { +const descriptionOptions = { format: update.DescriptionFormat.STANDARD, // Standard format language: "zh-cn" // Chinese -} +}; updater.getCurrentVersionDescription(descriptionOptions, (err, info) => { console.log(`getCurrentVersionDescription info ${JSON.stringify(info)}`); @@ -405,10 +405,10 @@ Obtains the description file of the current version. This API uses a promise to ```ts // Options of the description file -var descriptionOptions = { +const descriptionOptions = { format: update.DescriptionFormat.STANDARD, // Standard format language: "zh-cn" // Chinese -} +}; updater.getCurrentVersionDescription(descriptionOptions).then(info => { console.log(`getCurrentVersionDescription promise info ${JSON.stringify(info)}`); @@ -489,15 +489,15 @@ Downloads the new version. This API uses an asynchronous callback to return the ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Download options -var downloadOptions = { +const downloadOptions = { allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network order: update.Order.DOWNLOAD // Download -} +}; updater.download(versionDigestInfo, downloadOptions, (err) => { console.log(`download error ${JSON.stringify(err)}`); }); @@ -530,15 +530,15 @@ Downloads the new version. This API uses a promise to return the result. ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Download options -var downloadOptions = { +const downloadOptions = { allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network order: update.Order.DOWNLOAD // Download -} +}; updater.download(versionDigestInfo, downloadOptions).then(() => { console.log(`download start`); }).catch(err => { @@ -568,14 +568,14 @@ Resumes download of the new version. This API uses an asynchronous callback to r ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Options for resuming download -var resumeDownloadOptions = { +const resumeDownloadOptions = { allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network -} +}; updater.resumeDownload(versionDigestInfo, resumeDownloadOptions, (err) => { console.log(`resumeDownload error ${JSON.stringify(err)}`); }); @@ -608,14 +608,14 @@ Resumes download of the new version. This API uses a promise to return the resul ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Options for resuming download -var resumeDownloadOptions = { +const resumeDownloadOptions = { allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network -} +}; updater.resumeDownload(versionDigestInfo, resumeDownloadOptions).then(value => { console.log(`resumeDownload start`); }).catch(err => { @@ -645,14 +645,14 @@ Pauses download of the new version. This API uses an asynchronous callback to re ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Options for pausing download -var pauseDownloadOptions = { +const pauseDownloadOptions = { isAllowAutoResume: true // Whether to allow automatic resuming of download -} +}; updater.pauseDownload(versionDigestInfo, pauseDownloadOptions, (err) => { console.log(`pauseDownload error ${JSON.stringify(err)}`); }); @@ -685,14 +685,14 @@ Resumes download of the new version. This API uses a promise to return the resul ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Options for pausing download -var pauseDownloadOptions = { +const pauseDownloadOptions = { isAllowAutoResume: true // Whether to allow automatic resuming of download -} +}; updater.pauseDownload(versionDigestInfo, pauseDownloadOptions).then(value => { console.log(`pauseDownload`); }).catch(err => { @@ -722,14 +722,14 @@ Updates the version. This API uses an asynchronous callback to return the result ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Installation options -var upgradeOptions = { +const upgradeOptions = { order: update.Order.INSTALL // Installation command -} +}; updater.upgrade(versionDigestInfo, upgradeOptions, (err) => { console.log(`upgrade error ${JSON.stringify(err)}`); }); @@ -762,14 +762,14 @@ Updates the version. This API uses a promise to return the result. ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Installation options -var upgradeOptions = { +const upgradeOptions = { order: update.Order.INSTALL // Installation command -} +}; updater.upgrade(versionDigestInfo, upgradeOptions).then(() => { console.log(`upgrade start`); }).catch(err => { @@ -799,14 +799,14 @@ Clears errors. This API uses an asynchronous callback to return the result. ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Options for clearing errors -var clearOptions = { +const clearOptions = { status: update.UpgradeStatus.UPGRADE_FAIL, -} +}; updater.clearError(versionDigestInfo, clearOptions, (err) => { console.log(`clearError error ${JSON.stringify(err)}`); }); @@ -839,14 +839,14 @@ Clears errors. This API uses a promise to return the result. ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Options for clearing errors -var clearOptions = { +lconstet clearOptions = { status: update.UpgradeStatus.UPGRADE_FAIL, -} +}; updater.clearError(versionDigestInfo, clearOptions).then(() => { console.log(`clearError success`); }).catch(err => { @@ -926,7 +926,7 @@ Sets the update policy. This API uses an asynchronous callback to return the res **Example** ```ts -let policy = { +const policy = { downloadStrategy: false, autoUpgradeStrategy: false, autoUpgradePeriods: [ { start: 120, end: 240 } ] // Automatic update period, in minutes @@ -961,7 +961,7 @@ Sets the update policy. This API uses a promise to return the result. **Example** ```ts -let policy = { +const policy = { downloadStrategy: false, autoUpgradeStrategy: false, autoUpgradePeriods: [ { start: 120, end: 240 } ] // Automatic update period, in minutes @@ -1041,10 +1041,10 @@ Enables listening for update events. This API uses an asynchronous callback to r **Example** ```ts -var eventClassifyInfo = { +const eventClassifyInfo = { eventClassify: update.EventClassify.TASK, // Listening for update events extraInfo: "" -} +}; updater.on(eventClassifyInfo, (eventInfo) => { console.log("updater on " + JSON.stringify(eventInfo)); @@ -1068,10 +1068,10 @@ Disables listening for update events. This API uses an asynchronous callback to **Example** ```ts -var eventClassifyInfo = { +const eventClassifyInfo = { eventClassify: update.EventClassify.TASK, // Listening for update events extraInfo: "" -} +}; updater.off(eventClassifyInfo, (eventInfo) => { console.log("updater off " + JSON.stringify(eventInfo)); @@ -1153,10 +1153,10 @@ Verifies the update package. This API uses an asynchronous callback to return th **Example** ```ts -var upgradeFile = { +const upgradeFile = { fileType: update.ComponentType.OTA, // OTA package filePath: "path" // Path of the local update package -} +}; localUpdater.verifyUpgradePackage(upgradeFile, "cerstFilePath", (err) => { console.log(`factoryReset error ${JSON.stringify(err)}`); @@ -1189,10 +1189,10 @@ Verifies the update package. This API uses a promise to return the result. **Example** ```ts -var upgradeFile = { +const upgradeFile = { fileType: update.ComponentType.OTA, // OTA package filePath: "path" // Path of the local update package -} +}; localUpdater.verifyUpgradePackage(upgradeFile, "cerstFilePath").then(() => { console.log(`verifyUpgradePackage success`); }).catch(err => { @@ -1219,10 +1219,10 @@ Installs the update package. This API uses an asynchronous callback to return th **Example** ```ts -var upgradeFiles = [{ +const upgradeFiles = [{ fileType: update.ComponentType.OTA, // OTA package filePath: "path" // Path of the local update package -}] +}]; localUpdater.applyNewVersion(upgradeFiles, (err) => { console.log(`applyNewVersion error ${JSON.stringify(err)}`); @@ -1248,10 +1248,10 @@ Installs the update package. This API uses a promise to return the result. **Example** ```ts -var upgradeFiles = [{ +localUpdater upgradeFiles = [{ fileType: update.ComponentType.OTA, // OTA package filePath: "path" // Path of the local update package -}] +}]; localUpdater.applyNewVersion(upgradeFiles).then(() => { console.log(`applyNewVersion success`); }).catch(err => { @@ -1276,10 +1276,10 @@ Enables listening for update events. This API uses an asynchronous callback to r **Example** ```ts -var eventClassifyInfo = { +const eventClassifyInfo = { eventClassify: update.EventClassify.TASK, // Listening for update events extraInfo: "" -} +}; function onTaskUpdate(eventInfo) { console.log(`on eventInfo id `, eventInfo.eventId); @@ -1305,10 +1305,10 @@ Disables listening for update events. This API uses an asynchronous callback to **Example** ```ts -var eventClassifyInfo = { +const eventClassifyInfo = { eventClassify: update.EventClassify.TASK, // Listening for update events extraInfo: "" -} +}; function onTaskUpdate(eventInfo) { console.log(`on eventInfo id `, eventInfo.eventId); diff --git a/en/application-dev/reference/apis/js-apis-vibrator.md b/en/application-dev/reference/apis/js-apis-vibrator.md index 699ab299f5050594fd943c95e36c0538e9d0ec24..95654a5829967c3e6f3be2be8c5daf3baf527386 100644 --- a/en/application-dev/reference/apis/js-apis-vibrator.md +++ b/en/application-dev/reference/apis/js-apis-vibrator.md @@ -31,6 +31,14 @@ Triggers vibration with the specified effect and attribute. This API uses a prom | attribute | [VibrateAttribute](#vibrateattribute9) | Yes | Vibration attribute. | | callback | AsyncCallback<void> | Yes | Callback used to the result. If the vibration starts, **err** is **undefined**. Otherwise, **err** is an error object.| +**Error codes** + +For details about the error codes, see [Vibrator Error Codes](../errorcodes/errorcode-vibrator.md). + +| ID| Error Message | +| -------- | ------------------------- | +| 14600101 | Device operation failed.| + **Example** ```js @@ -76,6 +84,14 @@ Triggers vibration with the specified effect and attribute. This API uses a prom | ------------------- | -------------------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Vibrator Error Codes](../errorcodes/errorcode-vibrator.md). + +| ID| Error Message | +| -------- | ------------------------- | +| 14600101 | Device operation failed.| + **Example** ```js diff --git a/en/application-dev/reference/apis/js-apis-webSocket.md b/en/application-dev/reference/apis/js-apis-webSocket.md index 52f5367110bc35c33075ed291a796a657a468816..bda4ad227b32b18130682bb4fe10db9a446535ec 100644 --- a/en/application-dev/reference/apis/js-apis-webSocket.md +++ b/en/application-dev/reference/apis/js-apis-webSocket.md @@ -433,7 +433,7 @@ ws.off('open', callback1); on\(type: 'message', callback: AsyncCallback\): void -Enables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. +Enables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented. >![](public_sys-resources/icon-note.gif) **NOTE:** >The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\). @@ -462,7 +462,7 @@ ws.on('message', (err, value) => { off\(type: 'message', callback?: AsyncCallback\): void -Disables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. +Disables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented. >![](public_sys-resources/icon-note.gif) **NOTE:** >The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\). diff --git a/en/application-dev/reference/apis/js-apis-wifi.md b/en/application-dev/reference/apis/js-apis-wifi.md index 13014cfed8a6cc95d124535c89b399b12348395f..a8221a78898accf8d18724193df311a13693b998 100644 --- a/en/application-dev/reference/apis/js-apis-wifi.md +++ b/en/application-dev/reference/apis/js-apis-wifi.md @@ -302,7 +302,7 @@ Represents the WLAN configuration. ## IpType7+ -Enumerate the IP address types. +Enumerates the IP address types. **System API**: This is a system API. @@ -1851,7 +1851,7 @@ Unregisters the WLAN state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **wifiStateChange**.| - | callback | Callback<number> | No| Callback used to return the WLAN state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | callback | Callback<number> | No| Callback for the WLAN state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Example** ```js @@ -1909,7 +1909,7 @@ Unregisters the WLAN connection state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **wifiConnectionChange**.| - | callback | Callback<number> | No| Callback used to return the WLAN connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | callback | Callback<number> | No| Callback for the WLAN connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('wifiScanStateChange')7+ @@ -1952,7 +1952,7 @@ Unregisters the WLAN scan state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **wifiScanStateChange**.| -| callback | Callback<number> | No| Callback used to return the WLAN scan state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<number> | No| Callback for the WLAN scan state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('wifiRssiChange')7+ @@ -1988,7 +1988,7 @@ Unregisters the RSSI change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **wifiRssiChange**.| -| callback | Callback<number> | No| Callback used to return the RSSI. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<number> | No| Callback for the RSSI. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('hotspotStateChange')7+ @@ -2033,7 +2033,7 @@ Unregisters the hotspot state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **hotspotStateChange**.| -| callback | Callback<number> | No| Callback used to return the hotspot state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<number> | No| Callback for the hotspot state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pStateChange')8+ @@ -2078,7 +2078,7 @@ Unregisters the P2P state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pStateChange**.| -| callback | Callback<number> | No| Callback used to return the P2P state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<number> | No| Callback for the P2P state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pConnectionChange')8+ @@ -2114,7 +2114,7 @@ Unregisters the P2P connection state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pConnectionChange**.| -| callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | No| Callback used to return the P2P connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | No| Callback for the P2P connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pDeviceChange')8+ @@ -2150,7 +2150,7 @@ Unregisters the P2P device state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pDeviceChange**.| -| callback | Callback<[WifiP2pDevice](#wifip2pdevice8)> | No| Callback used to return the P2P device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<[WifiP2pDevice](#wifip2pdevice8)> | No| Callback for the P2P device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pPeerDeviceChange')8+ @@ -2186,7 +2186,7 @@ Unregisters the P2P peer device state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| -| callback | Callback<[WifiP2pDevice[]](#wifip2pdevice8)> | No| Callback used to return the peer device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<[WifiP2pDevice[]](#wifip2pdevice8)> | No| Callback for the peer device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pPersistentGroupChange')8+ @@ -2222,7 +2222,7 @@ Unregisters the P2P persistent group state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| -| callback | Callback<void> | No| Callback used to return the P2P persistent group state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<void> | No| Callback for the P2P persistent group state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pDiscoveryChange')8+ @@ -2265,4 +2265,4 @@ Unregisters the P2P device discovery state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| -| callback | Callback<number> | No| Callback used to return the P2P device discovery state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<number> | No| Callback for the P2P device discovery state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md b/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md index 1bc12e9014024c9c3fe02f783ca6d65934f98d9f..156e4ca3ac3c5b6e821258ce8baf77cd4f51322c 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md @@ -55,7 +55,7 @@ Creates a time picker whose default time range is from 00:00 to 23:59. @Entry @Component struct TimePickerExample { - private selectedTime: Date = new Date('7/22/2022 8:00:00') + private selectedTime: Date = new Date('2022-07-22T08:00:00') build() { Column() { diff --git a/en/application-dev/reference/arkui-ts/ts-components-canvas-lottie.md b/en/application-dev/reference/arkui-ts/ts-components-canvas-lottie.md index 8dd7d0943ced17f807da65c0aa1a8b232f39500d..aacc4d7e663d89abb4020c24d5fc57aaee1d8c56 100644 --- a/en/application-dev/reference/arkui-ts/ts-components-canvas-lottie.md +++ b/en/application-dev/reference/arkui-ts/ts-components-canvas-lottie.md @@ -16,7 +16,7 @@ import lottie from '@ohos/lottieETS' > **NOTE** > -> In the **Terminal** window, run the `npm install @ohos/lottieETS` command to download Lottie. +> In the **Terminal** window, run the `npm install @ohos/lottieETS` command to download Lottie. The download requires the related permission. > > To install an OpenHarmony npm third-party package, run the `npm config set @ohos:registry=https://repo.harmonyos.com/npm/` command to set the repository address. @@ -31,15 +31,15 @@ Loads an animation. Before calling this method, declare the **Animator('\__lotti **Parameters** - | Name | Type | Mandatory | Description | - | -------------- | --------------------------- | ---- | ---------------------------------------- | - | path | string | Yes | Path of the animation resource file in the HAP file. The resource file must be in JSON format. Example: **path: "common/lottie/data.json"**| - | container | object | Yes | Canvas drawing context. A **CanvasRenderingContext2D** object must be declared in advance.| - | render | string | Yes | Rendering type. The value can only be **"canvas"**. | - | loop | boolean \| number | No | If the value is of the Boolean type, this parameter indicates whether to repeat the animation cyclically after the animation ends; the default value is **true**. If the value is of the number type and is greater than or equal to 1, this parameter indicates the number of times the animation plays.| - | autoplay | boolean | No | Whether to automatically play the animation. The default value is **true**. | - | name | string | No | Custom animation name. In later versions, the name can be used to reference and control the animation. The default value is null. | - | initialSegment | [number, number] | No | Start frame and end frame of the animation, respectively. | +| Name | Type | Mandatory | Description | +| -------------- | --------------------------- | ---- | ---------------------------------------- | +| path | string | Yes | Path of the animation resource file in the HAP file. The resource file must be in JSON format. Example: **path: "common/lottie/data.json"**| +| container | object | Yes | Canvas drawing context. A **CanvasRenderingContext2D** object must be declared in advance.| +| render | string | Yes | Rendering type. The value can only be **"canvas"**. | +| loop | boolean \| number | No | If the value is of the Boolean type, this parameter indicates whether to repeat the animation cyclically after the animation ends; the default value is **true**. If the value is of the number type and is greater than or equal to 1, this parameter indicates the number of times the animation plays.| +| autoplay | boolean | No | Whether to automatically play the animation. The default value is **true**. | +| name | string | No | Custom animation name. In later versions, the name can be used to reference and control the animation. The default value is null. | +| initialSegment | [number, number] | No | Start frame and end frame of the animation, respectively. | ## lottie.destroy @@ -50,9 +50,9 @@ Destroys the animation. This method must be called when a page exits. This metho **Parameters** - | Name | Type | Mandatory | Description | - | ---- | ------ | ---- | ---------------------------------------- | - | name | string | Yes | Name of the animation to destroy, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are destroyed.| +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ---------------------------------------- | +| name | string | Yes | Name of the animation to destroy, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are destroyed.| **Example** ```ts @@ -131,9 +131,9 @@ Plays a specified animation. **Parameters** - | Name | Type | Mandatory | Description | - | ---- | ------ | ---- | ---------------------------------------- | - | name | string | Yes | Name of the animation to play, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are played.| +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ---------------------------------------- | +| name | string | Yes | Name of the animation to play, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are played.| **Example** @@ -150,9 +150,9 @@ Pauses a specified animation. The next time **lottie.play()** is called, the ani **Parameters** - | Name | Type | Mandatory | Description | - | ---- | ------ | ---- | ---------------------------------------- | - | name | string | Yes | Name of the animation to pause, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.| +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ---------------------------------------- | +| name | string | Yes | Name of the animation to pause, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.| **Example** @@ -169,9 +169,9 @@ Pauses or plays a specified animation. This method is equivalent to the switchin **Parameters** - | Name | Type | Mandatory | Description | - | ---- | ------ | ---- | ---------------------------------------- | - | name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.| +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ---------------------------------------- | +| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.| **Example** @@ -188,9 +188,9 @@ Stops the specified animation. The next time **lottie.play()** is called, the an **Parameters** - | Name | Type | Mandatory | Description | - | ---- | ------ | ---- | ---------------------------------------- | - | name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.| +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ---------------------------------------- | +| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.| **Example** @@ -207,10 +207,10 @@ Sets the playback speed of the specified animation. **Parameters** - | Name | Type | Mandatory | Description | - | ----- | ------ | ---- | ---------------------------------------- | - | speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays in forward direction. If the value is less than 0, the animation plays in reversed direction. If the value is 0, the animation is paused. If the value is 1.0 or -1.0, the animation plays at the normal speed.| - | name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are stopped.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------------------------------------- | +| speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays in forward direction. If the value is less than 0, the animation plays in reversed direction. If the value is 0, the animation is paused. If the value is 1.0 or -1.0, the animation plays at the normal speed.| +| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are stopped.| **Example** @@ -227,10 +227,10 @@ Sets the direction in which the specified animation plays. **Parameters** - | Name | Type | Mandatory | Description | - | --------- | ------------------ | ---- | ---------------------------------------- | - | direction | AnimationDirection | Yes | Direction in which the animation plays. **1**: forwards; **-1**: backwards. When set to play backwards, the animation plays from the current playback progress to the first frame. When this setting is combined with **loop** being set to **true**, the animation plays backwards continuously. When the value of **speed** is less than 0, the animation also plays backwards.
AnimationDirection: 1 \| -1 | - | name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are set.| +| Name | Type | Mandatory | Description | +| --------- | ------------------ | ---- | ---------------------------------------- | +| direction | AnimationDirection | Yes | Direction in which the animation plays. **1**: forwards; **-1**: backwards. When set to play backwards, the animation plays from the current playback progress to the first frame. When this setting is combined with **loop** being set to **true**, the animation plays backwards continuously. When the value of **speed** is less than 0, the animation also plays backwards.
AnimationDirection: 1 \| -1 | +| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are set.| **Example** @@ -275,9 +275,9 @@ Plays an animation. **Parameters** - | Name | Type | Mandatory | Description | - | ---- | ------ | ---- | --------------- | - | name | string | No | Name of the target animation. By default, the value is null.| +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | --------------- | +| name | string | No | Name of the target animation. By default, the value is null.| **Example** @@ -294,9 +294,9 @@ Destroys an animation. **Parameters** - | Name | Type | Mandatory | Description | - | ---- | ------ | ---- | --------------- | - | name | string | No | Name of the target animation. By default, the value is null.| +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | --------------- | +| name | string | No | Name of the target animation. By default, the value is null.| **Example** @@ -313,9 +313,9 @@ Pauses an animation. When the **play** interface is called next time, the animat **Parameters** - | Name | Type | Mandatory | Description | - | ---- | ------ | ---- | --------------- | - | name | string | No | Name of the target animation. By default, the value is null.| +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | --------------- | +| name | string | No | Name of the target animation. By default, the value is null.| **Example** @@ -332,9 +332,9 @@ Pauses or plays an animation. This method is equivalent to the switching between **Parameters** - | Name | Type | Mandatory | Description | - | ---- | ------ | ---- | --------------- | - | name | string | No | Name of the target animation. By default, the value is null.| +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | --------------- | +| name | string | No | Name of the target animation. By default, the value is null.| **Example** @@ -351,9 +351,9 @@ Stops an animation. When the **play** interface is called next time, the animati **Parameters** - | Name | Type | Mandatory | Description | - | ---- | ------ | ---- | --------------- | - | name | string | No | Name of the target animation. By default, the value is null.| +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | --------------- | +| name | string | No | Name of the target animation. By default, the value is null.| **Example** @@ -370,9 +370,9 @@ Sets the playback speed of an animation. **Parameters** - | Name | Type | Mandatory | Description | - | ----- | ------ | ---- | ---------------------------------------- | - | speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays forward. If the value is less than 0, the animation plays backward. If the value is 0, the animation is paused.|If the value is **1.0** or **-1.0**, the animation plays at the normal speed.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------------------------------------- | +| speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays forward. If the value is less than 0, the animation plays backward. If the value is 0, the animation is paused.|If the value is **1.0** or **-1.0**, the animation plays at the normal speed.| **Example** @@ -389,9 +389,9 @@ Sets the playback direction of an animation. **Parameters** - | Name | Type | Mandatory | Description | - | --------- | ------------------ | ---- | ---------------------------------------- | - | direction | AnimationDirection | Yes | Direction in which the animation plays. **1**: forwards; **-1**: backwards. When set to play backwards, the animation plays from the current playback progress to the first frame. When this setting is combined with **loop** being set to **true**, the animation plays backwards continuously. When the value of **speed** is less than 0, the animation also plays backwards.
AnimationDirection: 1 \| -1.| +| Name | Type | Mandatory | Description | +| --------- | ------------------ | ---- | ---------------------------------------- | +| direction | AnimationDirection | Yes | Direction in which the animation plays. **1**: forwards; **-1**: backwards. When set to play backwards, the animation plays from the current playback progress to the first frame. When this setting is combined with **loop** being set to **true**, the animation plays backwards continuously. When the value of **speed** is less than 0, the animation also plays backwards.
AnimationDirection: 1 \| -1.| **Example** @@ -408,11 +408,11 @@ Sets the animation to stop at the specified frame or time. **Parameters** - | Name | Type | Mandatory | Description | - | ------- | ------- | ---- | ---------------------------------------- | - | value | number | Yes | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will stop. | - | isFrame | boolean | No | Whether to set the animation to stop at the specified frame. The value **true** means to set the animation to stop at the specified frame, and **false** means to set the animation to stop at the specified time progress. The default value is **false**.| - | name | string | No | Name of the target animation. By default, the value is null. | +| Name | Type | Mandatory | Description | +| ------- | ------- | ---- | ---------------------------------------- | +| value | number | Yes | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will stop. | +| isFrame | boolean | No | Whether to set the animation to stop at the specified frame. The value **true** means to set the animation to stop at the specified frame, and **false** means to set the animation to stop at the specified time progress. The default value is **false**.| +| name | string | No | Name of the target animation. By default, the value is null. | **Example** @@ -432,11 +432,11 @@ Sets the animation to start from the specified frame or time progress. **Parameters** - | Name | Type | Mandatory | Description | - | ------- | ------- | ---- | ---------------------------------------- | - | value | number | Yes | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will start. | - | isFrame | boolean | Yes | Whether to set the animation to start from the specified frame. The value **true** means to set the animation to start from the specified frame, and **false** means to set the animation to start from the specified time progress. The default value is **false**.| - | name | string | No | Name of the target animation. By default, the value is null. | +| Name | Type | Mandatory | Description | +| ------- | ------- | ---- | ---------------------------------------- | +| value | number | Yes | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will start. | +| isFrame | boolean | Yes | Whether to set the animation to start from the specified frame. The value **true** means to set the animation to start from the specified frame, and **false** means to set the animation to start from the specified time progress. The default value is **false**.| +| name | string | No | Name of the target animation. By default, the value is null. | **Example** @@ -456,10 +456,10 @@ Sets the animation to play only the specified segment. **Parameters** - | Name | Type | Mandatory | Description | - | --------- | ---------------------------------------- | ---- | ---------------------------------------- | - | segments | AnimationSegment = [number, number] \| AnimationSegment[] | Yes | Segment or segment list.
If all segments in the segment list are played, only the last segment is played in the next cycle.| - | forceFlag | boolean | Yes | Whether the settings take effect immediately. The value **true** means the settings take effect immediately, and **false** means the settings take effect until the current cycle of playback is completed. | +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | ---------------------------------------- | +| segments | AnimationSegment = [number, number] \| AnimationSegment[] | Yes | Segment or segment list.
If all segments in the segment list are played, only the last segment is played in the next cycle.| +| forceFlag | boolean | Yes | Whether the settings take effect immediately. The value **true** means the settings take effect immediately, and **false** means the settings take effect until the current cycle of playback is completed. | **Example** @@ -479,9 +479,9 @@ Resets the settings configured by the **playSegments** method to play all the fr **Parameters** - | Name | Type | Mandatory | Description | - | --------- | ------- | ---- | ------------------------------ | - | forceFlag | boolean | Yes | Whether the settings take effect immediately. The value **true** means the settings take effect immediately, and **false** means the settings take effect until the current cycle of playback is completed.| +| Name | Type | Mandatory | Description | +| --------- | ------- | ---- | ------------------------------ | +| forceFlag | boolean | Yes | Whether the settings take effect immediately. The value **true** means the settings take effect immediately, and **false** means the settings take effect until the current cycle of playback is completed.| **Example** @@ -511,9 +511,9 @@ Sets the precision of the **currentFrame** attribute to display floating-point n **Parameters** - | Name | Type | Mandatory | Description | - | ------------ | ------- | ---- | ---------------------------------------- | - | useSubFrames | boolean | Yes | Whether the **currentFrame** attribute displays floating-point numbers. By default, the attribute displays floating-point numbers.
**true**: The **currentFrame** attribute displays floating-point numbers.
**false**: The **currentFrame** attribute displays an integer and does not display floating-point numbers.| +| Name | Type | Mandatory | Description | +| ------------ | ------- | ---- | ---------------------------------------- | +| useSubFrames | boolean | Yes | Whether the **currentFrame** attribute displays floating-point numbers. By default, the attribute displays floating-point numbers.
**true**: The **currentFrame** attribute displays floating-point numbers.
**false**: The **currentFrame** attribute displays an integer and does not display floating-point numbers.| **Example** @@ -530,9 +530,9 @@ Obtains the duration (irrelevant to the playback speed) or number of frames for **Parameters** - | Name | Type | Mandatory | Description | - | -------- | ------- | ---- | ---------------------------------------- | - | inFrames | boolean | No | Whether to obtain the duration or number of frames.
**true**: number of frames.
**false**: duration, in ms.
Default value: **false**| +| Name | Type | Mandatory | Description | +| -------- | ------- | ---- | ---------------------------------------- | +| inFrames | boolean | No | Whether to obtain the duration or number of frames.
**true**: number of frames.
**false**: duration, in ms.
Default value: **false**| **Example** @@ -549,10 +549,10 @@ Adds an event listener. After the event is complete, the specified callback func **Parameters** - | Name | Type | Mandatory | Description | - | -------- | ------------------------------- | ---- | ---------------------------------------- | - | name | AnimationEventName | Yes | Animation event type. The available options are as follows:
'enterFrame', 'loopComplete', 'complete', 'segmentStart', 'destroy', 'config_ready', 'data_ready', 'DOMLoaded', 'error', 'data_failed', 'loaded_images'| - | callback | AnimationEventCallback<T> | Yes | Custom callback. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ---------------------------------------- | +| name | AnimationEventName | Yes | Animation event type. The available options are as follows:
'enterFrame', 'loopComplete', 'complete', 'segmentStart', 'destroy', 'config_ready', 'data_ready', 'DOMLoaded', 'error', 'data_failed', 'loaded_images'| +| callback | AnimationEventCallback<T> | Yes | Custom callback. | **Example** @@ -575,10 +575,10 @@ Removes an event listener. **Parameters** - | Name | Type | Mandatory | Description | - | -------- | ------------------------------- | ---- | ---------------------------------------- | - | name | AnimationEventName | Yes | Animation event type. The available options are as follows:
'enterFrame', 'loopComplete', 'complete', 'segmentStart', 'destroy', 'config_ready', 'data_ready', 'DOMLoaded', 'error', 'data_failed', 'loaded_images'| - | callback | AnimationEventCallback<T> | No | Custom callback. By default, the value is null, meaning that all callbacks of the event will be removed. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ---------------------------------------- | +| name | AnimationEventName | Yes | Animation event type. The available options are as follows:
'enterFrame', 'loopComplete', 'complete', 'segmentStart', 'destroy', 'config_ready', 'data_ready', 'DOMLoaded', 'error', 'data_failed', 'loaded_images'| +| callback | AnimationEventCallback<T> | No | Custom callback. By default, the value is null, meaning that all callbacks of the event will be removed. | **Example** @@ -595,10 +595,10 @@ Directly triggers all configured callbacks of a specified event. **Parameters** - | Name | Type | Mandatory | Description | - | ---- | ------------------ | ---- | --------- | - | name | AnimationEventName | Yes | Animation event type. | - | args | any | Yes | Custom callback parameters.| +| Name | Type | Mandatory | Description | +| ---- | ------------------ | ---- | --------- | +| name | AnimationEventName | Yes | Animation event type. | +| args | any | Yes | Custom callback parameters.| **Example** diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md index c02876ce0f77ca67db58378aa68dc044846dbc75..c82ec4fab433b607cf344864a1126ac94332e89c 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md @@ -78,4 +78,4 @@ struct ImageEffectsExample { } ``` -image-effect +![](figures/image-effect.png) diff --git a/en/application-dev/reference/errorcodes/errorcode-huks.md b/en/application-dev/reference/errorcodes/errorcode-huks.md new file mode 100644 index 0000000000000000000000000000000000000000..7bab2f0be7353cefecbe458b6435aaaf213429d4 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-huks.md @@ -0,0 +1,228 @@ +# HUKS Error Codes + +## 12000001 Feature Not Supported + +**Error Message** + +`${messageInfo}` is not supported. + +**Possible Causes** + +The API is supported, but certain features in the API, such as the algorithm, are not supported. + +**Procedure** + +Modify the parameters and use the features supported. + +## 12000002 Missing Key Algorithm Parameter +**Error Message** + +Failed to obtain `${messageInfo}`. It is not set in ParamSet. + +**Possible Causes** + +The key parameter is not set. + +**Procedure** + +1. Determine the missing parameter from the error message. +2. Set the parameter. + +## 12000003 Invalid Key Algorithm Parameter + +**Error Message** + +Invalid `${messageInfo}`. + +**Possible Causes** + +An invalid parameter is found. + +**Procedure** + +1. Determine the invalid parameter from the error message. +2. Correct the invalid parameter. + +## 12000004 File Error + +**Error Message** + +Failed to read the file. + +Failed to write the file. + +**Possible Causes** + +The file operation failed. + +**Procedure** + +1. Check whether the disk space is used up and whether the file system is abnormal. +2. Clear the disk space. + +## 12000005 IPC Error + +**Error Message** + +IPC timed out. + +Failed to obtain messages from IPC. + +**Possible Causes** + +IPC failed. + +**Procedure** + +Locate and rectify the IPC failure. + +## 12000006 Algorithm Library Operation Failed + +**Error Message** + +Crypto engine error. + +**Possible Causes** + +The algorithm library operation fails. The possible causes include the following: + +1. The encryption and decryption on the algorithm library failed due to incorrect ciphertext data. +2. Incorrect key parameters exist. + +**Procedure** + +1. Check and correct the ciphertext data. +2. Check and correct the key parameters. + +## 12000007 Failed to Access the Key Due to Invalidated Credential + +**Error Message** + +This credential is invalidated permanently. + +**Possible Causes** + +The possible causes include the following: + +1. The key is configured with the user access control attribute and becomes invalid after the password is cleared. +2. The key is configured with the user access control attribute and becomes invalid after a new biometric feature is enrolled. + +**Procedure** + +1. Locate the cause of the authentication failure based on the log. +2. If the authentication fails due to the access control attribute configured, the key cannot be used any more. + +## 12000008 Failed to Access the Key Due to a Failure in Authentication Token Verification + +**Error Message** + +The authentication token verification failed. + +**Possible Causes** + +The authentication token verification failed due to an incorrect challenge value. + +**Procedure** + +1. Check whether the challenge for userIAM authentication is correctly assembled. +2. If the challenge value is incorrect, modify the assembly mode, use the bytes generated by HUKS to assembly challenge value, and pass it to userIAM for authentication. + +## 12000009 Key Access Timed Out + +**Error Message** + +The Authentication token timed out. + +**Possible Causes** + +The authentication failed because the authentication token timed out. + +**Procedure** + +The difference between the current time and the authentication token generation time must be less than the timeout interval. Otherwise, the access will be rejected. + +## 12000010 Key Operation Sessions Reaches the Limit + +**Error Message** + +The number of key operation sessions has reached the limit. + +**Possible Causes** + +The number of concurrent key operation sessions has reached the maximum (15). + +**Procedure** + +1. Check whether there are multiple key session operations (**init** operations) for the same application. If yes, modify the code to avoid concurrent invoking. +2. If the key operation sessions are set up for different applications, wait until the sessions are released. + +## 12000011 The Entity Does Not Exist + +**Error Message** + +The entity does not exist. + +**Possible Causes** + +The key corresponding to the key alias does not exist. + +**Procedure** + +1. Check whether the key alias is misspelled. +2. Check whether the key corresponding to the key alias is successfully generated. + +## 12000012 External Error + +**Error Message** + +External error `${messageInfo}`. + +**Possible Causes** + +An external error, such as a hardware fault or file error occurs. + +**Procedure** + +Provide the error code and log information to the related party. + +## 12000013 The Credential Does Not Exist + +**Error Message** + +The credential does not exist. + +**Possible Causes** + +The credential, such as the PIN, fingerprint, or face image, is not enrolled. + +**Procedure** + +Enroll the credential or change the authentication type bound to the key. + +## 12000014 Insufficient Memory + +**Error Message** + +Memory is insufficient. + +**Possible Causes** + +The system memory is insufficient. + +**Procedure** + +Release memory or restart the device. + +## 12000015 Failed to Invoke Other System Services + +**Error Message** + +Failed to call the `${messageInfo}` service to do `${messageInfo}`. + +**Possible Causes** + +The called system service has not started. + +**Procedure** + +Wait for the system service to start and call the API again. diff --git a/en/application-dev/reference/errorcodes/errorcode-sensor.md b/en/application-dev/reference/errorcodes/errorcode-sensor.md new file mode 100644 index 0000000000000000000000000000000000000000..571156ec00328b0ba564cd6174e6fb81aa5154b1 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-sensor.md @@ -0,0 +1,20 @@ +# Sensor Error Codes + +## 14500101 Service exception. + +**Error Message** + +Service exception. + +**Description** + +This error code is reported if the HDI service is abnormal when the **on**, **once**, or **off** interface of the sensor module is called. + +**Possible Causes** + +The HDI service is abnormal. + +**Procedure** + +1. Retry the operation at a specified interval (for example, 1s) or at an exponential increase interval. +2. If the operation fails for three consecutive times, stop the retry. You can also attempt to obtain the sensor list to check for device availability. diff --git a/en/application-dev/reference/errorcodes/errorcode-vibrator.md b/en/application-dev/reference/errorcodes/errorcode-vibrator.md new file mode 100644 index 0000000000000000000000000000000000000000..f5dc329c1e96d945f76c7625b365a53fe50477b4 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-vibrator.md @@ -0,0 +1,21 @@ +# Vibrator Error Codes + +## 14600101 Device operation failed. + +**Error Message** + +Device operation failed. + +**Description** + +This error code is reported if the HDI service is abnormal or the device is occupied when the **startVibration** interface of the vibrator module is called. + +**Possible Causes** + +1. The HDI service is abnormal. +2. The device is occupied. + +**Procedure** + +1. Retry the operation at a specified interval or at an exponential increase interval. If the operation fails for three consecutive times, stop the retry. You can also obtain the vibrator list to check for device availability. +2. Set a higher priority for the vibrator. diff --git a/en/application-dev/ui/ui-js-building-ui-layout-image.md b/en/application-dev/ui/ui-js-building-ui-layout-image.md index 75eee016fa91e8a94e58ef565fa0c3245f1b9ea9..fc7b696c5fd9385ab36673e3ca0d0bd75c9b1a7e 100644 --- a/en/application-dev/ui/ui-js-building-ui-layout-image.md +++ b/en/application-dev/ui/ui-js-building-ui-layout-image.md @@ -1,10 +1,11 @@ # Adding an Image +Generally, the **[\](../reference/arkui-js/js-components-basic-image.md)** component is used to add images on a page. The method of using this component is similar to that of using the **\** component. -Generally, the [<image>](../reference/arkui-js/js-components-basic-image.md) component is used to add images on a page. The method of using this component is similar to that of using the **\** component. -To reference images via the **\** component, you must create the common directory under jsdefault, and then store the image files in the common directory. For details about the directory structure, see [Directory Structure](../ui/js-framework-file.md). The following sample code shows you how to add an image and set its style. +To reference images via the **\** component, you are advised to store the image files under **js\default\common**. (You need to create the **common** directory on your own.) For details about the directory structure, see [Directory Structure](../ui/js-framework-file.md#directory-structure). The following sample code shows you how to add an image and set its style. + ```html diff --git a/en/application-dev/ui/ui-ts-creating-simple-page.md b/en/application-dev/ui/ui-ts-creating-simple-page.md index f5a73f166ef3077777c1a61c38ada070d9cd3157..bd08135a143e3b87d15c30b739b10f3eb22dfbda 100644 --- a/en/application-dev/ui/ui-ts-creating-simple-page.md +++ b/en/application-dev/ui/ui-ts-creating-simple-page.md @@ -1,6 +1,5 @@ # Creating a Simple Page - In this section, we will develop an infographic food details page, by building custom components through the container components **\** and **\** as well as basic components **\** and **\**. @@ -9,7 +8,7 @@ In this section, we will develop an infographic food details page, by building c 1. Create a food name. Delete the code of the **build** method in the project template, create a **\** component, and place the **\** component in the braces of the **\** component. When the **\** component contains multiple child components, the latter child component overwrites the former one. - + ``` @Entry @Component @@ -21,14 +20,14 @@ In this section, we will develop an infographic food details page, by building c .fontWeight(500) } } - } +} ``` -![en-us_image_0000001222967780](figures/en-us_image_0000001222967780.png) - + ![en-us_image_0000001222967780](figures/en-us_image_0000001222967780.png) + 2. Display food pictures. - Create an **\** component and specify a URL for it. The **\** and **\** components are mandatory. To display the **\** component above the **\** component, you need to declare the **\** component first. Image resources are stored in the **rawfile** folder in **resources**. When referencing the resources in the **rawfile** folder, use the `"$rawfile('filename')"` format, where **filename** indicates the relative path of the file in the **rawfile** folder. Currently, `$rawfile` only allows the **\** component to reference image resources. + Create an **\** component and specify a URL for it. To display the **\** component above the **\** component, declare the **\** component first. Image resources are stored in the **rawfile** folder in **resources**. When referencing the resources in the **rawfile** folder, use the `$rawfile('filename')` format, where **filename** indicates the relative path of the file in the **rawfile** folder. Currently,` $rawfile` only allows the **\** component to reference image resources. ``` @Entry @@ -45,17 +44,17 @@ In this section, we will develop an infographic food details page, by building c } ``` - ![en-us_image_0000001267887861](figures/en-us_image_0000001267887861.png) - -3. Access images through resources. - In addition to specifying the image path, you can also use the media resource symbol `$r` to reference resources in the **resources** folder based on the resource qualifier rules. Right-click the **resources** folder, choose **New** > **Resource Directory**, and set **Resource Type** to **Media (image resource)**. - - Place **Tomato.png** in the **media** folder. You can then can reference the application resource in the `$r('app.type.name')` format, that is, `$r('app.media.Tomato')`. +![en-us_image_0000001267887861](figures/en-us_image_0000001267887861.png) +3. Access images through resources. + + In addition to specifying the image path, you can also use the media resource symbol **$r** to reference resources based on the resource qualifier rules in the **resources** folder. Right-click the **resources** folder, choose **New** > **Resource Directory** from the shortcut menu, and set **Resource Type** to **Media** (image resource). + + Place **Tomato.png** in the **media** folder. You can then reference the application resources in the `$r('app.type.name')` format, which is `$r('app.media.Tomato')` in this example. - ``` - @Entry +``` +@Entry @Component struct MyComponent { build() { @@ -69,15 +68,18 @@ In this section, we will develop an infographic food details page, by building c } } } - ``` +``` -4. Set the width and height of the image, and set the **objectFit** attribute of the image to **ImageFit.Contain**, which means to keep the aspect ratio of the image to ensure that the image is completely displayed within the boundary. If the image fills the entire screen, the possible causes are as follows: + +4. Set the width and height of the image, and set the **objectFit** attribute of the image to **ImageFit.Contain**, which means to keep the aspect ratio of the image to ensure that the image is completely displayed within the boundary. - 1. The width and height of the image are not set. - 2. The default attribute of **objectFit** of the image is **ImageFit.Cover**, that is, the image is zoomed in or zoomed out to fill the entire display boundary with the aspect ratio locked. - - ``` - @Entry + If the image fills the entire screen, the possible causes are as follows: + + - The width and height of the image are not set. + - The default attribute of **objectFit** of the image is **ImageFit.Cover**, that is, the image is zoomed in or zoomed out to fill the entire display boundary with the aspect ratio locked. + +``` +@Entry @Component struct MyComponent { build() { @@ -91,14 +93,17 @@ In this section, we will develop an infographic food details page, by building c } } } - ``` +``` + -![en-us_image_0000001223127732](figures/en-us_image_0000001223127732.png) -​ -5. Set the food image and name layout. Set **alignContent** to **Alignment.BottomStart**. Similar to **FontWeight**, **Alignment** is a built-in enumeration type provided by the framework. + ![en-us_image_0000001223127732](figures/en-us_image_0000001223127732.png) + +5. Set the food image and name layout. + + Set **alignContent** of the **\** component to **Alignment.BottomStart**. Similar to **FontWeight**, **Alignment** is a built-in enumeration type provided by the framework. ``` - @Entry +@Entry @Component struct MyComponent { build() { @@ -114,15 +119,19 @@ In this section, we will develop an infographic food details page, by building c } ``` - ![en-us_image_0000001267647873](figures/en-us_image_0000001267647873.png) -6. You can change the background color of the food image by setting the background color of the **\** component in either of the following ways: - 1. Using the built-in **Color** enums provided by the framework. For example, **backgroundColor(Color.Red)** indicates that the background color is set to red. - 2. Using the string-type parameter. The supported color formats are rgb, rgba, and HEX. For example, you can set the background color to blue by setting **backgroundColor(??\#0000FF??)** and set the background color to white by setting **backgroundColor(??rgb(255, 255, 255)??)**. + ![en-us_image_0000001267647873](figures/en-us_image_0000001267647873.png) +6. You can change the background color of the food image by setting the background color of the **\** component in any of the following ways: + 1. Using a built-in enumeration value of **Color** provided by the framework. For example, **backgroundColor(Color.Red)** indicates that the background color is set to red. + 2. Using a value of the string type. The supported color formats are rgb, rgba, and HEX. For example, you can set the background color to blue through **backgroundColor(??#0000FF??)** and set the background color to white through **backgroundColor(??rgb(255, 255, 255)??)**. + 3. Using a value of the number type. Hexadecimal color values are supported. For example, **backgroundColor(0xFF0000)** indicates that the background color is red. + + 4. Using a value of the Resource type. For details about the Resource type, see [Resource Access](ts-resource-access.md). + - ``` - @Entry +``` +@Entry @Component struct MyComponent { build() { @@ -136,18 +145,19 @@ In this section, we will develop an infographic food details page, by building c } .backgroundColor('#FFedf2f5') } - } - ``` +} +``` - ![en-us_image_0000001222967772](figures/en-us_image_0000001222967772.png) -7. Adjust the left and bottom margin of the **\** component. **Margin** is a shorthand attribute. You can specify the margins of the four edges in a unified manner or separately. The configuration method is as follows: - 1. To set the margins of the four edges in a unified manner, use the **Margin(Length)** format. For example, **margin(20)** indicates that the outer margins of the top, right, bottom, and left edges are all 20. - 2. To set the margins of the four edges separately, use the **{top?: Length, right?: Length, bottom?: Length, left?:Length}** format. For example, **margin({ left: 26, bottom: 17.4 })** indicates that the left margin is 26 and the bottom margin is 17.4. + ![en-us_image_0000001222967772](figures/en-us_image_0000001222967772.png) +7. Adjust the left and bottom margin of the **\** component. Margin is a shorthand attribute. You can specify the margins of the four edges in a unified manner or separately. + - To set the margins of the four edges in a unified manner, use the **Margin(Length)** format. For example, **margin(20)** indicates that the margins of the top, right, bottom, and left edges are all 20. + + - To set the margins of the four edges separately, use the **{top?: Length, right?: Length, bottom?: Length, left?:Length}** format. For example, **margin({ left: 26, bottom: 17.4 })** indicates that the left margin is 26 and the bottom margin is 17.4. - ``` - @Entry +``` +@Entry @Component struct MyComponent { build() { @@ -163,17 +173,17 @@ In this section, we will develop an infographic food details page, by building c .backgroundColor('#FFedf2f5') } } - ``` +``` + ![en-us_image_0000001222967776](figures/en-us_image_0000001222967776.png) -8. Adjust the structure between components and semanticize component names. Create the **FoodDetail** page entry component, create a column in **FoodDetail**, and set the alignment to **alignItems(HorizontalAlign.Center)**. Change the name of the **MyComponent** component to **FoodImageDisplay**, which is a child component of the **FoodDetail** component. - - A column is a container component whose child components are vertically arranged. It is a linear layout in essence. Therefore, only the alignment in the cross axis direction can be set. +8. Adjust the structure between components and semanticize component names. Create the **FoodDetail** page entry component, create a **\** component in **FoodDetail**, and set the alignment to **alignItems(HorizontalAlign.Center)**. Change the name of the **MyComponent** component to **FoodImageDisplay**, which is a child component of the **FoodDetail** component. + The **\** component is a container whose child components are vertically arranged. It is in linear layout in essence. Therefore, only the alignment in the cross axis direction can be set. - ``` - @Component +``` +@Component struct FoodImageDisplay { build() { Stack({ alignContent: Alignment.BottomStart }) { @@ -199,17 +209,18 @@ In this section, we will develop an infographic food details page, by building c .alignItems(HorizontalAlign.Center) } } - ``` +``` + ## Building the Flex Layout -You can use the Flex layout to build a food composition table. In this way you do not need to worry about the width and height calculation. The size of different cells can be flexibly set based on the proportion. +Use the **Flex** layout to build a food composition table. In this way, cell sizes are flexibly set based on the proportion, eliminating the need for width and height calculation. 1. Create a **ContentTable** component as a child component of the **FoodDetail** component. - ``` - @Component +``` +@Component struct FoodImageDisplay { build() { Stack({ alignContent: Alignment.BottomStart }) { @@ -241,19 +252,19 @@ You can use the Flex layout to build a food composition table. In this way you d .alignItems(HorizontalAlign.Center) } } - ``` +``` -2. Create a Flex component to display two food composition categories in the tomato: **Calories** and **Nutrition**. + +2. Create a **\** component to display two food composition categories in the tomato: **Calories** and **Nutrition**. **Calories** contains information about calories. **Nutrition** contains information about protein, fat, carbohydrates, and vitamin C. - Create the **Calories** class. Create a Flex component and set its height to 280, and the top, right, and left margins to 30. The Flex component contains three **\** child components, which represent the category name (**Calories**), content name (**Calories**), and contain value (**17 kcal**), respectively. By default, child components in the Flex component are arranged horizontally. + Create the **Calories** class. Create a **\** component and set its height to **280**, and the top, right, and left margins to **30**. The **Flex** component contains three **\** child components, which represent the category name (**Calories**), content name (**Calories**), and contain value (**17 kcal**), respectively. By default, child components in the **Flex** component are arranged horizontally. In the following example, code of **FoodImageDisplay** is omitted, and only code of **ContentTable** is provided. - - ``` - @Component +``` +@Component struct ContentTable { build() { Flex() { @@ -281,14 +292,15 @@ You can use the Flex layout to build a food composition table. In this way you d .alignItems(HorizontalAlign.Center) } } - ``` +``` + ![en-us_image_0000001267767869](figures/en-us_image_0000001267767869.png) -3. Adjust the layout and set the proportion (**layoutWeight**) of each part. Set the proportion of the category name to **1**, and the total proportion of content name and content value to **2**. The content name and content value are in a same Flex, and the content name occupies all remaining space **flexGrow(1)**. +3. Adjust the layout and set the proportion (**layoutWeight**) of each part. Set **layoutWeight** of the category name to **1**, and **layoutWeight** of the content name and content value to **2**. The content name and content value are in a same **Flex**, and the content name occupies all remaining space **flexGrow(1)**. - ``` - @Component +``` +@Component struct FoodImageDisplay { build() { Stack({ alignContent: Alignment.BottomStart }) { @@ -337,7 +349,8 @@ You can use the Flex layout to build a food composition table. In this way you d .alignItems(HorizontalAlign.Center) } } - ``` +``` + ![en-us_image_0000001267607901](figures/en-us_image_0000001267607901.png) @@ -345,9 +358,8 @@ You can use the Flex layout to build a food composition table. In this way you d Set **FlexDirection.Column**, **FlexAlign.SpaceBetween**, and **ItemAlign.Start**. - - ``` - @Component +``` +@Component struct ContentTable { build() { Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Start }) { @@ -438,19 +450,19 @@ You can use the Flex layout to build a food composition table. In this way you d .alignItems(HorizontalAlign.Center) } } - ``` +``` -5. Use the custom constructor @Builder to simplify the code. It can be found that the food groups in each food composition table are actually of the same UI structure. +5. Use the custom constructor **\@Builder** to simplify the code. It can be found that the food groups in each food composition table are actually of the same UI structure. + ![en-us_image_0000001223287704](figures/en-us_image_0000001223287704.png) + + Currently, all food groups are declared, resulting in code duplication and redundancy. You can use **\@Builder** to build a custom method and abstract the same UI structure declaration. The **\@Builder** decorated method and the **build** method for the **@Component** decorated component are used to declare some UI rendering structures and comply with the same ArkTS syntax. You can define one or more methods decorated by **\@Builder**, but a component decorated by **@Component** can have only one **build** method. + + Declare the **IngredientItem** method decorated by **\@Builder** in **ContentTable** to declare the UI descriptions for the category name, content name, and content value. - Currently, all food groups are declared, resulting in code duplication and redundancy. You can use @Builder to build a custom method and abstract the same UI structure declaration. The @Builder decorated method and the build method for the @Component decorated component are used to declare some UI rendering structures and comply with the same eTS syntax. You can define one or more methods decorated by @Builder, but a component decorated by @Component can have only one build method. - - Declare the **IngredientItem** method decorated by @Builder in **ContentTable** to declare the UI descriptions for the category name, content name, and content value. - - - ``` - @Component +``` + @Component struct ContentTable { @Builder IngredientItem(title:string, name: string, value: string) { Flex() { @@ -469,13 +481,13 @@ You can use the Flex layout to build a food composition table. In this way you d } } } - ``` +``` - When the `IngredientItem` API is called in the **build** method of **ContentTable**, `this` needs to be used to invoke the method in the scope of the component to distinguish the global method call. +When the **IngredientItem** API is called in the **build** method of **ContentTable**, **this** needs to be used to invoke the method in the scope of the component to distinguish the global method call. - ``` - @Component +``` +@Component struct ContentTable { ...... build() { @@ -490,13 +502,13 @@ You can use the Flex layout to build a food composition table. In this way you d .padding({ top: 30, right: 30, left: 30 }) } } - ``` +``` - The overall code of the **ContentTable** component is as follows: +The overall code of the **ContentTable** component is as follows: - ``` - @Component +``` +@Component struct ContentTable { @Builder IngredientItem(title:string, name: string, value: string) { Flex() { @@ -514,18 +526,19 @@ You can use the Flex layout to build a food composition table. In this way you d .layoutWeight(2) } } - - build() { - Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Start }) { - this.IngredientItem('Calories', 'Calories', '17kcal') - this.IngredientItem('Nutrition', 'Protein', '0.9g') - this.IngredientItem('', 'Fat', '0.2g') - this.IngredientItem('', 'Carbohydrates', '3.9g') - this.IngredientItem('', 'VitaminC', '17.8mg') - } - .height(280) - .padding({ top: 30, right: 30, left: 30 }) - } + + build() { + Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Start }) { + this.IngredientItem('Calories', 'Calories', '17kcal') + this.IngredientItem('Nutrition', 'Protein', '0.9g') + this.IngredientItem('', 'Fat', '0.2g') + this.IngredientItem('', 'Carbohydrates', '3.9g') + this.IngredientItem('', 'VitaminC', '17.8mg') + } + .height(280) + .padding({ top: 30, right: 30, left: 30 }) + } + } @Entry @@ -539,8 +552,9 @@ You can use the Flex layout to build a food composition table. In this way you d .alignItems(HorizontalAlign.Center) } } - ``` +``` + -![en-us_image_0000001222807792](figures/en-us_image_0000001222807792.png) + ![en-us_image_0000001222807792](figures/en-us_image_0000001222807792.png) You've learned how to build a simple food details page. Read on to learn how to define the page layout and connection. diff --git a/en/application-dev/website.md b/en/application-dev/website.md index 123f42406d4570caf213019a48bcd8ff8b213f5c..8116d311b340c020f1ac5c07e6aa0269fa690a2d 100644 --- a/en/application-dev/website.md +++ b/en/application-dev/website.md @@ -37,7 +37,7 @@ - [Test Framework Usage](ability/ability-delegator.md) - UI Development - [ArkUI Overview](ui/arkui-overview.md) - - TypeScript-based Declarative Development Paradigm + - ArkTS-based Declarative Development Paradigm - [Overview](ui/ui-ts-overview.md) - Framework Overview - File Organization @@ -47,49 +47,10 @@ - [Resource File Categories](ui/ui-ts-basic-resource-file-categories.md) - [Accessing Resources](ui/ts-resource-access.md) - [Pixel Units](ui/ts-pixel-units.md) - - Declarative Syntax - - [Overview](ui/ts-syntax-intro.md) - - General UI Description Specifications - - [Basic Concepts](ui/ts-general-ui-concepts.md) - - Declarative UI Description Specifications - - [Configuration Without Parameters](ui/ts-parameterless-configuration.md) - - [Configuration with Mandatory Parameters](ui/ts-configuration-with-mandatory-parameters.md) - - [Attribute Configuration](ui/ts-attribution-configuration.md) - - [Event Configuration](ui/ts-event-configuration.md) - - [Child Component Configuration](ui/ts-child-component-configuration.md) - - Componentization - - [@Component](ui/ts-component-based-component.md) - - [@Entry](ui/ts-component-based-entry.md) - - [@Preview](ui/ts-component-based-preview.md) - - [@Builder](ui/ts-component-based-builder.md) - - [@Extend](ui/ts-component-based-extend.md) - - [@CustomDialog](ui/ts-component-based-customdialog.md) - - [@Styles](ui/ts-component-based-styles.md) - - About UI State Management - - [Basic Concepts](ui/ts-ui-state-mgmt-concepts.md) - - Managing Component States - - [@State](ui/ts-component-states-state.md) - - [@Prop](ui/ts-component-states-prop.md) - - [@Link](ui/ts-component-states-link.md) - - Managing Application States - - [AppStorage](ui/ts-application-states-appstorage.md) - - [LocalStorage](ui/ui-ts-local-storage.md) - - [PersistentStorage](ui/ts-application-states-apis-persistentstorage.md) - - [Environment](ui/ts-application-states-apis-environment.md) - - Managing Other States - - [@Observed and @ObjectLink](ui/ts-other-states-observed-objectlink.md) - - [@Consume and @Provide](ui/ts-other-states-consume-provide.md) - - [@Watch](ui/ts-other-states-watch.md) - - About Rendering Control Syntax - - [if/else](ui/ts-rending-control-syntax-if-else.md) - - [ForEach](ui/ts-rending-control-syntax-foreach.md) - - [LazyForEach](ui/ts-rending-control-syntax-lazyforeach.md) - - About @Component - - [build Function](ui/ts-function-build.md) + - Componentization - [Initialization of Custom Components' Member Variables](ui/ts-custom-component-initialization.md) - [Custom Component Lifecycle Callbacks](ui/ts-custom-component-lifecycle-callbacks.md) - [Component Creation and Re-initialization](ui/ts-component-creation-re-initialization.md) - - [About Syntactic Sugar](ui/ts-syntactic-sugar.md) - Common Component Development Guidelines - [Button](ui/ui-ts-basic-components-button.md) - [Web](ui/ui-ts-components-web.md) @@ -107,7 +68,7 @@ - [Building a Food Category Grid Layout](ui/ui-ts-building-category-grid-layout.md) - [Implementing Page Redirection and Data Transmission](ui/ui-ts-page-redirection-data-transmission.md) - [Recommendations for Improving Performance](ui/ts-performance-improvement-recommendation.md) - - JavaScript-based Web-like Development Paradigm + - JavaScript-compatible Web-like Development Paradigm - [Overview](ui/ui-js-overview.md) - Framework - [File Organization](ui/js-framework-file.md) @@ -183,9 +144,6 @@ - [Common Event and Notification Overview](notification/notification-brief.md) - [Common Event Development](notification/common-event.md) - [Notification Development](notification/notification-guidelines.md) - - Agent-Powered Scheduled Reminder - - [Agent-Powered Scheduled Reminder Overview](notification/background-agent-scheduled-reminder-overview.md) - - [Agent-Powered Scheduled Reminder Development](notification/background-agent-scheduled-reminder-guide.md) - [Debugging Assistant Usage](notification/assistant-guidelines.md) - Window Manager - [Window Overview](windowmanager/window-overview.md) @@ -313,7 +271,8 @@ - [Samples](https://gitee.com/openharmony/applications_app_samples/blob/master/README.md) - [Codelabs](https://gitee.com/openharmony/codelabs) - API References - - Component Reference (TypeScript-based Declarative Development Paradigm) + - [SysCap List](reference/syscap-list.md) + - Component Reference (ArkTS-based Declarative Development Paradigm) - Universal Component Information - Universal Events - [Click Event](reference/arkui-ts/ts-universal-events-click.md) @@ -446,12 +405,12 @@ - Canvas Components - [Canvas](reference/arkui-ts/ts-components-canvas-canvas.md) - [CanvasRenderingContext2D](reference/arkui-ts/ts-canvasrenderingcontext2d.md) - - [OffscreenCanvasRenderingConxt2D](reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md) - - [Lottie](reference/arkui-ts/ts-components-canvas-lottie.md) - - [Path2D](reference/arkui-ts/ts-components-canvas-path2d.md) - [CanvasGradient](reference/arkui-ts/ts-components-canvas-canvasgradient.md) - [ImageBitmap](reference/arkui-ts/ts-components-canvas-imagebitmap.md) - [ImageData](reference/arkui-ts/ts-components-canvas-imagedata.md) + - [OffscreenCanvasRenderingConxt2D](reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md) + - [Path2D](reference/arkui-ts/ts-components-canvas-path2d.md) + - [Lottie](reference/arkui-ts/ts-components-canvas-lottie.md) - Animation - [AnimatorProperty](reference/arkui-ts/ts-animatorproperty.md) - [Explicit Animation](reference/arkui-ts/ts-explicit-animation.md) @@ -460,8 +419,7 @@ - [Component Transition](reference/arkui-ts/ts-transition-animation-component.md) - [Transition of Shared Elements](reference/arkui-ts/ts-transition-animation-shared-elements.md) - [Motion Path Animation](reference/arkui-ts/ts-motion-path-animation.md) - - [Matrix Transformation](reference/arkui-ts/ts-matrix-transformation.md) - - [Interpolation Calculation](reference/arkui-ts/ts-interpolation-calculation.md) + - Global UI Methods - Pop-up Window - [Alert Dialog Box](reference/arkui-ts/ts-methods-alert-dialog-box.md) @@ -473,7 +431,7 @@ - [Menu](reference/arkui-ts/ts-methods-menu.md) - [Built-in Enums](reference/arkui-ts/ts-appendix-enums.md) - [Types](reference/arkui-ts/ts-types.md) - - Component Reference (JavaScript-based Web-like Development Paradigm) + - Component Reference (JavaScript-compatible Web-like Development Paradigm) - Universal Component Information - [Universal Attributes](reference/arkui-js/js-components-common-attributes.md) - [Universal Styles](reference/arkui-js/js-components-common-styles.md) @@ -719,7 +677,6 @@ - [@ohos.document](reference/apis/js-apis-document.md) - [@ohos.environment](reference/apis/js-apis-environment.md) - [@ohos.fileio](reference/apis/js-apis-fileio.md) - - [@ohos.fileManager](reference/apis/js-apis-filemanager.md) - [@ohos.multimedia.medialibrary](reference/apis/js-apis-medialibrary.md) - [@ohos.securityLabel](reference/apis/js-apis-securityLabel.md) - [@ohos.statfs](reference/apis/js-apis-statfs.md) @@ -752,6 +709,7 @@ - [tagSession](reference/apis/js-apis-tagSession.md) - Basic Features - [@ohos.accessibility](reference/apis/js-apis-accessibility.md) + - [@ohos.accessibility.config](reference/apis/js-apis-accessibility-config.md) - [@ohos.faultLogger](reference/apis/js-apis-faultLogger.md) - [@ohos.hiAppEvent](reference/apis/js-apis-hiappevent.md) - [@ohos.hichecker](reference/apis/js-apis-hichecker.md) diff --git a/en/contribute/template/errorcodes-template.md b/en/contribute/template/errorcodes-template.md new file mode 100644 index 0000000000000000000000000000000000000000..38fe0569a2c50ba7ad51c9893078221e32bc8fb6 --- /dev/null +++ b/en/contribute/template/errorcodes-template.md @@ -0,0 +1,117 @@ +# *ModuleName* Error Codes + +> **NOTE** +> +> 1. Delete all writing instructions from your document after you finish the writing. +> +> 2. The error code document must be named in the format of **errorcode-*moduleName*.md**, where *moduleName* must be the same as that used in the corresponding API reference document. + +| | Item | Writing Instruction | +| ---- | ------------------------------ | ------------------------------------------------------------ | +| 1 | error.errorNumber | Use the error code IDs that are designed based on the unified error code numbering rule. | +| 2 | error.message | **Meaning of this field**: If an exception occurs, an error object is thrown. The object contains **errorNumber** and **error.message**, which is a short text description of the error code in English.
**Instructions**
1. The description should be concise and specific.
2. The description should be grammatically correct. | +| 3 | Description | **Meaning of this field**: provides detailed description for the error code, including the use case when and the location where the error code is thrown.
**Instructions**
1. Describe the use case when the error code is thrown, for example, when developing a specific service or feature.
2. Describe the symptom and location of the error (for example, the exact module name, class name, and interface name).| +| 4 | Possible Causes | **Meaning of this field**: lists all possible causes of the error.
**Instructions**
1. List all the possible causes.
2. Use concise sentences.
3. Sort the causes by possibility in descending order.| +| 5 | Procedure | **Meaning of this field**: describes how to handle the error based on the symptom and possible causes.
**Instructions**
1. Provide the procedure step by step. Each step should correspond to a possible cause. You can use substeps for complex operations of a step.
2. The steps should be clear, specific, and executable. If judgment is involved, provide clear judgment criteria.
3. If an operation has impact on the system or services, provide warning information in the form of Caution or Warning before the operation. | + +## 1300001 Repeated Operation (Error Code + Space + Error Description) + +### Error Message + +Repeated operation. + +### Description + +> **NOTE** +> +> Describe the use case (for example, developing a specific service or feature) when the error code is thrown and the symptom. + +This error code is generated when a repeated operation is performed on the same **Window** object. + +### Possible Causes + +> **NOTE** +> +> List all possible causes of the error. +> +> *1. List all the possible causes.* +> +> *2. Use concise sentences.* +> +> *3. Sort the causes by possibility in descending order.* + +1. The **Window** object to create already exists. + +2. xxx. + +### Procedure + +> **NOTE** +> +> *Describe how to handle the error based on the symptom and possible causes.* +> +> 1. Provide the procedure step by step. Each step should correspond to a possible cause. You can use substeps for complex operations of a step. +> +> 2. The steps should be clear, specific, and executable. If judgment is involved, provide clear judgment criteria. +> +> 3. If an operation has impact on the system or services, provide warning information in the form of Caution or Warning before the operation. + +1. Check whether the **Window** object has been created. + + xxx. + + ``` + uth([in] String appId, [in] IHwShareCallback callback); + int shareFaInfo([in] PacMapEx pacMapEx); + } + ``` + +2. xxx. + + a. xxx. + + ``` + uth([in] String appId, [in] IHwShareCallback callback); + int shareFaInfo([in] PacMapEx pacMapEx); + } + ``` + + b. xxx. + +## 1300002 Abnormal Window Status + +### Error Message + +xxx + +### Description + +xxx + +### Possible Causes + +1. xxx + +### Procedure + +1. Check whether the **Window** object has been created. + + xxx. + + ``` + uth([in] String appId, [in] IHwShareCallback callback); + int shareFaInfo([in] PacMapEx pacMapEx); + } + ``` + +2. xxx. + + a. xxx. + + ``` + uth([in] String appId, [in] IHwShareCallback callback); + int shareFaInfo([in] PacMapEx pacMapEx); + } + ``` + + b. xxx. diff --git a/en/contribute/template/js-template.md b/en/contribute/template/js-template.md index 57910d025c4214fec8cc1f3a7a09b03c10f5f3ea..52c784838fc794ee2ebb5f3800ce881a66b17e35 100644 --- a/en/contribute/template/js-template.md +++ b/en/contribute/template/js-template.md @@ -1,7 +1,7 @@ # API Reference Template ## General Writing Instructions -> **NOTE** +> **NOTE** > > Delete all writing instructions after you finish the writing. @@ -141,10 +141,19 @@ Describe the method. For details, see the fourth and fifth points in "Writing In **Return value** (This part is optional. Delete it if there is no return value.) -| Type | Description | -| ------------------------------------------ | ------------------------------------------------------------ | -| string | Describe the return value, for example, what can be done after the return value is obtained. | -| Promise\> | Describe the return value. For details about how to write promise methods, see item 14 in "General Writing Instructions." | +| Type | Description | +| ------------------------------------------ | ----------------------------------------------- | +| string | Describe the return value, for example, what can be done after the return value is obtained.| +| Promise\> | Describe the return value. For details about how to write promise methods, see item 14 in "General Writing Instructions."| + +**Error codes** (This part is optional. Delete it if no error code is thrown.) + +For details about the error codes, see [moduleName Error Codes]\(link to the error code document of the corresponding module). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 1300001 | Repeated operation. | +| 1300002 | This window state is abnormal. | **Example** diff --git a/en/device-dev/get-code/gettools-acquire.md b/en/device-dev/get-code/gettools-acquire.md index 3e62d40ed004ff884aecb9c78b8b4d7b794a95dc..a3025ebd834424ff319aa25f3194609ead2cf1e9 100644 --- a/en/device-dev/get-code/gettools-acquire.md +++ b/en/device-dev/get-code/gettools-acquire.md @@ -7,7 +7,7 @@ OpenHarmony provides the following two types of Docker environments for you to q - Standalone Docker environment: applicable when using Ubuntu or Windows to build a distribution - HPM-based Docker environment: applicable when using the HarmonyOS Package Manager \(HPM\) to build a distribution -**Table 1** Docker image +**Table 1** Docker image

Docker Environment

@@ -67,11 +67,12 @@ OpenHarmony provides the following two types of Docker environments for you to q Before using the Docker environment, perform the following operations: -1. Install Docker. For details, see [Install Docker Engine](https://docs.docker.com/engine/install/). -2. Obtain the OpenHarmony source code. For details, see [Source Code Acquisition](sourcecode-acquire.md). +1. Install Docker. For details, see [Install Docker Engine](https://docs.docker.com/engine/install/). +2. Obtain the OpenHarmony source code. For details, see [Source Code Acquisition](sourcecode-acquire.md). - >![](../public_sys-resources/icon-note.gif) **NOTE**
- >You do not need to obtain the source code for the HPM-based Docker environment. + > **NOTE** + > + > You do not need to obtain the source code for the HPM-based Docker environment. ## Standalone Docker Environment @@ -94,7 +95,7 @@ The Docker image of OpenHarmony is hosted on HUAWEI CLOUD SWR. Using the Docker docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:1.0.0 ``` - Run the following command in Windows \(assuming that the source code directory is **D:\\OpenHarmony**\): + Run the following command in Windows \(assuming that the source code directory is **D:\\OpenHarmony**\): ``` docker run -it -v D:\OpenHarmony:/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:1.0.0 @@ -111,17 +112,17 @@ Set the build path to the current path. hb set ``` -**Figure 1** Setting page +**Figure 1** Setting page ![](figure/setting-page.png "setting-page") ->![](../public_sys-resources/icon-note.gif) **NOTE**
->The mapping between the development board and the building GUI: +> **NOTE**
+> The mapping between the development board and the building GUI: > ->- Hi3861: wifiiot\_hispark\_pegasus@hisilicon ->- Hi3516: ipcamera\_hispark\_taurus@hisilicon ->- Hi3518: ipcamera\_hispark\_aries@hisilicon +> - Hi3861: wifiiot\_hispark\_pegasus@hisilicon +> - Hi3516: ipcamera\_hispark\_taurus@hisilicon +> - Hi3518: ipcamera\_hispark\_aries@hisilicon -1. Select **ipcamera\_hispark\_taurus@hisilicon** and press **Enter**. +1. Select **ipcamera\_hispark\_taurus@hisilicon** and press **Enter**. 2. Start building. ``` @@ -130,7 +131,7 @@ hb set 3. View the build result. - The files will be generated in the **out/hispark\_taurus/ipcamera\_hispark\_taurus** directory. + The files will be generated in the **out/hispark\_taurus/ipcamera\_hispark\_taurus** directory. ### Setting Up the Docker Environment for Standard-System Devices \(reference memory ≥ 128 MB\) @@ -156,17 +157,17 @@ Run the following script to start building for standard-system devices \(referen ./build.sh --product-name {product_name} --ccache ``` -**product\_name** indicates the platform supported by the current distribution, for example, hispark_taurus_standard and rk3568. +**product\_name** indicates the platform supported by the current distribution, for example, hispark_taurus_standard and rk3568. -Files generated during building are stored in the **out/{device_name}/** directory, and the generated image is stored in the **out/{device_name}/packages/phone/images/** directory. +Files generated during building are stored in the **out/{device_name}/** directory, and the generated image is stored in the **out/{device_name}/packages/phone/images/** directory. >![](../public_sys-resources/icon-note.gif) **NOTE**
->You can exit Docker by simply running the **exit** command. +>You can exit Docker by simply running the **exit** command. ## HPM-based Docker Environment -**docker\_dist** is a template component in the [HPM](https://hpm.harmonyos.com/#/en/home) system. It helps to quickly initialize an HPM project and use the Docker image to quickly build a distribution of OpenHarmony, greatly simplifying environment configurations needed for building. After configuring the Ubuntu and hpm-cli development environments, perform the following steps to access the Docker environment: +**docker\_dist** is a template component in the [HPM](https://hpm.harmonyos.com/#/en/home) system. It helps to quickly initialize an HPM project and use the Docker image to quickly build a distribution of OpenHarmony, greatly simplifying environment configurations needed for building. After configuring the Ubuntu and hpm-cli development environments, perform the following steps to access the Docker environment: ### Setting Up the Docker Environment @@ -176,20 +177,20 @@ Files generated during building are stored in the **out/{device_name}/** direc hpm init -t @ohos/docker_dist ``` -2. Modify the **publishAs** field. +2. Modify the **publishAs** field. - The obtained bundle is of the template type. Open the **bundle.json** file in the current directory and change the value of **publishAs** from **template** to **distribution** as needed. + The obtained bundle is of the template type. Open the **bundle.json** file in the current directory and change the value of **publishAs** from **template** to **distribution** as needed. ### Obtaining and Building Source Code Start building. Docker can be automatically installed only in Ubuntu. If you are using any other operating system, manually install Docker before pulling the image. -- **Automatically Installing Docker \(Ubuntu\)** +- **Automatically Installing Docker \(Ubuntu\)** Running the following command will automatically install Docker, pull the Docker image, and start the pulling and building of the corresponding solution in the container. - **Method 1:** + **Method 1:** Add a parameter to specify the solution. For example: @@ -197,9 +198,9 @@ Start building. Docker can be automatically installed only in Ubuntu. If you are hpm run docker solution={product} ``` - **\{product\}** indicates the solution, for example, **@ohos/hispark\_taurus**, **@ohos/hispark\_aries**, and **@ohos/hispark\_pegasus**. + **\{product\}** indicates the solution, for example, **@ohos/hispark\_taurus**, **@ohos/hispark\_aries**, and **@ohos/hispark\_pegasus**. - **Method 2:** + **Method 2:** Set an environment variable to specify the solution, and then run the build command. @@ -209,7 +210,7 @@ Start building. Docker can be automatically installed only in Ubuntu. If you are export solution={product} ``` - **\{product\}** indicates the solution, for example, **@ohos/hispark\_taurus**, **@ohos/hispark\_aries**, and **@ohos/hispark\_pegasus**. + **\{product\}** indicates the solution, for example, **@ohos/hispark\_taurus**, **@ohos/hispark\_aries**, and **@ohos/hispark\_pegasus**. 2. Obtain and build the source code. @@ -217,7 +218,7 @@ Start building. Docker can be automatically installed only in Ubuntu. If you are hpm run docker ``` - This example uses the **@ohos/hispark\_taurus** solution for illustration. If the execution is successful, the output is as follows: + This example uses the **@ohos/hispark\_taurus** solution for illustration. If the execution is successful, the output is as follows: ``` ... @@ -226,7 +227,7 @@ Start building. Docker can be automatically installed only in Ubuntu. If you are ``` -- **Manually Installing Docker \(Non-Ubuntu\)** +- **Manually Installing Docker \(Non-Ubuntu\)** Perform the following operations to install Docker: diff --git a/en/device-dev/subsystems/subsys-boot-appspawn.md b/en/device-dev/subsystems/subsys-boot-appspawn.md index 7b9e10bb654aa3412615cef43a1ba86a78dc23e2..3b713c576e09d859ec623f0f483dc6341f457c5d 100644 --- a/en/device-dev/subsystems/subsys-boot-appspawn.md +++ b/en/device-dev/subsystems/subsys-boot-appspawn.md @@ -63,7 +63,7 @@ The appspawn module is used only for the standard system. - Support for cold start of applications by using the aa command ``` - param set appspawn.cold.boot true // Enable cold start. + param set startup.appspawn.cold.boot 1 // Enable cold start. aa start -d 12345 -a $name -b $package -C Reference command: aa start -d 12345 -a ohos.acts.startup.sysparam.function.MainAbility -b ohos.acts.startup.sysparam.function -C @@ -166,5 +166,5 @@ The following is the sample code for adding product-specific configuration for t
Applications fail to be started by running the cold start command. **Solution** -
1. Enable cold start by setting **param set appspawn.cold.boot true**. +
1. Enable cold start by setting **param set startup.appspawn.cold.boot 1**.
2. Make sure that the cold start command is correct. diff --git a/en/device-dev/subsystems/subsys-boot-init-service.md b/en/device-dev/subsystems/subsys-boot-init-service.md index dbbfee684673226663b9b61d931937e3bf0472ac..5b6954c4d595e03028365866b12ee81be22afeb7 100644 --- a/en/device-dev/subsystems/subsys-boot-init-service.md +++ b/en/device-dev/subsystems/subsys-boot-init-service.md @@ -163,6 +163,22 @@ By parsing the *.cfg file, you can obtain **service** fields, a | int StartServiceByTimer(const char *serviceName, uint64_t timeout) | Starts a service by timer.| Return value: Returns **0** if the operation is successful; returns **-1** otherwise.
Arguments:
**serviceName**: service name.
timeout: timeout interval.| | int StopServiceTimer(const char *serviceName) | Stops a service timer.| Return value: Returns **0** if the operation is successful; returns **-1** otherwise.
Arguments:
**serviceName**: service name.| +- DAC configuration for service control APIs + + Go to **/base/startup/init/services/etc/group** and add the correct user ID to **servicectrl**. For example: + + ```java + servicectrl:x:1050:root,shell,system,samgr,hdf_devmgr + ``` + +- SELinux configuration for service control APIs + + Add the required SELinux permissions to the **init.te** file. For example, grant the system parameter write permission for services such as **init**, **samgr**, and **hdf_devmgr**. + + ```java + allow { init samgr hdf_devmgr } servicectrl_param:parameter_service { set }; + ``` + ### How to Develop The following describes how to add a system service named **MySystemApp**: diff --git a/en/device-dev/subsystems/subsys-boot-init-sysparam.md b/en/device-dev/subsystems/subsys-boot-init-sysparam.md index ef97570ec672f727f5aae4c0a004d160efc0cf61..6f575f67aa430a22913be3b7164682626e79f050 100644 --- a/en/device-dev/subsystems/subsys-boot-init-sysparam.md +++ b/en/device-dev/subsystems/subsys-boot-init-sysparam.md @@ -98,6 +98,55 @@ Each subsystem defines the system parameters of its own modules, including the s ![UGO rule](figure/dac-definition.png) +- SELinux policy for system parameter configuration + + - Add SELinux tags. + + To add a SELinux tag to system parameters, you first need to define the tag in the **/base/security/selinux/sepolicy/base/public/parameter.te** file. For example: + + ```java + type servicectrl_param, parameter_attr + ``` + + After the tag is defined, add the system parameter prefix associated with the tag to **/base/security/selinux/sepolicy/base/public/parameter_contexts**. The following uses the prefix **ohos.servicectrl** as an example: + + ```java + ohos.servicectrl. u:object_r:servicectrl_param:s0 + ``` + + - Grant operation permissions. For example, to grant operation permissions such as map for the init process, add the following content to the **/base/security/selinux/sepolicy/ohos_policy/startup/init/public/init.te** file: + + ```java + allow servicectrl_param tmpfs:filesystem associate; + allow init servicectrl_param:file { map open read relabelto relabelfrom }; + ``` + + - Set the write permission. For example, grant the system parameter write permission for services such as **init**, **samgr**, and **hdf_devmgr**. + + ```java + allow { init samgr hdf_devmgr } servicectrl_param:parameter_service { set }; + ``` + + - Set the read permission. If you want to grant the permission only for certain services, replace **xxx** with the services in the following code: + + ```java + allow { xxx } servicectrl_param:file { map open read }; + ``` + + - If you want to grant the permission for all services, use the following code: + + ```java + allow { domain -limit_domain } servicectrl_param:file { map open read }; + ``` + +- Suggestions + + Keep only two system parameter tags for each subsystem: + + - A private tag to control system parameter settings. + + - A public tag to grant access from all services. + - Loading sequence The following table provides the sequence of loading system parameters. @@ -111,6 +160,22 @@ Each subsystem defines the system parameters of its own modules, including the s | System parameters| /system/etc/param/*.para | Load the parameters defined by each subsystem. If a system parameter already exists, ignore it.| | Persistent parameters| /data/parameters/ | If persistent parameters exist, load them at last. Persistent parameters will overwrite the default system parameters that have been loaded.| + +#### System Parameter Tag File Size + +If one tag corresponds to more than five system parameters, you need to set the size of the system parameter tag file in **/base/startup/init/services/etc/param/ohos.para.size**. The size value is **512** by default. + +Configuring rule: + +System parameter tag = Size + +Example: + +```java +startup_init_param=40960 +``` + + ### Constraints The service management module is available only for the mini system and standard system. diff --git a/en/device-dev/subsystems/subsys-build-all.md b/en/device-dev/subsystems/subsys-build-all.md index 6b97c76a32e18b105b03828112e7ca45aeeb98f8..7585a096ceb0b0c155446902e8e6af556b4c14ec 100644 --- a/en/device-dev/subsystems/subsys-build-all.md +++ b/en/device-dev/subsystems/subsys-build-all.md @@ -102,10 +102,12 @@ You must install the software packages required for build. The command is as fol - Method 2: Run the **apt-get install** and **pip3 install** commands. ```shell apt-get update -y - apt-get install -y apt-utils binutils bison flex bc build-essential make mtd-utils gcc-arm-linux-gnueabi u-boot-tools python3.9.2 python3-pip git zip unzip curl wget gcc g++ ruby dosfstools mtools default-jre default-jdk scons python3-distutils perl openssl libssl-dev cpio git-lfs m4 ccache zlib1g-dev tar rsync liblz4-tool genext2fs binutils-dev device-tree-compiler e2fsprogs git-core gnupg gnutls-bin gperf lib32ncurses5-dev libffi-dev zlib* libelf-dev libx11-dev libgl1-mesa-dev lib32z1-dev xsltproc x11proto-core-dev libc6-dev-i386 libxml2-dev lib32z-dev libdwarf-dev + apt-get install -y + # Install Python 3.9 for Ubuntu 20.04, and install Python 3.8 for Ubuntu 18.04. + apt-get install -y apt-utils binutils bison flex bc build-essential make mtd-utils gcc-arm-linux-gnueabi u-boot-tools python3.9 python3-pip git zip unzip curl wget gcc g++ ruby dosfstools mtools default-jre default-jdk scons python3-distutils perl openssl libssl-dev cpio git-lfs m4 ccache zlib1g-dev tar rsync liblz4-tool genext2fs binutils-dev device-tree-compiler e2fsprogs git-core gnupg gnutls-bin gperf lib32ncurses5-dev libffi-dev zlib* libelf-dev libx11-dev libgl1-mesa-dev lib32z1-dev xsltproc x11proto-core-dev libc6-dev-i386 libxml2-dev lib32z-dev libdwarf-dev apt-get install -y grsync xxd libglib2.0-dev libpixman-1-dev kmod jfsutils reiserfsprogs xfsprogs squashfs-tools pcmciautils quota ppp libtinfo-dev libtinfo5 libncurses5 libncurses5-dev libncursesw5 libstdc++6 gcc-arm-none-eabi vim ssh locales doxygen apt-get install -y libxinerama-dev libxcursor-dev libxrandr-dev libxi-dev - # The following modules must be installed for Python. You can obtain the **repo** file from the source code of the build environment mentioned in **Constraints**. + # The following modules must be installed for Python. You can obtain the repo file from the source code of the build environment you use. chmod +x /usr/bin/repo pip3 install --trusted-host https://repo.huaweicloud.com -i https://repo.huaweicloud.com/repository/pypi/simple requests setuptools pymongo kconfiglib pycryptodome ecdsa ohos-build pyyaml prompt_toolkit==1.0.14 redis json2html yagmail python-jenkins pip3 install esdk-obs-python --trusted-host pypi.org @@ -170,10 +172,10 @@ misc/ ├── scripts/ ├── subsystem_config.json ├── subsystem_config_example.json -├── templates/ # C/C++ build templates +├── templates/ # C/C++ build templates ├── test.gni* -├── toolchain # Build toolchain configuration -├── tools # Common tools +├── toolchain # Build toolchain configuration +├── tools # Common tools ├── version.gni ├── zip.py* @@ -207,18 +209,21 @@ Then, run the build commands in command line (CLI) mode or hb mode. ./build.sh --product-name {product_name} --gn-args is_debug=true ``` - ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
Due to the limitation of the image size, the full build for the debug version may fail to be burnt. You are advised to build the binary file for each module separately. Run the following command to build a module separately: - - ```shell - ./build.sh --product-name {product_name} --gn-args is_debug=true --build-target {target_name} - ``` - + >![icon-caution.gif](../public_sys-resources/icon-caution.gif) **CAUTION**
+ >Due to the limitation of the image size, the full build for the debug version may fail to be burnt. You are advised to build the binary file for each module separately. Run the following command to build a module separately: + > + >``` + >./build.sh --product-name {product_name} --gn-args is_debug=true --build-target {target_name} + >``` + > + > + **{product_name}** specifies the product platform supported by the current distribution, for example, **hispark_taurus_standard**. - + The image generated is stored in the **out/{device_name}/packages/phone/images/** directory. - + - The **./build.sh** command supports the following options: - + ```shell -h, --help # Display help information and exit. --source-root-dir=SOURCE_ROOT_DIR # Specify the path. @@ -240,6 +245,9 @@ Then, run the build commands in command line (CLI) mode or hb mode. --device-type=DEVICE_TYPE # Specify the device type. The default value is default. --build-variant=BUILD_VARIANT #Specify the device operation mode. The default value is user. ``` + + + 2. Using the hb tool @@ -357,7 +365,9 @@ Then, run the build commands in command line (CLI) mode or hb mode. -h, --help show this help message and exit ``` - +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> - For details about how to set up the build environment and perform the build, see the related topics in [Getting Started](../quick-start/Readme-EN.md). +> - OpenHarmony also provides the Docker environment, which spares the installation of the build tool. For details, see [Docker Environment](../get-code/gettools-acquire.md). ### Building Procedures @@ -375,6 +385,7 @@ You can add and build a product, component, chipset solution, and module. For de ## Reference - [deps and external_deps](subsys-build-reference.md#deps-and-external_deps) +- [Using Sanitizer](subsys-build-reference.md#using-sanitizer) - [Information Collected by the Open Source Software Notice](subsys-build-reference.md#information-collected-by-the-open-source-software-notice) - [Parameters for Accelerating Local Build](subsys-build-reference.md#parameters-for-accelerating-local-build) - [Viewing Ninja Build Information](subsys-build-reference.md#viewing-ninja-build-information) diff --git a/en/device-dev/subsystems/subsys-build-reference.md b/en/device-dev/subsystems/subsys-build-reference.md index 8813f4b11d6ccfe2ce54a9efd47696727f2be515..4ee1d2176b729b17f056afbc2c131c0d33272039 100644 --- a/en/device-dev/subsystems/subsys-build-reference.md +++ b/en/device-dev/subsystems/subsys-build-reference.md @@ -10,7 +10,7 @@ When adding a module, you must declare its dependencies in **BUILD.gn**. **deps* The dependency between modules can be classified into **deps** (left in the figure above) and **external_deps** (right in the figure above). -- **deps**: The dependent module to be added belongs to the same part with the current module. For example, module 2 depends on module 1, and both modules 1 and 2 belong to the same component. +- **deps**: The dependent module to be added belongs to the same part with the current module. For example, module 2 depends on module 1, and both modules 1 and 2 belong to the same component. - **external_deps**: The dependent module to be added belongs to another component. For example, module 2 depends on module 1, and modules 1 and 2 belong to different components. @@ -32,8 +32,8 @@ The dependency between modules can be classified into **deps** (left in the figu deps = [ "GN target of module 1", ... - ] # Intra-component dependency - part_name = "part1" # (Mandatory) Name of the component to which the module belongs. + ] # Intra-component dependency + part_name = "part1" # (Mandatory) Name of the component to which the module belongs. } ``` @@ -55,12 +55,61 @@ The dependency between modules can be classified into **deps** (left in the figu external_deps = [ "part1:module1", ... - ] # Inter-component dependency. The dependent module must be declared in inner_kits by the dependent component. - part_name = "part2" # (Mandatory) Name of the component to which the module belongs. + ] # Inter-component dependency. The dependent module must be declared in **inner_kits** by the dependent component. + part_name = "part2" # (Mandatory) Name of the component to which the module belongs. } ``` - ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
The dependency between components must be written in the format of **Component_name:Module_name** in **external_deps**. The dependent module must be declared in **inner_kits**. + ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
The dependency between components must be written in the format of **Component name:Module name** in **external_deps**. The dependent module must be declared in **inner_kits**. + +## Using Sanitizer + +When adding a module, you can enable Sanitizer features, such as the integer overflow detection and control-flow integrity (CFI) check, provided by the compiler as required. Each configuration item is optional. It is **false** by default, and can also be left empty. + +The following is an example of Sanitizer configuration: + +``` shell + ohos_shared_library("example") { + sanitize = { + cfi = true + integer_overflow = true + debug = true # Optional. The default mode is disabled by default. + blocklist = "./blocklist.txt" # Optional. Enter the path of the blocklist. + } + ... + } +``` + + + +**Supported Sanitizer Features** + +- Integer overflow detection: includes detection of unsigned intergers (unsigned_integer_overflow), signed integers (signed_integer_overflow detection), and both (integer_overflow). +- CFI: prevents malware attacks from redirecting the control flow of a program. + +**Other Sanitizer Settings** + +- Debug: specifies whether the debug mode or the release mode is used. The default value **false** indicates that the release mode is used. The value **true** explicitly declares the debug mode. This option is not provided in the build of the release version. + + Sanitizer is used to locate problems during development, which is irrelevant to the debug version built. In debug mode, abundant error-related information is provided to help locate errors. When an error occurs, the program will be restored instead of being interrupted to further identify subsequent errors. + + In release mode, the program will be directly interrupted when an error occurs to protect the system against errors or maliciously attacks. + +- Blocklist: specifies the functions or source programs that are not affected by Sanitizer in the module. It prevents benign behavior from being identified as errors or hotspot functions from generating unreasonable and unacceptable overheads. Exercise caution when using this function. + + Blocklist example: + + ``` + [cfi] + fun:*([Tt]est|TEST)* + fun: main + + [integer] + src:example/*.cpp + ``` + + + ## Information Collected by the Open Source Software Notice diff --git a/en/device-dev/subsystems/subsys-ota-guide.md b/en/device-dev/subsystems/subsys-ota-guide.md index 57aafa53300dfc4c2acdf5ef76880239ffd62850..290ffb986f5b192bda0060e94379011d320165b5 100644 --- a/en/device-dev/subsystems/subsys-ota-guide.md +++ b/en/device-dev/subsystems/subsys-ota-guide.md @@ -1,396 +1,345 @@ -# OTA Update +# OTA Update -## Introduction -Over the Air \(OTA\) is a technology that makes it easier for you to remotely update devices, such as IP cameras. Currently, the mini and small systems support update using a full package, but not a differential package. A full package contains all content of a new system, and a differential package contains the differences between the old and new systems. +## Introduction -## Constraints -- Only the open-source suites for devices powered by Hi3861, Hi3518E V300, and Hi3516D V300 are supported. -- Devices developed based on Hi3518E V300 and Hi3516D V300 must support the SD card in the Virtual Festival of Aerobatic Teams \(VFAT\) format. +### Overview - >![](../public_sys-resources/icon-note.gif) **NOTE:** - >Generation of update packages can only be performed on the Linux system. +With the rapid development of device systems, it has become a critical challenge for device vendors to help their users to access system updates in a timely manner to experience the new features and improve the system stability and security. +Over the Air (OTA) answers this challenge with the support for remote updating of device systems. By providing unified update APIs externally, the update subsystem shields the differences of underlying chips. After secondary development based on the update APIs, device vendors can easily implement remote updating for their devices, such as IP cameras. -## Generating a Public/Private Key Pair -1. Download the [OpenSSL](http://slproweb.com/products/Win32OpenSSL.html) tool, install it on a Windows PC, and configure environment variables. -2. Use the OpenSSL tool to generate a public/private key pair. -3. Keep the private key file properly as this file stores the private key used to sign the update package. You need to specify the private key file in the command used for preparing the update package. The public key is used to verify the signature of the update package during the upgrade, and it is stored as follows: +### Basic Concepts - For the mini and small systems, the generated public key is preset in the code. The vendor needs to implement the **HotaHalGetPubKey** API to obtain the key. For the standard system, the generated public key is stored in the **./device/hisilicon/hi3516dv300/build/updater\_config/signing\_cert.crt** file. +- Full package: an update package that packs all images of the target version. -4. For the mini and small systems that use the Hi3518E V300 or Hi3516D V300 suite, also use the content in **public\_arr.txt** to replace the content in **g\_pub\_key** in the **device\\hisilicon\\third\_party\\uboot\\u-boot-2020.01\\product\\hiupdate\\verify\\update\_public\_key.c** file of the U-Boot module. +- Differential package: an update package that packs the differential images between the source version and target version. - Example configuration for the public key of the U-Boot module: - ``` - static unsigned char g_pub_key[PUBKEY_LEN] = { - 0x30, 0x82, 0x01, 0x0A, 0x02, 0x82, 0x01, 0x01, - 0x00, 0xBF, 0xAA, 0xA5, 0xB3, 0xC2, 0x78, 0x5E, - } - ``` - - -## Generating an Update Package - -### Mini and Small Systems - -1. Create the **target\_package** folder with the following directory structure: - - ``` - target_package - ├── OTA.tag - ├── config - ├── {component_1} - ├── {component_2} - ├── ... - ├── {component_N} - └── updater_config - └── updater_specified_config.xml - ``` - -2. Place the components to be updated, including the image file \(for example, **rootfs.img**\), as \{component\_N\} in the root directory of the **target\_package** folder. -3. Configure the **updater\_specified\_config.xml** file in the **update\_config** folder. - - Example configuration of the **updater\_specified\_config.xml** file: - - ``` - - - - head info - - - ./OTA.tag - ./config - ./u-boot-xxxx.bin - - - ``` - - **Table 1** Description of nodes in the component configuration file - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Type

-

Node Name

-

Node Label

-

Mandatory

-

Description

-

Header information (head node)

-

info

-

/

-

Yes

-

Content of this node: head info

-

fileVersion

-

Yes

-

This field is reserved and does not affect the generation of the update package.

-

prdID

-

Yes

-

This field is reserved and does not affect the generation of the update package.

-

softVersion

-

Yes

-

Software version number, that is, the version number of the update package. The version number must be within the range specified by VERSION.mbn. Otherwise, an update package will not be generated.

-

date

-

Yes

-

Date when the update package is generated. This field is reserved and does not affect the generation of the update package.

-

time

-

Yes

-

Time when the update package is generated. This field is reserved and does not affect the generation of the update package.

-

Component information (group node)

-

component

-

/

-

Yes

-

Content of this node: path of the component or image file to be packed into the update package. It is the root directory of the version package by default.

-

compAddr

-

Yes

-

Name of the partition corresponding to the component, for example, system or vendor.

-

compId

-

Yes

-

Component ID, which must be unique.

-

resType

-

Yes

-

This field is reserved and does not affect the generation of the update package.

-

compType

-

Yes

-

Image type, which can be a full or differential package. The value 0 indicates a full package, and value 1 indicates a differential package.

-
- - >![](../public_sys-resources/icon-note.gif) **NOTE:** - >As mini and small systems do not support update using a differential package, **compType** must be set to **0**, other than **1**. - >For mini and small systems, an update package cannot be created by changing partitions. - -4. Create the **OTA.tag** file, which contains the magic number of the update package. The magic number is as follows: - - ``` - package_type:ota1234567890qwertw - ``` - -5. Create the **config** file, and configure the **bootargs** and **bootcmd** information in the file. - - Example configuration: - - ``` - setenv bootargs 'mem=128M console=ttyAMA0,115200 root=/dev/mmcblk0p3 rw rootfstype=ext4 rootwait blkdevparts=mmcblk0:1M - (u-boot.bin),9M(kernel.bin),50M(rootfs_ext4.img),50M(userfs.img)' setenv bootcmd 'mmc read 0x0 0x82000000 0x800 0x4800;bootm 0x82000000' - ``` - -6. Generate the update package. - - ``` - python build_update.py ./target_package/ ./output_package/ -pk ./rsa_private_key3072.pem -nz -nl2x - ``` - - - **./target\_package/**: path of **target\_package** - - **./output\_package/**: output path of the update package - - **-pk ./rsa\_private\_key3072.pem**: path of the private key file - - **-nz**: **not zip** mode - - **-nl2**: non-standard system mode - - -### Standard System - -1. Create the **target\_package** folder with the following directory structure: - - ``` +### Implementation Principle + +To implement an OTA update, you first need to use the packaging tool to pack the build version into an update package and upload the update package to the OTA server. Devices integrating the OTA update capability can then detect the update package and download it to implement a remote update. + +A/B Update: a typical application of OTA update. In this update mode, a device has a backup system B. When system A is running, system B is updated silently. After the update is successful, the device restarts and switches to the new system. + + +### Constraints + +- Only the open-source suites for devices powered by Hi3861, Hi3518E V300, and Hi3516D V300 are supported. + +- Devices developed based on Hi3518E V300 and Hi3516D V300 must support the SD card in the Virtual Festival of Aerobatic Teams (VFAT) format. + +- Generation of update packages can only be performed on the Linux system. + +- Currently, the mini and small systems support update using a full package, but not a differential package or an update package with partitions changed. + + +## Environment Preparation + +- On Windows, download and install the OpenSSL tool and configure environment variables. +- Prepare the packaging tool. +- Build version images using the packaging tool. +- On Linux, pack version images to generate the update package. +- To implement an A/B update, ensure that the devices running the standard system support booting from partitions A and B. + + +## OTA Update Guide + + +### Development Procedure + +1. Use the OpenSSL tool to generate a public/private key pair. + +2. Use the packaging tool to generate an update package. + +  2.1 Mini and small systems + +  2.2 Standard system + +3. Upload the update package to the vendor's OTA server. + +4. Download the update package from the vendor's OTA server. + +5. Integrate the OTA update capability. + +  5.1 API application scenario (default) + +  5.2 API application scenario (custom) + +  5.3 A/B update scenario + + +### How to Develop + + +#### Generating a Public/Private Key Pair +1. Use the OpenSSL tool to generate a public/private key pair. + +3. Keep the private key file properly as this file stores the private key used to sign the update package. You need to specify the private key file in the command used for preparing the update package. The public key is used to verify the signature of the update package during the update. For the mini and small systems, the generated public key is preset in the code. You need to implement the **HotaHalGetPubKey** API to obtain the key. For the standard system, the generated public key is stored in the **./device/hisilicon/hi3516dv300/build/updater_config/signing_cert.crt** file. + +5. For the mini and small systems that use the Hi3518E V300 or Hi3516D V300 suite, use the content in **public\_arr.txt** to replace the content in **g\_pub\_key** in the **device\hisilicon\third_party\uboot\u-boot-2020.01\product\hiupdate\verify\update\_public\_key.c** file of the U-Boot module. + Example configuration: + + ```c + static unsigned char g_pub_key[PUBKEY_LEN] = { + 0x30, 0x82, 0x01, 0x0A, 0x02, 0x82, 0x01, 0x01, + 0x00, 0xBF, 0xAA, 0xA5, 0xB3, 0xC2, 0x78, 0x5E, + } + ``` + + +#### Making an Update Package + + +##### Mini and Small Systems + +1. Create the **target\_package** folder with the following directory structure: + + ```text target_package + ├── OTA.tag + ├── config ├── {component_1} ├── {component_2} ├── ... ├── {component_N} └── updater_config - ├── BOARD.list - ├── VERSION.mbn - └── updater_specified_config.xml - ``` - -2. Place the components to be updated, including the image file \(for example, **system.img**\), as \{component\_N\} in the root directory of the **target\_package** folder. - -3. Configure the component configuration file in the **update\_config** folder. - -4. Configure the list of products supported by the current update package in **BOARD.list** in the **update\_config** folder. - - Example configuration: - - ``` - HI3516 - HI3518 - ``` - -5. Configure the versions supported by the current update package in **VERSION.mbn** in the **update\_config** folder. - - Version number format: Hi3516DV300-eng 10 QP1A.XXXXXX.\{Major version number \(6 digits\)\}.XXX\{Minor version number \(3 digits\)\} - - For example, Hi3516DV300-eng 10 QP1A.190711.020, where **190711** is the major version number, and **020** is the minor version number. - - Example configuration: - - ``` - Hi3516DV300-eng 10 QP1A.190711.001 - Hi3516DV300-eng 10 QP1A.190711.020 - Hi3518DV300-eng 10 QP1A.190711.021 - ``` - -6. For update using an incremental \(differential\) package, also prepare a source version package \(source\_package\) in the same format as the target version package \(target\_package\), and then compress it as a **.zip** file, that is, **source\_package.zip**. - -7. If you create an update package with partitions changed, also provide the partition table file named **partition\_file.xml**. You can specify the file using the **-pf** parameter. For details about the configuration nodes, see the description below. - - The partition table is generated with the image. The format is as follows: - - ``` - - - - - - ``` - - **Table 2** Description of labels in the partition table - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Label

-

Description

-

Sel

-

Whether the partition is effective. The value 1 indicates that the partition is effective, and value 0 indicates the opposite.

-

PartitionName

-

Partition name, for example, fastboot or boot.

-

FlashType

-

Flash type, for example, emmc or ufs.

-

FileSystem

-

File system type, for example, ext3/4 or f2fs. The value can also be none.

-

Start

-

Start address of the partition, in MB. The start address of all partitions is 0.

-

Length

-

Size of the partition, in MB.

-

SelectFile

-

Actual path of the image or file.

-
- -8. Generate the update package. - - **Full package** - - Run the following command: - - ``` - python build_update.py ./target_package/ ./output_package/ -pk ./rsa_private_key3072.pem - ``` - - - **./target\_package/**: path of **target\_package** - - **./output\_package/**: output path of the update package - - **-pk ./rsa\_private\_key3072.pem**: path of the private key file - - **Incremental \(differential\) package** - - Run the following command: - - ``` - python build_update.py ./target_package/ ./output_package/ -s ./source_package.zip -pk ./rsa_private_key3072.pem - ``` - - - **./target\_package/**: path of **target\_package** - - **./output\_package/**: output path of the update package - - **-s ./source\_package.zip**: path of the **source\_package.zip** file. For update using a differential package, use the **-s** parameter to specify the source version package. - - **-pk ./rsa\_private\_key3072.pem**: path of the private key file - - **Update package with partitions changed** - - Run the following command: - - ``` - python build_update.py ./target_package/ ./output_package/ -pk ./rsa_private_key3072.pem -pf ./partition_file.xml - ``` - - - **./target\_package/**: path of **target\_package** - - **./output\_package/**: output path of the update package - - **-pk ./rsa\_private\_key3072.pem**: path of the private key file - - **-pf ./partition\_file.xml**: path of the partition table file - - -## Uploading the Update Package + └── updater_specified_config.xml + ``` + +2. Place the components to be updated, including the image file (for example, **rootfs.img**), as **{component\_N}** in the root directory of the **target\_package** folder. + +3. Configure the **updater\_specified\_config.xml** file in the **updater_config** folder. + + Example configuration: + + + ```xml + + + + head info + + + ./OTA.tag + ./config + ./u-boot-xxxx.bin + + + ``` + + + **Table 1** Description of nodes in the component configuration file + + | Type| Node Name| Node Label| Mandatory| Description| + | -------- | -------- | -------- | -------- | -------- | + | Header information (head node)| info| / | Yes| Content of this node: head info| + | Header information (head node)| info| fileVersion | Yes| This field is reserved and does not affect the generation of the update package.| + | Header information (head node)| info| prdID | Yes| This field is reserved and does not affect the generation of the update package.| + | Header information (head node)| info| softVersion | Yes| Software version number, that is, the version number of the update package. The version number must be within the range specified by **VERSION.mbn**. Otherwise, an update package will not be generated.| + | Header information (head node)| info| date| Yes| Date when the update package is generated. This field is reserved and does not affect the generation of the update package.| + | Header information (head node)| info| time| Yes| Time when the update package is generated. This field is reserved and does not affect the generation of the update package.| + | Component information (group node)| component| / | Yes| Content of this node: path of the component or image file to be packed into the update package. It is the root directory of the version package by default.| + | Component information (group node)| component| compAddr | Yes| Name of the partition corresponding to the component, for example, **system** or **vendor**.| + | Component information (group node)| component| compId | Yes| Component ID, which must be unique.| + | Component information (group node)| component| resType | Yes| This field is reserved and does not affect the generation of the update package.| + | Component information (group node)| component| compType | Yes| Image type, which can be a full or differential package. The value **0** indicates a full package, and value **1** indicates a differential package.| + + > **NOTE** + > As mini and small systems do not support updating with a differential package, **compType** must be set to **0**, other than **1**. + > + > For mini and small systems, an update package cannot be created by changing partitions. + +4. Create the **OTA.tag** file, which contains the magic number of the update package. The magic number is fixed, as shown below: + + ```text + package_type:ota1234567890qwertw + ``` + +5. Create the **config** file, and configure the **bootargs** and **bootcmd** information in the file. + Example configuration: + + + ```text + setenv bootargs 'mem=128M console=ttyAMA0,115200 root=/dev/mmcblk0p3 rw rootfstype=ext4 rootwait blkdevparts=mmcblk0:1M + (u-boot.bin),9M(kernel.bin),50M(rootfs_ext4.img),50M(userfs.img)' setenv bootcmd 'mmc read 0x0 0x82000000 0x800 0x4800;bootm 0x82000000' + ``` + +6. Generate the update package. + + ```text + python build_update.py ./target_package/ ./output_package/ -pk ./rsa_private_key3072.pem -nz -nl2 + ``` + + - **./target\_package/**: path of **target\_package** + - **./output\_package/**: output path of the update package + - -**pk ./rsa\_private\_key3072.pem**: path of the private key file + - -**nz**: **not zip** mode + - -**nl2**: non-standard system mode + + +##### Standard System + +1. Create the **target\_package** folder with the following directory structure: + + + ```text + target_package + ├── {component_1} + ├── {component_2} + ├── ... + ├── {component_N} + └── updater_config + ├── BOARD.list + ├── VERSION.mbn + └── updater_specified_config.xml + ``` + +2. Place the components to be updated, including the image file (for example, **system.img**), as **{component\_N}** in the root directory of the **target\_package** folder. + +3. Configure the component configuration file in the **updater\_config** folder. + +4. Configure the list of products supported by the current update package in **BOARD.list** in the **updater\_config** folder. + + Example configuration: + + + ```text + HI3516 + HI3518 + ``` + +5. Configure the versions supported by the current update package in **VERSION.mbn** in the **updater\_config** folder. + + Version number format: Hi3516DV300-eng 10 QP1A.XXXXXX.{Major version number (6 digits)}.XXX{Minor version number (3 digits)} + + For example, **Hi3516DV300-eng 10 QP1A.190711.020**, where **190711** is the major version number, and **020** is the minor version number. + + Example configuration: + + + ```text + Hi3516DV300-eng 10 QP1A.190711.001 + Hi3516DV300-eng 10 QP1A.190711.020 + Hi3518DV300-eng 10 QP1A.190711.021 + ``` + +6. For an update using the incremental (differential) package, also prepare a source version package (source\_package) in the same format as the target version package (target\_package), and then compress it as a **.zip** file, that is, **source\_package.zip**. + +7. If you create an update package with partitions changed, also provide the partition table file named **partition\_file.xml**. You can specify the file using the **-pf** parameter. For details about the configuration nodes, see the description below. + + The partition table is generated with the image. The format is as follows: + + + ```xml + + + + + + ``` + + **Table 2** Description of labels in the partition table + + | Name | Description | + | ---- | ----------- | + | Sel | Whether the partition is effective. The value **1** indicates that the partition is effective, and value **0** indicates the opposite.| + | PartitionName | Partition name, for example, **fastboot** or **boot**.| + | FlashType | Flash type, for example, **emmc** or **ufs**.| + | FileSystem | File system type, for example, **ext3/4** or **f2fs**. The value can also be **none**.| + | Start | Start address of the partition, in MB. The start address of all partitions is **0**.| + | Length | Size of the partition, in MB.| + | SelectFile | Actual path of the image or file.| + +8. Generate the update package. + + **Full package** + + Run the following command: + + + ```text + python build_update.py ./target_package/ ./output_package/ -pk ./rsa_private_key2048.pem + ``` + + - **./target\_package/**: path of **target\_package** + - **./output\_package/**: output path of the update package + - -**pk ./rsa\_private\_key3072.pem**: path of the private key file + + **Incremental (differential) package** + + Run the following command: + + + ```text + python build_update.py ./target_package/ ./output_package/ -s ./source_package.zip -pk ./rsa_private_key2048.pem + ``` + + - **./target\_package/**: path of **target\_package** + - **./output\_package/**: output path of the update package + - -**s ./source\_package.zip**: path of the **source\_package.zip** file. For update using a differential package, use the **-s** parameter to specify the source version package. + - -**pk ./rsa\_private\_key3072.pem**: path of the private key file + + **Update package with partitions changed** + + Run the following command: + + + ```text + python build_update.py ./target_package/ ./output_package/ -pk ./rsa_private_key2048.pem -pf ./partition_file.xml + ``` + + - **./target\_package/**: path of **target_package** + - **./output\_package/**: output path of the update package + - -**pk ./rsa\_private_key3072.pem**: path of the private key file + - -**pf ./partition\_file.xml**: path of the partition table file + + +#### **Uploading the Update Package** Upload the update package to the vendor's OTA server. -## Downloading the Update Package -1. Download the update package from the OTA server. -2. \(Optional\) Insert an SD card \(with a capacity greater than 100 MB\) if the device is developed based on Hi3518E V300 or Hi3516D V300. +#### **Downloading the Update Package** + +1. Download the update package from the OTA server. -## Integrating OTA Update Capabilities +2. (Optional) Insert an SD card (with a capacity greater than 100 MB) if the device is developed based on Hi3518E V300 or Hi3516D V300. -1. For mini and small systems - - If a vendor requests OTA capabilities, use the dynamic library **libhota.so** and include the header files **hota\_partition.h** and **hota\_updater.h** in **base\\update\\ota\_lite\\interfaces\\kits**. +#### Integrating OTA Update Capabilities - - The **libhota.so** source code is stored in **base\\update\\ota\_lite\\frameworks\\source**. +1. For mini and small systems - - For details about how to use APIs, see _API Application Scenario_ and OTA APIs in _API Reference_. + - Call the dynamic library **libhota.so**. The corresponding header files **hota\_partition.h** and **hota\_updater.h** are located in **base\update\ota_lite\interfaces\kits**. + - The **libhota.so** source code is located in **base\update\ota_lite\frameworks\source**. + - For details about how to use APIs, see *API Application Scenarios* and update APIs in *API Reference*. + - If the development board needs to be adapted, see the **base\update\ota_lite\hals\hal\_hota\_board.h** file. - - If the development board needs to be adapted, see the **base\\update\\ota\_lite\\hals\\hal\_hota\_board.h** file. +2. For the standard system, see the [JS API Reference](../../application-dev/reference/apis/js-apis-update.md) for details. -2. For the standard system, see the [Reference Specifications](../../application-dev/reference/apis/js-apis-update.md) for details. -## API Application Scenario \(Default\) +##### API Application Scenario (Default) The update package is generated by following the instructions provided in Generating a Public/Private Key Pair and Generating an Update Package. -### **How to Develop** -1. Download the update package for the current device, and then call the **HotaInit** function to initialize the OTA module. +###### How to Develop -2. Call the **HotaWrite** function to verify, parse, and write data streams into the device. +1. Download the update package for the current device, and then call the **HotaInit** function to initialize the OTA module. -3. Call the **HotaRestart** function to restart the system for the update to take effect. Call the **HotaCancel** function if you want to cancel the update. +2. Call the **HotaWrite** function to verify, parse, and write data streams for the update into the device. +3. Call the **HotaRestart** function to restart the system for the update to take effect. Call the **HotaCancel** function if you want to cancel the update. -### **Sample Code** -Perform an OTA update using the update package format and verification method provided by OpenHarmony. +###### Sample Code -``` + Perform an OTA update using the update package format and verification method provided by OpenHarmony. + +```cpp int main(int argc, char **argv) { printf("this is update print!\r\n"); @@ -440,30 +389,32 @@ int main(int argc, char **argv) } ``` -## API Application Scenario \(Custom\) -The update package is generated in other ways instead of following the instructions provided in Generating a Public/Private Key Pair and Generating an Update Package. +##### API Application Scenario (Custom) -### **How to Develop** +The update package is generated in other ways instead of following the instructions provided in "Generating a Public/Private Key Pair" and "Generating an Update Package." -1. Download the update package for the current device, and then call the **HotaInit** function to initialize the OTA module. -2. Call the **HotaSetPackageType** function to set the package type to **NOT\_USE\_DEFAULT\_PKG**. +###### How to Develop -3. Call the **HotaWrite** function to write data streams into the device. +1. Download the update package for the current device, and then call the **HotaInit** function to initialize the OTA module. -4. Call the **HotaRead** function to read data. Vendors can choose whether to verify the data. +2. Call the **HotaSetPackageType** function to set the package type to **NOT\_USE\_DEFAULT\_PKG**. -5. \(Optional\) Call the **HotaSetBootSettings** function to set the startup tag used for entering the U-Boot mode during system restarting. +3. Call the **HotaWrite** function to write data streams into the device. -6. Call the **HotaRestart** function to restart the system for the update to take effect. Call the **HotaCancel** function if you want to cancel the update. +4. Call the **HotaRead** function to read data. Vendors can choose whether to verify the data. +5. (Optional) Call the **HotaSetBootSettings** function to set the startup tag used for entering the U-Boot mode during system restarting. -### **Sample Code** +6. Call the **HotaRestart** function to restart the system for the update to take effect. Call the **HotaCancel** function if you want to cancel the update. -Perform an OTA update using the update package format and verification method not provided by OpenHarmony. -``` +###### Sample Code + + Perform an OTA update using the update package format and verification method not provided by OpenHarmony. + +```cpp int main(int argc, char **argv) { printf("this is update print!\r\n"); @@ -512,7 +463,7 @@ int main(int argc, char **argv) while (leftLen > 0) { int tmpLen = leftLen >= READ_BUF_LEN ? READ_BUF_LEN : leftLen; (void)memset_s(g_readBuf, READ_BUF_LEN, 0, READ_BUF_LEN); - if (HotaRead(offset, READ_BUF_LEN, (unsigned char *)g_readBuf) != 0) {} + if (HotaRead(offset, READ_BUF_LEN, (unsigned char *)g_readBuf) != 0) { printf("ota write fail!\r\n"); (void)HotaCancel(); return -1; @@ -530,15 +481,16 @@ int main(int argc, char **argv) } ``` -## Upgrading the System -Vendor applications call APIs of the OTA module to perform functions such as signature verification of the update package, anti-rollback, burning and data flushing-to-disk. After the update is complete, the system automatically restarts. +###### System Updating -For the mini and small systems that use the Hi3518E V300 or Hi3516D V300 open source suite, add the value of **LOCAL\_VERSION** to the version that needs to implement the anti-rollback function. For example, for **"ohos default 1.0"-\>"ohos default 1.1"**, add the value of **LOCAL\_VERSION** in **device\\hisilicon\\third\_party\\uboot\\u-boot-2020.01\\product\\hiupdate\\ota\_update\\ota\_local\_info.c**. +An application calls APIs of the OTA module to perform functions such as signature verification of the update package, anti-rollback, as well as burning and flushing to disk. After the update is complete, the system automatically restarts. -Example for modification of the local version: +For the mini and small systems that use the Hi3518E V300 or Hi3516D V300 open source suite, add the value of **LOCAL\_VERSION** to the version that needs to implement the anti-rollback function. For example, for **"ohos default 1.0"->"ohos default 1.1"**, add the value of **LOCAL\_VERSION** in **device\hisilicon\third\_party\uboot\u-boot-2020.01\product\hiupdate\ota\_update\ota\_local_info.c**. -``` + Example configuration: + +```cpp const char *get_local_version(void) { #if defined(CONFIG_TARGET_HI3516EV200) || \ @@ -547,3 +499,88 @@ const char *get_local_version(void) #define LOCAL_VERSION "ohos default 1.0" /* increase: default release version */ ``` + +##### A/B Update Scenario + + +###### Development Procedure + +1. Download the update package through the update application. +2. Invoke update_service to start the system installation service through SAMGR. +3. Let the system installation service perform a silent update. +4. Activate the new version upon restarting. + + +###### How to Develop + +- Invoke update_service to call JS APIs to implement the related service logic in an A/B update. + + 1. Displaying the update package installation progress: + ```cpp + on(eventType: "upgradeProgress", callback: UpdateProgressCallback): void; + ``` + + 2. Setting the activation policy (immediate restart, restart at night, and activation on next restart): + ```cpp + upgrade(apply) + ``` + + +- Invoke update_service to start the system installation service through SAMGR. + + 1. Start the system installation service and set up an IPC connection. + ```cpp + int SysInstallerInit(void * callback) + ``` + + 2. Install the A/B update package in the specified path. + ```cpp + int StartUpdatePackageZip(string path) + ``` + + 3. Set the update progress callback. + ```cpp + int SetUpdateProgressCallback(void * callback) + ``` + + 4. Obtain the installation status of the update package (0: not started; 1: installing; 2: installed). + ```cpp + int GetUpdateStatus() + ``` + + +- Use HDI APIs to activate the new version. + + 1. Obtain the current boot slot to determine the partition to be updated. + ```cpp + int GetCurrentSlot() + ``` + + 2. Upon completion of the update, switch the updated slot and restart the system for the new version to take effect. + ```cpp + int SetActiveBootSlot(int slot) + ``` + + 3. Upon starting of the update, set the slot of the partition to be updated to the **unbootable** state. + ```cpp + int setSlotUnbootable(int slot) + ``` + + 4. Obtain the number of slots. The value **1** indicates a common update, and the value **2** indicates an A/B update. + ```cpp + int32 GetSlotNum(void) + ``` + + +###### FAQs + +1. An exception occurs during installation of the update package. +
The system keeps running with the current version. It will attempt a new update in the next package search period. + +2. An exception occurs during activation of the new version if the update package is installed in a non-boot partition. +
Perform a rollback and set the partition to the **unbootable** state so that the system does not boot from this partition. + + +###### Verification + +In normal cases, the device can download the update package from the OTA server in the background, perform a silent update, and then restart according to the preconfigured activation policy for the new version to take effect. diff --git a/en/readme/ai.md b/en/readme/ai.md index 9115a0024e450acd7a74f151bba0cda4db2c9841..83aa9a2381963c295ba1d54375c98117dff307fc 100644 --- a/en/readme/ai.md +++ b/en/readme/ai.md @@ -412,7 +412,7 @@ The AI subsystem is the part of OpenHarmony that provides native distributed AI [ai_engine](https://gitee.com/openharmony/ai_engine) -Dependency repositories: +## Dependency Repositories [build\_lite](https://gitee.com/openharmony/build_lite/blob/master/README.md) @@ -422,6 +422,6 @@ Dependency repositories: ## Reference -[AI Framework Development](https://gitee.com/openharmony/docs/blob/master/en/device-dev/subsystems/subsys-ai-aiframework-devguide.md) +[AI Framework Development Guide](https://gitee.com/openharmony/docs/blob/master/en/device-dev/subsystems/subsys-ai-aiframework-devguide.md) diff --git a/en/readme/figures/multimodal-architecture.png b/en/readme/figures/multimodal-architecture.png index 6c7bfa62475e4e6d5f01ce146fb0a3534caa2385..5962b1e6ff66d845f8ad97d3f1d884e195f0da53 100644 Binary files a/en/readme/figures/multimodal-architecture.png and b/en/readme/figures/multimodal-architecture.png differ diff --git a/en/readme/network-management.md b/en/readme/network-management.md index 3851fa87f79902e69d3fe82a09c69f04bfa19bd0..08e5ae88a87a5423efbf05bdf78a818c1ad7dc31 100644 --- a/en/readme/network-management.md +++ b/en/readme/network-management.md @@ -68,9 +68,13 @@ foundation/communication/ ### Sharing a Network 1. Import the network sharing namespace from **@ohos.net.sharing**. + 2. Set the network sharing type. + 3. Start network sharing. + 4. Stop network sharing. + ``` // Import the network sharing namespace. import sharing from '@ohos.net.sharing'; @@ -89,10 +93,15 @@ sharing.stopSharing(this.sharingType,(err)=>{ ### Initiating a Network Request 1. Import the HTTP namespace from **@ohos.net.http.d.ts**. + 2. Call **createHttp()** to create an **HttpRequest** object. + 3. Call **httpRequest.on()** to subscribe to an HTTP response header. This method returns a response earlier than the request. You can subscribe to HTTP response header events based on service requirements. + 4. Call **httpRequest.request()** to initiate a network request. You need to pass in the URL and optional parameters of the HTTP request. + 5. Parse the returned result based on service requirements. + 6. Call **httpRequest.destroy()** to release resources after the request is processed. ``` diff --git a/en/readme/user-iam.md b/en/readme/user-iam.md index 32cceeaa64ee0962455a42296c005b8fc03d5e96..9c80ac7226ed8feca8e116cc5ff1943a641e5fda 100644 --- a/en/readme/user-iam.md +++ b/en/readme/user-iam.md @@ -8,8 +8,7 @@ This subsystem is widely used in security-sensitive scenarios such as screen loc **Figure 1** Subsystem architecture -User IAM subsystem architecture - +![](figures/User-IAM-subsystem-architecture.png) The user IAM subsystem consists of the unified user authentication framework and authentication executor. The unified user authentication framework consists of the following parts: - Unified user authentication: provides unified user identity authentication externally and provides open biometric authentication capabilities for third-party applications to invoke. diff --git a/en/release-notes/OpenHarmony-v3.2-beta3.md b/en/release-notes/OpenHarmony-v3.2-beta3.md new file mode 100644 index 0000000000000000000000000000000000000000..25bcbf7e919ca3e107301ae9ad26f535b4cce352 --- /dev/null +++ b/en/release-notes/OpenHarmony-v3.2-beta3.md @@ -0,0 +1,224 @@ +# OpenHarmony 3.2 Beta3 + + +## Version Description + +OpenHarmony 3.2 Beta3 provides the following enhancements over OpenHarmony 3.2 Beta2: + +**Enhanced basic capabilities for the standard system** + +The pan-sensor subsystem adds vibrator priority management. + +The multimodal input subsystem adds mouse pointer style and speed setting, configuration of sequential ability startup, and ScreenHop; and enhances mouse event reporting. + +The Misc services subsystem adds the following basic features: pasteboard, upload and download, screen lock, and input method framework. + +The kernel subsystem adds the following basic capabilities: memory level notification to Ability Manager Service (AMS), reclaim priority management for resident system services, and reclaim priority management based on different Extension ability states. + +In the Design For X (DFX) subsystem, the faultloggerd component supports print in the hybrid JS and native stacks; the hilog component provides domain trustlist management and log statistics; the hisysevent and hiappeventssh components provide enhanced event capabilities; the hidumper component provides more detailed memory classification information. + +The parameterized data driver capability is added to the unit test framework. APIs related to fling and complex gestures (such as two-finger pinch) are added to the UI test framework. The xdevice component adds device-level DFX log collection upon task execution. + +The multi-language runtime subsystem adds the following capabilities: ES2021 in strict mode, modularization, runtime debugging and tuning enhancement, and bytecode hot reload. + +User identity authentication is added to the IAM account subsystem. The permission service supports precise positioning and fuzzy positioning, and other capabilities are enhanced. The privacy management service is provided. + +The multimedia subsystem adds native APIs for audio decoding, audio encoding, video decoding, and video encoding; audio and video synchronization; playback start time optimization; video hardware encoding and decoding based on the HDI codec interface; distributed audio, volume, and device status management; device listening and projection; preview, photographing, and video recording using distributed cameras. + +**Enhanced application development framework for the standard system** + +The common event and notification subsystem provides DLP adaptation. Subsystems can send notifications. + +The webview component supports copy and paste. Basic audio/video playback and HTTPS bidirectional authentication are supported. + +Permission verification, startup rules, and quick repair are added for the ability framework, and widgets can be flexibly separated and combined. + +The following capabilities are enhanced: ArkUI component, resource and media query, DFX, and toolchain. The memory and performance are optimized. + +The DeviceProfile subsystem supports adaptation to the automatic synchronization policy of the distributed database and supplements the type of information that can be collected. + +For the bundle management framework, Extension abilities are added for the thumbnail and preview. Certain features become tailorable. Foolproof and quick repair are added. Specific capabilities of preset applications can be managed. Applications can be installed without decompressing HAP files. + +For the system ability management subsystem (SAMGR), system services can be loaded across devices. The restart and recovery mechanism is provided for the foundation process. Distributed component management supports multi-user, cross-device invoking. Singleton ability continuation is supported. + +**Enhanced distributed capabilities for the standard system** + +The distributed database supports cross-device and cross-application sharing. The relational database (RDB) supports remote query, database encryption, and app twin. The KVDB supports backup and restore, condition-based synchronization, and centralized system data synchronization when the device goes online. + + +## Version Mapping + + **Table 1** Version mapping of software and tools + +| Software/Tool| Version| Remarks| +| -------- | -------- | -------- | +| OpenHarmony | 3.2 Beta3| NA | +| Public SDK | Ohos_sdk_public 3.2.7.5 (API Version 9 Beta3)| This toolkit is intended for application developers and does not contain system APIs that require system permissions.
It is provided as standard in DevEco Studio.| +| Full SDK | Ohos_sdk_full 3.2.7.5 (API Version 9 Beta3)| This toolkit is intended for original equipment manufacturers (OEMs) and contains system APIs that require system permissions.
To use the full SDK, manually obtain it from the mirror and switch to it in DevEco Studio. For details, see [Guide to Switching to Full SDK](../application-dev/quick-start/full-sdk-switch-guide.md).| +| (Optional) HUAWEI DevEco Studio| 3.0 Release| Recommended for developing OpenHarmony applications.| +| (Optional) HUAWEI DevEco Device Tool| 3.0 Release| Recommended for developing OpenHarmony devices.| + + +## Source Code Acquisition + + +### Prerequisites + +1. Register your account with Gitee. + +2. Register an SSH public key for access to Gitee. + +3. Install the [git client](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) and [git-lfs](https://gitee.com/vcs-all-in-one/git-lfs?_from=gitee_search#downloading), and configure user information. + + ``` + git config --global user.name "yourname" + git config --global user.email "your-email-address" + git config --global credential.helper store + ``` + +4. Run the following commands to install the **repo** tool: + + ``` + curl -s https://gitee.com/oschina/repo/raw/fork_flow/repo-py3 > /usr/local/bin/repo # If you do not have the permission, download the tool to another directory and configure it as an environment variable by running the chmod a+x /usr/local/bin/repo command. + pip3 install -i https://repo.huaweicloud.com/repository/pypi/simple requests + ``` + + +### Acquiring Source Code Using the repo Tool + +**Method 1 (recommended)** + +Use the **repo** tool to download the source code over SSH. (You must have an SSH public key for access to Gitee.) + +- Obtain the source code from the version branch. You can obtain the latest source code of the version branch, which includes the code that has been incorporated into the branch up until the time you run the following commands: + ``` + repo init -u git@gitee.com:openharmony/manifest.git -b OpenHarmony-3.2-Beta3 --no-repo-verify + repo sync -c + repo forall -c 'git lfs pull' + ``` + +- Obtain the source code from the version tag, which is the same as that released with the version. + ``` + repo init -u git@gitee.com:openharmony/manifest.git -b refs/tags/OpenHarmony-v3.2-Beta3 --no-repo-verify + repo sync -c + repo forall -c 'git lfs pull' + ``` + +**Method 2** + +Use the **repo** tool to download the source code over HTTPS. + +- Obtain the source code from the version branch. You can obtain the latest source code of the version branch, which includes the code that has been incorporated into the branch up until the time you run the following commands: + ``` + repo init -u https://gitee.com/openharmony/manifest -b OpenHarmony-3.2-Beta3 --no-repo-verify + repo sync -c + repo forall -c 'git lfs pull' + ``` + +- Obtain the source code from the version tag, which is the same as that released with the version. + ``` + repo init -u https://gitee.com/openharmony/manifest -b refs/tags/OpenHarmony-v3.2-Beta3 --no-repo-verify + repo sync -c + repo forall -c 'git lfs pull' + ``` + +### Acquiring Source Code from Mirrors + +**Table 2** Mirrors for acquiring source code + +| Source Code | Version| Mirror | SHA-256 Checksum | +| --------------------------------------- | ------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | +| Full code base (for mini, small, and standard systems) | 3.2 Beta3 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta3/code-v3.2-Beta3.tar.gz)| [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta3/code-v3.2-Beta3.tar.gz.sha256)| +| Hi3861 mini system solution (binary) | 3.2 Beta3 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta3/hispark_pegasus.tar.gz)| [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta3/hispark_pegasus.tar.gz.sha256) | +| Hi3516 mini system solution - LiteOS (binary)| 3.2 Beta3 | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Beta3/hispark_taurus_LiteOS.tar.gz) | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Beta3/hispark_taurus_LiteOS.tar.gz.sha256) | +| Hi3516 mini system solution - Linux (binary) | 3.2 Beta3 | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Beta3/hispark_taurus_Linux.tar.gz) | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Beta3/hispark_taurus_Linux.tar.gz.sha256) | +| RK3568 standard system solution (binary) | 3.2 Beta3 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta3/dayu200_standard_arm32.tar.gz)| [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta3/dayu200_standard_arm32.tar.gz.sha256) | +| Full SDK package for the standard system (macOS) | 3.2.7.5 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta3/ohos-sdk-mac-full.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta3/ohos-sdk-mac-full.tar.gz.sha256) | +| Full SDK package for the standard system (Windows/Linux) | 3.2.7.5 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta3/ohos-sdk-windows_linux-full.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta3/ohos-sdk-windows_linux-full.tar.gz.sha256) | +| Public SDK package for the standard system (macOS) | 3.2.7.5 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta3/ohos-sdk-mac-public.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta3/ohos-sdk-mac-public.tar.gz.sha256) | +| Public SDK package for the standard system (Windows/Linux) | 3.2.7.5 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta3/ohos-sdk-windows_linux-public.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta3/ohos-sdk-windows_linux-public.tar.gz.sha256) | + + + +## Updates + +This version has the following updates to OpenHarmony 3.2 Beta2. + + +### Feature Updates + + **Table 3** New and enhanced features + +| Subsystem| Standard System| Mini and Small Systems| +| -------- | -------- | -------- | +| Ability framework| Permission verification, startup rules, and quick repair are added, and widgets can be flexibly separated and combined.
The following requirements are involved:
I581RO [New feature] Adaptation of **Recents** to the sandbox process of encrypted files
I581SE [New feature] AMS permission verification for the sandbox process
I581XD [New feature] Capturing of JavaScript crashes by application
I581YL [New feature] Widget sharing
I58213 [Enhanced feature] APIs for listening for the association between Service, Data, and Extension abilities
I5824D [New feature] Worker thread of JS runtime
I5825N [New feature] Application code loading without HAP decompression
I5826I [New feature] Application resource loading without HAP decompression
I5826Y [New feature] Loading of code in the dependency HAP file
I5HQEM [New feature] Listening for the window stage lifecycle by context
I5MVKZ [New feature] Intra-application widget loading
I5OD2E [New feature] Quick repair service - patch installation
I5ODCD [New feature] Quick repair service - patch query
I5PXW4 [Enhanced feature] Querying and listening for process and component visibility
I5Q8IU [New feature] Forcible intra-application widget refresh
I5QGMS [New feature] Intra-application widget event management| NA | +| Bundle management framework| Extension abilities are added for the thumbnail and preview. Certain features become tailorable. Foolproof and quick repair are added. Specific capabilities of preset applications can be managed. Applications can be installed without decompressing HAP files.
The following requirements are involved:
I5MZ33 [New feature] Extension abilities for the thumbnail and preview
I56WAY [New feature] Tailorable bundle management
I56WA0 [New feature] Foolproof
I56W8O [New feature] Capability management for preset applications
I56WGB [New Feature] Application installation without HAP decompression
I5N7AD [New feature] Patch installation
I5MZ6Z [New feature] Patch package scan upon startup| NA | +| DFX | The faultloggerd component supports print in the hybrid JS and native stacks. The hilog component provides domain trustlist management and log statistics. The hisysevent and hiappeventssh components provide enhanced event capabilities. The hidumper component provides more detailed memory classification information.
The following requirements are involved:
I5PJ9O [New specifications] [faultloggerd] Print in the hybrid JS and native stacks
I5OA3F [New specifications] [hisysevent] Improved usability of the HiSysEvent subscription and query interfaces
I5NU4L [New feature] [hilog] System domain trustlist management
I5NU71 [New feature] [hilog] Log statistics
I5NU7F [New feature] [hilog] Log service permission management
I5KDIG [New specifications] [hisysevent] Handling system event storms of the subscription interface
I5L2RV [New specifications] [hisysevent] Handling system event storms of the query interface
I5LFCZ [New specifications] [hisysevent] Handling of system event storms of the system event storage and processing interface
I5FNPQ [New specifications] [hisysevent] Handling system event storms of the system event dotting interface
I5NTOS [New specifications] [hiappevent] Event clearance
I5NTOD [New specifications] [hiappevent] Event query
I5LB4N [New specifications] [hiappevent] Event subscription
I5KYYI [New specifications] [hiappevent] Event distribution
I5K0X6 [New specifications] [hiappevent] Event management
I5NULM [New specifications] [hiview] Reading kernel events
I5NWZQ [New feature] Further smaps classification of processes; display of more detailed classification information in the exported hidumper information
I5GXTG [New feature] Optimized hidumper permission privacy| NA | +| Test subsystem| The parameterized data driver capability is added to the unit test framework. APIs related to fling and complex gestures (such as two-finger pinch) are added to the UI test framework. The xdevice component adds device-level DFX log collection upon task execution.
The following requirements are involved:
I5LI56 [New specifications] DFX integration for log collection
I5LUI8 [New specifications] Parameterized data driver for the unit test framework
I5L5DL [New specifications] APIs related to fling and complex gestures of the UI test framework
I5K2LZ [New specifications] Updated readme file for the unit test framework and UI test framework
I5MQTL [New feature] Updated readme files for WuKong| NA | +| SAMGR| System services can be loaded across devices. The restart and recovery mechanism is provided for the foundation process. Distributed component management supports multi-user, cross-device invoking. Singleton ability continuation is supported.
The following requirements are involved:
I5KMF7 [samgr] [Enhanced feature] Remote loading of system services
I5IZ7R [safwk] [New Feature] Restart and recovery for the foundation process
I5LO67 [dmsfwk] [New feature] Multi-user adaptation
I5I5FV [dmsfwk] [New feature] Singleton ability continuation
I5OJD [dmsfwk] [New feature] Automatic component status continuation
I5NOA1 [dmsfwk] [New feature] Application information reporting by DMS on the target device| NA | +| DeviceProfile subsystem| The DeviceProfile subsystem supports adaptation to the automatic synchronization policy of the distributed database and supplements the type of information that can be collected.
The following requirements are involved:
I5QPGN [device_profile] [Enhanced feature] Adaptation to the automatic database synchronization policy
I5J7PW [device_profile] [Enhanced feature] Basic DeviceProfile information supplementation| NA | +| Common event and notification subsystem| DLP adaptation is added. Subsystems can send notifications.
The following requirements are involved:
I582TY [New specifications] DLP adaptation for notifications
I582VA [New specifications] DLP adaptation for events
I5P1GU [distributed_notification_service] Sending notifications by subsystems| NA | +| Multimodal input subsystem| The following features are added: mouse pointer style and speed setting, configuration of sequential ability startup, and ScreenHop. Mouse event reporting is enhanced.
The following requirements are involved:
I530UX [New feature] Changing the mouse pointer speed
I530VT [New feature] Displaying or hiding the mouse pointer
I530XP [New feature] Mouse acceleration algorithm
I530XS [New feature] Multiple mouse pointer styles
I530UQ [New feature] Distributed input
I5HMF3 [Enhanced feature] Event reporting when the mouse pointer leaves the window
I5HMEF [Enhanced feature] Enhancement of mouse events
I5HMD9 [input] Ability startup based on the configuration of the key event sequence
I5P6TG Adaptive display of the mouse pointer in ScreenHop
I5P6UW ScreenHop status management
I5HMCX [New feature] Enabling or disabling keys on the keyboard
I5HMCB [input] Multiple touch targets related to the input device| NA | +| Pan-sensor subsystem| Vibrator priority management is supported.
The following requirement is involved:
I53SGE [New specifications] Vibrator priority management| NA | +| Distributed data management subsystem| Cross-device and cross-application sharing is supported. The RDB supports remote query, database encryption, and app twin. The KVDB supports backup and restore, condition-based synchronization, and centralized system data synchronization when the device goes online.
The following requirements are involved:
I5JV75 [New feature] [relational_store] Remote query
I5LBDS [New feature] [kv_store] Independent isolation of DLP sandbox application data
I5JZM1 [data_object] App twin
I5OM83 [kv_store] Condition-based synchronization
I5OE57 [New feature] [relational_store] Encrypted database storage
I5QN1E [kv_store] Centralized system data synchronization when the device goes online| NA | +| Web subsystem| The webview component supports copy and paste. Basic audio/video playback and HTTPS bidirectional authentication are supported.
The following requirements are involved:
I5QA3D [New feature] [webview] Content selection and copy on a page with both texts and images
I5P97S [Enhanced feature] Input method binding when the W3C input tag is set to autofocus
I5P001 [Enhanced feature] [webview] Selecting of multiple texts by holding down Shift
I5OZZ8 [New feature] [webview] Text selection by clicking and sliding the left mouse button
I5OURV [Enhanced feature] [webview] Optimization of the soft keyboard pop-up effect
I5ORNO [New feature] [webview] HTTPS bidirectional verification
I5OESN [Enhanced feature] [webview] W3C draggable attribute
I5O4BN [New feature] [webview] Connection between the webview pasteboard and system pasteboard
I5O4BB [New feature] [webview] Obtaining page images (rendered images)
I5O4B5 [New feature] [webview] Pasting plain text based on the input tag
I5O4AZ [New feature] [webview] Obtaining plain text on the page
I5NXG9 [New specifications] [web] Support for the touch, scroll, and gesture events
I5LIL6 [New feature] [web] Message exchange between applications and HTML5
I5JTLQ [New specifications] [web] Handle event notification
I5HRX9 [New feature] [webview] Basic multimedia playback capabilities| NA | +| Kernel subsystem| The following basic capabilities are added: memory level notification to AMS, reclaim priority management for resident system services, and reclaim priority management based on different Extension ability states.
Forward edge CFI is added.
The clang compiler is used for kernel compilation.
The following requirements are involved:
I5K0VE Memory level notification to AMS
I5BND4 Reporting to the adj module whether a system application can be restarted after being killed
I5BNEC Listening for the association between Service, Data, and Extension abilities
I5MXBS Forward edge CFI
I5P4FB Enable CFI configurations
I5LX3A Building Linux with Clang/LLVM| NA | +| Multimedia subsystem| The following features are added: distributed audio, volume, and device status management; device listening and projection; preview, photographing, and video recording using distributed cameras; metadata management. Connection to 3.5 mm headsets is supported.
I5NYBJ [Performance] Media playback start time
I5NYCF [New feature] Video hardware encoding based on the HDI codec interface
I5NYCP [New feature] Video hardware decoding based on the HDI codec interface
I5OOKN [New feature] H.265 video hardware decoding
I5OOKW [New feature] H.265 video hardware encoding
I5OWXY [New feature] Native audio decoding APIs
I5OXCD [New feature] Native audio encoding APIs
I5P8N0 [New feature] Native video encoding APIs
I5O336 [New feature] Projection of a single-application audio stream or all audio streams in the system
I5OEWG [New feature] Setting and obtaining the volume of a single audio stream by system applications| NA | +| Multi-language runtime subsystem| The front-end compilation performance is improved, for example, by using the es2abc component.
Runtime performance is improved through ISA reconstruction, assembly interpreter, and TS Ahead of Time (AOT) compiler.
New functions are added, such as ES2021 in strict mode, modularization, runtime debugging and tuning enhancement, and bytecode hot reload.
The following requirements are involved:
I5MYM9 [New specifications] Merging and adaptation of the abc file for multiple modules
I59TAQ [New specifications] Standard compilation lowering of the TS AOT compiler and pass description optimization
I5OJ8Q [New specifications] Displaying the attribute types defined ES2021 in DevEco Studio
I5ODV4 [New feature] Uninstalling bytecode patch files
I5OXSC [New feature] Installing bytecode patch files
I5HNNZ [New feature] Enabling the namespace of the loader
I5HVQE [New feature] Product-specific stack size setting of the thread, and stack page guard
I5MCUF [Enhanced feature] New CAPIs of libc and support for symbols such as pthread
I5HVNH [New feature] RM.006. Enhanced dynamic library symbol management
I5HVQ0 [New feature] RM.008. Fortify supported by musl
I5KT7X [New feature] RM.002. API detection for API header files
I5TB3Y [New feature] ABI using emutls by default
I5R119 [Enhanced feature] Separated use of memory for loader and libc
Open-source Clang toolchain
I5MYM9 [New specifications] Modular compilation supported by the front-end compiler toolchain
I5IKO1 [New specifications] Compiling Commonjs module with the es2abc component
I5RRAJ [New specifications] Patch file source code identification tool
I5PRFT [New specifications] Patch bytecode compiler
I5RHDH [New specifications] Hot loading of ArkCompiler bytecode
I5RA7C [New specifications] Support for ES2021 in strict mode
I5HRUY [New specifications] Converting from JS code to ArkCompiler bytecode by the es2abc component| NA | +| IAM account subsystem and program access control subsystem| User identity authentication is added to the IAM account subsystem. The permission service supports precise positioning and fuzzy positioning, and other capabilities are enhanced. The privacy management service is provided.
The following requirements are involved:
I5N90B [New specifications] Application accounts adaptation to sandbox applications
I5N90O [New specifications] User identity authentication of the IAM account subsystem
I5NOQI [New feature] Precise positioning and fuzzy positioning of the permission service
I5NT1X [New feature] Enhanced permission usage record management
I5NU8U [New feature] Improved UX effect for the permission request dialog box
I5P4IU [New feature] Privacy management
I5P530 [New feature] Location service usage status management| NA | +| Globalization subsystem| The pseudo-localization capability is added.
The following requirement is involved:
I4WLSJ [New feature] Pseudo-localization| NA | +| Misc services subsystem| The following basic module features are added: pasteboard, upload and download, screen lock, and input method framework.
The following requirements are involved:
I5JPMG [request] [download] Background task notification
I5NXHK [input_method_fwk] Binding of only the innerkits interface of the input method and the JS interface that independently controls the display and hiding of the soft keyboard
I5NG2X [theme_screenlock] Screen lock requested by specific system applications
I5IU1Z Adding image data to pasteboard data
I5OGA3 Cross-device pasteboard switch at the device level
I5NMKI [pasteboard] Adding binary data to pasteboard data
I5MAMN Limiting the pasteboard data range to within the application
I5OX20 [input_method_fwk] Added the API for obtaining the input method| NA | +| ArkUI development framework| The following capabilities are enhanced: ArkUI component, resource and media query, DFX, and toolchain. The memory and performance are optimized.
The following requirements are involved:
I5IZZ7 [ace_engine_standard] Separate **borderRadius** setting for each corner by the **\** component
I5JQ1R [ace_engine_standard] Image copy and paste
I5JQ3F [ace_engine_standard] Enhanced text box capabilities
I5JQ3J [ace_engine_standard] Event topology of the **\** component
I5JQ54 [ace_engine_standard] Specifying a component to get the focus
I5MX7J [ace_engine_standard] Left sliding, right sliding, and rebound effect of the **\** component
I5MWS0 [ace_engine_standard] Height notification of the **\** component
I5IZVY [ace_engine_standard] Component refresh upon the keyboard and mouse connection
I5JQ5Y [ace_engine_standard] Enhanced focus navigation
I5IY7K [New requirement] [ace_engine_standard] Theme capability
I5MWTB [ace_engine_standard] vp query for media
I5IZU9 [ace_engine_standard] Optimization of the resident memory of ui_service
I5JQ26 [ace_engine_standard] Optimized Vsync request mechanism
I5JQ2O [ace_engine] Preloading of public resources
I5JQ2D [ace_engine_standard] Optimized resampling of move events
I5IZXS [toolchain] Display of the plaintext of the developer variable name in the DFX error stack print
I5IZYG [toolchain] Display of the plaintext of the developer variable name in the DFX error stack print
I5IZX0 [toolchain] Adding the **bundleName** and **moduleName** parameters to **$r** during compilation
I5J09I [toolchain] Export of \@Builder| NA | + + + + +### Chip and Development Board Adaptation + +For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard.md). + + +### Samples + + **Table 4** New samples + +| Subsystem| Name| Introduction| Programming Language| +| -------- | -------- | -------- | -------- | +| ArkUI development framework| [HealthyDiet](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/HealthyDiet)| This sample app helps you keep food records and view food information. After you add food records, including the food type, weight, and meal time, the app can calculate nutrition data (calories, proteins, fats, and carbon water) for the meals and display the data in a bar chart.| eTS | +| ArkUI development framework| [MusicAlbum](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/MusicAlbum)| This sample shows the home page of a music album app. The adaptive layout and responsive layout are used to ensure that the app can be properly displayed on devices irrespective of screen sizes.| eTS | +| Ability framework and file management subsystem| [Share](https://gitee.com/openharmony/applications_app_samples/tree/master/Share/Share)| Using this sample app, you can share texts, links, and images with third-party applications and display them in these applications.| eTS | +| Ability framework| [GalleryForm](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/GalleryForm)| This sample demonstrates the display of **Gallery** images in a widget and periodic update of the widget.| eTS | +| ArkUI development framework| [AppMarket](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/AppMarket)| This sample shows the home page of an application market, which contains the tab bar, banner, featured apps, and featured games.| eTS | +| ArkUI development framework| [Weather](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/Weather)| This sample demonstrates one-time development for multi-device deployment by showing how to develop a weather app and deploy it across different devices. The demo app includes the following: home page, **Manage City** page, **Add City** page, and **Update Time** page.| eTS | +| Multimedia subsystem| [MediaCollections](https://gitee.com/openharmony/applications_app_samples/tree/master/media/MediaCollections)| This sample shows the capabilities of online streaming, audio and video playback control, and volume adjustment.| eTS | + +For more information, visit [Samples](https://gitee.com/openharmony/app_samples). + + +## Resolved Issues + + **Table 5** Resolved issues + +| Issue No.| Description| +| -------- | -------- | +| I5I4GJ | There is a possibility that the RK3568 device is disconnected from DevEco Studio.| +| I5HTGF | The photo taken is rotated by 90 degrees clockwise when compared with the preview image.| +| I5FUNB | There are no patches for the known Linux kernel vulnerabilities yet.
CVE-2022-1462 | + + + +## Known Issues + + **Table 6** Known issues + +| Issue No.| Description| Impact| To Be Resolved By| +| -------- | -------- | -------- | -------- | +| I59PWR | In the memory usage test performed on the RK3568 device, the actual value of the com.ohos.launcher process is 84279 KB, which exceeds the baseline value by 200 MB.| Though the process consumes more memory than what is expected, it does not affect the overall memory usage of the system.| October 20| +| I59QII | In the resident memory test performed on the RK3568 device, the actual value of the netmanager process is 3884 KB, which exceeds the baseline value (1241 KB) by 2.58 MB. In the memory test, the actual value of the netmanager process exceeds the baseline value (1241 KB) by 1 MB.| Though the process consumes more memory than what is expected, it does not affect the overall memory usage of the system.| October 20| +| I5LH57 | In the resident memory test performed on the RK3568 device, the actual value of the telephony process is 10329 KB, which exceeds the baseline value (8434 KB) by 1.85 MB.| Though the process consumes more memory than what is expected, it does not affect the overall memory usage of the system.| October 20| +| I5Q5PR | In the resident memory test performed on the RK3568 device, the actual value of the wifi_hal_service process is 4374 KB, which exceeds the baseline value (829 KB) by 3.4 MB.| The memory usage exceeds the expected value, but the memory usage of the entire system is not affected. The baseline value has been met, and no function is affected.| October 20| +| I5T71O | In the dynamic memory test performed on the RK3568 device, the actual value of the com.ohos.settings process is 76123 KB, which exceeds the baseline value (15824 KB) by 58.8 MB.| Though the process consumes more memory than what is expected, it does not affect the overall memory usage of the system.| October 20| +| I5S40B | The actual sliding frame rate of **Contacts** is 30.3 fps, which is less than the baseline value (54 fps) by 23.7 fps.| The load success rate is affected. This issue depends on the ArkUI framework reconstruction.| October 15| +| I5MVDK | A crash occurs when a socket fuzz test is performed on **/data/data/.pulse_dir/runtime/cli**.| The process crashes during the test.| October 18| +| I5M3UO | [TTE WRC team] There is new line injection via the Wi-Fi SSID in the wifi_manager_service.| If the Wi-Fi SSID contains invalid characters (\n), an exception occurs when saving or parsing the configuration file.| October 12| +| I5T8FV | The verification permission is not defined in the system and does not take effect.| The authentication fails. No process can request the permission. Currently, no service uses this permission.| October 18| diff --git a/en/release-notes/Readme.md b/en/release-notes/Readme.md index bcecbe9d2288800cacc9df870d35ca4fdd1e515b..d7efa0580a1a901e20428a1e7160f7861075cefd 100644 --- a/en/release-notes/Readme.md +++ b/en/release-notes/Readme.md @@ -1,29 +1,31 @@ # OpenHarmony Release Notes ## OpenHarmony 3.x Releases -- [OpenHarmony v3.1.2 Release (2022-08-24)](OpenHarmony-v3.1.2-release.md) -- [OpenHarmony v3.2 Beta2 (2022-07-30)](OpenHarmony-v3.2-beta2.md) -- [OpenHarmony v3.2 Beta1 (2022-05-31)](OpenHarmony-v3.2-beta1.md) -- [OpenHarmony v3.1.1 Release (2022-05-31)](OpenHarmony-v3.1.1-release.md) -- [OpenHarmony v3.1 Release (2022-03-30)](OpenHarmony-v3.1-release.md) -- [OpenHarmony v3.1 Beta (2021-12-31)](OpenHarmony-v3.1-beta.md) -- [OpenHarmony v3.0.5 LTS (2022-07-01)](OpenHarmony-v3.0.5-LTS.md) -- [OpenHarmony v3.0.3 LTS (2022-04-08)](OpenHarmony-v3.0.3-LTS.md) -- [OpenHarmony v3.0.2 LTS (2022-03-18)](OpenHarmony-v3.0.2-LTS.md) -- [OpenHarmony v3.0.1 LTS (2022-01-12)](OpenHarmony-v3.0.1-LTS.md) -- [OpenHarmony v3.0 LTS (2021-09-30)](OpenHarmony-v3.0-LTS.md) +- [OpenHarmony v3.2 Beta3 (2022-09-30)](OpenHarmony-v3.2-beta3.md) +- [OpenHarmony v3.2 Beta2 (2022-07-30)](OpenHarmony-v3.2-beta2.md) +- [OpenHarmony v3.2 Beta1 (2022-05-31)](OpenHarmony-v3.2-beta1.md) +- [OpenHarmony v3.1 Release (2022-03-30)](OpenHarmony-v3.1-release.md) + - [OpenHarmony v3.1.2 Release (2022-08-24)](OpenHarmony-v3.1.2-release.md) + - [OpenHarmony v3.1.1 Release (2022-05-31)](OpenHarmony-v3.1.1-release.md) +- [OpenHarmony v3.1 Beta (2021-12-31)](OpenHarmony-v3.1-beta.md) +- [OpenHarmony v3.0 LTS (2021-09-30)](OpenHarmony-v3.0-LTS.md) + - [OpenHarmony v3.0.5 LTS (2022-07-01)](OpenHarmony-v3.0.5-LTS.md) + - [OpenHarmony v3.0.3 LTS (2022-04-08)](OpenHarmony-v3.0.3-LTS.md) + - [OpenHarmony v3.0.2 LTS (2022-03-18)](OpenHarmony-v3.0.2-LTS.md) + - [OpenHarmony v3.0.1 LTS (2022-01-12)](OpenHarmony-v3.0.1-LTS.md) ## OpenHarmony 2.x Releases -- [OpenHarmony v2.2 beta2 (2021-08-04)](OpenHarmony-v2.2-beta2.md) -- [OpenHarmony 2.0 Canary (2021-06-01)](OpenHarmony-2-0-Canary.md) +- [OpenHarmony v2.2 beta2 (2021-08-04)](OpenHarmony-v2.2-beta2.md) +- [OpenHarmony 2.0 Canary (2021-06-01)](OpenHarmony-2-0-Canary.md) ## OpenHarmony 1.x Releases -- [OpenHarmony v1.1.5 LTS (2022-08-24)](OpenHarmony-v1.1.5-LTS.md) -- [OpenHarmony v1.1.4 LTS (2022-02-11)](OpenHarmony-v1-1-4-LTS.md) -- [OpenHarmony v1.1.3 LTS (2021-09-30)](OpenHarmony-v1-1-3-LTS.md) -- [OpenHarmony v1.1.2 LTS (2021-08-04)](OpenHarmony-v1.1.2-LTS.md) -- [OpenHarmony 1.1.1 LTS (2021-06-22)](OpenHarmony-1-1-1-LTS.md) -- [OpenHarmony 1.1.0 LTS (2021-04-01)](OpenHarmony-1-1-0-LTS.md) -- [OpenHarmony 1.0 (2020-09-10)](OpenHarmony-1-0.md) + +- [OpenHarmony v1.0 (2020-09-10)](OpenHarmony-1-0.md) + - [OpenHarmony v1.1.5 LTS (2022-08-24)](OpenHarmony-v1.1.5-LTS.md) + - [OpenHarmony v1.1.4 LTS (2022-02-11)](OpenHarmony-v1-1-4-LTS.md) + - [OpenHarmony v1.1.3 LTS (2021-09-30)](OpenHarmony-v1-1-3-LTS.md) + - [OpenHarmony v1.1.2 LTS (2021-08-04)](OpenHarmony-v1.1.2-LTS.md) + - [OpenHarmony v1.1.1 LTS (2021-06-22)](OpenHarmony-1-1-1-LTS.md) + - [OpenHarmony v1.1.0 LTS (2021-04-01)](OpenHarmony-1-1-0-LTS.md) diff --git a/en/release-notes/api-change/v3.2-beta1/js-apidiff-window.md b/en/release-notes/api-change/v3.2-beta1/js-apidiff-window.md index 17e4312d9955fbcd21278a9788bc90d6da3d62dd..871dfe4665c7d5f277071e6c871e1310fd516463 100644 --- a/en/release-notes/api-change/v3.2-beta1/js-apidiff-window.md +++ b/en/release-notes/api-change/v3.2-beta1/js-apidiff-window.md @@ -4,6 +4,8 @@ The table below lists the APIs changes of the window manager subsystem in OpenHa ## API Changes + + | Module| Class| Method/Attribute/Enumeration/Constant| Change Type| |---|---|---|---| | ohos.screen | ScreenModeInfo | refreshRate: number; | Added| @@ -20,6 +22,8 @@ The table below lists the APIs changes of the window manager subsystem in OpenHa | ohos.screen | Orientation | UNSPECIFIED = 0 | Added| | ohos.screen | Screen | setScreenActiveMode(modeIndex: number, callback: AsyncCallback\): void;
setScreenActiveMode(modeIndex: number): Promise\; | Added| | ohos.screen | Screen | setOrientation(orientation: Orientation, callback: AsyncCallback\): void;
setOrientation(orientation: Orientation): Promise\; | Added| +| ohos.screen | Screen | on(eventType: 'connect' \| 'disconnect' \| 'change', callback: Callback): void; | Added| +| ohos.screen | Screen | off(eventType: 'connect' \| 'disconnect' \| 'change', callback?: Callback): void; | Added| | ohos.screen | Screen | readonly orientation: Orientation; | Added| | ohos.screen | Screen | readonly activeModeIndex: number; | Added| | ohos.screen | Screen | readonly supportedModeInfo: Array\; | Added| @@ -36,6 +40,8 @@ The table below lists the APIs changes of the window manager subsystem in OpenHa | ohos.window | WindowStage | getSubWindow(): Promise\>;
getSubWindow(callback: AsyncCallback\>): void; | Added| | ohos.window | WindowStage | createSubWindow(name: string): Promise\;
createSubWindow(name: string, callback: AsyncCallback\): void; | Added| | ohos.window | WindowStage | getMainWindow(): Promise\;
getMainWindow(callback: AsyncCallback\): void; | Added| +| ohos.window | WindowStage | on(eventType: 'windowStageEvent', callback: Callback): void; | Added| +| ohos.window | WindowStage | off(eventType: 'windowStageEvent', callback?: Callback): void; | Added| | ohos.window | WindowStageEventType | BACKGROUND | Added| | ohos.window | WindowStageEventType | INACTIVE | Added| | ohos.window | WindowStageEventType | ACTIVE | Added| diff --git a/en/website.md b/en/website.md index 158b3a9361862cbb14bc7dfca3c1af5fbbea3e99..dcd1bc06fea931fb3fe160b92f1333ba2f416981 100644 --- a/en/website.md +++ b/en/website.md @@ -4,29 +4,29 @@ - [Glossary](glossary.md) - OpenHarmony Release Notes - OpenHarmony 3.x Releases - - [OpenHarmony v3.2 Beta2 (2022-07-30)](release-notes/OpenHarmony-v3.2-beta2.md) - - [OpenHarmony v3.2 Beta1 (2022-05-31)](release-notes/OpenHarmony-v3.2-beta1.md) - - [OpenHarmony v3.1.1 Release (2022-05-31)](release-notes/OpenHarmony-v3.1.1-release.md) - - [OpenHarmony v3.1 Release (2022-03-30)](release-notes/OpenHarmony-v3.1-release.md) - - [OpenHarmony v3.1 Beta (2021-12-31)](release-notes/OpenHarmony-v3.1-beta.md) - - [OpenHarmony v3.0.5 LTS (2022-07-01)](release-notes/OpenHarmony-v3.0.5-LTS.md) - - [OpenHarmony v3.0.3 LTS (2022-04-08)](release-notes/OpenHarmony-v3.0.3-LTS.md) - - [OpenHarmony v3.0.2 LTS (2022-03-18)](release-notes/OpenHarmony-v3.0.2-LTS.md) - - [OpenHarmony v3.0.1 LTS (2022-01-12)](release-notes/OpenHarmony-v3.0.1-LTS.md) - - [OpenHarmony v3.0 LTS (2021-09-30)](release-notes/OpenHarmony-v3.0-LTS.md) - + - [OpenHarmony v3.2 Beta3 (2022-09-30)](release-notes/OpenHarmony-v3.2-beta3.md) + - [OpenHarmony v3.2 Beta2 (2022-07-30)](release-notes/OpenHarmony-v3.2-beta2.md) + - [OpenHarmony v3.2 Beta1 (2022-05-31)](release-notes/OpenHarmony-v3.2-beta1.md) + - [OpenHarmony v3.1 Release (2022-03-30)](release-notes/OpenHarmony-v3.1-release.md) + - [OpenHarmony v3.1.2 Release (2022-08-24)](release-notes/OpenHarmony-v3.1.2-release.md) + - [OpenHarmony v3.1.1 Release (2022-05-31)](release-notes/OpenHarmony-v3.1.1-release.md) + - [OpenHarmony v3.1 Beta (2021-12-31)](release-notes/OpenHarmony-v3.1-beta.md) + - [OpenHarmony v3.0 LTS (2021-09-30)](release-notes/OpenHarmony-v3.0-LTS.md) + - [OpenHarmony v3.0.5 LTS (2022-07-01)](release-notes/OpenHarmony-v3.0.5-LTS.md) + - [OpenHarmony v3.0.3 LTS (2022-04-08)](release-notes/OpenHarmony-v3.0.3-LTS.md) + - [OpenHarmony v3.0.2 LTS (2022-03-18)](release-notes/OpenHarmony-v3.0.2-LTS.md) + - [OpenHarmony v3.0.1 LTS (2022-01-12)](release-notes/OpenHarmony-v3.0.1-LTS.md) - OpenHarmony 2.x Releases - - [OpenHarmony v2.2 beta2 (2021-08-04)](release-notes/OpenHarmony-v2.2-beta2.md) - - [OpenHarmony 2.0 Canary (2021-06-01)](release-notes/OpenHarmony-2-0-Canary.md) - - - OpenHarmony 1.x Releases - - - [OpenHarmony v1.1.4 LTS (2022-02-11)](release-notes/OpenHarmony-v1-1-4-LTS.md) - - [OpenHarmony v1.1.3 LTS (2021-09-30)](release-notes/OpenHarmony-v1-1-3-LTS.md) - - [OpenHarmony v1.1.2 LTS (2021-08-04)](release-notes/OpenHarmony-v1.1.2-LTS.md) - - [OpenHarmony 1.1.1 LTS (2021-06-22)](release-notes/OpenHarmony-1-1-1-LTS.md) - - [OpenHarmony 1.1.0 LTS (2021-04-01)](release-notes/OpenHarmony-1-1-0-LTS.md) - - [OpenHarmony 1.0 (2020-09-10)](release-notes/OpenHarmony-1-0.md) + - [OpenHarmony v2.2 beta2 (2021-08-04)](release-notes/OpenHarmony-v2.2-beta2.md) + - [OpenHarmony 2.0 Canary (2021-06-01)](release-notes/OpenHarmony-2-0-Canary.md) + - OpenHarmony 1.x Releases + - [OpenHarmony 1.0 (2020-09-10)](release-notes/OpenHarmony-1-0.md) + - [OpenHarmony v1.1.5 LTS (2022-08-24)](release-notes/OpenHarmony-v1.1.5-LTS.md) + - [OpenHarmony v1.1.4 LTS (2022-02-11)](release-notes/OpenHarmony-v1-1-4-LTS.md) + - [OpenHarmony v1.1.3 LTS (2021-09-30)](release-notes/OpenHarmony-v1-1-3-LTS.md) + - [OpenHarmony v1.1.2 LTS (2021-08-04)](release-notes/OpenHarmony-v1.1.2-LTS.md) + - [OpenHarmony v1.1.1 LTS (2021-06-22)](release-notes/OpenHarmony-1-1-1-LTS.md) + - [OpenHarmony v1.1.0 LTS (2021-04-01)](release-notes/OpenHarmony-1-1-0-LTS.md) - API Differences - OpenHarmony 3.2 Beta3 diff --git a/zh-cn/application-dev/Readme-CN.md b/zh-cn/application-dev/Readme-CN.md index dde8993091b6eb93c20db2f5b35e86fb670c40e6..b46bb3d89e7ffb99bde5bda90c7e2664e7547cdf 100644 --- a/zh-cn/application-dev/Readme-CN.md +++ b/zh-cn/application-dev/Readme-CN.md @@ -16,6 +16,7 @@ - [应用包结构说明(Stage模型)](quick-start/stage-structure.md) - [SysCap说明](quick-start/syscap.md) - [HarmonyAppProvision配置文件](quick-start/app-provision-structure.md) + - [资源分类与访问](quick-start/resource-categories-and-access.md) - 学习ArkTS语言 - [初识ArkTS语言](quick-start/arkts-get-started.md) - ArkTS语法(声明式UI) diff --git a/zh-cn/application-dev/ability/continuationmanager.md b/zh-cn/application-dev/ability/continuationmanager.md index d5a92c9deb6f5433db1c8ec96efdf0c2a18328cb..470d9bbb79db74dc5cc24f4bcdad9e3e298d2f54 100644 --- a/zh-cn/application-dev/ability/continuationmanager.md +++ b/zh-cn/application-dev/ability/continuationmanager.md @@ -15,10 +15,10 @@ continuationManager作为流转能力的入口,主要用于拉起系统中的 | registerContinuation(callback: AsyncCallback\): void | 注册流转管理服务,并获取对应的注册token,无过滤条件(AsyncCallback)。 | | registerContinuation(options: ContinuationExtraParams, callback: AsyncCallback\): void | 注册流转管理服务,并获取对应的注册token(AsyncCallback)。 | | registerContinuation(options?: ContinuationExtraParams): Promise\ | 连接流转管理服务,并获取对应的注册token(Promise)。 | -| on(type: "deviceConnect", token: number, callback: Callback\>): void | 监听设备连接状态(Callback)。 | -| on(type: "deviceDisconnect", token: number, callback: Callback\>): void | 监听设备断开状态(Callback)。 | -| off(type: "deviceConnect", token: number): void | 取消监听设备连接状态。 | -| off(type: "deviceDisconnect", token: number): void | 取消监听设备断开状态。 | +| on(type: "deviceSelected", token: number, callback: Callback\>): void | 监听设备连接状态(Callback)。 | +| on(type: "deviceUnselected", token: number, callback: Callback\>): void | 监听设备断开状态(Callback)。 | +| off(type: "deviceSelected", token: number): void | 取消监听设备连接状态。 | +| off(type: "deviceUnselected", token: number): void | 取消监听设备断开状态。 | | startContinuationDeviceManager(token: number, callback: AsyncCallback\): void | 拉起设备选择模块,可显示组网内可选择设备列表信息,无过滤条件(AsyncCallback)。 | | startContinuationDeviceManager(token: number, options: ContinuationExtraParams, callback: AsyncCallback\): void | 拉起设备选择模块,可显示组网内可选择设备列表信息(AsyncCallback)。 | | startContinuationDeviceManager(token: number, options?: ContinuationExtraParams): Promise\ | 拉起设备选择模块,可显示组网内可选择设备列表信息(Promise)。 | @@ -34,7 +34,7 @@ continuationManager作为流转能力的入口,主要用于拉起系统中的 import continuationManager from '@ohos.continuation.continuationManager'; ``` -2. 跨端迁移或多端协同操作需要申请权限。 +2. 申请分布式权限 DISTRIBUTED_DATASYNC。 权限申请在FA平台和Stage平台有区别,FA平台需要在`config.json`里面进行配置请求权限,示例代码如下: @@ -161,8 +161,8 @@ continuationManager作为流转能力的入口,主要用于拉起系统中的 try { // 参数token为注册token - continuationManager.on("deviceConnect", token, (continuationResults) => { - console.info('registerDeviceConnectCallback len: ' + continuationResults.length); + continuationManager.on("deviceSelected", token, (continuationResults) => { + console.info('registerDeviceSelectedCallback len: ' + continuationResults.length); if (continuationResults.length <= 0) { console.info('no selected device'); return; @@ -175,7 +175,6 @@ continuationManager作为流转能力的入口,主要用于拉起系统中的 bundleName: 'ohos.samples.continuationmanager', abilityName: 'MainAbility' }; - // 发起多端协同操作,需申请ohos.permission.DISTRIBUTED_DATASYNC权限 globalThis.abilityContext.startAbility(want).then((data) => { console.info('StartRemoteAbility finished, ' + JSON.stringify(data)); }).catch((err) => { @@ -212,15 +211,15 @@ continuationManager作为流转能力的入口,主要用于拉起系统中的 ```ts try { // 参数token为注册token - continuationManager.on("deviceDisconnect", token, (deviceIds) => { - console.info('onDeviceDisconnect len: ' + deviceIds.length); - if (deviceIds.length <= 0) { + continuationManager.on("deviceUnselected", token, (continuationResults) => { + console.info('onDeviceUnselected len: ' + continuationResults.length); + if (continuationResults.length <= 0) { console.info('no unselected device'); return; } // 更新设备流转状态 - let unselectedDeviceId: string = deviceIds[0]; // 将取消选择的第一个远端设备deviceId赋值给unselectedDeviceId变量 + let unselectedDeviceId: string = continuationResults[0].id; // 将取消选择的第一个远端设备deviceId赋值给unselectedDeviceId变量 let deviceConnectStatus: continuationManager.DeviceConnectState = continuationManager.DeviceConnectState.DISCONNECTING; // 设备断开状态 // 参数token为注册token,参数unselectedDeviceId为获取到的unselectedDeviceId diff --git a/zh-cn/application-dev/ability/fa-formability.md b/zh-cn/application-dev/ability/fa-formability.md index 3fbe75aba88249f3248233b5626a3b1fa9139a70..c974cb44ed9ad08899842a4fdba480697aecd3a7 100644 --- a/zh-cn/application-dev/ability/fa-formability.md +++ b/zh-cn/application-dev/ability/fa-formability.md @@ -10,7 +10,7 @@ - 卡片使用方:显示卡片内容的宿主应用,控制卡片在宿主中展示的位置。 - 卡片管理服务:用于管理系统中所添加卡片的常驻代理服务,包括卡片对象的管理与使用,以及卡片周期性刷新等。 -> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> **说明:** > 卡片使用方和提供方不要求常驻运行,在需要添加/删除/请求更新卡片时,卡片管理服务会拉起卡片提供方获取卡片信息。 开发者仅需作为卡片提供方进行卡片内容的开发,卡片使用方和卡片管理服务由系统自动处理。 diff --git a/zh-cn/application-dev/ability/stage-ability.md b/zh-cn/application-dev/ability/stage-ability.md index 4a39afa52ebff9f2d33fc8dcac0a79e17fdaaf75..31e252617d90c4a0576761a7224f0ff8e968d007 100644 --- a/zh-cn/application-dev/ability/stage-ability.md +++ b/zh-cn/application-dev/ability/stage-ability.md @@ -170,13 +170,13 @@ context.requestPermissionsFromUser(permissions).then((data) => { }) ``` ### 系统环境变化通知 -环境变化,包括全局配置的变化和Ability配置的变化。全局配置指全局的、系统的配置,目前包括“语言”和“颜色模式”,全局配置的变化一般由“设置”中的配置项或“控制中心”中的图标触发。Ability配置指与单个Ability实例相关的配置,目前包括“displayId”、“屏幕分辨率”,“横竖屏”,这些配置与Ability所在的Display有关,Ability配置的变化一般由窗口触发。配置项目前均定义在[Configuration](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-configuration.md)类中。 +环境变化,包括全局配置的变化和Ability配置的变化。全局配置指全局的、系统的配置,目前包括“语言”和“颜色模式”,全局配置的变化一般由“设置”中的配置项或“控制中心”中的图标触发。Ability配置指与单个Ability实例相关的配置,目前包括“displayId”(物理屏幕Id)、“屏幕分辨率”,“横竖屏”,这些配置与Ability所在的Display有关,Ability配置的变化一般由窗口触发。配置项目前均定义在[Configuration](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-configuration.md)类中。 对于Stage模型的应用,配置发生变化时,不会重启Ability,会触发应用的`onConfigurationUpdated(config: Configuration)`回调,若应用希望根据配置变化做相应处理,可以重写`onConfigurationUpdated`回调,若无需处理配置变化,则可以不必实现`onConfigurationUpdated`回调。应该注意的是,回调中的Configuration对象包括当前Ability所有的配置,不仅是发生变化的配置。 如下示例展示了AbilityStage的`onConfigurationUpdated`回调实现,系统语言和颜色模式发生变化时触发该回调。具体示例代码如下: ```ts -import Ability from '@ohos.application.Ability' +import AbilityStage from '@ohos.application.AbilityStage' import ConfigurationConstant from '@ohos.application.ConfigurationConstant' export default class MyAbilityStage extends AbilityStage { @@ -271,7 +271,7 @@ function getRemoteDeviceId() { } } ``` -向用户申请数据同步'ohos.permission.DISTRIBUTED_DATASYNC'的权限。申请授权示例代码见[应用向用户申请授权](###应用向用户申请授权)。 +向用户申请数据同步'ohos.permission.DISTRIBUTED_DATASYNC'的权限。申请授权示例代码见[应用向用户申请授权](#应用向用户申请授权)。 ### 指定页面启动Ability 当Ability的启动模式设置为单例时,若Ability已被拉起,再次启动Ability会触发onNewWant回调。应用开发者可以通过want传递启动参数,比如希望指定页面启动Ability,可以通过want中的uri参数或parameters参数传递pages信息。目前,Stage模型中Ability暂时无法直接使用router的能力,可以将启动参数传递给自定义组件,在自定义组件的生命周期中调用router接口显示指定页面。具体示例代码如下: diff --git a/zh-cn/application-dev/application-test/Readme-CN.md b/zh-cn/application-dev/application-test/Readme-CN.md index 5343a514a78c17609da4a4b4c1c6d7cab344fa6c..fd564e2ce05ac355ca629519783c60b229e5abfe 100644 --- a/zh-cn/application-dev/application-test/Readme-CN.md +++ b/zh-cn/application-dev/application-test/Readme-CN.md @@ -1,8 +1,5 @@ # 应用测试 -- 自动化测试框架 - - [自动化测试框架使用指导](arkxtest-guidelines.md) -- SmartPerf性能工具 - - [SmartPerf性能工具使用指导](smartperf-guidelines.md) -- wukong稳定性工具 - - [wukong稳定性工具使用指导](wukong-guidelines.md) +- [自动化测试框架使用指导](arkxtest-guidelines.md) +- [SmartPerf性能工具使用指导](smartperf-guidelines.md) +- [wukong稳定性工具使用指导](wukong-guidelines.md) diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/case.md b/zh-cn/application-dev/key-features/multi-device-app-dev/case.md index c6e0d4e6072305b218fc6a70da44840b44ad85b7..ff3e1737f699d4a1d808f358615ec1dd491bc40b 100644 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/case.md +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/case.md @@ -526,7 +526,7 @@ struct Conversation { - 通过[Flex组件](../../reference/arkui-ts/ts-container-flex.md)将三个部分组合起来,注意justifyContent: FlexAlign.SpaceBetween配置项是将Flex组件中的元素按照主轴方向均匀分配,其中第一个元素与顶部对齐,最后一个元素与底部对齐。 -- 通过[List组件](../../reference/arkui-ts/ts-container-list.md)和[ForEach语法](../../ui/ts-rending-control-syntax-foreach.md),显示整个消息列表。 +- 通过[List组件](../../reference/arkui-ts/ts-container-list.md)和[ForEach语法](../../quick-start/arkts-rendering-control.md#循环渲染),显示整个消息列表。 | 默认设备 | 平板 | | -------- | -------- | diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/page-development-intro.md b/zh-cn/application-dev/key-features/multi-device-app-dev/page-development-intro.md index 6594527ed42816661e24aa4d4a9df7ed8060fbba..5c54f556c809c56c2e85cae96bf602f03d421d96 100644 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/page-development-intro.md +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/page-development-intro.md @@ -19,7 +19,7 @@ > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** -> 开发多设备上同一页面时,建议开发者多使用[自定义组件](../../ui/ts-component-based-component.md),既可以增加代码的可读性和可维护性,同时也可以尽可能的实现代码复用。 +> 开发多设备上同一页面时,建议开发者多使用自定义组件,既可以增加代码的可读性和可维护性,同时也可以尽可能的实现代码复用。 diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/resource-usage.md b/zh-cn/application-dev/key-features/multi-device-app-dev/resource-usage.md index 95f87482f70ad83d0cb437f156f89955a466e67c..00087b4de01593b4eb1e519c5e8b7f5d5c0fc765 100644 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/resource-usage.md +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/resource-usage.md @@ -35,7 +35,7 @@ resources base目录默认存在,而限定词目录需要开发者自行创建,其名称可以由一个或多个表征应用场景或设备特征的限定词组合而成。应用使用某资源时,系统会根据当前设备状态优先从相匹配的限定词目录中寻找该资源。只有当resources目录中没有与设备状态匹配的限定词目录,或者在限定词目录中找不到该资源时,才会去base目录中查找。rawfile是原始文件目录,它不会根据设备状态去匹配不同的资源,故不在本文的讨论范文内。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** -> - 请访问[声明式开发范式资源文件分类](../../ui/ui-ts-basic-resource-file-categories.md),了解限定词目录的命名规则、创建流程、匹配规则等,本文不展开介绍。 +> - 请访问[声明式开发范式资源文件分类](../../quick-start/resource-categories-and-access.md#资源分类),了解限定词目录的命名规则、创建流程、匹配规则等,本文不展开介绍。 > > - 没有设备状态匹配的限定词目录,或者在限定词目录中找不到目标资源时,会继续在base目录中查找。**强烈建议对于所有应用自定义资源都在base目录中定义默认值**,防止出现找不到资源值的异常场景。 > @@ -73,7 +73,7 @@ base目录与限定词目录下面可以创建资源组目录(包括element、 在工程中,通过 "$r('app.type.name')" 的形式引用应用资源。app代表是应用内resources目录中定义的资源;type 代表资源类型(或资源的存放位置),可以取 color、float、string、plural和media,name代表资源命名,由开发者添加资源时确定。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** -> 可以查看[声明式范式访问应用资源](../../ui/ts-resource-access.md),了解资源访问的更多细节。 +> 可以查看[声明式范式访问应用资源](../../quick-start/resource-categories-and-access.md#应用资源),了解资源访问的更多细节。 ### 示例 diff --git a/zh-cn/application-dev/media/camera.md b/zh-cn/application-dev/media/camera.md index 5840b57d53683eb3252ce9cf1ae6514240ff963a..2b3ae2fba5874f4db7f73b44195b6b110adf5905 100644 --- a/zh-cn/application-dev/media/camera.md +++ b/zh-cn/application-dev/media/camera.md @@ -2,7 +2,13 @@ ## 场景介绍 -相机模块支持相机相关基础功能的开发,主要包括预览、拍照、录像等。本文将对相机各种基础功能的开发进行介绍说明。 +OpenHarmony相机模块支持相机业务的开发,开发者可以通过已开放的接口实现相机硬件的访问、操作和新功能开发,最常见的操作如:预览、拍照和录像等。开发者也可以通过合适的接口或者接口组合实现闪光灯控制、曝光时间控制、手动对焦和自动对焦控制、变焦控制以及更多的功能。 + +开发者在调用Camera能力时,需要了解Camera的一些基本概念: + +- **相机静态能力**:用于描述相机的固有能力的一系列参数,比如朝向、支持的分辨率等信息。 +- **物理相机**:物理相机就是独立的实体摄像头设备。物理相机ID是用于标志每个物理摄像头的唯一字串。 +- **异步操作**:为保证UI线程不被阻塞,大部分Camera调用都是异步的。对于每个API均提供了callback函数和Promise函数。 ## 开发步骤 @@ -12,53 +18,63 @@ ### 全流程场景 -包含流程:创建实例、参数设置、会话管理、拍照、录像、释放资源等。 +包含流程:权限申请、创建实例、参数设置、会话管理、拍照、录像、释放资源等。 -Xcomponent创建方法可参考:[XComponent创建方法](#xcomponent创建方法) +#### 权限申请 -拍照保存接口可参考:[图片处理API文档](image.md#imagereceiver的使用) +在使用相机之前,需要申请相机的相关权限,保证应用拥有相机硬件及其他功能权限,应用权限的介绍请参考权限章节,相机涉及权限如下表。 + +| 权限名称 | 权限属性值 | +| -------- | ------------------------------ | +| 相机权限 | ohos.permission.CAMERA | +| 录音权限 | ohos.permission.MICROPHONE | +| 存储权限 | ohos.permission.WRITE_MEDIA | +| 读取权限 | ohos.permission.READ_MEDIA | +| 位置权限 | ohos.permission.MEDIA_LOCATION | + +参考代码如下: + +```typescript +const PERMISSIONS: Array = [ + 'ohos.permission.CAMERA', + 'ohos.permission.MICROPHONE', + 'ohos.permission.MEDIA_LOCATION', + 'ohos.permission.READ_MEDIA', + 'ohos.permission.WRITE_MEDIA' +] + +function applyPermission() { + console.info('[permission] get permission'); + globalThis.abilityContext.requestPermissionFromUser(PERMISSIONS) + } +``` #### 创建实例 -```js +在实现一个相机应用之前必须先创建一个独立的相机设备,然后才能继续相机的其他操作。如果此步骤操作失败,相机可能被占用或无法使用。如果被占用,必须等到相机释放后才能重新获取CameraManager对象。通过getSupportedCameras() 方法,获取当前使用的设备支持的相机列表。相机列表中存储了当前设备拥有的所有相机ID,如果列表不为空,则列表中的每个ID都支持独立创建相机对象;否则,说明正在使用的设备无可用的相机,不能继续后续的操作。相机设备具备预览、拍照、录像、Metadata等输出流,需要通过getSupportedOutputCapability()接口获取各个输出流的具体能力,通过该接口,可以获取当前设备支持的所有输出流能力,分别在CameraOutputCapability中的各个profile字段中,相机设备创建的建议步骤如下: + +```typescript import camera from '@ohos.multimedia.camera' import image from '@ohos.multimedia.image' import media from '@ohos.multimedia.media' -import featureAbility from '@ohos.ability.featureAbility' // 创建CameraManager对象 -let cameraManager -await camera.getCameraManager(globalThis.Context, (err, manager) => { - if (err) { - console.error('Failed to get the CameraManager instance ${err.message}'); - return; - } - console.log('Callback returned with the CameraManager instance'); - cameraManager = manager -}) - -// 注册回调函数监听相机状态变化,获取状态变化的相机信息 -cameraManager.on('cameraStatus', (cameraStatusInfo) => { - console.log('camera : ' + cameraStatusInfo.camera.cameraId); - console.log('status: ' + cameraStatusInfo.status); -}) +let cameraManager = await camera.getCameraManager(null) +if (!cameraManager) { + console.error('Failed to get the CameraManager instance'); +} // 获取相机列表 -let cameraArray -await cameraManager.getCameras((err, cameras) => { - if (err) { - console.error('Failed to get the cameras. ${err.message}'); - return; - } - console.log('Callback returned with an array of supported cameras: ' + cameras.length); - cameraArray = cameras -}) +let cameraArray = await cameraManager.getSupportedCameras() +if (!cameraArray) { + console.error('Failed to get the cameras'); +} -for(let cameraIndex = 0; cameraIndex < cameraArray.length; cameraIndex++) { - console.log('cameraId : ' + cameraArray[cameraIndex].cameraId) // 获取相机ID - console.log('cameraPosition : ' + cameraArray[cameraIndex].cameraPosition) // 获取相机位置 - console.log('cameraType : ' + cameraArray[cameraIndex].cameraType) // 获取相机类型 - console.log('connectionType : ' + cameraArray[cameraIndex].connectionType) // 获取相机连接类型 +for (let index = 0; index < cameraArray.length; index++) { + console.log('cameraId : ' + cameraArray[index].cameraId) // 获取相机ID + console.log('cameraPosition : ' + cameraArray[index].cameraPosition) // 获取相机位置 + console.log('cameraType : ' + cameraArray[index].cameraType) // 获取相机类型 + console.log('connectionType : ' + cameraArray[index].connectionType) // 获取相机连接类型 } // 创建相机输入流 @@ -68,52 +84,73 @@ await cameraManager.createCameraInput(cameraArray[0].cameraId).then((input) => { cameraInput = input }) +// 获取相机设备支持的输出流能力 +let cameraOutputCap = await camera.getSupportedOutputCapability(cameraInput); +if (!cameraOutputCap) { + console.error("outputCapability outputCapability == null || undefined") +} else { + console.info("outputCapability: " + JSON.stringify(cameraOutputCap)); +} + +let previewProfilesArray = cameraOutputCap.previewProfiles; +if (!previewProfilesArray) { + console.error("createOutput previewProfilesArray == null || undefined") +} + +let photoProfilesArray = cameraOutputCap.photoProfiles; +if (!photoProfilesArray) { + console.error("createOutput photoProfilesArray == null || undefined") +} + +let videoProfilesArray = cameraOutputCap.videoProfiles; +if (!videoProfilesArray) { + console.error("createOutput videoProfilesArray == null || undefined") +} + +let metadataObjectTypesArray = cameraOutputCap.supportedMetadataObjectTypes; +if (!metadataObjectTypesArray) { + console.error("createOutput metadataObjectTypesArray == null || undefined") +} + // 创建预览输出流 -let previewOutput -camera.createPreviewOutput((globalThis.surfaceId), (err, output) => { - if (err) { - console.error('Failed to create the PreviewOutput instance. ${err.message}'); - return; - } - console.log('Callback returned with previewOutput instance'); - previewOutput = output -}); +let previewOutput = await camera.createPreviewOutput(previewProfilesArray[0], surfaceId) +if (!previewOutput) { + console.error("Failed to create the PreviewOutput instance.") +} // 创建ImageReceiver对象,并设置照片参数 let imageReceiver = await image.createImageReceiver(1920, 1080, 4, 8) // 获取照片显示SurfaceId let photoSurfaceId = await imageReceiver.getReceivingSurfaceId() // 创建拍照输出流 -let photoOutput -camera.createPhotoOutput((photoSurfaceId), (err, output) => { - if (err) { - console.error('Failed to create the PhotoOutput instance. ${err.message}'); - return; - } - console.log('Callback returned with the PhotoOutput instance.'); - photoOutput = output -}); +let photoOutput = await this.camera.createPhotoOutput(photoProfilesArray[0], photoSurfaceId) +if (!photoOutput) { + console.error('Failed to create the PhotoOutput instance.'); + return; +} // 创建视频录制的参数 -let videoProfile = { - audioBitrate : 48000, - audioChannels : 2, - audioCodec : 'audio/mp4a-latm', - audioSampleRate : 48000, - fileFormat : 'mp4', - videoBitrate : 48000, - videoCodec : 'video/mp4v-es', - videoFrameWidth : 640, - videoFrameHeight : 480, - videoFrameRate : 30 -} let videoConfig = { - audioSourceType : 1, - videoSourceType : 0, - profile : videoProfile, - url : 'file:///data/media/01.mp4', - orientationHint : 0, - location : { latitude : 30, longitude : 130 }, + audioSourceType: 1, + videoSourceType: 1, + profile: { + audioBitrate: 48000, + audioChannels: 2, + audioCodec: 'audio/mp4v-es', + audioSampleRate: 48000, + durationTime: 1000, + fileFormat: 'mp4', + videoBitrate: 48000, + videoCodec: 'video/mp4v-es', + videoFrameWidth: 640, + videoFrameHeight: 480, + videoFrameRate: 30 + }, + url: 'file:///data/media/01.mp4', + orientationHint: 0, + maxSize: 100, + maxDuration: 500, + rotation: 0 } // 创建录像输出流 @@ -129,159 +166,110 @@ await videoRecorder.getInputSurface().then((id) => { console.log('getInputSurface called') videoSurfaceId = id }) -``` -videoRecorder详细创建方法可参考:[视频录制开发指导](./video-recorder.md) -```js -// 创建VideoOutput对象 -let videoOutput -camera.createVideoOutput((surfaceId), (err, output) => { - if (err) { - console.error('Failed to create the VideoOutput instance. ${err.message}'); - return; - } - console.log('Callback returned with the VideoOutput instance'); - videoOutput = output -}); +// 创建VideoOutput对象 +let videoOutput = camera.createVideoOutput(videoProfilesArray[0], videoSurfaceId) +if (!videoOutput) { + console.error('Failed to create the videoOutput instance.'); + return; +} ``` +预览流、拍照流和录像流的输入均需要提前创建surface,其中预览流为XComponent组件提供的surface,拍照流为ImageReceiver提供的surface,录像流为VideoRecorder的surface。 -#### 参数设置 +**XComponent** -```js -// 判断设备是否支持闪光灯 -let flashStatus -await cameraInput.hasFlash().then((status) => { - console.log('Promise returned with the flash light support status:' + status); - flashStatus = status -}) -if(flashStatus) { - // 判断是否支持自动闪光灯模式 - let flashModeStatus - cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO, (err, status) => { - if (err) { - console.error('Failed to check whether the flash mode is supported. ${err.message}'); - return; - } - console.log('Callback returned with the flash mode support status: ' + status); - flashModeStatus = status - }) - if(flashModeStatus) { - // 设置自动闪光灯模式 - cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO, (err) => { - if (err) { - console.error('Failed to set the flash mode ${err.message}'); - return; - } - console.log('Callback returned with the successful execution of setFlashMode.'); - }) - } -} +```typescript +mXComponentController: XComponentController = new XComponentController // 创建XComponentController -// 判断是否支持连续自动变焦模式 -let focusModeStatus -cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO, (err, status) => { - if (err) { - console.error('Failed to check whether the focus mode is supported. ${err.message}'); - return; +build() { + Flex() { + XComponent({ // 创建XComponent + id: '', + type: 'surface', + libraryname: '', + controller: this.mXComponentController + }) + .onload(() => { // 设置onload回调 + // 设置Surface宽高(1920*1080) + this.mXComponentController.setXComponentSurfaceSize({surfaceWidth:1920,surfaceHeight:1080}) + // 获取Surface ID + globalThis.surfaceId = mXComponentController.getXComponentSurfaceId() + }) + .width('1920px') // 设置XComponent宽度 + .height('1080px') // 设置XComponent高度 } - console.log('Callback returned with the focus mode support status: ' + status); - focusModeStatus = status -}) -if(focusModeStatus) { - // 设置连续自动变焦模式 - cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO, (err) => { - if (err) { - console.error('Failed to set the focus mode ${err.message}'); - return; - } - console.log('Callback returned with the successful execution of setFocusMode.'); - }) } +``` -// 获取相机支持的可变焦距比范围 -let zoomRatioRange -cameraInput.getZoomRatioRange((err, range) => { - if (err) { - console.error('Failed to get the zoom ratio range. ${err.message}'); - return; +**ImageReceiver** + +```typescript +function getImageReceiverSurfaceId() { + var receiver = image.createImageReceiver(640, 480, 4, 8) + console.log(TAG + 'before ImageReceiver check') + if (receiver !== undefined) { + console.log('ImageReceiver is ok') + surfaceId1 = await receiver.getReceivingSurfaceId() + console.log('ImageReceived id: ' + JSON.stringify(surfaceId1)) + } else { + console.log('ImageReceiver is not ok') } - console.log('Callback returned with zoom ratio range: ' + range.length); - zoomRatioRange = range -}) + } +``` -// 设置可变焦距比 -cameraInput.setZoomRatio(zoomRatioRange[0], (err) => { - if (err) { - console.error('Failed to set the zoom ratio value ${err.message}'); - return; +**VideoRecorder** + +```typescript +function getVideoRecorderSurface() { + await getFd('CameraManager.mp4'); + mVideoConfig.url = mFdPath; + media.createVideoRecorder((err, recorder) => { + console.info('Entering create video receiver') + mVideoRecorder = recorder + console.info('videoRecorder is :' + JSON.stringify(mVideoRecorder)) + console.info('videoRecorder.prepare called.') + mVideoRecorder.prepare(mVideoConfig, (err) => { + console.info('videoRecorder.prepare success.') + mVideoRecorder.getInputSurface((err, id) => { + console.info('getInputSurface called') + mVideoSurface = id + console.info('getInputSurface surfaceId: ' + JSON.stringify(mVideoSurface)) + }) + }) + }) } - console.log('Callback returned with the successful execution of setZoomRatio.'); -}) ``` #### 会话管理 ##### 创建会话 -```js +```typescript // 创建Context对象 let context = featureAbility.getContext() //创建会话 -let captureSession -await camera.createCaptureSession((context), (err, session) => { - if (err) { - console.error('Failed to create the CaptureSession instance. ${err.message}'); - return; - } - console.log('Callback returned with the CaptureSession instance.' + session); - captureSession = session -}); +let captureSession = await camera.createCaptureSession() +if (!captureSession) { + console.error('Failed to create the CaptureSession instance.'); + return; +} +console.log('Callback returned with the CaptureSession instance.' + session); // 开始配置会话 -await captureSession.beginConfig((err) => { - if (err) { - console.error('Failed to start the configuration. ${err.message}'); - return; - } - console.log('Callback invoked to indicate the begin config success.'); -}); +await captureSession.beginConfig() // 向会话中添加相机输入流 -await captureSession.addInput(cameraInput, (err) => { - if (err) { - console.error('Failed to add the CameraInput instance. ${err.message}'); - return; - } - console.log('Callback invoked to indicate that the CameraInput instance is added.'); -}); +await captureSession.addInput(cameraInput) // 向会话中添加预览输入流 -await captureSession.addOutput(previewOutput, (err) => { - if (err) { - console.error('Failed to add the PreviewOutput instance ${err.message}'); - return; - } - console.log('Callback invoked to indicate that the PreviewOutput instance is added.'); -}); +await captureSession.addOutput(previewOutput) // 向会话中添加拍照输出流 -await captureSession.addOutput(photoOutput, (err) => { - if (err) { - console.error('Failed to add the PhotoOutput instance ${err.message}'); - return; - } - console.log('Callback invoked to indicate that the PhotoOutput instance is added.'); -}); +await captureSession.addOutput(photoOutput) // 提交会话配置 -await captureSession.commitConfig((err) => { - if (err) { - console.error('Failed to commit the configuration. ${err.message}'); - return; - } - console.log('Callback invoked to indicate the commit config success.'); -}); +await captureSession.commitConfig() // 启动会话 await captureSession.start().then(() => { @@ -291,67 +279,108 @@ await captureSession.start().then(() => { ##### 切换会话 -```js +```typescript // 停止当前会话 -await captureSession.stop((err) => { - if (err) { - console.error('Failed to stop the session ${err.message}'); - return; - } - console.log('Callback invoked to indicate the session stop success.'); -}); +await captureSession.stop() // 开始配置会话 -await captureSession.beginConfig((err) => { - if (err) { - console.error('Failed to start the configuration. ${err.message}'); - return; - } - console.log('Callback invoked to indicate the begin config success.'); -}); +await captureSession.beginConfig() // 从会话中移除拍照输出流 -await captureSession.removeOutput(photoOutput, (err) => { - if (err) { - console.error('Failed to remove the PhotoOutput instance. ${err.message}'); - return; - } - console.log('Callback invoked to indicate that the PhotoOutput instance is removed.'); -}); +await captureSession.removeOutput(photoOutput) // 向会话中添加录像输出流 -await captureSession.addOutput(videoOutput, (err) => { +await captureSession.addOutput(videoOutput) + +// 提交会话配置 +await captureSession.commitConfig() + +// 启动会话 +await captureSession.start().then(() => { + console.log('Promise returned to indicate the session start success.'); +}) +``` + +#### 参数设置 + +```typescript +// 判断设备是否支持闪光灯 +let flashStatus = await captureSession.hasFlash() +if (!flashStatus) { + console.error('Failed to check whether the device has the flash mode.'); +} +console.log('Promise returned with the flash light support status:' + flashStatus); + +if (flashStatus) { + // 判断是否支持自动闪光灯模式 + let flashModeStatus + captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO, async (err, status) => { + if (err) { + console.error('Failed to check whether the flash mode is supported. ${err.message}'); + return; + } + console.log('Callback returned with the flash mode support status: ' + status); + flashModeStatus = status + }) + if(flashModeStatus) { + // 设置自动闪光灯模式 + captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO, async (err) => { + if (err) { + console.error('Failed to set the flash mode ${err.message}'); + return; + } + console.log('Callback returned with the successful execution of setFlashMode.'); + }) + } +} + +// 判断是否支持连续自动变焦模式 +let focusModeStatus +captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO, async (err, status) => { if (err) { - console.error('Failed to add the VideoOutput instance ${err.message}'); + console.error('Failed to check whether the focus mode is supported. ${err.message}'); return; } - console.log('Callback invoked to indicate that the VideoOutput instance is added.'); -}); + console.log('Callback returned with the focus mode support status: ' + status); + focusModeStatus = status +}) +if (focusModeStatus) { + // 设置连续自动变焦模式 + captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO, async (err) => { + if (err) { + console.error('Failed to set the focus mode ${err.message}'); + return; + } + console.log('Callback returned with the successful execution of setFocusMode.'); + }) +} -// 提交会话配置 -await captureSession.commitConfig((err) => { +// 获取相机支持的可变焦距比范围 +let zoomRatioRange = await captureSession.getZoomRatioRange() +if (!zoomRatioRange) { + console.error('Failed to get the zoom ratio range.'); + return; +} + +// 设置可变焦距比 +captureSession.setZoomRatio(zoomRatioRange[0], async (err) => { if (err) { - console.error('Failed to commit the configuration. ${err.message}'); + console.error('Failed to set the zoom ratio value ${err.message}'); return; } - console.log('Callback invoked to indicate the commit config success.'); -}); - -// 启动会话 -await captureSession.start().then(() => { - console.log('Promise returned to indicate the session start success.'); + console.log('Callback returned with the successful execution of setZoomRatio.'); }) ``` #### 拍照 -```js +```typescript let settings = { quality: camera.QualityLevel.QUALITY_LEVEL_HIGH, // 设置图片质量高 rotation: camera.ImageRotation.ROTATION_0 // 设置图片旋转角度0 } // 使用当前拍照设置进行拍照 -photoOutput.capture(settings, (err) => { +photoOutput.capture(settings, async (err) => { if (err) { console.error('Failed to capture the photo ${err.message}'); return; @@ -362,9 +391,9 @@ photoOutput.capture(settings, (err) => { #### 录像 -```js +```typescript // 启动录像输出流 -videoOutput.start((err) => { +videoOutput.start(async (err) => { if (err) { console.error('Failed to start the video output ${err.message}'); return; @@ -392,81 +421,34 @@ await videoOutput.stop((err) => { }); ``` +拍照保存接口可参考:[图片处理API文档](image.md#imagereceiver的使用) + #### 释放资源 -```js +```typescript // 停止当前会话 -await captureSession.stop((err) => { - if (err) { - console.error('Failed to stop the session ${err.message}'); - return; - } - console.log('Callback invoked to indicate the session stop success.'); -}); +await captureSession.stop() + // 释放相机输入流 -await cameraInput.release((err) => { - if (err) { - console.error('Failed to release the CameraInput instance ${err.message}'); - return; - } - console.log('Callback invoked to indicate that the CameraInput instance is released successfully.'); -}); +await cameraInput.release() + // 释放预览输出流 -await previewOutput.release((err) => { - if (err) { - console.error('Failed to release the PreviewOutput instance ${err.message}'); - return; - } - console.log('Callback invoked to indicate that the PreviewOutput instance is released successfully.'); -}); +await previewOutput.release() + // 释放拍照输出流 -await photoOutput.release((err) => { - if (err) { - console.error('Failed to release the PhotoOutput instance ${err.message}'); - return; - } - console.log('Callback invoked to indicate that the PhotoOutput instance is released successfully.'); -}); +await photoOutput.release() + // 释放录像输出流 -await videoOutput.release((err) => { - if (err) { - console.error('Failed to release the VideoOutput instance ${err.message}'); - return; - } - console.log('Callback invoked to indicate that the VideoOutput instance is released successfully.'); -}); +await videoOutput.release() + // 释放会话 -await captureSession.release((err) => { - if (err) { - console.error('Failed to release the CaptureSession instance ${err.message}'); - return; - } - console.log('Callback invoked to indicate that the CaptureSession instance is released successfully.'); -}); -``` +await captureSession.release() -#### XComponent创建方法 -预览画面显示需要获取SurfaceId +// 会话置空 +captureSession = null +``` -```js -mXComponentController: XComponentController = new XComponentController // 创建XComponentController +## 流程图 -build() { - Flex() { - XComponent({ // 创建XComponent - id: '', - type: 'surface', - libraryname: '', - controller: this.mXComponentController - }) - .onload(() => { // 设置onload回调 - // 设置Surface宽高(1920*1080) - this.mXComponentController.setXComponentSurfaceSize({surfaceWidth:1920,surfaceHeight:1080}) - // 获取Surface ID - globalThis.surfaceId = mXComponentController.getXComponentSurfaceId() - }) - .width('1920px') // 设置XComponent宽度 - .height('1080px') // 设置XComponent高度 - } -} -``` \ No newline at end of file +应用使用相机的流程示意图如下 +![camera_framework process](figures/camera_framework_process.jpg) \ No newline at end of file diff --git a/zh-cn/application-dev/media/figures/camera_framework_process.jpg b/zh-cn/application-dev/media/figures/camera_framework_process.jpg new file mode 100644 index 0000000000000000000000000000000000000000..91f88cc6d5b0372031236be55f5785f49b33e2b0 Binary files /dev/null and b/zh-cn/application-dev/media/figures/camera_framework_process.jpg differ diff --git a/zh-cn/application-dev/napi/native-window-guidelines.md b/zh-cn/application-dev/napi/native-window-guidelines.md index 3a9d8c136d7005f3df5d4c0c6749e749d3877b2d..f62485e260ed60cd2658245e55a688da973f49e5 100644 --- a/zh-cn/application-dev/napi/native-window-guidelines.md +++ b/zh-cn/application-dev/napi/native-window-guidelines.md @@ -2,112 +2,105 @@ ## 场景介绍 -NativeWindow是`OpenHarmony`**本地平台化窗口**,包括从`Surface`构建`NativeWindow`,从`SurfaceBuffer`构建出`NativeWindowBuffer`的能力,开发者可以通过`NativeWindow`接口进行申请和提交`Buffer`。 +NativeWindow是`OpenHarmony`**本地平台化窗口**,表示图形队列的生产者端。接口能力包括从`Surface`构建`NativeWindow`的能力,从`SurfaceBuffer`构建出`NativeWindowBuffer`的能力,开发者可以通过`NativeWindow`接口进行申请和提交`Buffer`。 针对NativeWindow,常见的开发场景如下: -* 通过`Native C++`代码绘制内容并显示在屏幕上 -* 在适配EGL层的`eglswapbuffer`接口时,进行提交和申请`Buffer` +* 通过`NativeWindow`提供的`NAPI`接口申请图形`Buffer`,并将生产图形内容写入图形`Buffer`,最终提交`Buffer`到图形队列 +* 在适配EGL层的`eglswapbuffer`接口时,进行申请和提交`Buffer` ## 接口说明 | 接口名 | 描述 | | -------- | -------- | | OH_NativeWindow_CreateNativeWindowFromSurface (void \*pSurface) | 创建NativeWindow实例,每次调用都会产生一个新的NativeWindow实例。 | -| OH_NativeWindow_DestroyNativeWindow (struct NativeWindow \*window) | 将NativeWindow对象的引用计数减1,当引用计数为0的时候,该NativeWindow对象会被析构掉。 | +| OH_NativeWindow_DestroyNativeWindow (OHNativeWindow \*window) | 将NativeWindow对象的引用计数减1,当引用计数为0的时候,该NativeWindow对象会被析构掉。 | | OH_NativeWindow_CreateNativeWindowBufferFromSurfaceBuffer (void \*pSurfaceBuffer) | 创建NativeWindowBuffer实例,每次调用都会产生一个新的NativeWindowBuffer实例。 | -| OH_NativeWindow_DestroyNativeWindowBuffer (struct NativeWindowBuffer \*buffer) | 将NativeWindowBuffer对象的引用计数减1,当引用计数为0的时候,该NativeWindowBuffer对象会被析构掉。 | -| OH_NativeWindow_NativeWindowRequestBuffer (struct NativeWindow \*window struct NativeWindowBuffer \*\*buffer, int \*fenceFd) | 通过NativeWindow对象申请一块NativeWindowBuffer,用以内容生产。 | -| OH_NativeWindow_NativeWindowFlushBuffer (struct NativeWindow \*window, struct NativeWindowBuffer \*buffer, int fenceFd, Region region) | 通过NativeWindow将生产好内容的NativeWindowBuffer放回到Buffer队列中,用以内容消费。 | -| OH_NativeWindow_NativeWindowCancelBuffer (struct NativeWindow \*window, struct NativeWindowBuffer \*buffer) | 通过NativeWindow将之前申请出来的NativeWindowBuffer返还到Buffer队列中,供下次再申请。 | -| OH_NativeWindow_NativeWindowHandleOpt (struct NativeWindow \*window, int code,...) | 设置/获取NativeWindow的属性,包括设置/获取宽高、内容格式等。 | -| OH_NativeWindow_GetBufferHandleFromNative (struct NativeWindowBuffer \*buffer) | 通过NativeWindowBuffer获取该buffer的BufferHandle指针。 | +| OH_NativeWindow_DestroyNativeWindowBuffer (OHNativeWindowBuffer \*buffer) | 将NativeWindowBuffer对象的引用计数减1,当引用计数为0的时候,该NativeWindowBuffer对象会被析构掉。 | +| OH_NativeWindow_NativeWindowRequestBuffer (OHNativeWindow \*window, OHNativeWindowBuffer \*\*buffer, int \*fenceFd) | 通过NativeWindow对象申请一块NativeWindowBuffer,用以内容生产。 | +| OH_NativeWindow_NativeWindowFlushBuffer (OHNativeWindow \*window, OHNativeWindowBuffer \*buffer, int fenceFd, Region region) | 通过NativeWindow将生产好内容的NativeWindowBuffer放回到Buffer队列中,用以内容消费。 | +| OH_NativeWindow_NativeWindowAbortBuffer (OHNativeWindow \*window, OHNativeWindowBuffer \*buffer) | 通过NativeWindow将之前申请出来的NativeWindowBuffer返还到Buffer队列中,供下次再申请。 | +| OH_NativeWindow_NativeWindowHandleOpt (OHNativeWindow \*window, int code,...) | 设置/获取NativeWindow的属性,包括设置/获取宽高、内容格式等。 | +| OH_NativeWindow_GetBufferHandleFromNative (OHNativeWindowBuffer \*buffer) | 通过NativeWindowBuffer获取该buffer的BufferHandle指针。 | | OH_NativeWindow_NativeObjectReference (void \*obj) | 增加一个NativeObject的引用计数。 | | OH_NativeWindow_NativeObjectUnreference (void \*obj) | 减少一个NativeObject的引用计数,当引用计数减少为0时,该NativeObject将被析构掉。 | | OH_NativeWindow_GetNativeObjectMagic (void \*obj) | 获取NativeObject的MagicId。 | +| OH_NativeWindow_NativeWindowSetScalingMode (OHNativeWindow \*window, uint32_t sequence, OHScalingMode scalingMode) | 设置NativeWindow的缩放模式。 | +| OH_NativeWindow_NativeWindowSetMetaData(OHNativeWindow \*window, uint32_t sequence, int32_t size, const OHHDRMetaData \*metaData) | 设置NativeWindow的HDR静态元数据。 | +| OH_NativeWindow_NativeWindowSetMetaDataSet(OHNativeWindow \*window, uint32_t sequence, OHHDRMetadataKey key, int32_t size, const uint8_t \*metaData) | 设置NativeWindow的HDR静态元数据集。 | +| OH_NativeWindow_NativeWindowSetTunnelHandle(OHNativeWindow \*window, const OHExtDataHandle \*handle) | 设置NativeWindow的TunnelHandle。 | 详细的接口说明请参考[native_window](../reference/native-apis/_native_window.md)。 ## 开发步骤 -以下步骤描述了在**OpenHarmony**中如何利用`OH_NativeXComponent`通过`Native C++`代码绘制内容并显示在屏幕上。 +以下步骤描述了在**OpenHarmony**中如何使用`NativeWindow`提供的`NAPI`接口,申请图形`Buffer`,并将生产图形内容写入图形`Buffer`后,最终提交`Buffer`到图形队列。 -1. **在页面中定义XComponent组件**,在`index.ets`中定义一个`texture`类型的`XComponent`,用于显示内容。 - ```js - XComponent({ id: 'xcomponentId', type: 'texture', libraryname: 'nativerender'}) - .borderColor(Color.Red) - .borderWidth(5) - .onLoad(() => {}) - .onDestroy(() => {}) - ``` - -2. **获取OH_NativeXComponent实例**。使用 `napi_get_named_property` 接口获取一个`OH_NativeXComponent`实例 `nativeXComponent`,通过注册该实例的回调接口获取`NativeWindow`实例。 +1. **获取NativeWindow实例**。例如,使用`Surface`创建`NativeWindow`实例。 + ```c++ + sptr cSurface = Surface::CreateSurfaceAsConsumer(); + sptr listener = new BufferConsumerListenerTest(); + cSurface->RegisterConsumerListener(listener); + sptr producer = cSurface->GetProducer(); + sptr pSurface = Surface::CreateSurfaceAsProducer(producer); + OHNativeWindow* nativeWindow = OH_NativeWindow_CreateNativeWindow(&pSurface); + ``` +2. **设置NativeWindowBuffer的属性**。使用`OH_NativeWindow_NativeWindowHandleOpt`设置`NativeWindowBuffer`的属性。 ```c++ - // 定义 napi instance - napi_value exportInstance = nullptr; - // 定义一个 OH_NativeXComponent 实例 - OH_NativeXComponent *nativeXComponent = nullptr; - // 通过 OH_NATIVE_XCOMPONENT_OBJ export 实例 - napi_getname_property(env, exports, OH_NATIVE_XCOMPONENT_OBJ, &exportInstance); - // 将 napi instance 转化为 OH_NativeXComponent 实例 - napi_unwarp(env, exportInstance, reinterpret_cast(&nativeXComponent)); + // 设置 NativeWindowBuffer 的读写场景 + 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); + // 设置 NativeWindowBuffer 的宽高 + code = SET_BUFFER_GEOMETRY; + int32_t width = 0x100; + int32_t height = 0x100; + ret = OH_NativeWindow_NativeWindowHandleOpt(nativeWindow, code, width, height); + // 设置 NativeWindowBuffer 的步长 + code = SET_STRIDE; + int32_t stride = 0x8; + ret = OH_NativeWindow_NativeWindowHandleOpt(nativeWindow, code, stride); + // 设置 NativeWindowBuffer 的格式 + code = SET_FORMAT; + int32_t format = PIXEL_FMT_RGBA_8888; + ret = OH_NativeWindow_NativeWindowHandleOpt(nativeWindow, code, format); ``` -3. **定义回调函数OnSurfaceCreated**。用于在`Surface`创建时,通过回调函数初始化开发者的渲染环境,例如`Skia`渲染环境。并将要显示的内容写入`NativeWindow`: +3. **从图形队列申请NativeWindowBuffer**。 + ```c++ + struct NativeWindowBuffer* buffer = nullptr; + int fenceFd; + // 通过 OH_NativeWindow_NativeWindowRequestBuffer 获取 NativeWindowBuffer 实例 + OH_NativeWindow_NativeWindowRequestBuffer(nativeWindow_, &buffer, &fenceFd); + // 通过 OH_NativeWindow_GetNativeBufferHandleFromNative 获取 buffer 的 handle + BufferHandle* bufferHandle = OH_NativeWindow_GetNativeBufferHandleFromNative(buffer); + ``` +4. **将生产的内容写入NativeWindowBuffer**。 ```c++ - void OnSurfaceCreatedCB(NativeXComponent* component, void* window) { - //获取 native window 的宽高 - uint64_t width_ = 0, height_ = 0; - OH_NativeXComponent_GetXComponentSize(nativeXComponent, window, &width_, &height_); - // 将void* 转换为 NativeWindow 实例,NativeWindow 定义在 native_window/external_window.h 中 - NativeWindow* nativeWindow_ = (NativeWindow*)(window); - - // 通过 OH_NativeWindow_NativeWindowHandleOpt 设置或者获取NativeWindow的属性 - // 1.通过 SET_USAGE 设置 Native Window 的 usage 属性, 例如:HBM_USE_CPU_READ - OH_NativeWindow_NativeWindowHandleOpt(nativeWindow_, SET_USAGE, HBM_USE_CPU_READ | HBM_USE_CPU_WRITE |HBM_USE_MEM_DMA); - // 2.通过 SET_BUFFER_GEOMETRY 设置 Native Window 的 宽高属性 - OH_NativeWindow_NativeWindowHandleOpt(nativeWindow_, SET_BUFFER_GEOMETRY, width_, height_); - // 3.通过 SET_FORMAT 设置 Native Window 的 format 属性, 例如:PIXEL_FMT_RGBA_8888 - OH_NativeWindow_NativeWindowHandleOpt(nativeWindow_, SET_FORMAT, PIXEL_FMT_RGBA_8888); - // 4.通过 SET_STRIDE 设置 Native Window 的 stride 属性 - OH_NativeWindow_NativeWindowHandleOpt(nativeWindow_, SET_STRIDE, 0x8); - - // 通过 OH_NativeWindow_NativeWindowRequestBuffer 获取 NativeWindowBuffer 实例 - struct NativeWindowBuffer* buffer = nullptr; - int fenceFd; - OH_NativeWindow_NativeWindowRequestBuffer(nativeWindow_, &buffer, &fenceFd); - - // 通过 OH_NativeWindow_GetNativeBufferHandleFromNative 获取 buffer handle - BufferHandle* bufferHandle = OH_NativeWindow_GetNativeBufferHandleFromNative(buffer); - - // 通过 BufferHandle 创建Skia Bitmap - SkBitmap bitmap; - SkImageInfo imageInfo = ... - bitmap.setInfo(imageInfo, bufferHandle->stride); - bitmap.setPixels(bufferHandle->virAddr); - //创建 Skia Canvas 并将内容写入native window - ... - - //写入完成后,通过OH_NativeWindow_NativeWindowFlushBuffer 提交给消费者使用,例如:显示在屏幕上 - Region region{nullptr, 0}; - OH_NativeWindow_NativeWindowFlushBuffer(nativeWindow_, buffer, fenceFd, region) + auto image = static_cast(buffer->sfbuffer->GetVirAddr()); + static uint32_t value = 0x00; + value++; + + uint32_t *pixel = static_cast(image); + for (uint32_t x = 0; x < width; x++) { + for (uint32_t y = 0; y < height; y++) { + *pixel++ = value; + } } ``` -4. **注册回调函数OnSurfaceCreated等**。使用 `OH_NativeXComponent_RegisterCallback` 接口注册上一步中创建的回调函数。 +5. **提交NativeWindowBuffer到图形队列**。 ```c++ - OH_NativeXComponent_Callback &callback_; - callback_->OnSurfaceCreated = OnSurfaceCreatedCB; - callback_->OnSurfaceChanged = OnSurfaceChangedCB; - callback_->OnSurfaceDestroyed = OnSurfaceDestroyedCB; - callback_->DispatchTouchEvent = DispatchTouchEventCB; - OH_NativeXComponent_RegisterCallback(nativeXComponent, callback_) + // 设置刷新区域,如果Region中的Rect为nullptr,或者rectNumber为0,则认为NativeWindowBuffer全部有内容更改。 + Region region{nullptr, 0}; + // 通过OH_NativeWindow_NativeWindowFlushBuffer 提交给消费者使用,例如:显示在屏幕上。 + OH_NativeWindow_NativeWindowFlushBuffer(nativeWindow_, buffer, fenceFd, region); ``` ## 相关实例 针对NativeWindow的使用,有以下相关实例可供参考: -- [使用NativeWindow接口获取Buffer](https://gitee.com/openharmony/graphic_graphic_2d/blob/master/rosen/samples/hello_native_window/hello_native_window.cpp) +- [使用NativeWindow接口获取并提交Buffer](https://gitee.com/openharmony/graphic_graphic_2d/blob/master/rosen/samples/hello_native_window/hello_native_window.cpp) diff --git a/zh-cn/application-dev/quick-start/Readme-CN.md b/zh-cn/application-dev/quick-start/Readme-CN.md index 5e82e49502ed6523d297546178ce5973e585b881..429b62a2cf66d8a20401184d8fa6fc3a56a3f7a9 100755 --- a/zh-cn/application-dev/quick-start/Readme-CN.md +++ b/zh-cn/application-dev/quick-start/Readme-CN.md @@ -1,17 +1,15 @@ # 快速开始 - - 快速入门 - [开发准备](start-overview.md) - [使用ArkTS语言开发(Stage模型)](start-with-ets-stage.md) - [使用ArkTS语言开发(FA模型)](start-with-ets-fa.md) - - [使用JS语言开发(FA模型)](start-with-js-fa.md) - + - [使用JS语言开发(FA模型)](start-with-js-fa.md) - 开发基础知识 - [应用包结构说明(FA模型)](package-structure.md) - [应用包结构说明(Stage模型)](stage-structure.md) - - [SysCap说明](syscap.md) - [HarmonyAppProvision配置文件](app-provision-structure.md) + - [资源分类与访问](resource-categories-and-access.md) - 学习ArkTS语言 - [初识ArkTS语言](arkts-get-started.md) - ArkTS语法(声明式UI) diff --git a/zh-cn/application-dev/quick-start/arkts-basic-ui-description.md b/zh-cn/application-dev/quick-start/arkts-basic-ui-description.md index 9bcdcd80c6716abf591cd38c90e15163c17e4fcc..ebc415b897960099317c5aadf39dcf0150869ac5 100644 --- a/zh-cn/application-dev/quick-start/arkts-basic-ui-description.md +++ b/zh-cn/application-dev/quick-start/arkts-basic-ui-description.md @@ -4,9 +4,9 @@ ArkTS通过装饰器@Component和@Entry装饰struct关键字声明的数据结 ## 基本概念 -- struct:组件可以基于struct实现,不能有继承关系,对于struct的实例化,可以省略new。 +- struct:自定义组件可以基于struct实现,不能有继承关系,对于struct的实例化,可以省略new。 -- 装饰器:装饰器给被装饰的对象赋予某一种能力,其不仅可以装饰类或结构体,还可以装饰类的属性。多个装饰器可以叠加到目标元素,定义在同一行上或者多行上,推荐定义在多行上。 +- 装饰器:装饰器给被装饰的对象赋予某一种能力,其不仅可以装饰类或结构体,还可以装饰类的属性。多个装饰器可以叠加到目标元素上,定义在同一行中或者分开多行,推荐分开多行定义。 ```ts @Entry @@ -15,7 +15,7 @@ ArkTS通过装饰器@Component和@Entry装饰struct关键字声明的数据结 } ``` -- build函数:自定义组件必须定义build函数,并且自定义组件禁止自定义构造函数。build函数满足Builder构造器接口定义,用于定义组件的声明式UI描述。 +- build函数:自定义组件必须定义build函数,并且禁止自定义构造函数。build函数满足Builder构造器接口定义,用于定义组件的声明式UI描述。 ```ts interface Builder { @@ -23,21 +23,21 @@ ArkTS通过装饰器@Component和@Entry装饰struct关键字声明的数据结 } ``` -- @Component:装饰struct,结构体在装饰后具有基于组件的能力,需要实现build方法来更新UI。 +- @Component:装饰struct,结构体在装饰后具有基于组件的能力,需要实现build方法来创建UI。 - @Entry: 装饰struct,组件被装饰后作为页面的入口,页面加载时将被渲染显示。 -- @Preview:装饰struct, 用@Preview装饰的自定义组件可以在DevEco Studio的预览器上进行实时预览,加载页面时,将创建并呈现@Preview装饰的自定义组件。 +- @Preview:装饰struct, 用@Preview装饰的自定义组件可以在DevEco Studio的预览器上进行实时预览,加载页面时,将创建并显示@Preview装饰的自定义组件。 > **说明:** 在单个源文件中,最多可以使用10个@Preview装饰自定义组件,更多说明请参考[查看ArkTS组件预览效果](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-previewing-app-service-0000001218760596#section146052489820)。 -- 链式调用:以 "." 链式调用的方式配置UI结构及其属性、事件等。 +- 链式调用:以 "." 链式调用的方式配置UI组件的属性方法、事件方法等。 ## UI描述规范 ### 无参数构造配置 -组件的接口定义不包含必选构造参数,组件后面的“()”中不需要配置任何内容。例如,Divider组件不包含构造参数: +如果组件的接口定义中不包含必选构造参数,组件后面的“()”中不需要配置任何内容。例如,Divider组件不包含构造参数: ```ts Column() { @@ -49,27 +49,27 @@ Column() { ### 必选参数构造配置 -如果组件的接口定义中包含必选构造参数,则在组件后面的“()”中必须配置参数,参数可以使用常量进行赋值。 +如果组件的接口定义中包含必选构造参数,则在组件后面的“()”中必须配置相应参数,参数可以使用常量进行赋值。 例如: - Image组件的必选参数src: ```ts - Image('http://xyz/a.jpg') + Image('https://xyz/test.jpg') ``` - Text组件的必选参数content: ```ts - Text('123') + Text('test') ``` -变量或表达式也可以用于参数赋值,其中表达式返回的结果类型必须满足参数类型要求。例如,传递变量或表达式来构造Image和Text组件的参数: +变量或表达式也可以用于参数赋值,其中表达式返回的结果类型必须满足参数类型要求,变量的定义详见[页面级变量的状态管理](arkts-state-mgmt-page-level.md)与[应用级变量的状态管理](arkts-state-mgmt-application-level.md)。例如,设置变量或表达式来构造Image和Text组件的参数: ```ts Image(this.imagePath) -Image('http://' + this.imageUrl) +Image('https://' + this.imageUrl) Text(`count: ${this.count}`) ``` @@ -80,14 +80,14 @@ Text(`count: ${this.count}`) - 配置Text组件的字体大小属性: ```ts - Text('123') + Text('test') .fontSize(12) ``` -- 使用"."操作进行链式调用并同时配置组件的多个属性,如下所示: +- 使用"."运算符进行链式调用并同时配置组件的多个属性,如下所示: ```ts - Image('a.jpg') + Image('test.jpg') .alt('error.jpg') .width(100) .height(100) @@ -98,12 +98,12 @@ Text(`count: ${this.count}`) ```ts Text('hello') .fontSize(this.size) - Image('a.jpg') + Image('test.jpg') .width(this.count % 2 === 0 ? 100 : 200) .height(this.offset + 100) ``` -- 对于系统内置组件,框架还为其属性预定义了一些[枚举类型](../reference/arkui-ts/ts-appendix-enums.md)供开发人员调用,枚举类型必须满足参数类型要求,枚举值可以作为参数传递。可以按以下方式配置Text组件的颜色和字体属性: +- 对于系统内置组件,框架还为其属性预定义了一些[枚举类型](../reference/arkui-ts/ts-appendix-enums.md)供开发人员调用,枚举类型可以作为参数传递,且必须满足参数类型要求。例如,可以按以下方式配置Text组件的颜色和字体属性: ```ts Text('hello') @@ -114,7 +114,7 @@ Text(`count: ${this.count}`) ### 事件配置 -通过事件方法可以配置组件支持的事件。 +通过事件方法可以配置组件支持的事件,事件方法紧随组件,并用"."运算符连接。 - 使用lambda表达式配置组件的事件方法: @@ -138,18 +138,18 @@ Text(`count: ${this.count}`) ```ts myClickHandler(): void { - + this.counter += 2 } ... - + Button('add counter') .onClick(this.myClickHandler) ``` ### 子组件配置 -对于支持子组件配置的组件,例如容器组件,在"{ ... }"里为组件添加子组件的UI描述。Column、Row、Stack、Button、Grid和List组件都是容器组件。 +对于支持子组件配置的组件,例如容器组件,在"{ ... }"里为组件添加子组件的UI描述。Column、Row、Stack、Grid、List等组件都是容器组件。 - 以下是简单的Column示例: @@ -164,32 +164,40 @@ Text(`count: ${this.count}`) } ``` -- 可以嵌套多个子组件: +- 容器组件之间也可以互相嵌套,实现相对复杂的多级嵌套效果: ```ts Column() { - Column() { - Button() { - Text('+ 1') - }.type(ButtonType.Capsule) - .onClick(() => console.log ('+1 clicked!')) - Image('1.jpg') - } - Divider() - Column() { - Button() { - Text('+ 2') - }.type(ButtonType.Capsule) - .onClick(() => console.log ('+2 clicked!')) - Image('2.jpg') - } - Divider() - Column() { - Button() { - Text('+ 3') - }.type(ButtonType.Capsule) - .onClick(() => console.log('+3 clicked!')) - Image('3.jpg') - } - }.alignItems(HorizontalAlign.Center) + Row() { + Image('test1.jpg') + .width(100) + .height(100) + Button('click +1') + .onClick(() => { + console.info('+1 clicked!') + }) + } + + Divider() + Row() { + Image('test2.jpg') + .width(100) + .height(100) + Button('click +2') + .onClick(() => { + console.info('+2 clicked!') + }) + } + + Divider() + Row() { + Image('test3.jpg') + .width(100) + .height(100) + Button('click +3') + .onClick(() => { + console.info('+3 clicked!') + }) + } + } ``` \ No newline at end of file diff --git a/zh-cn/application-dev/quick-start/arkts-dynamic-ui-elememt-building.md b/zh-cn/application-dev/quick-start/arkts-dynamic-ui-elememt-building.md index 83f0be992b6547d997e2723b4fb29f44a65141c3..3de63bc1291d343afe73d9117f0ec0157348c657 100644 --- a/zh-cn/application-dev/quick-start/arkts-dynamic-ui-elememt-building.md +++ b/zh-cn/application-dev/quick-start/arkts-dynamic-ui-elememt-building.md @@ -1,31 +1,29 @@ # 动态构建UI元素 -前面章节介绍的是如何创建一个组件内部UI结构固定的自定义组件,为了满足开发者自定义组件内部UI结构的需求,ArkTS同时提供了动态构建UI元素的能力。 +[基本UI描述](arkts-basic-ui-description.md)介绍的是如何创建一个内部UI结构固定的自定义组件,为了满足开发者自定义组件内部UI结构的需求,ArkTS同时提供了动态构建UI元素的能力。 ## @Builder - -可通过@Builder装饰器进行描述,该装饰器可以修饰一个函数,此函数可以在build函数之外声明,并在build函数中或其他@Builder修饰的函数中使用,在一个自定义组件内快速生成多个布局内容。使用方式如下面示例所示。 - +可通过@Builder装饰器进行描述,该装饰器可以修饰一个函数,此函数可以在build函数之外声明,并在build函数中或其他@Builder修饰的函数中使用,从而实现在一个自定义组件内快速生成多个布局内容。使用方式如下面示例所示。 ```ts // xxx.ets - @Component struct CompB { - @State CompValue: string = ''; + @State CompValue: string = '' aboutToAppear() { - console.info('CompB aboutToAppear.'); + console.info('CompB aboutToAppear.') } aboutToDisappear() { - console.info('CompB aboutToDisappear.'); + console.info('CompB aboutToDisappear.') } build() { Column() { - Button(this.CompValue); + Button(this.CompValue) + .margin(5) } } } @@ -33,22 +31,24 @@ struct CompB { @Entry @Component struct CompA { - size1: number = 100; - @State CompValue1: string = "Hello,CompValue1"; - @State CompValue2: string = "Hello,CompValue2"; - @State CompValue3: string = "Hello,CompValue3"; + size1: number = 100 + @State CompValue1: string = "Hello,CompValue1" + @State CompValue2: string = "Hello,CompValue2" + @State CompValue3: string = "Hello,CompValue3" - // @Builder装饰的函数内使用自定义组件 + // @Builder装饰的函数CompC内使用自定义组件CompB @Builder CompC(value: string) { - CompB({ CompValue: value }); + CompB({ CompValue: value }) } @Builder SquareText(label: string) { Text(label) + .fontSize(18) .width(1 * this.size1) .height(1 * this.size1) } + // @Builder装饰的函数RowOfSquareTexts内使用@Builder装饰的函数SquareText @Builder RowOfSquareTexts(label1: string, label2: string) { Row() { this.SquareText(label1) @@ -63,7 +63,6 @@ struct CompA { Row() { this.SquareText("A") this.SquareText("B") - // or as long as tsc is used } .width(2 * this.size1) .height(1 * this.size1) @@ -71,9 +70,9 @@ struct CompA { this.RowOfSquareTexts("C", "D") Column() { // 使用三次@Builder装饰的自定义组件 - this.CompC(this.CompValue1); - this.CompC(this.CompValue2); - this.CompC(this.CompValue3); + this.CompC(this.CompValue1) + this.CompC(this.CompValue2) + this.CompC(this.CompValue3) } .width(2 * this.size1) .height(2 * this.size1) @@ -83,34 +82,37 @@ struct CompA { } } ``` +![builder](figures/builder.PNG) + ## @BuilderParam8+ -@BuilderParam装饰器用于修饰自定义组件内函数类型的属性(例如:`@BuilderParam content: () => any;`),并且在初始化自定义组件时被@BuilderParam修饰的属性必须赋值。 +@BuilderParam装饰器用于修饰自定义组件内函数类型的属性(例如:`@BuilderParam noParam: () => void`),并且在初始化自定义组件时被@BuilderParam修饰的属性必须赋值。 ### 引入动机 -当开发者创建自定义组件,想对该组件添加特定功能时(如:仅对自定义组件添加一个点击跳转操作)。若直接在组件内嵌入事件方法,将会导致所有初始化该组件的地方均增加了该功能。为解决此问题,引入了@BuilderParam装饰器,此装饰器修饰的属性值可为@Builder修饰的方法,开发者可在初始化自定义组件时对此属性进行赋值,为自定义组件增加特定的的功能。 +当开发者创建自定义组件,并想对该组件添加特定功能时(例如在自定义组件中添加一个点击跳转操作)。若直接在组件内嵌入事件方法,将会导致所有引入该自定义组件的地方均增加了该功能。为解决此问题,引入了@BuilderParam装饰器,此装饰器修饰的属性值可为@Builder装饰的函数,开发者可在初始化自定义组件时对此属性进行赋值,为自定义组件增加特定的功能。 ### 参数初始化组件 -通过参数初始化组件时,将@Builder装饰的方法赋值给@BuilderParam修饰的属性,并在自定义组件内调用content属性值。对@BuilderParam修饰的属性进行赋值时不带参数(如:`content: this.specificParam`),则此属性的类型需定义成无返回值的函数(如:`@BuilderParam content: () => void`)。若带参数(如:`callContent: this.specificParam1("111")`),则此属性的类型需定义成any(如:`@BuilderParam callContent: any;`)。 +通过参数初始化组件时,将@Builder装饰的函数赋值给@BuilderParam修饰的属性,并在自定义组件内调用该属性值。若@BuilderParam修饰的属性在进行赋值时不带参数(如:`noParam: this.specificNoParam`),则此属性的类型需定义为无返回值的函数(如:`@BuilderParam noParam: () => void`);若带参数(如:`withParam: this.SpecificWithParam('WithParamA')`),则此属性的类型需定义成any(如:`@BuilderParam withParam: any`)。 ```ts // xxx.ets @Component struct CustomContainer { - header: string = ""; - @BuilderParam noParam: () => void; - @BuilderParam withParam: any; - footer: string = ""; + header: string = '' + @BuilderParam noParam: () => void + @BuilderParam withParam: any + footer: string = '' + build() { Column() { Text(this.header) - .fontSize(50) + .fontSize(30) this.noParam() this.withParam() Text(this.footer) - .fontSize(50) + .fontSize(30) } } } @@ -120,69 +122,86 @@ struct CustomContainer { struct CustomContainerUser { @Builder specificNoParam() { Column() { - Text("noParam").fontSize(50) + Text('noParam').fontSize(30) } } + @Builder SpecificWithParam(label: string) { Column() { - Text(label).fontSize(50) + Text(label).fontSize(30) } } build() { Column() { CustomContainer({ - header: "Header", + header: 'HeaderA', + noParam: this.specificNoParam, + withParam: this.SpecificWithParam('WithParamA'), + footer: 'FooterA' + }) + Divider() + .strokeWidth(3) + .margin(10) + CustomContainer({ + header: 'HeaderB', noParam: this.specificNoParam, - withParam: this.SpecificWithParam("WithParam"), - footer: "Footer", + withParam: this.SpecificWithParam('WithParamB'), + footer: 'FooterB' }) } } } ``` +![builder1](figures/builder1.PNG) + ### 尾随闭包初始化组件 -在自定义组件中使用@BuilderParam修饰的属性接收尾随闭包(在初始化自定义组件时,组件名称紧跟一个大括号“{}”形成尾随闭包场景(`CustomComponent(){}`)。开发者可把尾随闭包看做一个容器,向其填充内容,如在闭包内增加组件(`{Column(){Text("content")}`),闭包内语法规范与build函数一致。此场景下自定义组件内有且仅有一个使用@BuilderParam修饰的属性。 +在自定义组件中使用@BuilderParam修饰的属性时也可通过尾随闭包进行初始化(在初始化自定义组件时,组件后紧跟一个大括号“{}”形成尾随闭包场景(`CustomContainer(){}`)。开发者可把尾随闭包看做一个容器,向其中填充内容,如在闭包内增加组件(`{Column(){...}`),闭包内语法规范与build函数一致。此场景下自定义组件内有且仅有一个使用@BuilderParam修饰的属性。 -示例:在闭包内增加Column组件并添加点击事件,在新增的Column组件内调用@Builder修饰的specificParam方法,点击Column组件后该改变自定义组件中header的属性值为“changeHeader”。并且在初始化自定义组件时会把尾随闭包的内容赋值给使用@BuilderParam修饰的closer属性。 +示例:在闭包内添加Column组件并设置点击事件,在Column组件内调用@Builder修饰的specificParam函数,点击Column组件后将自定义组件CustomContainer中header的属性值由“header”改变为“changeHeader”。在初始化自定义组件CustomContainer时,尾随闭包的内容会被赋值给@BuilderParam修饰的closer属性。 ```ts // xxx.ets @Component struct CustomContainer { - header: string = ""; - @BuilderParam closer: () => void; + header: string = '' + @BuilderParam closer: () => void + build() { Column() { Text(this.header) - .fontSize(50) + .fontSize(30) this.closer() } } } + @Builder function specificParam(label1: string, label2: string) { Column() { Text(label1) - .fontSize(50) + .fontSize(30) Text(label2) - .fontSize(50) + .fontSize(30) } } + @Entry @Component struct CustomContainerUser { - @State text: string = "header" + @State text: string = 'header' + build() { Column() { CustomContainer({ header: this.text, - }){ - Column(){ - specificParam("111", "22") - }.onClick(()=>{ - this.text = "changeHeader" + }) { + Column() { + specificParam('testA', 'testB') + }.backgroundColor(Color.Yellow) + .onClick(() => { + this.text = 'changeHeader' }) } } @@ -190,87 +209,103 @@ struct CustomContainerUser { } ``` +![builder2](figures/builder2.gif) + ## @Styles -ArkTS为了避免开发者对重复样式的设置,通过@Styles装饰器可以将多条样式设置提炼成一个方法,直接在组件声明的位置使用。@Styles装饰器将新的属性函数添加到基本组件上,如Text、Column、Button等。当前@Styles仅支持通用属性。通过@Styles装饰器可以快速定义并复用组件的自定义样式。 +ArkTS为了避免开发者对重复样式的设置,通过@Styles装饰器可以将多个样式设置提炼成一个方法,直接在组件声明时调用,通过@Styles装饰器可以快速定义并复用自定义样式。当前@Styles仅支持通用属性。 -@Styles可以定义在组件内或组件外,在组件外定义时需在方法前添加function关键字,组件内定义时不需要添加function关键字。 +@Styles可以定义在组件内或组件外,在组件外定义时需在方法名前面添加function关键字,组件内定义时则不需要添加function关键字。 ```ts // xxx.ets -@Styles function globalFancy() { - .backgroundColor(Color.Red) +@Styles function globalFancy () { + .width(150) + .height(100) + .backgroundColor(Color.Pink) } @Entry @Component struct FancyUse { @Styles componentFancy() { - .backgroundColor(Color.Blue) + .width(100) + .height(200) + .backgroundColor(Color.Yellow) } + build() { Column({ space: 10 }) { - Text("Fancy") + Text('FancyA') .globalFancy() - .width(100) - .height(100) .fontSize(30) - Text("Fancy") + Text('FancyB') + .globalFancy() + .fontSize(20) + Text('FancyC') .componentFancy() - .width(100) - .height(100) .fontSize(30) + Text('FancyD') + .componentFancy() + .fontSize(20) } } } ``` +![styles](figures/styles.PNG) + @Styles还可以在[StateStyles](../reference/arkui-ts/ts-universal-attributes-polymorphic-style.md)属性内部使用,在组件处于不同的状态时赋予相应的属性。 -在StateStyles内可以直接调用组件外定义的Styles,但需要通过this关键字调用组件内定义的Styles。 +在StateStyles内可以直接调用组件外定义的@Styles方法,但需要通过this关键字调用组件内定义的@Styles方法。 ```ts // xxx.ets -@Styles function globalFancy() { - .width(100) - .height(100) +@Styles function globalFancy () { + .width(120) + .height(120) + .backgroundColor(Color.Green) } @Entry @Component struct FancyUse { @Styles componentFancy() { - .width(50) - .height(50) + .width(80) + .height(80) + .backgroundColor(Color.Red) } + build() { Row({ space: 10 }) { - Button() { - Text("Fancy") - } - .stateStyles({ - normal: { - .width(80) - .height(80) - }, - disabled: this.componentFancy, - pressed: globalFancy - }) + Button('Fancy') + .stateStyles({ + normal: { + .width(100) + .height(100) + .backgroundColor(Color.Blue) + }, + disabled: this.componentFancy, + pressed: globalFancy + }) } } } ``` +![styles1](figures/styles1.gif) + ## @Extend -@Extend装饰器将新的属性函数添加到内置组件上,如Text、Column、Button等。通过@Extend装饰器可以快速的扩展原生组件。@Extend装饰器不能用在自定义组件struct定义框内。 +@Extend装饰器将新的属性方法添加到Text、Column、Button等内置组件上,通过@Extend装饰器可以快速地扩展原生组件。@Extend不能定义在自定义组件struct内。 ```ts // xxx.ets -@Extend(Text) function fancy(fontSize: number) { +@Extend(Text) function fancy (fontSize: number) { .fontColor(Color.Red) .fontSize(fontSize) .fontStyle(FontStyle.Italic) + .fontWeight(600) } @Entry @@ -282,63 +317,69 @@ struct FancyUse { .fancy(16) Text("Fancy") .fancy(24) + Text("Fancy") + .fancy(32) } } } + ``` > **说明:** > -> - @Extend装饰器不能用在自定义组件struct定义框内。 -> - @Extend装饰器内仅支持属性函数语句。 +> - @Extend装饰器不能定义在自定义组件struct内。 +> - @Extend装饰器内仅支持属性方法设置。 + +![extend](figures/extend.PNG) ## @CustomDialog -@CustomDialog装饰器用于装饰自定义弹窗,使得弹窗可以动态设置样式。 +@CustomDialog装饰器用于装饰自定义弹窗组件,使得弹窗可以动态设置内容及样式。 ```ts -// custom-dialog-demo.ets +// xxx.ets @CustomDialog struct DialogExample { - controller: CustomDialogController; - action: () => void; - - build() { - Row() { - Button ("Close CustomDialog") - .onClick(() => { - this.controller.close(); - this.action(); - }) - }.padding(20) - } + controller: CustomDialogController + action: () => void + + build() { + Row() { + Button('Close CustomDialog') + .onClick(() => { + this.controller.close() + this.action() + }) + }.padding(20) + } } @Entry @Component struct CustomDialogUser { - dialogController : CustomDialogController = new CustomDialogController({ - builder: DialogExample({action: this.onAccept}), - cancel: this.existApp, - autoCancel: true - }); - - onAccept() { - console.log("onAccept"); - } - existApp() { - console.log("Cancel dialog!"); - } + dialogController: CustomDialogController = new CustomDialogController({ + builder: DialogExample({ action: this.onAccept }), + cancel: this.existApp, + autoCancel: true + }); + + onAccept() { + console.info('onAccept'); + } - build() { - Column() { - Button("Click to open Dialog") - .onClick(() => { - this.dialogController.open() - }) - } + existApp() { + console.info('Cancel dialog!'); + } + + build() { + Column() { + Button('Click to open Dialog') + .onClick(() => { + this.dialogController.open() + }) } + } } ``` -![custom-dialog-demo](figures/custom-dialog-demo.gif) \ No newline at end of file +![customdialog](figures/customDialog.gif) \ No newline at end of file diff --git a/zh-cn/application-dev/quick-start/arkts-get-started.md b/zh-cn/application-dev/quick-start/arkts-get-started.md index af17ba43f336ceb42634fe7636de55978fba0939..af97f571b9c0fa336d501b3cd322f65e61fb2cd4 100644 --- a/zh-cn/application-dev/quick-start/arkts-get-started.md +++ b/zh-cn/application-dev/quick-start/arkts-get-started.md @@ -4,27 +4,27 @@ ArkTS是OpenHarmony优选的主力应用开发语言。ArkTS基于TypeScript( - ArkTS继承了TS的所有特性。 -- 当前,ArkTS在TS基础上主要扩展了[声明式UI](arkts-basic-ui-description.md)能力,让开发者以更简洁、更自然的方式开发高性能应用。 +- 当前,ArkTS在TS的基础上主要扩展了[声明式UI](arkts-basic-ui-description.md)能力,让开发者能够以更简洁、更自然的方式开发高性能应用。 - 当前扩展的声明式UI包括如下特性。 + 当前扩展的声明式UI能力包括如下特性。 - - [基本UI描述](arkts-basic-ui-description.md):ArkTS定义了各种装饰器、自定义组件、UI描述机制,再配合UI开发框架中的UI内置组件、事件方法、属性方法等共同构成了UI开发的主体。 - - [状态管理](arkts-state-mgmt-page-level.md):ArkTS提供了多维度的状态管理机制,在UI开发框架中,和UI相关联的数据,不仅可以在组件内使用,还可以在不同组件层级间传递,比如父子组件之间、爷孙组件之间,也可以是全局范围内的传递,还可以是 跨设备传递。另外,从数据的传递形式来看,可分为只读的单向传递和可变更的双向传递。开发者可以灵活的利用这些能力来实现数据和UI的联动。 - - [动态构建UI元素](arkts-dynamic-ui-elememt-building.md):ArkTS提供了动态构建UI元素的能力,不仅可以自定义组件内部的UI结构,还可复用组件样式,扩展原生组件。 - - [渲染控制](arkts-rendering-control.md):ArkTS提供了渲染控制的能力。条件渲染可根据应用的不同状态,渲染对应状态下的部分内容。循环渲染可从数据源中迭代获取数据,并在每次迭代过程中创建相应的组件。 + - [基本UI描述](arkts-basic-ui-description.md):ArkTS定义了各种装饰器、自定义组件、UI描述机制,再配合UI开发框架中的内置组件及其相关的事件方法、属性方法等共同构成了UI开发的主体。 + - [状态管理](arkts-state-mgmt-page-level.md):ArkTS提供了多维度的状态管理机制,在UI开发框架中,和UI相关联的数据,不仅可以在组件内使用,还可以在不同组件层级间传递,比如父子组件之间、爷孙组件之间,也可以是应用全局范围内的传递,还可以是跨设备传递。另外,从数据的传递形式来看,可分为只读的单向传递和可变更的双向传递。开发者可以灵活的利用这些能力来实现数据和UI的联动。 + - [动态构建UI元素](arkts-dynamic-ui-elememt-building.md):ArkTS提供了动态构建UI元素的能力,不仅可以自定义组件内部的UI结构,还可以复用组件样式,扩展原生组件。 + - [渲染控制](arkts-rendering-control.md):ArkTS提供了渲染控制的能力。条件渲染可根据应用的不同状态,渲染对应状态下的UI内容。循环渲染可从数据源中迭代获取数据,并在每次迭代过程中创建相应的组件。 - [使用限制与扩展](arkts-restrictions-and-extensions.md):ArkTS在使用过程中存在限制与约束,同时也扩展了双向绑定等能力。 -- 未来,ArkTS会结合应用开发/运行的需求持续演进,逐步提供并行和并发能力增强、类型系统增强、分布式开发范式等更多特性。 +- 未来,ArkTS会结合应用开发/运行的需求持续演进,逐步提供并行和并发能力增强、系统类型增强、分布式开发范式等更多特性。 -下面我们以一个具体的示例来说明ArkTS的基本组成。如下图所示的代码示例,UI界面会两段文本和一个按钮,当开发者点击按钮时,文本内容会从'Hello World'变为 'Hello ArkUI'。 +下面我们以一个具体的示例来说明ArkTS的基本组成。如下图所示的代码示例,UI界面包含两段文本、一条分割线和一个按钮,当开发者点击按钮时,文本内容会从'Hello World'变为 'Hello ArkUI'。 ![arkts-get-started](figures/arkts-get-started.png) 这个示例中所包含的ArkTS声明式开发范式的基本组成说明如下: -- 装饰器: 用于装饰类、结构、方法以及变量,赋予其特殊的含义,如上述示例中@Entry、@Component和@State都是装饰器。 具体而言,@Component表示这是个自定义组件;@Entry则表示这是个入口组件;@State表示组件中的状态变量,这个状态变换会引起UI变更。 +- 装饰器: 用于装饰类、结构、方法以及变量,赋予其特殊的含义,如上述示例中@Entry、@Component和@State都是装饰器。 具体而言,@Component表示这是个自定义组件;@Entry则表示这是个入口组件;@State表示这是组件中的状态变量,这个变量变化会触发UI刷新。 - 自定义组件:可复用的UI单元,可组合其他组件,如上述被@Component装饰的struct Hello。 - UI描述:声明式的方法来描述UI的结构,例如build()方法中的代码块。 -- 内置组件:ArkTS中默认内置的基本组件和布局组件,开发者可以直接调用,如Column、Text、Divider、Button等。 +- 内置组件:ArkTS中默认内置的基础组件、容器组件、媒体组件、绘制组件、画布组件等各种组件,开发者可以直接调用,如示例中的Column、Text、Divider、Button等。 - 属性方法:用于组件属性的配置,如fontSize()、width()、height()、color()等,可通过链式调用的方式设置多项属性。 -- 事件方法:用于添加组件对事件的响应逻辑,统一通过事件方法进行设置,如跟随在Button后面的onClick()。 +- 事件方法:用于添加组件对事件的响应逻辑,如跟随在Button后面的onClick(),同样可以通过链式调用的方式设置多个事件响应逻辑。 diff --git a/zh-cn/application-dev/quick-start/arkts-rendering-control.md b/zh-cn/application-dev/quick-start/arkts-rendering-control.md index 71210480f08d4059409107f24d786d51e4da663f..08663ab440ede2aa39dcc722da1fdb54217942a3 100644 --- a/zh-cn/application-dev/quick-start/arkts-rendering-control.md +++ b/zh-cn/application-dev/quick-start/arkts-rendering-control.md @@ -1,6 +1,6 @@ # 渲染控制 -ArkTS也提供了渲染控制的能力。条件渲染可根据应用的不同状态,渲染对应状态下的部分内容。循环渲染可从数据源中迭代获取数据,并在每次迭代过程中创建相应的组件。 +ArkTS也提供了渲染控制的能力。条件渲染可根据应用的不同状态,渲染对应状态下的UI内容。循环渲染可从数据源中迭代获取数据,并在每次迭代过程中创建相应的组件。 ## 条件渲染 @@ -9,61 +9,61 @@ ArkTS也提供了渲染控制的能力。条件渲染可根据应用的不同状 > **说明:** > -> - if条件语句可以使用状态变量。 +> - if/else条件语句可以使用状态变量。 > -> - 使用if可以使子组件的渲染依赖条件语句。 +> - 使用if/else可以使子组件的渲染依赖条件语句。 > > - 必须在容器组件内使用。 > -> - 某些容器组件限制子组件的类型或数量。将if放置在这些组件内时,这些限制将应用于if和else语句内创建的组件。例如,Grid组件的子组件仅支持GridItem组件,在Grid组件内使用if时,则if条件语句内仅允许使用GridItem组件。 +> - 某些容器组件限制子组件的类型或数量,将if/else用于这些组件内时,这些限制将同样应用于if/else语句内创建的组件。例如,Grid容器组件的子组件仅支持GridItem组件,在Grid内使用if/else时,则if/else语句内也仅允许使用GridItem组件。 ```ts Column() { - if (this.count < 0) { - Text('count is negative') - } else if (this.count % 2 === 0) { - Divider() - Text('even') - } else { - Divider() - Text('odd') - } + if (this.count < 0) { + Text('count is negative').fontSize(14) + } else if (this.count % 2 === 0) { + Text('count is even').fontSize(14) + } else { + Text('count is odd').fontSize(14) + } } ``` ## 循环渲染 -通过循环渲染(ForEach组件)来迭代数组,并为每个数组项创建相应的组件,可减少代码复杂度。 +通过循环渲染(ForEach)从数组中获取数据,并为每个数据项创建相应的组件,可减少代码复杂度。 ``` - ForEach( - arr: any[], - itemGenerator: (item: any, index?: number) => void, - keyGenerator?: (item: any, index?: number) => string - ) +ForEach( + arr: any[], + itemGenerator: (item: any, index?: number) => void, + keyGenerator?: (item: any, index?: number) => string +) ``` **参数:** | 参数名 | 参数类型 | 必填 | 参数描述 | | ------------- | ------------------------------------- | ---- | ------------------------------------------------------------ | -| arr | any[] | 是 | 必须是数组,允许空数组,空数组场景下不会创建子组件。同时允许设置返回值为数组类型的函数,例如arr.slice(1, 3),设置的函数不得改变包括数组本身在内的任何状态变量,如Array.splice、Array.sort或Array.reverse这些改变原数组的函数。 | -| itemGenerator | (item: any, index?: number) => void | 是 | 生成子组件的lambda函数,为给定数组项生成一个或多个子组件,单个组件和子组件列表必须括在大括号“{....}”中。 | -| keyGenerator | (item: any, index?: number) => string | 否 | 匿名参数,用于给定数组项生成唯一且稳定的键值。当子项在数组中的位置更改时,子项的键值不得更改,当数组中的子项被新项替换时,被替换项的键值和新项的键值必须不同。键值生成器的功能是可选的,但是,为了使开发框架能够更好地识别数组更改,提高性能,建议提供。如将数组反向时,如果没有提供键值生成器,则ForEach中的所有节点都将重建。 | +| arr | any[] | 是 | 必须是数组,允许设置为空数组,空数组场景下将不会创建子组件。同时允许设置返回值为数组类型的函数,例如arr.slice(1, 3),设置的函数不得改变包括数组本身在内的任何状态变量,如Array.splice、Array.sort或Array.reverse这些改变原数组的函数。 | +| itemGenerator | (item: any, index?: number) => void | 是 | 生成子组件的lambda函数,为数组中的每一个数据项创建一个或多个子组件,单个子组件或子组件列表必须包括在大括号“{...}”中。 | +| keyGenerator | (item: any, index?: number) => string | 否 | 匿名函数,用于给数组中的每一个数据项生成唯一且固定的键值。当数据项在数组中的位置更改时,其键值不得更改,当数组中的数据项被新项替换时,被替换项的键值和新项的键值必须不同。键值生成器的功能是可选的,但是,为了使开发框架能够更好地识别数组更改,提高性能,建议提供。如将数组反向时,如果没有提供键值生成器,则ForEach中的所有节点都将重建。 | > **说明:** > -> - ForEach组件必须在容器组件内使用; +> - ForEach必须在容器组件内使用。 > -> - 生成的子组件允许在ForEach的父容器组件中,允许子组件生成器函数中包含if/else条件渲染,同时也允许ForEach包含在if/else条件渲染语句中; +> - 生成的子组件应当是允许包含在ForEach父容器组件中的子组件。 > -> - 子项生成器函数的调用顺序不一定和数组中的数据项相同,在开发过程中不要假设子项生成器和键值生成器函数是否执行以及执行顺序。如下示例可能无法正常工作: +> - 允许子组件生成器函数中包含if/else条件渲染,同时也允许ForEach包含在if/else条件渲染语句中。 > -> ``` +> - itemGenerator函数的调用顺序不一定和数组中的数据项相同,在开发过程中不要假设itemGenerator和keyGenerator函数是否执行及其执行顺序。例如,以下示例可能无法正常工作: +> +> ```ts > ForEach(anArray.map((item1, index1) => { return { i: index1 + 1, data: item1 }; }), -> item => Text(`${item.i}. item.data.label`), -> item => item.data.id.toString()) +> item => Text(`${item.i}. item.data.label`), +> item => item.data.id.toString()) > ``` ## 示例 @@ -76,49 +76,47 @@ struct MyComponent { @State arr: number[] = [10, 20, 30] build() { - Column() { - Button() { - Text('Reverse Array') - }.onClick(() => { - this.arr.reverse() - }) - - ForEach(this.arr, - (item: number) => { - Text(`item value: ${item}`) - Divider() - }, - (item: number) => item.toString() - ) + Column({ space: 5 }) { + Button('Reverse Array') + .onClick(() => { + this.arr.reverse() + }) + + ForEach(this.arr, (item: number) => { + Text(`item value: ${item}`).fontSize(18) + Divider().strokeWidth(2) + }, (item: number) => item.toString()) } } } ``` +![forEach1](figures/forEach1.gif) + ## 数据懒加载 -通过数据懒加载(LazyForEach组件)从提供的数据源中按需迭代数据,并在每次迭代过程中创建相应的组件。 +通过数据懒加载(LazyForEach)从提供的数据源中按需迭代数据,并在每次迭代过程中创建相应的组件。 ```ts LazyForEach( - dataSource: IDataSource, - itemGenerator: (item: any) => void, - keyGenerator?: (item: any) => string + dataSource: IDataSource, + itemGenerator: (item: any) => void, + keyGenerator?: (item: any) => string ): void interface IDataSource { - totalCount(): number; - getData(index: number): any; - registerDataChangeListener(listener: DataChangeListener): void; - unregisterDataChangeListener(listener: DataChangeListener): void; + totalCount(): number; + getData(index: number): any; + registerDataChangeListener(listener: DataChangeListener): void; + unregisterDataChangeListener(listener: DataChangeListener): void; } interface DataChangeListener { - onDataReloaded(): void; - onDataAdd(index: number): void; - onDataMove(from: number, to: number): void; - onDataDelete(index: number): void; - onDataChange(index: number): void; + onDataReloaded(): void; + onDataAdd(index: number): void; + onDataMove(from: number, to: number): void; + onDataDelete(index: number): void; + onDataChange(index: number): void; } ``` @@ -127,19 +125,19 @@ interface DataChangeListener { | 参数名 | 参数类型 | 必填 | 参数描述 | | ------------- | --------------------- | ---- | ------------------------------------------------------------ | | dataSource | IDataSource | 是 | 实现IDataSource接口的对象,需要开发者实现相关接口。 | -| itemGenerator | (item: any) => void | 是 | 生成子组件的lambda函数,为给定数组项生成一个或多个子组件,单个组件和子组件列表必须括在大括号“{....}”中。 | -| keyGenerator | (item: any) => string | 否 | 匿名函数,用于键值生成,为给定数组项生成唯一且稳定的键值。当子项在数组中的位置更改时,子项的键值不得更改,当数组中的子项被新项替换时,被替换项的键值和新项的键值必须不同。键值生成器的功能是可选的,但是,为了使开发框架能够更好地识别数组更改,提高性能,建议提供。如将数组反向时,如果没有提供键值生成器,则LazyForEach中的所有节点都将重建。 | +| itemGenerator | (item: any) => void | 是 | 生成子组件的lambda函数,为数组中的每一个数据项创建一个或多个子组件,单个子组件或子组件列表必须包括在大括号“{...}”中。 | +| keyGenerator | (item: any) => string | 否 | 匿名函数,用于给数组中的每一个数据项生成唯一且固定的键值。当数据项在数组中的位置更改时,其键值不得更改,当数组中的数据项被新项替换时,被替换项的键值和新项的键值必须不同。键值生成器的功能是可选的,但是,为了使开发框架能够更好地识别数组更改,提高性能,建议提供。如将数组反向时,如果没有提供键值生成器,则LazyForEach中的所有节点都将重建。 | -表2 IDataSource类型说明 +### IDataSource类型说明 | 名称 | 描述 | | ------------------------------------------------------------ | ---------------------- | | totalCount(): number | 获取数据总数。 | -| getData(index: number): any | 获取索引对应的数据。 | -| registerDataChangeListener(listener:DataChangeListener): void | 注册改变数据的控制器。 | -| unregisterDataChangeListener(listener:DataChangeListener): void | 注销改变数据的控制器。 | +| getData(index: number): any | 获取索引值index对应的数据。 | +| registerDataChangeListener(listener:DataChangeListener): void | 注册数据改变的监听器。 | +| unregisterDataChangeListener(listener:DataChangeListener): void | 注销数据改变的监听器。 | -表3 DataChangeListener类型说明 +### DataChangeListener类型说明 | 名称 | 描述 | | -------------------------------------------------------- | -------------------------------------- | @@ -156,115 +154,129 @@ interface DataChangeListener { ## 示例 ```ts +// xxx.ets class BasicDataSource implements IDataSource { - private listeners: DataChangeListener[] = [] + private listeners: DataChangeListener[] = [] - public totalCount(): number { - return 0 - } - public getData(index: number): any { - return undefined - } + public totalCount(): number { + return 0 + } - 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) - } - } + public getData(index: number): any { + return undefined + } - notifyDataReload(): void { - this.listeners.forEach(listener => { - listener.onDataReloaded() - }) + registerDataChangeListener(listener: DataChangeListener): void { + if (this.listeners.indexOf(listener) < 0) { + console.info('add listener') + this.listeners.push(listener) } - 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) - }) + } + + 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[] = ['/path/image0', '/path/image1', '/path/image2', '/path/image3'] + // 初始化数据列表 + private dataArray: string[] = ['/path/image0.png', '/path/image1.png', '/path/image2.png', '/path/image3.png'] - public totalCount(): number { - return this.dataArray.length - } - public getData(index: number): any { - return this.dataArray[index] - } + public totalCount(): number { + return this.dataArray.length + } - 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) - } + public getData(index: number): any { + return this.dataArray[index] + } + + public addData(index: number, data: string): void { + this.dataArray.splice(index, 0, data) + this.notifyDataAdd(index) + } + + public pushData(data: string): void { + this.dataArray.push(data) + this.notifyDataAdd(this.dataArray.length - 1) + } } @Entry @Component struct MyComponent { - private data: MyDataSource = new MyDataSource() - build() { - List({space: 3}) { - LazyForEach(this.data, (item: string) => { - ListItem() { - Row() { - Image(item).width("30%").height(50) - Text(item).fontSize(20).margin({left:10}) - }.margin({left: 10, right: 10}) - } - .onClick(()=>{ - this.data.pushData('/path/image' + this.data.totalCount()) - }) - }, item => item) + private data: MyDataSource = new MyDataSource() + + build() { + List({ space: 3 }) { + LazyForEach(this.data, (item: string) => { + ListItem() { + Row() { + Image(item).width(50).height(50) + Text(item).fontSize(20).margin({ left: 10 }) + }.margin({ left: 10, right: 10 }) } + .onClick(() => { + // 每点击一次列表项,数据增加一项 + this.data.pushData('/path/image' + this.data.totalCount() + '.png') + }) + }, item => item) } + } } ``` > **说明:** > -> - 数据懒加载必须在容器组件内使用,且仅有List、Grid以及Swiper组件支持数据的懒加载(即只加载可视部分以及其前后少量数据用于缓冲),其他组件仍然是一次加载所有的数据; +> - LazyForEach必须在容器组件内使用,目前仅有List、Grid以及Swiper组件支持数据懒加载(即只加载可视部分以及其前后少量数据用于缓冲),其他组件仍然是一次性加载所有的数据。 > -> - LazyForEach在每次迭代中,必须且只允许创建一个子组件; +> - LazyForEach在每次迭代中,必须创建且只允许创建一个子组件。 > -> - 生成的子组件必须允许在LazyForEach的父容器组件中; +> - 生成的子组件必须是允许包含在LazyForEach父容器组件中的子组件。 > -> - 允许LazyForEach包含在if/else条件渲染语句中,不允许LazyForEach中出现if/else条件渲染语句; +> - 允许LazyForEach包含在if/else条件渲染语句中,但不允许LazyForEach中出现if/else条件渲染语句。 > -> - 为了高性能渲染,通过DataChangeListener对象的onDataChange方法来更新UI时,仅itemGenerator中的UI描述的组件内使用了状态变量时,才会触发组件刷新; +> - 为了高性能渲染,通过DataChangeListener对象的onDataChange方法来更新UI时,仅当itemGenerator中创建的子组件内使用了状态变量时,才会触发组件刷新。 > -> - 子项生成器函数的调用顺序不一定和数据源中的数据项相同,在开发过程中不要假设子项生成器和键值生成器函数是否执行以及执行顺序。如下示例可能无法正常工作: +> - itemGenerator函数的调用顺序不一定和数据源中的数据项相同,在开发过程中不要假设itemGenerator和keyGenerator函数是否执行及其执行顺序。例如,以下示例可能无法正常工作: > > ```ts > LazyForEach(dataSource, -> item => Text(`${item.i}. item.data.label`)), -> item => item.data.id.toString()) -> ``` \ No newline at end of file +> item => Text(`${item.i}. item.data.label`)), +> item => item.data.id.toString()) +> ``` + +![lazyForEach](figures/lazyForEach.gif) \ No newline at end of file diff --git a/zh-cn/application-dev/quick-start/arkts-restrictions-and-extensions.md b/zh-cn/application-dev/quick-start/arkts-restrictions-and-extensions.md index 0d7caec54ab82007b88df7d4c6684a19d9670c4f..075dfa40213d997a7cd56171f729844e5d6656a2 100644 --- a/zh-cn/application-dev/quick-start/arkts-restrictions-and-extensions.md +++ b/zh-cn/application-dev/quick-start/arkts-restrictions-and-extensions.md @@ -4,48 +4,49 @@ ArkTS语言的使用在生成器函数中存在一定的限制: -- 表达式仅允许在字符串(${expression})、if条件、ForEach的参数和组件的参数中使用; -- 任何表达式都不能导致任何应用程序状态变量(@State、@Link、@Prop)的改变,否则会导致未定义和潜在不稳定的框架行为; +- 表达式仅允许在字符串(${expression})、if/else条件语句、ForEach的参数以及组件的参数中使用。 + +- 任何表达式都不能导致应用程序中状态变量(@State、@Link、@Prop)的改变,否则会造成未定义和潜在不稳定的框架行为。 + - 生成器函数内部不能有局部变量。 -上述限制都不适用于事件处理函数(例如onClick)的匿函数实现。 +上述限制都不适用于事件方法(如onClick)的匿名函数实现。 ## 变量的双向绑定 ArkTS支持通过$$双向绑定变量,通常应用于状态值频繁改变的变量。 - 当前$$支持基础类型变量,以及@State、@Link和@Prop装饰的变量。 -- 当前$$仅支持[bindPopup](../reference/arkui-ts/ts-universal-attributes-popup.md)属性的show参数和@State变量之间的渲染,Radio组件的checked属性。 -- $$绑定的变量变更时,仅渲染当前组件,提高渲染速度。 +- 当前$$仅支持[bindPopup](../reference/arkui-ts/ts-universal-attributes-popup.md)属性方法的show参数,[Radio](../reference/arkui-ts/ts-basic-components-radio.md)组件的checked属性,[Refresh](../reference/arkui-ts/ts-container-refresh.md)组件的refreshing参数。 +- $$绑定的变量变化时,仅渲染刷新当前组件,提高渲染速度。 ```ts // xxx.ets @Entry @Component -struct bindPopup { - @State customPopup: boolean = false - build() { - column() { - button() { - Text('Popup') - } - .onClick(() => { - this.customPopup = !this.customPopup - }) - .bindPopup( - $$this.customPopup, { - mesage: "showPopup" - } - ) - } - } -} +struct bindPopupPage { + @State customPopup: boolean = false + build() { + Column() { + Button('Popup') + .margin(20) + .onClick(() => { + this.customPopup = !this.customPopup + }) + .bindPopup($$this.customPopup, { + message: "showPopup" + }) + } + } +} ``` -## 状态变量多种数据类型声明使用限制 +![popup](figures/popup.gif) + +## 状态变量数据类型声明使用限制 -@State、@Provide、 @Link和@Consume四种状态变量的多种数据类型只能同时由简单数据类型或引用数据类型其中一种构成。 +@State、@Provide、 @Link和@Consume四种状态变量的数据类型声明只能由简单数据类型或引用数据类型的其中一种构成。 示例: @@ -53,14 +54,14 @@ struct bindPopup { // xxx.ets @Entry @Component -struct Index { +struct IndexPage { //错误写法: @State message: string | Resource = 'Hello World' @State message: string = 'Hello World' build() { Row() { Column() { - Text(`${ this.message }`) + Text(`${this.message}`) .fontSize(50) .fontWeight(FontWeight.Bold) } @@ -69,4 +70,66 @@ struct Index { .height('100%') } } -``` \ No newline at end of file +``` + +![hello](figures/hello.PNG) + +## 自定义组件成员变量初始化的方式与约束 + +组件的成员变量可以通过两种方式初始化: + +- 本地初始化: + + ```ts + @State counter: Counter = new Counter() + ``` +- 在构造组件时通过构造参数初始化: + + ```ts + MyComponent({counter: $myCounter}) + ``` + +具体允许哪种方式取决于状态变量的装饰器: + +| 装饰器类型 | 本地初始化 | 通过构造函数参数初始化 | +| ------------ | ----- | ----------- | +| @State | 必须 | 可选 | +| @Prop | 禁止 | 必须 | +| @Link | 禁止 | 必须 | +| @StorageLink | 必须 | 禁止 | +| @StorageProp | 必须 | 禁止 | +| @Provide | 必须 | 可选 | +| @Consume | 禁止 | 禁止 | +| @ObjectLink | 禁止 | 必须 | +| 常规成员变量 | 推荐 | 可选 | + +从上表中可以看出: + +- @State变量需要本地初始化,初始化的值可以被构造参数覆盖。 + +- @Prop和@Link变量必须且仅通过构造函数参数进行初始化。 + +通过构造函数方法初始化成员变量,需要遵循如下规则: + +| 从父组件中的变量(下)到子组件中的变量(右) | @State | @Link | @Prop | 常规变量 | +| ---------------------- | ------ | ----- | ----- | ---- | +| @State | 不允许 | 允许 | 允许 | 允许 | +| @Link | 不允许 | 允许 | 不推荐 | 允许 | +| @Prop | 不允许 | 不允许 | 允许 | 允许 | +| @StorageLink | 不允许 | 允许 | 不允许 | 允许 | +| @StorageProp | 不允许 | 不允许 | 不允许 | 允许 | +| 常规变量 | 允许 | 不允许 | 不允许 | 允许 | + +从上表中可以看出: + +- 父组件的常规变量可以用于初始化子组件的@State变量,但不能用于初始化@Link或@Prop变量。 + +- 父组件的@State变量可以初始化子组件的@Prop、@Link(通过$)或常规变量,但不能初始化子组件的@State变量。 + +- 父组件的@Link变量可以初始化子组件的@Link或常规变量。但是初始化子组件的@State成员是语法错误,此外不建议初始化@Prop。 + +- 父组件的@Prop变量可以初始化子组件的常规变量或@Prop变量,但不能初始化子组件的@State或@Link变量。 + +- @StorageLink和@StorageProp不允许由父组件中传递到子组件。 + +- 除了上述规则外,还需要遵循TS的强类型规则。 \ No newline at end of file diff --git a/zh-cn/application-dev/quick-start/arkts-state-mgmt-application-level.md b/zh-cn/application-dev/quick-start/arkts-state-mgmt-application-level.md index c4e7e7cf211265eb5837f7e2c8967aa6aaaa38ac..7f083da6d9e3f6d79c5b4639063f9f02ea167aaa 100644 --- a/zh-cn/application-dev/quick-start/arkts-state-mgmt-application-level.md +++ b/zh-cn/application-dev/quick-start/arkts-state-mgmt-application-level.md @@ -1,75 +1,80 @@ # 应用级变量的状态管理 -在前面的章节中,已经讲述了如何管理页面级变量的状态,本章将说明如何管理应用级变量的状态,具体接口请参考[应用级变量的状态管理接口](../reference/arkui-ts/ts-state-management.md)。 +在前面的章节中,已经讲述了如何管理页面级变量的状态,本章将说明如何管理应用级变量的状态,具体接口说明请参考[应用级变量的状态管理接口](../reference/arkui-ts/ts-state-management.md)。 ## AppStorage -AppStorage是应用程序中的单例对象,由UI框架在应用程序启动时创建,在应用程序退出时销毁,为应用程序范围内的可变状态属性提供中央存储。 +[AppStorage](../reference/arkui-ts/ts-state-management.md#appstorage)是应用程序中的单例对象,由UI框架在应用程序启动时创建,在应用程序退出时销毁,为应用程序范围内的可变状态属性提供中央存储。 AppStorage包含整个应用程序中需要访问的所有状态属性,只要应用程序保持运行,AppStorage就会保存所有属性及属性值,属性值可以通过唯一的键值进行访问。 - 组件可以通过装饰器将应用程序状态数据与AppStorage进行同步,应用业务逻辑的实现也可以通过接口访问AppStorage。 - AppStorage的选择状态属性可以与不同的数据源或数据接收器同步,这些数据源和接收器可以是设备上的本地或远程,并具有不同的功能,如数据持久性。这样的数据源和接收器可以独立于UI在业务逻辑中实现。 默认情况下,AppStorage中的属性是可变的,AppStorage还可使用不可变(只读)属性。 +> **说明**:[Worker](../reference/apis/js-apis-worker.md)和主线程只能通过[postMessage](../reference/apis/js-apis-worker.md#postmessage)交互,不能使用AppStorage进行交互。 + ### @StorageLink装饰器 组件通过使用@StorageLink(key)装饰的状态变量,与AppStorage建立双向数据绑定,key为AppStorage中的属性键值。当创建包含@StorageLink的状态变量的组件时,该状态变量的值将使用AppStorage中的值进行初始化。在UI组件中对@StorageLink的状态变量所做的更改将同步到AppStorage,并从AppStorage同步到任何其他绑定实例中,如PersistentStorage或其他绑定的UI组件。 ### @StorageProp装饰器 -组件通过使用@StorageProp(key)装饰的状态变量,将与AppStorage建立单向数据绑定,key标识AppStorage中的属性键值。当创建包含@StoageProp的状态变量的组件时,该状态变量的值将使用AppStorage中的值进行初始化。AppStorage中的属性值的更改会导致绑定的UI组件进行状态更新。 +组件通过使用@StorageProp(key)装饰的状态变量,与AppStorage建立单向数据绑定,key标识AppStorage中的属性键值。当创建包含@StorageProp的状态变量的组件时,该状态变量的值将使用AppStorage中的值进行初始化。AppStorage中属性值的更改会导致绑定该状态变量的UI组件进行状态更新。 ### 示例 -每次用户单击Count按钮时,this.varA变量值都会增加,此变量与AppStorage中的varA同步。每次用户单击当前语言按钮时,修改AppStorage中的languageCode,此修改会同步给this.lang变量。 +每次用户单击Count按钮时,this.varA变量值都会增加1,此变量与AppStorage中的varA同步。每次用户单击language按钮时,修改AppStorage中的languageCode,此修改会同步给this.languageCode变量。 ```ts // xxx.ets - @Entry @Component struct ComponentA { @StorageLink('varA') varA: number = 2 - @StorageProp('languageCode') lang: string = 'en' + @StorageProp('languageCode') languageCode: string = 'en' private label: string = 'count' aboutToAppear() { - this.label = (this.lang === 'zh') ? '数' : 'Count' + this.label = (this.languageCode === 'zh') ? '数量' : 'Count' } build() { - Column(){ + Column() { Row({ space: 20 }) { Button(`${this.label}: ${this.varA}`) .onClick(() => { AppStorage.Set('varA', AppStorage.Get('varA') + 1) }) - Button(`lang: ${this.lang}`) + Button(`language: ${this.languageCode}`) .onClick(() => { - if (this.lang === 'zh') { + if (AppStorage.Get('languageCode') === 'zh') { AppStorage.Set('languageCode', 'en') } else { AppStorage.Set('languageCode', 'zh') } - this.label = (this.lang === 'zh') ? '数' : 'Count' + this.label = (this.languageCode === 'zh') ? '数量' : 'Count' }) } .margin({ bottom: 50 }) - Row(){ - Button(`更改@StorageLink修饰的变量:${this.varA}`).fontSize(10) + + Row() { + Button(`更改@StorageLink修饰的变量:${this.varA}`).height(40).fontSize(14) .onClick(() => { this.varA++ }) }.margin({ bottom: 50 }) - Row(){ - Button(`更改@StorageProp修饰的变量:${this.lang}`).fontSize(10) + + Row() { + Button(`更改@StorageProp修饰的变量:${this.languageCode}`).height(40).fontSize(14) .onClick(() => { - this.lang = 'test' + if (this.languageCode === 'zh') { + this.languageCode = 'en' + } else { + this.languageCode = 'zh' + } }) } } @@ -77,17 +82,19 @@ struct ComponentA { } ``` - ![appstorage](figures/appstorage.gif) +![appstorage](figures/appstorage.gif) ## LocalStorage -> **说明:** 该组件从API version 9开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 +> **说明:** +> +> 该接口从API version 9开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 -LocalStorage是应用程序中的存储单元,生命周期跟随其关联的Ability。LocalStorage为应用程序范围内的可变状态属性和非可变状态属性提供存储,可变状态属性和非可变状态属性是构建应用程序UI的一部分,如一个Ability的UI。 +[LocalStorage](../reference/arkui-ts/ts-state-management.md#localstorage9)是应用程序中的存储单元,生命周期跟随其关联的Ability。LocalStorage为应用程序范围内的可变状态属性和非可变状态属性提供存储,可变状态属性和非可变状态属性是构建应用程序UI的一部分,如一个Ability的UI。 应用层:一个应用程序可以创建多个LocalStorage实例,应用程序的每一个Ability对应一个LocalStorage实例。 -Ability: 一个应用程序可以拥有多个Ability,一个Ability中的所有子组件最多可以分配一个LocalStorage实例。并且,Ability中的所有子组件都将继承对此LocalStorage实例存储对象的访问权。 +Ability:一个应用程序可以拥有多个Ability,一个Ability中的所有子组件最多可以分配一个LocalStorage实例。并且,Ability中的所有子组件都将继承对此LocalStorage实例存储对象的访问权。 一个组件最多可以访问一个LocalStorage实例,一个LocalStorage对象可以分配给多个组件。 @@ -101,150 +108,174 @@ Ability: 一个应用程序可以拥有多个Ability,一个Ability中的所 > **说明:** 创建LocalStorage实例时如未定义初始值,可以使用组件内@LocalStorageLink和@LocalStorageProp的初始值。如果定义时给定了初始值,那么不会再使用@LocalStorageLink和@LocalStorageProp的初始值。 -### 示例1(在一个Ability创建的LocalStorage) +### 示例1(在一个Ability中创建LocalStorage) -LocalStorage通过loadContent接口加载,接口详见[loadContent](../reference/apis/js-apis-window.md#loadcontent9-1)。 +LocalStorage通过loadContent接口加载,接口说明详见[loadContent](../reference/apis/js-apis-window.md#loadcontent9-1)。 -``` +```ts +// MainAbility.ts import Ability from '@ohos.application.Ability' -export default class MainAbility extends Ability { - storage : LocalStorage - onCreate() { - this.storage = new LocalStorage(); - this.storage.setOrCreate("storageSimpleProp",121); - console.log("[Demo MainAbility onCreate]"); - } - onDestroy() { - console.log("[Demo MainAbility onDestroy]") - } - onWindowStageCreate(windowStage) { - // storage作为参数传递给loadContent接口。 - windowStage.loadContent("pages/index",this.storage) - } - onWindowStageDestroy() { - console.log("[Demo] MainAbility onWindoeStageDestroy") - } - onForeground() { - console.log("[Demo] MainAbility onForeground") - } - onBackground() { - console.log("[Demo] MainAbility onBackground") - } + +export default class MainAbility extends Ability { + storage: LocalStorage + + onCreate() { + this.storage = new LocalStorage() + this.storage.setOrCreate('storageSimpleProp', 121) + console.info('[Demo MainAbility onCreate]') + } + + onDestroy() { + console.info('[Demo MainAbility onDestroy]') + } + + onWindowStageCreate(windowStage) { + // storage作为参数传递给loadContent接口 + windowStage.loadContent('pages/index', this.storage) + } + + onWindowStageDestroy() { + console.info('[Demo] MainAbility onWindowStageDestroy') + } + + onForeground() { + console.info('[Demo] MainAbility onForeground') + } + + onBackground() { + console.info('[Demo] MainAbility onBackground') + } } ``` @Component组件获取数据 -``` +```ts +// index.ets let storage = LocalStorage.GetShared() + @Entry(storage) @Component struct LocalStorageComponent { - @LocalStorageLink("storageSimpleProp") simpleVarName: number = 0 + @LocalStorageLink('storageSimpleProp') simpleVarName: number = 0 + build() { - Column(){ - Button(`LocalStorageLink: ${ this.simpleVarName.toString() }`) - .onClick(()=>{ - this.simpleVarName +=1; + Column() { + Button(`LocalStorageLink: ${this.simpleVarName.toString()}`) + .margin(20) + .onClick(() => { + this.simpleVarName += 1 }) Text(JSON.stringify(this.simpleVarName)) .fontSize(50) - LocalStorageComponentProp(); - } - .height(500) + LocalStorageComponentProp() + }.width('100%') } } + @Component struct LocalStorageComponentProp { - @LocalStorageProp("storageSimpleProp") simpleVarName: number = 0 + @LocalStorageProp('storageSimpleProp') simpleVarName: number = 0 + build() { Column() { - Button(`LocalStorageProp: ${ this.simpleVarName.toString() }`) + Button(`LocalStorageProp: ${this.simpleVarName.toString()}`) + .margin(20) .onClick(() => { - this.simpleVarName += 1; + this.simpleVarName += 1 }) Text(JSON.stringify(this.simpleVarName)) .fontSize(50) - } - .height(500) + }.width('100%') } } ``` +![appstorage1](figures/appstorage1.gif) + ### 示例2(在Entry页面定义LocalStorage) -``` -let storage = new LocalStorage({"PropA":47}); +```ts +// xxx.ets +let storage = new LocalStorage({ "PropA": 47 }) + @Entry(storage) -@Component -struct ComA { - @LocalStorageLink("PropA") storLink: number = 1; - build() { - Column() { - Text(`Parent from LocalStorage ${ this.storLink }`) - .onClick(()=>this.storLink+=1) - Child() - } +@Component +struct ComA { + @LocalStorageLink("PropA") storageLink: number = 1 + + build() { + Column() { + Text(`Parent from LocalStorage ${this.storageLink}`) + .fontSize(18) + .margin(20) + .onClick(() => this.storageLink += 1) + Child() + } } } - @Component -struct Child{ - @LocalStorageLink("PropA") storLink: number = 1; - build() { - Text(`Parent from LocalStorage ${ this.storLink }`) - .onClick(()=>this.storLink+=1) +struct Child { + @LocalStorageLink("PropA") storageLink: number = 1 + + build() { + Text(`Child from LocalStorage ${this.storageLink}`) + .fontSize(18) + .margin(20) + .onClick(() => this.storageLink += 1) } } ``` +![appstorage2](figures/appstorage2.gif) + ## PersistentStorage -PersistentStorage类提供了一些静态方法用来管理应用持久化数据,可以将特定标记的持久化数据链接到AppStorage中,并由AppStorage接口访问对应持久化数据,或者通过@StorageLink装饰器来访问对应key的变量。 +[PersistentStorage](../reference/arkui-ts/ts-state-management.md#persistentstorage)提供了一些静态方法用来管理应用持久化数据,可以将特定标记的持久化数据链接到AppStorage中,并由AppStorage接口访问对应持久化数据,或者通过@StorageLink装饰器来访问对应key的变量。 > **说明:** > -> - PersistProp接口使用时,需要保证输入对应的key应当在AppStorage存在。 -> - DeleteProp接口使用时,只能对本次启动已经link过的数据生效。 +> - PersistentStorage的PersistProp接口使用时,需要保证输入对应的key在AppStorage中存在。 +> - PersistentStorage的DeleteProp接口使用时,只能对本次应用启动时已经link过的数据生效。 ```ts // xxx.ets -PersistentStorage.PersistProp("highScore", "0"); +PersistentStorage.PersistProp('highScore', '0') @Entry @Component struct PersistentComponent { - @StorageLink('highScore') highScore: string = '0' - @State currentScore: number = 0 - build() { - Column() { - if (this.currentScore === Number(this.highScore)) { - Text(`new highScore : ${this.highScore}`) - } - Button() { - Text(`goal!, currentScore : ${this.currentScore}`) - .fontSize(10) - }.onClick(() => { - this.currentScore++ - if (this.currentScore > Number(this.highScore)) { - this.highScore = this.currentScore.toString() - } - }) - } - } + @StorageLink('highScore') highScore: string = '0' + @State currentScore: number = 0 + + build() { + Column() { + if (this.currentScore === Number(this.highScore)) { + Text(`new highScore : ${this.highScore}`).fontSize(18) + } + Button(`goal!, currentScore : ${this.currentScore}`) + .margin(20) + .onClick(() => { + this.currentScore++ + if (this.currentScore > Number(this.highScore)) { + this.highScore = this.currentScore.toString() + } + }) + }.width('100%') + } } ``` - ![PersistentStorage](figures/PersistentStorage.gif) +![appstorage3](figures/appstorage3.gif) ## Environment -Environment是框架在应用程序启动时创建的单例对象,它为AppStorage提供了一系列应用程序需要的环境状态属性,这些属性描述了应用程序运行的设备环境。Environment及其属性是不可变的,所有属性值类型均为简单类型。如下示例展示了从Environment获取语音环境: +[Environment](../reference/arkui-ts/ts-state-management.md#environment)是框架在应用程序启动时创建的单例对象,它为AppStorage提供了一系列应用程序需要的环境状态数据,这些数据描述了应用程序运行的设备环境,包括系统语言、深浅色模式等等。Environment及其属性是不可变的,所有数据类型均为简单类型。如下示例展示了从Environment获取系统是否开启无障碍屏幕朗读: -``` -Environment.EnvProp("accessibilityEnabled", "default"); -var enable = AppStorage.Get("accessibilityEnabled"); +```ts +Environment.EnvProp('accessibilityEnabled', 'default') +var enable = AppStorage.Get('accessibilityEnabled') ``` -accessibilityEnabled是Environment提供默认系统变量识别符。首先需要将对应系统属性绑定到AppStorage中,再通过AppStorage中的方法或者装饰器访问对应系统的属性数据。 +accessibilityEnabled是Environment提供的系统默认变量识别符。首先需要将对应系统属性绑定到AppStorage上,再通过AppStorage中的方法或者装饰器访问对应的系统属性数据。 \ No newline at end of file diff --git a/zh-cn/application-dev/quick-start/arkts-state-mgmt-concepts.md b/zh-cn/application-dev/quick-start/arkts-state-mgmt-concepts.md index b4a1c095ed531dec3796b3133673d96243b05906..c984324d66f335212b2256c4162abfe38f22e1d8 100644 --- a/zh-cn/application-dev/quick-start/arkts-state-mgmt-concepts.md +++ b/zh-cn/application-dev/quick-start/arkts-state-mgmt-concepts.md @@ -1,6 +1,6 @@ # 基本概念 -ArkTS提供了多维度的状态管理机制,在UI开发框架中,和UI相关联的数据,不仅可以在组件内使用,还可以在不同组件层级间传递,比如父子组件之间、爷孙组件之前,也可以时全局范围内的传递。另外,从数据的传递形式来看,可分为只读的单向传递和可变更的双向传递。开发者可以灵活的利用这些能力来实现数据和UI的联动。 +ArkTS提供了多维度的状态管理机制,在ArkUI开发框架中,和UI相关联的数据,不仅可以在组件内使用,还可以在不同组件层级间传递,比如父子组件之间、爷孙组件之间,也可以是应用全局范围内的传递。另外,从数据的传递形式来看,可分为只读的单向传递和可变更的双向传递。开发者可以灵活地利用这些能力来实现数据和UI的联动。 ![](figures/CoreSpec_figures_state-mgmt-overview.png) @@ -11,20 +11,20 @@ ArkTS提供了多维度的状态管理机制,在UI开发框架中,和UI相 | 装饰器 | 装饰内容 | 说明 | | ----------- | ------------------------- | ------------------------------------------------------------ | | @State | 基本数据类型,类,数组 | 修饰的状态数据被修改时会触发组件的build方法进行UI界面更新。 | -| @Prop | 基本数据类型 | 修改后的状态数据用于在父组件和子组件之间建立单向数据依赖关系。修改父组件关联数据时,更新当前组件的UI。 | +| @Prop | 基本数据类型 | 修改后的状态数据用于在父组件和子组件之间建立单向数据依赖关系。修改父组件关联数据时,当前组件会重新渲染。 | | @Link | 基本数据类型,类,数组 | 父子组件之间的双向数据绑定,父组件的内部状态数据作为数据源,任何一方所做的修改都会反映给另一方。 | | @Observed | 类 | @Observed应用于类,表示该类中的数据变更被UI页面管理。 | -| @ObjectLink | 被@Observed所装饰类的对象 | 装饰的状态数据被修改时,在父组件或者其他兄弟组件内与它关联的状态数据所在的组件都会更新UI。 | +| @ObjectLink | 被@Observed所装饰类的对象 | @ObjectLink装饰的状态数据被修改时,在父组件或者其他兄弟组件内与它关联的状态数据所在的组件都会重新渲染。 | | @Consume | 基本数据类型,类,数组 | @Consume装饰的变量在感知到@Provide装饰的变量更新后,会触发当前自定义组件的重新渲染。 | -| @Provide | 基本数据类型,类,数组 | @Provide作为数据的提供方,可以更新其子孙节点的数据,并触发页面渲染。 | +| @Provide | 基本数据类型,类,数组 | @Provide作为数据的提供方,可以更新其子孙节点的数据,并触发页面重新渲染。 | ## 应用级变量的状态管理 -AppStorage是整个UI应用程序状态的中心“数据库”,UI框架会针对应用程序创建单例AppStorage对象,并提供相应的装饰器和接口供应用程序使用。 +AppStorage是整个应用程序状态的中心“数据库”,UI框架会针对应用程序创建单例AppStorage对象,并提供相应的装饰器和接口供应用程序使用。 - @StorageLink:@StorageLink(name)的原理类似于@Consume(name),不同的是,该给定名称的链接对象是从AppStorage中获得的,在UI组件和AppStorage之间建立双向绑定同步数据。 -- @StorageProp:@StorageProp(name)将UI组件属性与AppStorage进行单向同步,AppStorage中值的更改会更新组件中的属性,但UI组件无法更改AppStorage中的属性值。 -- AppStorage还提供用于业务逻辑实现的API,用于添加、读取、修改和删除应用程序的状态属性,此API所做的更改会导致修改的状态数据同步到UI组件上进行UI更新。 -- PersistentStorage类提供了一些静态方法用来管理应用持久化数据,可以将特定标记的持久化数据链接到AppStorage中,并由AppStorage接口访问对应持久化数据,或者通过@StorageLink装饰器来访问对应key的变量。 -- Environment是框架在应用程序启动时创建的单例对象,它为AppStorage提供了一系列应用程序需要的环境状态属性,这些属性描述了应用程序运行的设备环境。 +- @StorageProp:@StorageProp(name)将UI组件数据与AppStorage进行单向同步,AppStorage中值的更改会更新UI组件中的数据,但UI组件无法更改AppStorage中的数据。 +- AppStorage还提供了用于业务逻辑实现的API,用于添加、读取、修改和删除应用程序的状态数据,此API所做的更改会导致修改的状态数据同步到UI组件上进行UI更新。 +- PersistentStorage提供了一些静态方法用来管理应用持久化数据,可以将特定标记的持久化数据链接到AppStorage中,并由AppStorage接口访问对应持久化数据,或者通过@StorageLink装饰器来访问对应key的变量。 +- Environment是框架在应用程序启动时创建的单例对象,它为AppStorage提供了一系列应用程序需要的环境状态数据,这些数据描述了应用程序运行的设备环境。 diff --git a/zh-cn/application-dev/quick-start/arkts-state-mgmt-page-level.md b/zh-cn/application-dev/quick-start/arkts-state-mgmt-page-level.md index 586f3f22473f4e0d3f9d4068d134a893268756fe..959f924a34bbe7fd48ded0a20c3b38178b323035 100644 --- a/zh-cn/application-dev/quick-start/arkts-state-mgmt-page-level.md +++ b/zh-cn/application-dev/quick-start/arkts-state-mgmt-page-level.md @@ -2,188 +2,199 @@ @State、@Prop、@Link、@Provide、Consume、@ObjectLink、@Observed和@Watch用于管理页面级变量的状态。 +请参考[状态变量多种数据类型声明的使用限制](./arkts-restrictions-and-extensions.md)了解@State、@Provide、 @Link和@Consume四种状态变量的约束条件。 + ## @State @State装饰的变量是组件内部的状态数据,当这些状态数据被修改时,将会调用所在组件的build方法进行UI刷新。 @State状态数据具有以下特征: - -- 支持多种类型:允许class、number、boolean、string强类型的按值和按引用类型。允许这些强类型构成的数组,即Array<class>、Array<string>、Array<boolean>、Array<number>。不允许object和any。 +- 支持多种类型数据:支持class、number、boolean、string强类型数据的值类型和引用类型,以及这些强类型构成的数组,即Array<class>、Array<string>、Array<boolean>、Array<number>。不支持object和any。 - 支持多实例:组件不同实例的内部状态数据独立。 - 内部私有:标记为@State的属性是私有变量,只能在组件内访问。 -- 需要本地初始化:必须为所有@State变量分配初始值,将变量保持未初始化可能导致框架行为未定义。 -- 创建自定义组件时支持通过状态变量名设置初始值:在创建组件实例时,可以通过变量名显式指定@State状态属性的初始值。 +- 需要本地初始化:必须为所有@State变量分配初始值,变量未初始化可能导致未定义的框架异常行为。 +- 创建自定义组件时支持通过状态变量名设置初始值:在创建组件实例时,可以通过变量名显式指定@State状态变量的初始值。 **示例:** 在下面的示例中: - - 用户定义的组件MyComponent定义了@State状态变量count和title。如果count或title的值发生变化,则执行MyComponent的build方法来重新渲染组件; - EntryComponent中有多个MyComponent组件实例,第一个MyComponent内部状态的更改不会影响第二个MyComponent; - 创建MyComponent实例时通过变量名给组件内的变量进行初始化,如: + ```ts - MyComponent({title: {value: 'Hello, World 2'}, count: 7}) + MyComponent({ title: { value: 'Hello World 2' }, count: 7 }) ``` ```ts // xxx.ets class Model { - value: string - constructor(value: string) { - this.value = value - } + value: string + + constructor(value: string) { + this.value = value + } } @Entry @Component struct EntryComponent { - build() { - Column() { - MyComponent({count: 1, increaseBy: 2}) // MyComponent1 in this document - MyComponent({title: {value: 'Hello, World 2'}, count: 7}) //MyComponent2 in this document - } + build() { + Column() { + MyComponent({ count: 1, increaseBy: 2 }) // 第1个MyComponent实例 + MyComponent({ title: { value: 'Hello World 2' }, count: 7 }) // 第2个MyComponent实例 } + } } @Component struct MyComponent { - @State title: Model = {value: 'Hello World'} - @State count: number = 0 - private toggle: string = 'Hello World' - private increaseBy: number = 1 - - build() { - Column() { - Text(`${this.title.value}`).fontSize(30) - Button() { - Text(`Click to change title`).fontSize(20).fontColor(Color.White) - }.onClick(() => { - this.title.value = (this.toggle == this.title.value) ? 'Hello World' : 'Hello UI' - }) // Modify the internal state of MyComponent using the anonymous method. - - Button() { - Text(`Click to increase count=${this.count}`).fontSize(20).fontColor(Color.White) - }.onClick(() => { - this.count += this.increaseBy - }) // Modify the internal state of MyComponent using the anonymous method. - } + @State title: Model = { value: 'Hello World' } + @State count: number = 0 + private toggle: string = 'Hello World' + private increaseBy: number = 1 + + build() { + Column() { + Text(`${this.title.value}`).fontSize(30) + Button('Click to change title') + .margin(20) + .onClick(() => { + // 修改内部状态变量title + this.title.value = (this.toggle == this.title.value) ? 'Hello World' : 'Hello ArkUI' + }) + + Button(`Click to increase count=${this.count}`) + .margin(20) + .onClick(() => { + // 修改内部状态变量count + this.count += this.increaseBy + }) } + } } ``` -![@state1](figures/@state.png) ## @Prop -@Prop与@State有相同的语义,但初始化方式不同。@Prop装饰的变量必须使用其父组件提供的@State变量进行初始化,允许组件内部修改@Prop变量,但更改不会通知给父组件,即@Prop属于单向数据绑定。 +@Prop与@State有相同的语义,但初始化方式不同。@Prop装饰的变量必须使用其父组件提供的@State变量进行初始化,允许组件内部修改@Prop变量,但变量的更改不会通知给父组件,即@Prop属于单向数据绑定。 @Prop状态数据具有以下特征: -- 支持简单类型:仅支持number、string、boolean简单类型; -- 私有:仅在组件内访问; +- 支持简单类型:仅支持number、string、boolean等简单数据类型; +- 私有:仅支持组件内访问; - 支持多个实例:一个组件中可以定义多个标有@Prop的属性; - 创建自定义组件时将值传递给@Prop变量进行初始化:在创建组件的新实例时,必须初始化所有@Prop变量,不支持在组件内部进行初始化。 **示例:** -在下面的示例中,当按“+1”或“-1”按钮时,父组件状态发生变化,重新执行build方法,此时将创建一个新的CountDownComponent组件。父组件的countDownStartValue状态属性被用于初始化子组件的@Prop变量,当按下子组件的“Try again”按钮时,其@Prop变量count将被更改,CountDownComponent重新渲染。但是count值的更改不会影响父组件的countDownStartValue值。 +在下面的示例中,当按“+1”或“-1”按钮时,父组件状态发生变化,重新执行build方法,此时将创建一个新的CountDownComponent组件实例。父组件的countDownStartValue状态变量被用于初始化子组件的@Prop变量,当按下子组件的“count - costOfOneAttempt”按钮时,其@Prop变量count将被更改,CountDownComponent重新渲染,但是count值的更改不会影响父组件的countDownStartValue值。 ```ts // xxx.ets @Entry @Component struct ParentComponent { - @State countDownStartValue: number = 10 // 10 Nuggets default start value in a Game - build() { - Column() { - Text(`Grant ${this.countDownStartValue} nuggets to play.`) - Button() { - Text('+1 - Nuggets in New Game') - }.onClick(() => { - this.countDownStartValue += 1 - }) - Button() { - Text('-1 - Nuggets in New Game') - }.onClick(() => { - this.countDownStartValue -= 1 - }) - // 创建子组件时,必须在构造函数参数中提供其@Prop变量的初始值,同时初始化常规变量CostOfOneAttump(非Prop) - CountDownComponent({ count: this.countDownStartValue, costOfOneAttempt: 2}) - } + @State countDownStartValue: number = 10 // 初始化countDownStartValue + + build() { + Column() { + Text(`Grant ${this.countDownStartValue} nuggets to play.`).fontSize(18) + Button('+1 - Nuggets in New Game') + .margin(15) + .onClick(() => { + this.countDownStartValue += 1 + }) + + Button('-1 - Nuggets in New Game') + .margin(15) + .onClick(() => { + this.countDownStartValue -= 1 + }) + // 创建子组件时,必须在构造函数参数中提供其@Prop变量count的初始值,同时初始化常规变量costOfOneAttempt(非Prop变量) + CountDownComponent({ count: this.countDownStartValue, costOfOneAttempt: 2 }) } + } } @Component struct CountDownComponent { - @Prop count: number - private costOfOneAttempt: number - - build() { - Column() { - if (this.count > 0) { - Text(`You have ${this.count} Nuggets left`) - } else { - Text('Game over!') - } - - Button() { - Text('Try again') - }.onClick(() => { - this.count -= this.costOfOneAttempt - }) - } + @Prop count: number + private costOfOneAttempt: number + + build() { + Column() { + if (this.count > 0) { + Text(`You have ${this.count} Nuggets left`).fontSize(18) + } else { + Text('Game over!').fontSize(18) + } + + Button('count - costOfOneAttempt') + .margin(15) + .onClick(() => { + this.count -= this.costOfOneAttempt + }) } + } } ``` -> **说明:** 创建新组件实例时,必须初始化其所有@Prop变量。 ## @Link @Link装饰的变量可以和父组件的@State变量建立双向数据绑定: -- 支持多种类型:@Link变量的值与@State变量的类型相同,即class、number、string、boolean或这些类型的数组; -- 私有:仅在组件内访问; -- 单个数据源:初始化@Link变量的父组件的变量必须是@State变量; -- 双向通信:子组件对@Link变量的更改将同步修改父组件的@State变量; +- 支持多种类型:@Link支持的数据类型与@State相同,即class、number、string、boolean或这些类型的数组; +- 私有:仅支持组件内访问; +- 单个数据源:父组件中用于初始化子组件@Link变量的必须是@State变量; +- 双向通信:子组件对@Link变量的更改将同步修改父组件中的@State变量; - 创建自定义组件时需要将变量的引用传递给@Link变量,在创建组件的新实例时,必须使用命名参数初始化所有@Link变量。@Link变量可以使用@State变量或@Link变量的引用进行初始化,@State变量可以通过`'$'`操作符创建引用。 -> 说明: @Link变量不能在组件内部进行初始化 +> **说明:** @Link变量不能在组件内部进行初始化。 **简单类型示例:** -@Link语义是从`'$'`操作符引出,即`$isPlaying`是`this.isPlaying`内部状态的双向数据绑定。当单击PlayButton时,PlayButton的Image组件和Text组件将同时进行刷新。 +@Link语义是从`'$'`操作符引出,即`$isPlaying`是`this.isPlaying`内部状态的双向数据绑定。当单击子组件PlayButton中的按钮时,@Link变量更改,PlayButton与父组件中的Text和Button将同时进行刷新,同样地,当点击父组件中的Button修改`this.isPlaying`时,子组件PlayButton与父组件中的Text和Button也将同时刷新。 ```ts // xxx.ets @Entry @Component struct Player { - @State isPlaying: boolean = false - build() { - Column() { - PlayButton({buttonPlaying: $isPlaying}) - Text(`Player is ${this.isPlaying? '':'not'} playing`) - } + @State isPlaying: boolean = false + + build() { + Column() { + PlayButton({ buttonPlaying: $isPlaying }) + Text(`Player is ${this.isPlaying ? '' : 'not'} playing`).fontSize(18) + Button('Parent:' + this.isPlaying) + .margin(15) + .onClick(() => { + this.isPlaying = !this.isPlaying + }) } + } } @Component struct PlayButton { - @Link buttonPlaying: boolean - build() { - Column() { - Button() { - Image(this.buttonPlaying? 'play.png' : 'pause.png') - }.onClick(() => { - this.buttonPlaying = !this.buttonPlaying - }) - } + @Link buttonPlaying: boolean + + build() { + Column() { + Button(this.buttonPlaying ? 'pause' : 'play') + .margin(20) + .onClick(() => { + this.buttonPlaying = !this.buttonPlaying + }) } + } } ``` @@ -194,82 +205,97 @@ struct PlayButton { @Entry @Component struct Parent { - @State arr: number[] = [1, 2, 3] - build() { - Column() { - Child({items: $arr}) - ForEach(this.arr, - item => Text(`${item}`), - item => item.toString()) - } + @State arr: number[] = [1, 2, 3] + + build() { + Column() { + Child({ items: $arr }) + Button('Parent Button: splice') + .margin(10) + .onClick(() => { + this.arr.splice(0, 1, 60) + }) + ForEach(this.arr, item => { + Text(item.toString()).fontSize(18).margin(10) + }, item => item.toString()) } + } } + @Component struct Child { - @Link items: number[] - build() { - Column() { - Button() { - Text('Button1: push') - }.onClick(() => { - this.items.push(100) - }) - Button() { - Text('Button2: replace whole item') - }.onClick(() => { - this.items = [100, 200, 300] - }) - } + @Link items: number[] + + build() { + Column() { + Button('Child Button1: push') + .margin(15) + .onClick(() => { + this.items.push(100) + }) + Button('Child Button2: replace whole item') + .margin(15) + .onClick(() => { + this.items = [100, 200, 300] + }) } + } } ``` -## @Link、@State和@Prop结合使用示例 +**@Link、@State和@Prop结合使用示例:** -下面示例中,ParentView包含ChildA和ChildB两个子组件,ParentView的状态变量counter分别初始化ChildA和ChildB。 +下面示例中,ParentView包含ChildA和ChildB两个子组件,ParentView的状态变量counter分别用于初始化ChildA的@Prop变量和ChildB的@Link变量。 -- ChildB使用@Link建立双向状态绑定。当ChildB修改counterRef状态变量值时,该更改将同步到ParentView和ChildA共享; -- ChildA使用@Prop建立从ParentView到自身的单向状态绑定。当ChildA修改状态时,ChildA将重新渲染,但该更改不会传达给ParentView和ChildB。 +- ChildB使用@Link建立双向数据绑定,当ChildB修改counterRef状态变量值时,该更改将同步到ParentView和ChildA共享; +- ChildA使用@Prop建立从ParentView到自身的单向数据绑定,当ChildA修改counterVal状态变量值时,ChildA将重新渲染,但该更改不会传达给ParentView和ChildB。 ```ts // xxx.ets @Entry @Component struct ParentView { - @State counter: number = 0 - build() { - Column() { - ChildA({counterVal: this.counter}) // pass by value - ChildB({counterRef: $counter}) // $ creates a Reference that can be bound to counterRef - } + @State counter: number = 0 + + build() { + Column() { + ChildA({ counterVal: this.counter }) + ChildB({ counterRef: $counter }) } + } } @Component struct ChildA { - @Prop counterVal: number - build() { - Button() { - Text(`ChildA: (${this.counterVal}) + 1`) - }.onClick(() => {this.counterVal+= 1}) - } + @Prop counterVal: number + + build() { + Button(`ChildA: (${this.counterVal}) + 1`) + .margin(15) + .onClick(() => { + this.counterVal += 1 + }) + } } @Component struct ChildB { - @Link counterRef: number - build() { - Button() { - Text(`ChildB: (${this.counterRef}) + 1`) - }.onClick(() => {this.counterRef+= 1}) - } + @Link counterRef: number + + build() { + Button(`ChildB: (${this.counterRef}) + 1`) + .margin(15) + .onClick(() => { + this.counterRef += 1 + }) + } } ``` -## Observed和ObjectLink数据管理 +## @Observed和ObjectLink数据管理 -当开发者需要在子组件中针对父组件的一个变量(parent_a)设置双向同步时,开发者可以在父组件中使用\@State装饰变量(parent_a),并在子组件中使用@Link装饰相应的变量(child_a)。这样的话,不仅可以实现父组件与单个子组件之间的数据同步,也可以实现父组件与多个子组件之间的数据同步。如下图所示,可以看到,父子组件针对ClassA类型的变量设置了双向同步,那么当子组件1中变量的属性c的值变化时,会通知父组件同步变化,而当父组件中属性c的值变化时,会通知所有子组件同步变化。 +当开发者需要在子组件中针对父组件的一个变量(parent_a)设置双向同步时,开发者可以在父组件中使用@State装饰变量(parent_a),并在子组件中使用@Link装饰对应的变量(child_a)。这样不仅可以实现父组件与单个子组件之间的数据同步,也可以实现父组件与多个子组件之间的数据同步。如下图所示,可以看到,父子组件针对ClassA类型的变量设置了双向同步,那么当子组件1中变量对应的属性c的值变化时,会通知父组件同步变化,而当父组件中属性c的值变化时,会通知所有子组件同步变化。 ![zh-cn_image_0000001251090821](figures/zh-cn_image_0000001251090821.png) @@ -279,17 +305,17 @@ struct ChildB { ### 设置要求 -- @Observed 用于类,@ObjectLink 用于变量。 +- @Observed用于类,@ObjectLink用于变量。 - @ObjectLink装饰的变量类型必须为类(class type)。 - - 类要被\@Observed装饰器所装饰。 + - 类要被@Observed装饰器所装饰。 - 不支持简单类型参数,可以使用@Prop进行单向同步。 -- @ObjectLink装饰的变量是不可变的(immutable)。 - - 属性的改动是被允许的,当改动发生时,如果同一个对象被多个@ObjectLink变量所引用,那么所有拥有这些变量的自定义组件都会被通知去重新渲染。 +- @ObjectLink装饰的变量是不可变的。 + - 属性的改动是被允许的,当改动发生时,如果同一个对象被多个@ObjectLink变量所引用,那么所有拥有这些变量的自定义组件都会被通知进行重新渲染。 - @ObjectLink装饰的变量不可设置默认值。 - - 必须让父组件中有一个由@State、@Link、@StorageLink、@Provide或@Consume所装饰变量参与的TS表达式进行初始化。 + - 必须让父组件中有一个由@State、@Link、@StorageLink、@Provide或@Consume装饰的变量所参与的TS表达式进行初始化。 - @ObjectLink装饰的变量是私有变量,只能在组件内访问。 @@ -299,30 +325,31 @@ struct ChildB { ```ts // xxx.ets // 父组件ViewB中的类对象ClassA与子组件ViewA保持数据同步时,可以使用@ObjectLink和@Observed,绑定该数据对象的父组件和其他子组件同步更新 - -var nextID: number = 0; +var nextID: number = 0 @Observed class ClassA { - public name : string; - public c: number; - public id : number; + public name: string + public c: number + public id: number + constructor(c: number, name: string = 'OK') { - this.name = name; - this.c = c; - this.id = nextID++; + this.name = name + this.c = c + this.id = nextID++ } } @Component struct ViewA { - label : string = "ViewA1"; - @ObjectLink a: ClassA; + label: string = 'ViewA1' + @ObjectLink a: ClassA + build() { Row() { Button(`ViewA [${this.label}] this.a.c= ${this.a.c} +1`) .onClick(() => { - this.a.c += 1; + this.a.c += 1 }) }.margin({ top: 10 }) } @@ -331,59 +358,57 @@ struct ViewA { @Entry @Component struct ViewB { - @State arrA : ClassA[] = [ new ClassA(0), new ClassA(0) ]; + @State arrA: ClassA[] = [new ClassA(0), new ClassA(0)] + build() { Column() { - ForEach (this.arrA, (item) => { - ViewA({label: `#${item.id}`, a: item}) - }, - (item) => item.id.toString() - ) - ViewA({label: `ViewA this.arrA[first]`, a: this.arrA[0]}) - ViewA({label: `ViewA this.arrA[last]`, a: this.arrA[this.arrA.length-1]}) + ForEach(this.arrA, (item) => { + ViewA({ label: `#${item.id}`, a: item }) + }, (item) => item.id.toString()) + ViewA({ label: `this.arrA[first]`, a: this.arrA[0] }) + ViewA({ label: `this.arrA[last]`, a: this.arrA[this.arrA.length - 1] }) Button(`ViewB: reset array`) .margin({ top: 10 }) .onClick(() => { - this.arrA = [ new ClassA(0), new ClassA(0) ]; + this.arrA = [new ClassA(0), new ClassA(0)] }) Button(`ViewB: push`) - .margin({ top: 10 }) + .margin({ top: 10 }) .onClick(() => { - this.arrA.push(new ClassA(0)) + this.arrA.push(new ClassA(0)) }) Button(`ViewB: shift`) - .margin({ top: 10 }) + .margin({ top: 10 }) .onClick(() => { - this.arrA.shift() + this.arrA.shift() }) - } + }.width('100%') } } ``` - ![Observed](figures/Observed.gif) ## @Consume和@Provide -Provide作为数据的提供方,可以更新其子孙节点的数据,并触发页面渲染。Consume在感知到Provide数据的更新后,会触发当前view的重新渲染。 +@Provide作为数据的提供方,可以更新其子孙节点的数据,并触发页面渲染。@Consume在感知到@Provide数据的更新后,会触发当前自定义组件的重新渲染。 -> **说明:** 使用@Provide 和@Consume时避免循环引用导致死循环。 +> **说明:** 使用@Provide和@Consume时应避免循环引用导致死循环。 -表1 @Provide +### @Provide | 名称 | 说明 | | -------------- | ------------------------------------------------------------ | -| 装饰器参数 | 是一个string类型的常量,用于给装饰的变量起别名。如果规定别名,则提供对应别名的数据更新。如果没有,则使用变量名作为别名。推荐使用@Provide("alias")这种形式。 | +| 装饰器参数 | 是一个string类型的常量,用于给装饰的变量起别名。如果规定别名,则提供对应别名的数据更新。如果没有,则使用变量名作为别名。推荐使用@Provide('alias')这种形式。 | | 同步机制 | @Provide的变量类似@State,可以修改对应变量进行页面重新渲染。也可以修改@Consume装饰的变量,反向修改@State变量。 | -| 初始值 | 必须制定初始值。 | +| 初始值 | 必须设置初始值。 | | 页面重渲染场景 | 触发页面渲染的修改:
- 基础类型(boolean,string,number)变量的改变;
- @Observed class类型变量及其属性的修改;
- 添加,删除,更新数组中的元素。 | -表2 @Consume +### @Consume | 类型 | 说明 | | ------ | ---------------- | -| 初始值 | 不可设置默认值。 | +| 初始值 | 不可设置默认初始值。 | ### 示例 @@ -392,18 +417,16 @@ Provide作为数据的提供方,可以更新其子孙节点的数据,并触 @Entry @Component struct CompA { - @Provide("reviewVote") reviewVotes : number = 0; + @Provide("reviewVote") reviewVotes: number = 0; build() { Column() { CompB() - Button() { - Text(`${this.reviewVotes}`) - .fontSize(30) - } - .onClick(() => { - this.reviewVotes += 1; - }) + Button(`CompA: ${this.reviewVotes}`) + .margin(10) + .onClick(() => { + this.reviewVotes += 1; + }) } } } @@ -419,17 +442,16 @@ struct CompB { @Component struct CompC { - @Consume("reviewVote") reviewVotes : number; + @Consume("reviewVote") reviewVotes: number + build() { Column() { - Button() { - Text(`${this.reviewVotes}`) - .fontSize(30) - } - .onClick(() => { - this.reviewVotes += 1; - }) - }.margin({ left:10, top: 10 }) + Button(`CompC: ${this.reviewVotes}`) + .margin(10) + .onClick(() => { + this.reviewVotes += 1 + }) + }.width('100%') } } ``` @@ -438,41 +460,53 @@ struct CompC { @Watch用于监听状态变量的变化,语法结构为: -``` +```ts @State @Watch("onChanged") count : number = 0 ``` -如上给状态变量增加一个@Watch装饰器,通过@Watch注册一个回调方法onChanged, 当状态变量count被改变时, 触发onChanged回调。 +如上所示,给状态变量增加一个@Watch装饰器,通过@Watch注册一个回调方法onChanged, 当状态变量count被改变时, 触发onChanged回调。 -装饰器@State、@Prop、@Link、@ObjectLink、@Provide、@Consume、@StorageProp以及@StorageLink装饰的变量可以监听其变化。 +装饰器@State、@Prop、@Link、@ObjectLink、@Provide、@Consume、@StorageProp以及@StorageLink所装饰的变量均可以通过@Watch监听其变化。 -``` +```ts // xxx.ets @Entry @Component struct CompA { - @State @Watch("onBasketUpdated") shopBasket : Array = [ 7, 12, 47, 3 ]; - @State totalPurchase : number = 0; - - updateTotal() : number { - let sum = 0; - this.shopBasket.forEach((i) => { sum += i; }); - // 计算新的购物篮总价值,如果超过100RMB,则适用折扣 - this.totalPurchase = (sum < 100) ? sum : 0.9 * sum; - return this.totalPurchase; - } + @State @Watch('onBasketUpdated') shopBasket: Array = [7, 12, 47, 3] + @State totalPurchase: number = 0 + @State addPurchase: number = 0 - // @Watch cb - onBasketUpdated(propName: string) : void { - this.updateTotal(); - } + aboutToAppear() { + this.updateTotal() + } + + updateTotal(): number { + let sum = 0; + this.shopBasket.forEach((i) => { + sum += i + }) + // 计算新的购物篮总价值,如果超过100,则适用折扣 + this.totalPurchase = (sum < 100) ? sum : 0.9 * sum + return this.totalPurchase + } - build() { - Column() { - Button("add to basket").onClick(() => { this.shopBasket.push(Math.round(100 * Math.random())) }) - Text(`${this.totalPurchase}`) - .fontSize(30) - } + // shopBasket更改时触发该方法 + onBasketUpdated(propName: string): void { + this.updateTotal() + } + + build() { + Column() { + Button('add to basket ' + this.addPurchase) + .margin(15) + .onClick(() => { + this.addPurchase = Math.round(100 * Math.random()) + this.shopBasket.push(this.addPurchase) + }) + Text(`${this.totalPurchase}`) + .fontSize(30) } + } } ``` \ No newline at end of file diff --git a/zh-cn/application-dev/quick-start/figures/appstorage.gif b/zh-cn/application-dev/quick-start/figures/appstorage.gif index 907447553819293cf3e7e143aec39116c4166d8d..74fb655faba656a8542c8b8dd1619c307565dbac 100644 Binary files a/zh-cn/application-dev/quick-start/figures/appstorage.gif and b/zh-cn/application-dev/quick-start/figures/appstorage.gif differ diff --git a/zh-cn/application-dev/quick-start/figures/appstorage1.gif b/zh-cn/application-dev/quick-start/figures/appstorage1.gif new file mode 100644 index 0000000000000000000000000000000000000000..1b61274beda905c252825ad7e821aec92b93cdc0 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/appstorage1.gif differ diff --git a/zh-cn/application-dev/quick-start/figures/appstorage2.gif b/zh-cn/application-dev/quick-start/figures/appstorage2.gif new file mode 100644 index 0000000000000000000000000000000000000000..c56396af8365fd8fcf8b5d019c25d628828303fc Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/appstorage2.gif differ diff --git a/zh-cn/application-dev/quick-start/figures/appstorage3.gif b/zh-cn/application-dev/quick-start/figures/appstorage3.gif new file mode 100644 index 0000000000000000000000000000000000000000..1538d1218f4f0ed987e50b4bb97d9abdb56781dc Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/appstorage3.gif differ diff --git a/zh-cn/application-dev/quick-start/figures/builder.PNG b/zh-cn/application-dev/quick-start/figures/builder.PNG new file mode 100644 index 0000000000000000000000000000000000000000..2f7d50693ba58a78fb0c42b12cf4d924d398dcd4 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/builder.PNG differ diff --git a/zh-cn/application-dev/quick-start/figures/builder1.PNG b/zh-cn/application-dev/quick-start/figures/builder1.PNG new file mode 100644 index 0000000000000000000000000000000000000000..4b78a289a0878cd120370ce1eaae8ef66c56a591 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/builder1.PNG differ diff --git a/zh-cn/application-dev/quick-start/figures/builder2.gif b/zh-cn/application-dev/quick-start/figures/builder2.gif new file mode 100644 index 0000000000000000000000000000000000000000..9b79d29ea8d25e4838f7bf798b00e7162d9ed3e7 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/builder2.gif differ diff --git a/zh-cn/application-dev/ui/figures/create-resource-file-1.png b/zh-cn/application-dev/quick-start/figures/create-resource-file-1.png similarity index 100% rename from zh-cn/application-dev/ui/figures/create-resource-file-1.png rename to zh-cn/application-dev/quick-start/figures/create-resource-file-1.png diff --git a/zh-cn/application-dev/ui/figures/create-resource-file-2.png b/zh-cn/application-dev/quick-start/figures/create-resource-file-2.png similarity index 100% rename from zh-cn/application-dev/ui/figures/create-resource-file-2.png rename to zh-cn/application-dev/quick-start/figures/create-resource-file-2.png diff --git a/zh-cn/application-dev/ui/figures/create-resource-file-3.png b/zh-cn/application-dev/quick-start/figures/create-resource-file-3.png similarity index 100% rename from zh-cn/application-dev/ui/figures/create-resource-file-3.png rename to zh-cn/application-dev/quick-start/figures/create-resource-file-3.png diff --git a/zh-cn/application-dev/quick-start/figures/customDialog.gif b/zh-cn/application-dev/quick-start/figures/customDialog.gif new file mode 100644 index 0000000000000000000000000000000000000000..e3788315f506df46d95b321a910cf81092677202 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/customDialog.gif differ diff --git a/zh-cn/application-dev/quick-start/figures/extend.PNG b/zh-cn/application-dev/quick-start/figures/extend.PNG new file mode 100644 index 0000000000000000000000000000000000000000..cf1c87c65db58084c8a62124c1f41f2b829c90cb Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/extend.PNG differ diff --git a/zh-cn/application-dev/quick-start/figures/forEach1.gif b/zh-cn/application-dev/quick-start/figures/forEach1.gif new file mode 100644 index 0000000000000000000000000000000000000000..8e9e35e98b8c5fec6baf58997ae78992a554e069 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/forEach1.gif differ diff --git a/zh-cn/application-dev/quick-start/figures/hello.PNG b/zh-cn/application-dev/quick-start/figures/hello.PNG new file mode 100644 index 0000000000000000000000000000000000000000..8098a2fc4ae0322c1a5b5a12d7cc0eb72ad073f5 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/hello.PNG differ diff --git a/zh-cn/application-dev/quick-start/figures/lazyForEach.gif b/zh-cn/application-dev/quick-start/figures/lazyForEach.gif new file mode 100644 index 0000000000000000000000000000000000000000..e8f92b92fd63c572e22964d8caa6132d318cf5bd Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/lazyForEach.gif differ diff --git a/zh-cn/application-dev/quick-start/figures/popup.gif b/zh-cn/application-dev/quick-start/figures/popup.gif new file mode 100644 index 0000000000000000000000000000000000000000..35c61c38947aea3c09c49e240fcc19bdb91e943f Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/popup.gif differ diff --git a/zh-cn/application-dev/quick-start/figures/styles.PNG b/zh-cn/application-dev/quick-start/figures/styles.PNG new file mode 100644 index 0000000000000000000000000000000000000000..46e3c761e72854f16a78e7cb3a0518a3d39e79e5 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/styles.PNG differ diff --git a/zh-cn/application-dev/quick-start/figures/styles1.gif b/zh-cn/application-dev/quick-start/figures/styles1.gif new file mode 100644 index 0000000000000000000000000000000000000000..7b72040aeaea3260bf9ccfdce0495d911d5752be Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/styles1.gif differ diff --git a/zh-cn/application-dev/ui/ui-ts-basic-resource-file-categories.md b/zh-cn/application-dev/quick-start/resource-categories-and-access.md similarity index 63% rename from zh-cn/application-dev/ui/ui-ts-basic-resource-file-categories.md rename to zh-cn/application-dev/quick-start/resource-categories-and-access.md index 09b1d6fcd32a9c22158c9b090fd8e9bad4a0b174..c06202130ca10ce0ea3f3944b90bb59dea4a07d5 100644 --- a/zh-cn/application-dev/ui/ui-ts-basic-resource-file-categories.md +++ b/zh-cn/application-dev/quick-start/resource-categories-and-access.md @@ -1,10 +1,12 @@ -# 资源文件的分类 +# 资源分类与访问 + +## 资源分类 应用开发中使用的各类资源文件,需要放入特定子目录中存储管理。 -## resources目录 +### resources目录 -应用的资源文件(字符串、图片、音频等)统一存放于resources目录下,便于开发者使用和维护。resources目录包括两大类目录,一类为base目录与限定词目录,另一类为rawfile目录,详见resources目录分类,stage模型多工程情况下共有的资源文件放到AppScope下的resources目录。 +resources目录包括三大类目录,一类为base目录,一类为限定词目录,还有一类为rawfile目录。stage模型多工程情况下共有的资源文件放到AppScope下的resources目录。 资源目录示例: @@ -23,7 +25,7 @@ resources |---rawfile ``` - **表1** resources目录分类 +**表1** resources目录分类 | 分类 | base目录 | 限定词目录 | rawfile目录 | | ---- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | @@ -32,15 +34,15 @@ resources | 引用方式 | 通过指定资源类型(type)和资源名称(name)来引用。 | 通过指定资源类型(type)和资源名称(name)来引用。 | 通过指定文件路径和文件名来引用。 | -## 限定词目录 +### 限定词目录 -限定词目录可以由一个或多个表征应用场景或设备特征的限定词组合而成,包括移动国家码和移动网络码、语言、文字、国家或地区、横竖屏、设备类型、颜色模式和屏幕密度等维度,限定词之间通过下划线(_)或者中划线(-)连接。开发者在创建限定词目录时,需要掌握限定词目录的命名要求,以及限定词目录与设备状态的匹配规则。 +限定词目录可以由一个或多个表征应用场景或设备特征的限定词组合而成,包括移动国家码和移动网络码、语言、文字、国家或地区、横竖屏、设备类型、颜色模式和屏幕密度等维度,限定词之间通过下划线(\_)或者中划线(\-)连接。开发者在创建限定词目录时,需要掌握限定词目录的命名要求,以及限定词目录与设备状态的匹配规则。 **限定词目录的命名要求** -- 限定词的组合顺序:_移动国家码_移动网络码-语言_文字_国家或地区-横竖屏-设备类型-颜色模式-屏幕密度_。开发者可以根据应用的使用场景和设备特征,选择其中的一类或几类限定词组成目录名称。 +- 限定词的组合顺序:\_移动国家码_移动网络码-语言_文字_国家或地区-横竖屏-设备类型-颜色模式-屏幕密度_。开发者可以根据应用的使用场景和设备特征,选择其中的一类或几类限定词组成目录名称。 -- 限定词的连接方式:语言、文字、国家或地区之间采用下划线(_)连接,移动国家码和移动网络码之间也采用下划线(_)连接,除此之外的其他限定词之间均采用中划线(-)连接。例如:**zh_Hant_CN**、**zh_CN-car-ldpi**。 +- 限定词的连接方式:语言、文字、国家或地区之间采用下划线(\_)连接,移动国家码和移动网络码之间也采用下划线(\_)连接,除此之外的其他限定词之间均采用中划线(-)连接。例如:**zh_Hant_CN**、**zh_CN-car-ldpi**。 - 限定词的取值范围:每类限定词的取值必须符合限定词取值要求表中的条件,否则,将无法匹配目录中的资源文件。 @@ -64,9 +66,9 @@ resources - 如果限定词目录中包含**移动国家码和移动网络码、语言、文字、横竖屏、设备类型、颜色模式**限定词,则对应限定词的取值必须与当前的设备状态完全一致,该目录才能够参与设备的资源匹配。例如,限定词目录“zh_CN-car-ldpi”不能参与“en_US”设备的资源匹配。 -## 资源组目录 +### 资源组目录 -base目录与限定词目录下面可以创建资源组目录(包括element、media、animation、layout、graphic、profile),用于存放特定类型的资源文件,详见资源组目录说明。 +base目录与限定词目录下面可以创建资源组目录(包括element、media、profile),用于存放特定类型的资源文件,详见资源组目录说明。 **表3** 资源组目录说明 @@ -77,9 +79,9 @@ base目录与限定词目录下面可以创建资源组目录(包括element、 | media | 表示媒体资源,包括图片、音频、视频等非文本格式的文件。 | 文件名可自定义,例如:icon.png。 | | rawfile | 表示其他类型文件,在应用构建为hap包后,以原始文件形式保存,不会被集成到resources.index文件中。 | 文件名可自定义。 | -### 媒体资源类型说明 +**媒体资源类型说明** -表1 图片资源类型说明 +**表4** 图片资源类型说明 | 格式 | 文件后缀名 | | ---- | ----- | @@ -90,7 +92,7 @@ base目录与限定词目录下面可以创建资源组目录(包括element、 | WEBP | .webp | | BMP | .bmp | -表2 音视频资源类型说明 +**表5** 音视频资源类型说明 | 格式 | 支持的文件类型 | | ------------------------------------ | --------------- | @@ -99,7 +101,94 @@ base目录与限定词目录下面可以创建资源组目录(包括element、 | MPEG-4 SP | .3gp | | VP8 | .webm
.mkv | -## 创建资源文件 +**资源文件示例** + +color.json文件的内容如下: + + +```json +{ + "color": [ + { + "name": "color_hello", + "value": "#ffff0000" + }, + { + "name": "color_world", + "value": "#ff0000ff" + } + ] +} +``` + +float.json文件的内容如下: + + +```json +{ + "float":[ + { + "name":"font_hello", + "value":"28.0fp" + }, + { + "name":"font_world", + "value":"20.0fp" + } + ] +} +``` + +string.json文件的内容如下: + + +```json +{ + "string":[ + { + "name":"string_hello", + "value":"Hello" + }, + { + "name":"string_world", + "value":"World" + }, + { + "name":"message_arrive", + "value":"We will arrive at %s." + } + ] +} +``` + +plural.json文件的内容如下: + + +```json +{ + "plural":[ + { + "name":"eat_apple", + "value":[ + { + "quantity":"one", + "value":"%d apple" + }, + { + "quantity":"other", + "value":"%d apples" + } + ] + } + ] +} +``` + +## 资源访问 + +### 应用资源 + +**创建资源文件** 在resources目录下,可按照限定词目录和资源组目录的说明创建子目录和目录内的文件。 @@ -129,4 +218,72 @@ base目录与限定词目录下面可以创建资源组目录(包括element、 例如,在element目录下可新建Element Resource File。 - ![create-resource-file-3](figures/create-resource-file-3.png) \ No newline at end of file + ![create-resource-file-3](figures/create-resource-file-3.png) + +**访问应用资源** + +在工程中,通过```"$r('app.type.name')"```的形式引用应用资源。app代表是应用内resources目录中定义的资源;type代表资源类型(或资源的存放位置),可以取“color”、“float”、“string”、“plural”、“media”,name代表资源命名,由开发者定义资源时确定。 + +引用rawfile下资源时使用```"$rawfile('filename')"```的形式,filename需要表示为rawfile目录下的文件相对路径,文件名需要包含后缀,路径开头不可以以"/"开头。 + +> **说明:** +> +> 资源描述符不能拼接使用,仅支持普通字符串如`'app.type.name'`。 +> +> `$r`返回值为Resource对象,可通过[getStringValue](../reference/apis/js-apis-resource-manager.md#getstringvalue9) 方法获取对应的字符串。 + +在xxx.ets文件中,可以使用在resources目录中定义的资源。 + +```ts +Text($r('app.string.string_hello')) + .fontColor($r('app.color.color_hello')) + .fontSize($r('app.float.font_hello')) +} + +Text($r('app.string.string_world')) + .fontColor($r('app.color.color_world')) + .fontSize($r('app.float.font_world')) +} + +Text($r('app.string.message_arrive', "five of the clock")) // 引用string资源,$r的第二个参数用于替换%s + .fontColor($r('app.color.color_hello')) + .fontSize($r('app.float.font_hello')) +} + +Text($r('app.plural.eat_apple', 5, 5)) // plural$r引用,第一个指定plural资源,第二个参数指定单复数的数量,此处第三个数字为对%d的替换 + .fontColor($r('app.color.color_world')) + .fontSize($r('app.float.font_world')) +} + +Image($r('app.media.my_background_image')) // media资源的$r引用 + +Image($rawfile('test.png')) // rawfile$r引用rawfile目录下图片 + +Image($rawfile('newDir/newTest.png')) // rawfile$r引用rawfile目录下图片 +``` + +### 系统资源 + +系统资源包含色彩、圆角、字体、间距、字符串及图片等。通过使用系统资源,不同的开发者可以开发出具有相同视觉风格的应用。 + + +开发者可以通过```“$r('sys.type.resource_id')”```的形式引用系统资源。sys代表是系统资源;type代表资源类型,可以取“color”、“float”、“string”、“media”;resource_id代表资源id。 + +```ts +Text('Hello') + .fontColor($r('sys.color.ohos_id_color_emphasize')) + .fontSize($r('sys.float.ohos_id_text_size_headline1')) + .fontFamily($r('sys.string.ohos_id_text_font_family_medium')) + .backgroundColor($r('sys.color.ohos_id_color_palette_aux1')) +Image($r('sys.media.ohos_app_icon')) + .border({color: $r('sys.color.ohos_id_color_palette_aux1'), radius: $r('sys.float.ohos_id_corner_radius_button'), width: 2}) + .margin({top: $r('sys.float.ohos_id_elements_margin_horizontal_m'), bottom: $r('sys.float.ohos_id_elements_margin_horizontal_l')}) + .height(200) + .width(300) +``` + +## 相关实例 + +针对访问应用资源,有以下相关实例可供参考: + +- [`ResourceManager`:资源管理器(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/ResourceManager) diff --git a/zh-cn/application-dev/quick-start/start-with-ets-fa.md b/zh-cn/application-dev/quick-start/start-with-ets-fa.md index 7dc4539e81e291b8b5f79774f4b69752588ad7bc..36eb3e0ddabb0bbe436aeced75fcff82037cc7b0 100644 --- a/zh-cn/application-dev/quick-start/start-with-ets-fa.md +++ b/zh-cn/application-dev/quick-start/start-with-ets-fa.md @@ -35,7 +35,7 @@ - **src > main > ets > MainAbility > pages**:MainAbility包含的页面。 - **src > main > ets > MainAbility > pages > index.ets**:pages列表中的第一个页面,即应用的首页入口。 - **src > main > ets > MainAbility > app.ets**:承载Ability生命周期。 - - **src > main > resources**:用于存放应用/服务所用到的资源文件,如图形、多媒体、字符串、布局文件等。关于资源文件,详见[资源文件的分类](../ui/ui-ts-basic-resource-file-categories.md)。 + - **src > main > resources**:用于存放应用/服务所用到的资源文件,如图形、多媒体、字符串、布局文件等。关于资源文件,详见[资源文件的分类](resource-categories-and-access.md#资源分类)。 - **src > main > config.json**:模块配置文件。主要包含HAP包的配置信息、应用/服务在具体设备上的配置信息以及应用/服务的全局配置信息。具体的配置文件说明,详见[应用包结构配置文件的说明(FA模型)](package-structure.md)。 - **build-profile.json5**:当前的模块信息 、编译信息配置项,包括buildOption、targets配置等。 - **hvigorfile.js**:模块级编译构建任务脚本,开发者可以自定义相关任务和代码实现。 diff --git a/zh-cn/application-dev/quick-start/start-with-ets-stage.md b/zh-cn/application-dev/quick-start/start-with-ets-stage.md index 8ff628f5a300a4257f6414431ef32d9e037e62f2..5c1a5e116eb4170e4930f924348eb9efebceaaad 100644 --- a/zh-cn/application-dev/quick-start/start-with-ets-stage.md +++ b/zh-cn/application-dev/quick-start/start-with-ets-stage.md @@ -40,7 +40,7 @@ - **src > main > ets > MainAbility**:应用/服务的入口。 - **src > main > ets > MainAbility > MainAbility.ts**:承载Ability生命周期。 - **src > main > ets > pages**:MainAbility包含的页面。 - - **src > main > resources**:用于存放应用/服务所用到的资源文件,如图形、多媒体、字符串、布局文件等。关于资源文件,详见[资源文件的分类](../ui/ui-ts-basic-resource-file-categories.md)。 + - **src > main > resources**:用于存放应用/服务所用到的资源文件,如图形、多媒体、字符串、布局文件等。关于资源文件,详见[资源文件的分类](resource-categories-and-access.md#资源分类)。 - **src > main > module.json5**:模块配置文件。主要包含HAP包的配置信息、应用/服务在具体设备上的配置信息以及应用/服务的全局配置信息。具体的配置文件说明,详见[应用包结构配置文件的说明(Stage模型)](stage-structure.md)。 - **build-profile.json5**:当前的模块信息 、编译信息配置项,包括buildOption、targets配置等。 - **hvigorfile.js**:模块级编译构建任务脚本,开发者可以自定义相关任务和代码实现。 @@ -54,7 +54,7 @@ 1. 使用文本组件。 - 工程同步完成后,在“**Project**”窗口,点击“**entry > src > main > ets > MainAbility > pages**”,打开“**index.ets**”文件,可以看到页面由Text组件组成。“**index.ets**”文件的示例如下: + 工程同步完成后,在“**Project**”窗口,点击“**entry > src > main > ets > pages**”,打开“**index.ets**”文件,可以看到页面由Text组件组成。“**index.ets**”文件的示例如下: ```ts // index.ets diff --git a/zh-cn/application-dev/reference/apis/Readme-CN.md b/zh-cn/application-dev/reference/apis/Readme-CN.md index 65a286bb55c14edf6ed87386f51421dafa959e4a..d1962ca8f56e2503059ef32127d66e045419bda2 100755 --- a/zh-cn/application-dev/reference/apis/Readme-CN.md +++ b/zh-cn/application-dev/reference/apis/Readme-CN.md @@ -195,7 +195,7 @@ - [@ohos.hiAppEvent (应用打点)](js-apis-hiappevent.md) - [@ohos.hichecker (检测模式)](js-apis-hichecker.md) - [@ohos.hidebug (Debug调试)](js-apis-hidebug.md) - - [@ohos.hilog (日志打印)](js-apis-hilog.md) + - [@ohos.hilog (HiLog日志打印)](js-apis-hilog.md) - [@ohos.hiSysEvent (系统事件打点)](js-apis-hisysevent.md) - [@ohos.hiTraceChain (分布式跟踪)](js-apis-hitracechain.md) - [@ohos.hiTraceMeter (性能打点)](js-apis-hitracemeter.md) @@ -209,6 +209,7 @@ - [@ohos.systemTimer(系统定时器)](js-apis-system-timer.md) - [@ohos.wallpaper (壁纸)](js-apis-wallpaper.md) - [@ohos.web.webview(Web)](js-apis-webview.md) + - [console (日志打印)](js-apis-logs.md) - [Timer (定时器)](js-apis-timer.md) - 设备管理 @@ -235,7 +236,7 @@ - [@ohos.systemParameter (系统属性)](js-apis-system-parameter.md) - [@ohos.thermal (热管理)](js-apis-thermal.md) - [@ohos.update (升级)](js-apis-update.md) - - [@ohos.usb (USB管理)](js-apis-usb.md) + - [@ohos.usbV9 (USB管理)](js-apis-usb.md) - [@ohos.vibrator (振动)](js-apis-vibrator.md) - 帐号管理 - [@ohos.account.appAccount (应用帐号管理)](js-apis-appAccount.md) @@ -273,6 +274,7 @@ - [@ohos.data.distributedData (分布式数据管理)](js-apis-distributed-data.md) - [@ohos.prompt (弹窗)](js-apis-prompt.md) - [@ohos.reminderAgent (后台代理提醒)](js-apis-reminderAgent.md) + - [@ohos.usb (USB管理)](js-apis-usb-deprecated.md) - [@system.app (应用上下文)](js-apis-system-app.md) - [@system.battery (电量信息)](js-apis-system-battery.md) - [@system.bluetooth (蓝牙)](js-apis-system-bluetooth.md) @@ -292,4 +294,3 @@ - [@system.sensor (传感器)](js-apis-system-sensor.md) - [@system.storage (数据存储)](js-apis-system-storage.md) - [@system.vibrator (振动)](js-apis-system-vibrate.md) - - [console (日志打印)](js-apis-logs.md) diff --git a/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md b/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md index 5d9652b9b8b19146444f6e689ba415becf2288e3..3bf7786bb7175ba951fbce561abe33050f5d8e52 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md +++ b/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md @@ -29,7 +29,7 @@ createAtManager(): AtManager **示例:** ```js -var AtManager = abilityAccessCtrl.createAtManager(); +let atManager = abilityAccessCtrl.createAtManager(); ``` ## AtManager @@ -38,7 +38,7 @@ var AtManager = abilityAccessCtrl.createAtManager(); ### checkAccessToken9+ -checkAccessToken(tokenID: number, permissionName: string): Promise<GrantStatus> +checkAccessToken(tokenID: number, permissionName: Permissions): Promise<GrantStatus> 校验应用是否授予权限。使用Promise异步回调。 @@ -49,7 +49,7 @@ checkAccessToken(tokenID: number, permissionName: string): Promise<GrantStatu | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------- | ---- | ------------------------------------------ | | tokenID | number | 是 | 要校验的目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得 | -| permissionName | string | 是 | 需要校验的权限名称。 | +| permissionName | Permissions | 是 | 需要校验的权限名称。 | **返回值:** @@ -69,10 +69,10 @@ checkAccessToken(tokenID: number, permissionName: string): Promise<GrantStatu ```js import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; -let AtManager = abilityAccessCtrl.createAtManager(); +let atManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId try { - AtManager.checkAccessToken(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS").then((data) => { + atManager.checkAccessToken(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS").then((data) => { console.log(`checkAccessToken success, data->${JSON.stringify(data)}`); }).catch((err) => { console.log(`checkAccessToken fail, err->${JSON.stringify(err)}`); @@ -84,7 +84,7 @@ try { ### verifyAccessTokenSync9+ -verifyAccessTokenSync(tokenID: number, permissionName: string): GrantStatus +verifyAccessTokenSync(tokenID: number, permissionName: Permissions): GrantStatus 校验应用是否被授予权限,同步返回结果。 @@ -95,7 +95,7 @@ verifyAccessTokenSync(tokenID: number, permissionName: string): GrantStatus | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------- | ---- | ------------------------------------------ | | tokenID | number | 是 | 要校验应用的身份标识。 | -| permissionName | string | 是 | 需要校验的权限名称。 | +| permissionName | Permissions | 是 | 需要校验的权限名称。 | **返回值:** @@ -113,15 +113,15 @@ verifyAccessTokenSync(tokenID: number, permissionName: string): GrantStatus **示例:** ```js -var AtManager = abilityAccessCtrl.createAtManager(); +let atManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; -let data = AtManager.verifyAccessTokenSync(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); +let data = atManager.verifyAccessTokenSync(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); console.log(`data->${JSON.stringify(data)}`); ``` ### grantUserGrantedPermission -grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number): Promise<void> +grantUserGrantedPermission(tokenID: number, permissionName: Permissions, permissionFlag: number): Promise<void> 授予应用user grant权限。使用Promise异步回调。 @@ -136,7 +136,7 @@ grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFl | 参数名 | 类型 | 必填 | 说明 | | --------- | ------------------- | ---- | ------------------------------------------------------------ | | tokenID | number | 是 | 目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得 | -| permissionName | string | 是 | 被授予的权限名称。 | +| permissionName | Permissions | 是 | 被授予的权限名称。 | | permissionFlag | number | 是 | 授权选项,1表示下次仍需弹窗,2表示允许、禁止后不再提醒,3表示系统授权不允许更改。 | **返回值:** @@ -160,11 +160,11 @@ grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFl ```js import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; -let AtManager = abilityAccessCtrl.createAtManager(); +let atManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId let permissionFlag = 1; try { - AtManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag).then(() => { + atManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag).then(() => { console.log('grantUserGrantedPermission success'); }).catch((err) => { console.log(`grantUserGrantedPermission fail, err->${JSON.stringify(err)}`); @@ -176,7 +176,7 @@ try { ### grantUserGrantedPermission -grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number, callback: AsyncCallback<void>): void +grantUserGrantedPermission(tokenID: number, permissionName: Permissions, permissionFlag: number, callback: AsyncCallback<void>): void 授予应用user grant权限。使用callback异步回调。 @@ -191,7 +191,7 @@ grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFl | 参数名 | 类型 | 必填 | 说明 | | --------- | ------------------- | ---- | ------------------------------------------------------------ | | tokenID | number | 是 | 目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得 | -| permissionName | string | 是 | 被授予的权限名称。 | +| permissionName | Permissions | 是 | 被授予的权限名称。 | | permissionFlag | number | 是 | 授权选项,1表示下次仍需弹窗,2表示允许、禁止后不再提醒,3表示系统授权不允许更改。 | | callback | AsyncCallback<void> | 是 | 授予应用user grant权限。当授予权限成功时,err为undefine;否则为错误对象。 | @@ -210,11 +210,11 @@ grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFl ```js import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; -var AtManager = abilityAccessCtrl.createAtManager(); +let atManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId let permissionFlag = 1; try { - AtManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag, (err, data) => { + atManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag, (err, data) => { if (err) { console.log(`grantUserGrantedPermission fail, err->${JSON.stringify(err)}`); } else { @@ -228,7 +228,7 @@ try { ### revokeUserGrantedPermission -revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number): Promise<void> +revokeUserGrantedPermission(tokenID: number, permissionName: Permissions, permissionFlag: number): Promise<void> 撤销应用user grant权限。使用Promise异步回调。 @@ -243,7 +243,7 @@ revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionF | 参数名 | 类型 | 必填 | 说明 | | --------- | ------------------- | ---- | ------------------------------------------------------------ | | tokenID | number | 是 | 目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得 | -| permissionName | string | 是 | 被撤销的权限名称。 | +| permissionName | Permissions | 是 | 被撤销的权限名称。 | | permissionFlag | number | 是 | 授权选项,1表示下次仍需弹窗,2表示允许、禁止后不再提醒,3表示系统授权不允许更改。 | **返回值:** @@ -267,11 +267,11 @@ revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionF ```js import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; -let AtManager = abilityAccessCtrl.createAtManager(); +let atManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId let permissionFlag = 1; try { - AtManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag).then(() => { + atManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag).then(() => { console.log('revokeUserGrantedPermission success'); }).catch((err) => { console.log(`revokeUserGrantedPermission fail, err->${JSON.stringify(err)}`); @@ -283,7 +283,7 @@ try { ### revokeUserGrantedPermission -revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number, callback: AsyncCallback<void>): void +revokeUserGrantedPermission(tokenID: number, permissionName: Permissions, permissionFlag: number, callback: AsyncCallback<void>): void 撤销应用user grant权限。使用callback异步回调。 @@ -298,7 +298,7 @@ revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionF | 参数名 | 类型 | 必填 | 说明 | | --------- | ------------------- | ---- | ------------------------------------------------------------ | | tokenID | number | 是 | 目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得 | -| permissionName | string | 是 | 被撤销的权限名称。 | +| permissionName | Permissions | 是 | 被撤销的权限名称。 | | permissionFlag | number | 是 | 授权选项,1表示下次仍需弹窗,2表示允许、禁止后不再提醒,3表示系统授权不允许更改。 | | callback | AsyncCallback<void> | 是 | 撤销应用user grant权限。当撤销权限成功时,err为undefine;否则为错误对象。 | @@ -317,11 +317,11 @@ revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionF ```js import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; -var AtManager = abilityAccessCtrl.createAtManager(); +let atManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId let permissionFlag = 1; try { - AtManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag, (err, data) => { + atManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag, (err, data) => { if (err) { console.log(`revokeUserGrantedPermission fail, err->${JSON.stringify(err)}`); } else { @@ -335,7 +335,7 @@ try { ### getPermissionFlags -getPermissionFlags(tokenID: number, permissionName: string): Promise<number> +getPermissionFlags(tokenID: number, permissionName: Permissions): Promise<number> 获取指定应用的指定权限的flag。使用Promise异步回调。 @@ -350,7 +350,7 @@ getPermissionFlags(tokenID: number, permissionName: string): Promise<number&g | 参数名 | 类型 | 必填 | 说明 | | --------- | ------------------- | ---- | ------------------------------------------------------------ | | tokenID | number | 是 | 目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得 | -| permissionName | string | 是 | 查询的权限名称。 | +| permissionName | Permissions | 是 | 查询的权限名称。 | **返回值:** @@ -373,11 +373,11 @@ getPermissionFlags(tokenID: number, permissionName: string): Promise<number&g ```js import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; -let AtManager = abilityAccessCtrl.createAtManager(); +let atManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId let permissionFlag = 1; try { - AtManager.getPermissionFlags(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS").then((data) => { + atManager.getPermissionFlags(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS").then((data) => { console.log(`getPermissionFlags success, data->${JSON.stringify(data)}`); }).catch((err) = > { console.log(`getPermissionFlags fail, err->${JSON.stringify(err)}`); @@ -406,8 +406,8 @@ getVersion(): Promise<number> **示例:** ```js -var AtManager = abilityAccessCtrl.createAtManager(); -let promise = AtManager.getVersion(); +let atManager = abilityAccessCtrl.createAtManager(); +let promise = atManager.getVersion(); promise.then(data => { console.log(`promise: data->${JSON.stringify(data)}`); }); @@ -415,7 +415,7 @@ promise.then(data => { ### on9+ -on(type: 'permissionStateChange', tokenIDList: Array<number>, permissionNameList: Array<string>, callback: Callback<PermissionStateChangeInfo>): void; +on(type: 'permissionStateChange', tokenIDList: Array<number>, permissionNameList: Array<Permissions>, callback: Callback<PermissionStateChangeInfo>): void; 订阅指定tokenId列表与权限列表的权限状态变更事件。 @@ -431,7 +431,7 @@ on(type: 'permissionStateChange', tokenIDList: Array<number>, permissionNa | ------------------ | --------------------- | ---- | ------------------------------------------------------------ | | type | string | 是 | 订阅事件类型,固定为'permissionStateChange',权限状态变更事件。 | | tokenIDList | Array<number> | 否 | 订阅的tokenId列表,为空时表示订阅所有的应用的权限状态变化。 | -| permissionNameList | Array<string> | 否 | 订阅的权限名列表,为空时表示订阅所有的权限状态变化。 | +| permissionNameList | Array<Permissions> | 否 | 订阅的权限名列表,为空时表示订阅所有的权限状态变化。 | | callback | Callback<[PermissionStateChangeInfo](#permissionstatechangeinfo9)> | 是 | 订阅指定tokenId与指定权限名状态变更事件的回调。| **错误码:** @@ -450,7 +450,7 @@ import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); let tokenIDList: Array = []; -let permissionNameList: Array = []; +let permissionNameList: Array = []; try { atManager.on('permissionStateChange', tokenIDList, permissionNameList, (data) => { console.debug("receive permission state change, data:" + JSON.stringify(data)); @@ -462,7 +462,7 @@ try { ### off9+ -off(type: 'permissionStateChange', tokenIDList: Array<number>, permissionNameList: Array<string>, callback?: Callback<PermissionStateChangeInfo>): void; +off(type: 'permissionStateChange', tokenIDList: Array<number>, permissionNameList: Array<Permissions>, callback?: Callback<PermissionStateChangeInfo>): void; 取消订阅指定tokenId列表与权限列表的权限状态变更事件,使用callback回调异步返回结果。 @@ -478,7 +478,7 @@ off(type: 'permissionStateChange', tokenIDList: Array<number>, permissionN | ------------------ | --------------------- | ---- | ------------------------------------------------------------ | | type | string | 是 | 订阅事件类型,固定为'permissionStateChange',权限状态变更事件。 | | tokenIDList | Array<number> | 否 | 订阅的tokenId列表,为空时表示订阅所有的应用的权限状态变化,必须与on的输入一致。 | -| permissionNameList | Array<string> | 否 | 订阅的权限名列表,为空时表示订阅所有的权限状态变化,必须与on的输入一致。 | +| permissionNameList | Array<Permissions> | 否 | 订阅的权限名列表,为空时表示订阅所有的权限状态变化,必须与on的输入一致。 | | callback | Callback<[PermissionStateChangeInfo](#permissionstatechangeinfo9)> | 否 | 取消订阅指定tokenId与指定权限名状态变更事件的回调。| **错误码:** @@ -496,7 +496,7 @@ import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); let tokenIDList: Array = []; -let permissionNameList: Array = []; +let permissionNameList: Array = []; try { atManager.off('permissionStateChange', tokenIDList, permissionNameList); } catch(err) { @@ -504,6 +504,42 @@ try { } ``` +### verifyAccessToken9+ + +verifyAccessToken(tokenID: number, permissionName: Permissions): Promise<GrantStatus> + +校验应用是否授予权限。使用Promise异步回调。 + +> **说明:** 建议使用[checkAccessToken](#checkaccesstoken9)替代。 + +**系统能力:** SystemCapability.Security.AccessToken + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------- | ---- | ------------------------------------------ | +| tokenID | number | 是 | 要校验的目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得。 | +| permissionName | Permissions | 是 | 需要校验的权限名称。仅支持输入有效的权限名称。 | + +**返回值:** + +| 类型 | 说明 | +| :------------ | :---------------------------------- | +| Promise<GrantStatus> | Promise对象。返回授权状态结果。 | + +**示例:** + +```js +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; + +let atManager = abilityAccessCtrl.createAtManager(); +let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId +let promise = atManager.verifyAccessToken(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); +promise.then(data => { + console.log(`promise: data->${JSON.stringify(data)}`); +}); +``` + ### verifyAccessToken(deprecated) verifyAccessToken(tokenID: number, permissionName: string): Promise<GrantStatus> @@ -532,9 +568,9 @@ verifyAccessToken(tokenID: number, permissionName: string): Promise<GrantStat ```js import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; -var AtManager = abilityAccessCtrl.createAtManager(); +let atManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId -let promise = AtManager.verifyAccessToken(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); +let promise = atManager.verifyAccessToken(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); promise.then(data => { console.log(`promise: data->${JSON.stringify(data)}`); }); @@ -576,4 +612,4 @@ promise.then(data => { | -------------- | ------------------------- | ---- | ---- | ------------------ | | change | [PermissionStateChangeType](#permissionstatechangetype9) | 是 | 否 | 权限授权状态变化类型 | | tokenID | number | 是 | 否 | 被订阅的应用身份标识 | -| permissionName | string | 是 | 否 | 当前授权状态发生变化的权限名 | +| permissionName | Permissions | 是 | 否 | 当前授权状态发生变化的权限名 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-appAccount.md b/zh-cn/application-dev/reference/apis/js-apis-appAccount.md index a11141d837c647265bb39b925f4d3a54d5cf6d28..2cd6742fd00715e88dac368cb493f1979790f96e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-appAccount.md +++ b/zh-cn/application-dev/reference/apis/js-apis-appAccount.md @@ -1,6 +1,6 @@ # 应用帐号管理 -本模块不仅用于对应用帐号的添加、删除、查询、修改和授权,且提供帐号将数据写入磁盘和数据同步的能力。 +本模块提供应用帐号信息的添加、删除、修改和查询基础能力,并支持应用间鉴权和分布式数据同步功能。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 @@ -17,7 +17,7 @@ import account_appAccount from '@ohos.account.appAccount'; createAppAccountManager(): AppAccountManager -获取应用帐号模块的对象。 +创建应用帐号管理器对象。 **系统能力:** SystemCapability.Account.AppAccount @@ -25,51 +25,51 @@ createAppAccountManager(): AppAccountManager | 类型 | 说明 | | ----------------- | ------------ | -| AppAccountManager | 获取应用帐号模块的实例。 | +| AppAccountManager | 应用帐号管理器对象。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); ``` ## AppAccountManager -管理应用帐号模块的实例。 +应用帐号管理器类。 ### createAccount9+ createAccount(name: string, callback: AsyncCallback<void>): void; -将此应用的帐号名添加到帐号管理服务中。使用callback异步回调。 +根据帐号名创建应用帐号。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | -------------------- | -| name | string | 是 | 要添加的应用帐号名称。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当此应用的帐号名添加到帐号管理服务成功时,err为undefined,否则为错误对象。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ----- | -------------------- | +| name | string | 是 | 应用帐号的名称。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当创建成功时,err为null,否则为错误对象。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name or options. | - | 12300008 | the account indicated by name already exist. | - | 12300011 | the account number has reached the upper limit. | +| 错误码ID | 错误信息 | +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name. | +| 12300004 | Account already exists. | +| 12300007 | The number of accounts reaches the upper limit. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.createAccount("WangWu", (err) => { - console.log("createAccount err: " + JSON.stringify(err)); - }); + appAccountManager.createAccount("WangWu", (err) => { + console.log("createAccount err: " + JSON.stringify(err)); + }); } catch (err) { - console.log("createAccount err: " + JSON.stringify(err)); + console.log("createAccount err: " + JSON.stringify(err)); } ``` @@ -77,7 +77,7 @@ createAccount(name: string, callback: AsyncCallback<void>): void; createAccount(name: string, options: CreateAccountOptions, callback: AsyncCallback<void>): void -将此应用程序的帐号名和额外信息(能转换string类型的其它信息,如token)添加到帐号管理服务中。使用callback异步回调。 +根据帐号名和可选项创建应用帐号。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -85,42 +85,47 @@ createAccount(name: string, options: CreateAccountOptions, callback: AsyncCallba | 参数名 | 类型 | 必填 | 说明 | | --------- | ------------------------- | ---- | ---------------------------------------- | -| name | string | 是 | 要添加的应用帐号名称。 | -| options | [CreateAccountOptions](#createaccountoptions9) | 是 | 要添加的应用帐号的选项,选项中不能包含应用帐号的敏感信息(如应用帐号密码)。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当此应用程序的帐号名和额外信息添加到帐号管理服务成功时,err为undefined,否则为错误对象。 | +| name | string | 是 | 应用帐号的名称。 | +| options | [CreateAccountOptions](#createaccountoptions9) | 是 | 创建应用帐号的选项,可提供自定义数据,但不建议包含敏感数据(如密码、Token等)。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当创建成功时,err为null,否则为错误对象。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name or options. | - | 12300008 | the account indicated by name already exist. | - | 12300011 | the account number has reached the upper limit. | +| 错误码ID | 错误信息 | +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or options. | +| 12300004 | Account already exists. | +| 12300007 | The number of accounts reaches the upper limit. | +| 12400003 | The number of custom data reaches the upper limit. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); + let options = { + customData: { + "age": "10" + } + } try { - var option : CreateAccountOptions = { - customData: { - "age":10 - } + appAccountManager.createAccount("LiSi", options, (err) => { + if (err) { + console.log("createAccount failed, error: " + JSON.stringify(err)); + } else { + console.log("createAccount successfully"); } - appAccountManager.createAccount("LiSi", option, (err) => { - console.log("createAccount err: " + JSON.stringify(err)); - }); - } catch (err) { - console.log("createAccount err: " + JSON.stringify(err)); + }); + } catch(err) { + console.log("createAccount exception: " + JSON.stringify(err)); } ``` ### createAccount9+ -createAccount(name: string, extraInfo?: string): Promise<void> +createAccount(name: string, options?: CreateAccountOptions): Promise<void> -将此应用的帐号名或额外信息(能转换成string类型的其它信息)添加到帐号管理服务中。使用Promise异步回调。 +根据帐号名和可选项创建应用帐号。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -128,8 +133,8 @@ createAccount(name: string, extraInfo?: string): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | --------- | ------ | ---- | ---------------------------------------- | -| name | string | 是 | 要添加的应用帐号名称。 | -| options | [CreateAccountOptions](#createaccountoptions9) | 否 | 要添加的应用帐号的选项,选项中不能包含应用帐号的敏感信息(如应用帐号密码),不填写不附带选项信息。 | +| name | string | 是 | 应用帐号的名称。 | +| options | [CreateAccountOptions](#createaccountoptions9) | 否 | 创建应用帐号的选项,可提供自定义数据,但不建议包含敏感数据(如密码、Token等)。不填无影响。 | **返回值:** @@ -139,30 +144,31 @@ createAccount(name: string, extraInfo?: string): Promise<void> **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name or options. | - | 12300008 | the account indicated by name already exist. | - | 12300011 | the account number has reached the upper limit. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or options. | +| 12300004 | Account already exists. | +| 12300007 | The number of accounts reaches the upper limit. | +| 12400003 | The number of custom data reaches the upper limit. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); + let options = { + customData: { + "age": "10" + } + } try { - var option : CreateAccountOptions = { - customData: { - "age":10 - } - } - appAccountManager.createAccount("LiSi", option).then(()=> { - console.log('createAccount Success'); - }).catch((err) => { - console.log("createAccount err: " + JSON.stringify(err)); - }); - } catch (err) { - console.log("createAccount err: " + JSON.stringify(err)); + appAccountManager.createAccount("LiSi", options).then(() => { + console.log("createAccount successfully"); + }).catch((err) => { + console.log("createAccount failed, error: " + JSON.stringify(err)); + }); + } catch(err) { + console.log("createAccount exception: " + JSON.stringify(err)); } ``` @@ -170,25 +176,27 @@ createAccount(name: string, extraInfo?: string): Promise<void> createAccountImplicitly(owner: string, callback: AuthCallback): void -根据指定的帐号所有者隐式地添加应用帐号,并使用callback回调异步返回结果。 +根据指定的帐号所有者隐式地创建应用帐号。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------- | ---- | ----------------------- | -| owner | string | 是 | 要添加的应用帐号所有者包名。 | -| callback | [AuthCallback](#authcallback9) | 是 | 认证回调,用于返回鉴权结果。 | +| owner | string | 是 | 应用帐号所有者的包名。 | +| callback | [AuthCallback](#authcallback9) | 是 | 认证器回调对象,返回创建结果。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name or options. | - | 12300011 | the account number has reached the upper limit. | - | 12300008 | the account authenticator service does not exist. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid owner. | +| 12300007 | The number of accounts reaches the upper limit. | +| 12300010 | Account service busy. | +| 12300113 | Authenticator service not found. | +| 12300114 | Authenticator service exception. | **示例:** @@ -196,25 +204,25 @@ createAccountImplicitly(owner: string, callback: AuthCallback): void import featureAbility from '@ohos.ability.featureAbility'; function onResultCallback(code, result) { - console.log("resultCode: " + code); - console.log("result: " + JSON.stringify(result)); + console.log("resultCode: " + code); + console.log("result: " + JSON.stringify(result)); } function onRequestRedirectedCallback(request) { - let abilityStartSetting = {want: request}; - featureAbility.startAbility(abilityStartSetting, (err)=>{ - console.log("startAbility err: " + JSON.stringify(err)); - }); + let abilityStartSetting = {want: request}; + featureAbility.startAbility(abilityStartSetting, (err) => { + console.log("startAbility err: " + JSON.stringify(err)); + }); } - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.createAccountImplicitly("com.example.ohos.accountjsdemo", { - onResult: onResultCallback, - onRequestRedirected: onRequestRedirectedCallback - }); + appAccountManager.createAccountImplicitly("com.example.accountjsdemo", { + onResult: onResultCallback, + onRequestRedirected: onRequestRedirectedCallback + }); } catch (err) { - console.log("createAccountImplicitly err: " + JSON.stringify(err)); + console.log("createAccountImplicitly exception: " + JSON.stringify(err)); } ``` @@ -222,7 +230,7 @@ createAccountImplicitly(owner: string, callback: AuthCallback): void createAccountImplicitly(owner: string, options: CreateAccountImplicitlyOptions, callback: AuthCallback): void -根据指定的帐号所有者和可选项隐式地添加应用帐号,并使用callback回调异步返回结果。 +根据指定的帐号所有者和可选项隐式地创建应用帐号。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -230,18 +238,20 @@ createAccountImplicitly(owner: string, options: CreateAccountImplicitlyOptions, | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------- | ---- | ----------------------- | -| owner | string | 是 | 要添加的应用帐号所有者包名。 | -| options | [CreateAccountImplicitlyOptions](#createaccountimplicitlyoptions9) | 是 | 隐式创建账号的选项。 | -| callback | [AuthCallback](#authcallback9) | 是 | 认证回调,用于返回鉴权结果。 | +| owner | string | 是 | 应用帐号所有者的包名。 | +| options | [CreateAccountImplicitlyOptions](#createaccountimplicitlyoptions9) | 是 | 隐式创建账号的选项。 | +| callback | [AuthCallback](#authcallback9) | 是 | 认证器回调对象,返回创建结果。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name or options. | - | 12300011 | the account number has reached the upper limit. | - | 12300008 | the account authenticator service does not exist. | +| 错误码ID | 错误信息 | +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or options. | +| 12300007 | The number of accounts reaches the upper limit. | +| 12300010 | Account service busy. | +| 12300113 | Authenticator service not found. | +| 12300114 | Authenticator service exception. | **示例:** @@ -249,35 +259,37 @@ createAccountImplicitly(owner: string, options: CreateAccountImplicitlyOptions, import featureAbility from '@ohos.ability.featureAbility'; function onResultCallback(code, result) { - console.log("resultCode: " + code); - console.log("result: " + JSON.stringify(result)); + console.log("resultCode: " + code); + console.log("result: " + JSON.stringify(result)); } function onRequestRedirectedCallback(request) { - let abilityStartSetting = {want: request}; - featureAbility.startAbility(abilityStartSetting, (err)=>{ - console.log("startAbility err: " + JSON.stringify(err)); - }); + let abilityStartSetting = {want: request}; + featureAbility.startAbility(abilityStartSetting, (err) => { + console.log("startAbility err: " + JSON.stringify(err)); + }); } - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); + let options = { + authType: "getSocialData", + requiredLabels: [ "student" ] + }; try { - appAccountManager.createAccountImplicitly("com.example.ohos.accountjsdemo", { - requiredLabels: ["student"], authType: "getSocialData"}, { - onResult: onResultCallback, - onRequestRedirected: onRequestRedirectedCallback + appAccountManager.createAccountImplicitly("com.example.accountjsdemo", options, { + onResult: onResultCallback, + onRequestRedirected: onRequestRedirectedCallback }); } catch (err) { - console.log("createAccountImplicitly err: " + JSON.stringify(err)); + console.log("createAccountImplicitly exception: " + JSON.stringify(err)); } - ``` ### removeAccount9+ removeAccount(name: string, callback: AsyncCallback<void>): void -从帐号管理服务中移除应用帐号。使用callback异步回调。 +删除应用帐号。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -285,36 +297,39 @@ removeAccount(name: string, callback: AsyncCallback<void>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ---------------- | -| name | string | 是 | 要删除的应用帐号名称。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当帐号管理服务中移除应用帐号成功时,err为undefined,否则为错误对象。 | +| name | string | 是 | 应用帐号的名称。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当删除成功时,err为null,否则为错误对象。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name. | - | 12300003 | the account indicated by name dose not exist. | +| 错误码ID | 错误信息 | +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name. | +| 12300003 | Account not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.removeAccount("ZhaoLiu", (err) => { - console.log("removeAccount err: " + JSON.stringify(err)); + appAccountManager.removeAccount("ZhaoLiu", (err) => { + if (err) { + console.log("removeAccount failed, error: " + JSON.stringify(err)); + } else { + console.log("removeAccount successfully"); + } }); - } catch (err) { - console.log("removeAccount err: " + JSON.stringify(err)); + } catch(err) { + console.log("removeAccount exception: " + JSON.stringify(err)); } - ``` ### removeAccount9+ -deleteAccount(name: string): Promise<void> +removeAccount(name: string): Promise<void> -从帐号管理服务中移除应用帐号。使用Promise异步回调。 +删除应用帐号。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -322,7 +337,7 @@ deleteAccount(name: string): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | ---- | ------ | ---- | ----------- | -| name | string | 是 | 要移除的应用帐号名称。 | +| name | string | 是 | 应用帐号的名称。 | **返回值:** @@ -332,73 +347,75 @@ deleteAccount(name: string): Promise<void> **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name. | - | 12300003 | the account indicated by name dose not exist. | +| 错误码ID | 错误信息 | +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name. | +| 12300003 | Account not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.deleteAccount("ZhaoLiu").then(() => { - console.log('removeAccount Success'); - }).catch((err) => { - console.log("removeAccount err: " + JSON.stringify(err)); - }); + appAccountManager.removeAccount("Lisi").then(() => { + console.log("removeAccount successfully"); + }).catch((err) => { + console.log("removeAccount failed, error: " + JSON.stringify(err)); + }); } catch (err) { - console.log("removeAccount err: " + JSON.stringify(err)); + console.log("removeAccount exception: " + JSON.stringify(err)); } - ``` ### setAppAccess9+ setAppAccess(name: string, bundleName: string, isAccessible: boolean, callback: AsyncCallback<void>): void -设置指定第三方应用帐号名称对指定包名称的第三方应用的访问权限,由isAccessible指明是允许访问还是禁止访问,callback回调异步返回结果。 +设置指定应用对特定帐号的访问权限。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------- | ---- | --------------------------------- | -| name | string | 是 | 应用帐号名称。 | -| bundleName | string | 是 | 第三方应用的包名。 | -| isAccessible | boolean | 是 | 访问控制,允许访问或禁止访问。 | -| callback | AsyncCallback<void> | 是 | 访问权限设置的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------------ | ------------------------- | ---- | --------------------------------- | +| name | string | 是 | 应用帐号的名称。 | +| bundleName | string | 是 | 第三方应用的包名。 | +| isAccessible | boolean | 是 | 是否可访问。true表示允许访问,false表示禁止访问。 | +| callback | AsyncCallback<void> | 是 | 回调函数,如果设置成功,err为null,否则为错误对象。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name or bundlename. | - | 12300003 | the account indicated by localId dose not exist. | - | 12400001 | the application indicated by bundlename does not exist. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or bundleName. | +| 12300003 | Account not found. | +| 12400001 | Application not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.setAppAccess("ZhangSan", "com.example.ohos.accountjsdemo", true, (err) => { - console.log("enableAppAccess: " + JSON.stringify(err)); - }); + appAccountManager.setAppAccess("ZhangSan", "com.example.accountjsdemo", true, (err) => { + if (err) { + console.log("setAppAccess failed: " + JSON.stringify(err)); + } else { + console.log("setAppAccess successfully"); + } + }); } catch (err) { - console.log("enableAppAccess: " + JSON.stringify(err)); + console.log("setAppAccess exception: " + JSON.stringify(err)); } - ``` ### setAppAccess9+ setAppAccess(name: string, bundleName: string, isAccessible: boolean): Promise<void> -设置指定第三方应用帐号名称对指定包名称的第三方应用的访问权限,由isAccessible指明是允许访问还是禁止访问。使用Promise异步回调。 +设置指定应用对特定帐号的数据访问权限。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -406,9 +423,9 @@ setAppAccess(name: string, bundleName: string, isAccessible: boolean): Promise&l | 参数名 | 类型 | 必填 | 说明 | | ---------- | ------ | ---- | --------- | -| name | string | 是 | 应用帐号名称。 | +| name | string | 是 | 应用帐号的名称。 | | bundleName | string | 是 | 第三方应用的包名。 | -| isAccessible | boolean | 是 | 访问控制,允许访问或禁止访问。 | +| isAccessible | boolean | 是 | 是否可访问。true表示允许访问,false表示禁止访问。 | **返回值:** @@ -418,25 +435,25 @@ setAppAccess(name: string, bundleName: string, isAccessible: boolean): Promise&l **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name or bundlename. | - | 12300003 | the account indicated by localId dose not exist. | - | 12400001 | the application indicated by bundlename does not exist. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or bundleName. | +| 12300003 | Account not found. | +| 12400001 | Application not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.setAppAccess("ZhangSan", "com.example.ohos.accountjsdemo", true).then(() => { - console.log('setAppAccess Success'); - }).catch((err) => { - console.log("setAppAccess err: " + JSON.stringify(err)); - }); + appAccountManager.setAppAccess("ZhangSan", "com.example.accountjsdemo", true).then(() => { + console.log("setAppAccess successfully"); + }).catch((err) => { + console.log("setAppAccess failed: " + JSON.stringify(err)); + }); } catch (err) { - console.log("setAppAccess err: " + JSON.stringify(err)); + console.log("setAppAccess exception: " + JSON.stringify(err)); } ``` @@ -444,7 +461,7 @@ setAppAccess(name: string, bundleName: string, isAccessible: boolean): Promise&l checkAppAccess(name: string, bundleName: string, callback: AsyncCallback<boolean>): void -查看指定第三方应用帐号名称对指定包名称的第三方应用的访问权限,callback回调异步返回结果。 +检查指定应用对特定帐号的数据是否可访问。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -452,38 +469,41 @@ checkAppAccess(name: string, bundleName: string, callback: AsyncCallback<bool | 参数名 | 类型 | 必填 | 说明 | | ---------- | ------------------------- | ---- | --------------------------------- | -| name | string | 是 | 应用帐号名称。 | +| name | string | 是 | 应用帐号的名称。 | | bundleName | string | 是 | 第三方应用的包名。 | -| callback | AsyncCallback<void> | 是 | 查看访问权限的回调。 | +| callback | AsyncCallback<void> | 是 | 回调函数。返回true表示指定应用可访问特定帐号的数据;返回false表示不可访问。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name or bundlename. | - | 12300003 | the account indicated by localId dose not exist. | - | 12400001 | the application indicated by bundlename does not exist. | +| 错误码ID | 错误信息 | +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or bundleName. | +| 12300003 | Account not found. | +| 12400001 | Application not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.checkAppAccess("ZhangSan", "com.example.ohos.accountjsdemo", (err) => { - console.log("checkAppAccess: " + JSON.stringify(err)); - }); + appAccountManager.checkAppAccess("ZhangSan", "com.example.accountjsdemo", (err, isAccessible) => { + if (err) { + console.log("checkAppAccess failed, error: " + JSON.stringify(err)); + } else { + console.log("checkAppAccess successfully"); + } + }); } catch (err) { - console.log("checkAppAccess: " + JSON.stringify(err)); + console.log("checkAppAccess exception: " + JSON.stringify(err)); } - ``` ### checkAppAccess9+ -checkAppAccess(name: string, bundleName: string): Promise<void> +checkAppAccess(name: string, bundleName: string): Promise<boolean> -查看指定第三方应用帐号名称对指定包名称的第三方应用的访问权限。使用Promise异步回调。 +检查指定应用对特定帐号的数据是否可访问。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -491,45 +511,44 @@ checkAppAccess(name: string, bundleName: string): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | ---------- | ------ | ---- | --------- | -| name | string | 是 | 应用帐号名称。 | +| name | string | 是 | 应用帐号的名称。 | | bundleName | string | 是 | 第三方应用的包名。 | **返回值:** | 类型 | 说明 | -| :------------------ | :-------------------- | -| Promise<void> | Promise对象。无返回结果的Promise对象。 | +| ------------------- | --------------------- | +| Promise<boolean> | Promise对象,返回true表示指定应用可访问特定帐号的数据;返回false表示不可访问。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name or bundlename. | - | 12300003 | the account indicated by localId dose not exist. | - | 12400001 | the application indicated by bundlename does not exist. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or bundleName. | +| 12300003 | Account not found. | +| 12400001 | Application not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.checkAppAccess("ZhangSan", "com.example.ohos.accountjsdemo").then(() => { - console.log('checkAppAccess Success'); - }).catch((err) => { - console.log("checkAppAccess err: " + JSON.stringify(err)); - }); + appAccountManager.checkAppAccess("ZhangSan", "com.example.accountjsdemo").then((isAccessible) => { + console.log("checkAppAccess successfully, isAccessible: " + isAccessible); + }).catch((err) => { + console.log("checkAppAccess failed, error: " + JSON.stringify(err)); + }); } catch (err) { - console.log("checkAppAccess err: " + JSON.stringify(err)); + console.log("checkAppAccess exception: " + JSON.stringify(err)); } - ``` -### checkDataSyncEnabled9+ +### setDataSyncEnabled9+ -checkDataSyncEnabled(name: string, callback: AsyncCallback<boolean>): void +setDataSyncEnabled(name: string, isEnabled: boolean, callback: AsyncCallback<void>): void -检查指定应用帐号是否允许应用数据同步。使用callback异步回调。 +开启或禁止指定应用帐号的数据同步功能。使用callback异步回调。 **需要权限:** ohos.permission.DISTRIBUTED_DATASYNC @@ -537,39 +556,38 @@ checkDataSyncEnabled(name: string, callback: AsyncCallback<boolean>): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------- | ---- | --------------------- | -| name | string | 是 | 应用帐号名称。 | -| callback | AsyncCallback<boolean> | 是 | 回调函数。返回true表示指定应用帐号允许应用数据同步;返回false表示指定应用帐号不允许应用数据同步。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ------------------------- | +| name | string | 是 | 应用帐号的名称。 | +| isEnabled | boolean | 是 | 是否开启数据同步。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当开启或禁止成功时,err为null,否则为错误对象。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name. | - | 12300003 | the account indicated by localId dose not exist. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name. | +| 12300003 | Account not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.checkDataSyncEnabled("ZhangSan", (err, result) => { - console.log("checkDataSyncEnabled err: " + JSON.stringify(err)); - console.log('checkDataSyncEnabled result: ' + result); + appAccountManager.setDataSyncEnabled("ZhangSan", true, (err) => { + console.log("setDataSyncEnabled err: " + JSON.stringify(err)); }); } catch (err) { - console.log("checkDataSyncEnabled err: " + JSON.stringify(err)); + console.log("setDataSyncEnabled err: " + JSON.stringify(err)); } - ``` -### checkDataSyncEnabled9+ +### setDataSyncEnabled9+ -checkDataSyncEnabled(name: string): Promise<boolean> +setDataSyncEnabled(name: string, isEnabled: boolean): Promise<void> -检查指定应用帐号是否允许应用数据同步。使用Promise异步回调。 +开启或禁止指定应用帐号的数据同步功能。使用Promise异步回调。 **需要权限:** ohos.permission.DISTRIBUTED_DATASYNC @@ -577,663 +595,679 @@ checkDataSyncEnabled(name: string): Promise<boolean> **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---- | ------ | ---- | ------- | -| name | string | 是 | 应用帐号名称。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------- | ---- | ----------- | +| name | string | 是 | 应用帐号的名称。 | +| isEnabled | boolean | 是 | 是否开启数据同步。 | **返回值:** -| 类型 | 说明 | -| :--------------------- | :-------------------- | -| Promise<boolean> | Promise对象。返回true表示允许应用数据同步;返回false表示不允许应用数据同步。 | +| 类型 | 说明 | +| :------------------ | :-------------------- | +| Promise<void> | Promise对象。无返回结果的Promise对象。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name. | - | 12300003 | the account indicated by localId dose not exist. | +| 错误码ID | 错误信息 | +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name. | +| 12300003 | Account not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.checkDataSyncEnabled("ZhangSan").then((data) => { - console.log('checkDataSyncEnabled, result: ' + data); + appAccountManager .setDataSyncEnabled("ZhangSan", true).then(() => { + console.log('setDataSyncEnabled Success'); }).catch((err) => { - console.log("checkDataSyncEnabled err: " + JSON.stringify(err)); + console.log("setDataSyncEnabled err: " + JSON.stringify(err)); }); } catch (err) { - console.log("checkDataSyncEnabled err: " + JSON.stringify(err)); + console.log("setDataSyncEnabled err: " + JSON.stringify(err)); } - ``` -### setCredential9+ +### checkDataSyncEnabled9+ -setCredential(name: string, credentialType: string, credential: string,callback: AsyncCallback<void>): void +checkDataSyncEnabled(name: string, callback: AsyncCallback<boolean>): void + +检查指定应用帐号是否开启数据同步功能。使用callback异步回调。 -设置此应用程序帐号的凭据。使用callback异步回调。 +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------------- | ------------------------- | ---- | ------------- | -| name | string | 是 | 应用程序帐号名称。 | -| credentialType | string | 是 | 要设置的凭据类型。 | -| credential | string | 是 | 要设置的凭据。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当设置此应用程序帐号的凭据成功时,err为undefined,否则为错误对象。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------- | ---- | --------------------- | +| name | string | 是 | 应用帐号的名称。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。返回true表示指定应用帐号已开启数据同步功能;返回false表示未开启。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name or credentialType. | - | 12300003 | the account indicated by localId dose not exist. | +| 错误码ID | 错误信息 | +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name. | +| 12300003 | Account not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.setCredential("ZhangSan", "credentialType001", "credential001", (err) => { - console.log("setCredential err: " + JSON.stringify(err)); - }); + appAccountManager.checkDataSyncEnabled("ZhangSan", (err, isEnabled) => { + if (err) { + console.log("checkDataSyncEnabled failed, err: " + JSON.stringify(err)); + } else { + console.log('checkDataSyncEnabled successfully, isEnabled: ' + isEnabled); + } + }); } catch (err) { - console.log("setCredential err: " + JSON.stringify(err)); + console.log("checkDataSyncEnabled err: " + JSON.stringify(err)); } ``` -### setCredential9+ +### checkDataSyncEnabled9+ -setCredential(name: string, credentialType: string, credential: string): Promise<void> +checkDataSyncEnabled(name: string): Promise<boolean> -设置此应用程序帐号的凭据。使用Promise异步回调。 +检查指定应用帐号是否开启数据同步功能。使用Promise异步回调。 -> **说明:** 从API version 9开始废弃。 -> -> 从 API version 7开始支持。 +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------------- | ------ | ---- | ---------- | -| name | string | 是 | 应用帐号的名称。 | -| credentialType | string | 是 | 要设置的凭据的类型。 | -| credential | string | 是 | 要设置的凭据。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---- | ------ | ---- | ------- | +| name | string | 是 | 应用帐号的名称。 | **返回值:** -| 类型 | 说明 | -| :------------------ | :-------------------- | -| Promise<void> | Promise对象。无返回结果的Promise对象。 | +| 类型 | 说明 | +| :--------------------- | :-------------------- | +| Promise<boolean> | Promise对象,返回true表示指定应用帐号已开启数据同步功能;返回false表示未开启。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name or credentialType. | - | 12300003 | the account indicated by localId dose not exist. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name. | +| 12300003 | Account not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.setCredential("ZhangSan", "credentialType001", "credential001").then(() => { - console.log('setCredential Success'); - }).catch((err) => { - console.log("setCredential err: " + JSON.stringify(err)); - }); + appAccountManager.checkDataSyncEnabled("ZhangSan").then((isEnabled) => { + console.log("checkDataSyncEnabled successfully, isEnabled: " + isEnabled); + }).catch((err) => { + console.log("checkDataSyncEnabled failed, err: " + JSON.stringify(err)); + }); } catch (err) { - console.log("setCredential err: " + JSON.stringify(err)); + console.log("checkDataSyncEnabled err: " + JSON.stringify(err)); } - ``` - -### setDataSyncEnabled9+ -setDataSyncEnabled(name: string, isEnable: boolean, callback: AsyncCallback<void>): void +### setCredential9+ -设置指定的应用程序帐号是否允许应用程序数据同步。使用callback异步回调。 +setCredential(name: string, credentialType: string, credential: string,callback: AsyncCallback<void>): void -**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC +设置指定应用帐号的凭据。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | ------------------------- | -| name | string | 是 | 应用帐号名称。 | -| isEnable | boolean | 是 | 是否允许应用数据同步。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当指定的应用帐号是否允许应用程序数据设置成功时,err为undefined,否则为错误对象。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------------- | ------------------------- | ---- | ------------- | +| name | string | 是 | 应用帐号的名称。 | +| credentialType | string | 是 | 凭据类型。 | +| credential | string | 是 | 凭据取值。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当凭据设置成功时,err为null,否则为错误对象。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name. | - | 12300003 | the account indicated by name dose not exist. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or credentialType or credential. | +| 12300003 | Account not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.setDataSyncEnabled("ZhangSan", true, (err) => { - console.log("setDataSyncEnabled err: " + JSON.stringify(err)); - }); + appAccountManager.setCredential("ZhangSan", "PIN_SIX", "xxxxxx", (err) => { + if (err) { + console.log("setCredential failed, error: " + JSON.stringify(err)); + } else { + console.log("setCredential successfully"); + } + }); } catch (err) { - console.log("setDataSyncEnabled err: " + JSON.stringify(err)); + console.log("setCredential exception: " + JSON.stringify(err)); } ``` -### setDataSyncEnabled9+ - -setDataSyncEnabled(name: string, isEnable: boolean): Promise<void> +### setCredential9+ -设置指定的应用程序帐号是否允许应用程序数据同步。使用Promise异步回调。 +setCredential(name: string, credentialType: string, credential: string): Promise<void> -**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC +设置指定应用帐号的凭据。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------- | ---- | ----------- | -| name | string | 是 | 应用帐号名称。 | -| isEnable | boolean | 是 | 是否允许应用数据同步。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------------- | ------ | ---- | ---------- | +| name | string | 是 | 应用帐号的名称。 | +| credentialType | string | 是 | 凭据类型。 | +| credential | string | 是 | 凭据取值。 | **返回值:** -| 类型 | 说明 | +| 类型 | 说明 | | :------------------ | :-------------------- | | Promise<void> | Promise对象。无返回结果的Promise对象。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name. | - | 12300003 | the account indicated by name dose not exist. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or credentialType or credential. | +| 12300003 | Account not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager .setDataSyncEnabled("ZhangSan", true).then(() => { - console.log('setDataSyncEnabled Success'); - }).catch((err) => { - console.log("setDataSyncEnabled err: " + JSON.stringify(err)); - }); + appAccountManager.setCredential("ZhangSan", "PIN_SIX", "xxxxxx").then(() => { + console.log("setCredential successfully"); + }).catch((err) => { + console.log("setCredential failed, error: " + JSON.stringify(err)); + }); } catch (err) { - console.log("setDataSyncEnabled err: " + JSON.stringify(err)); + console.log("setCredential exception: " + JSON.stringify(err)); } ``` -### setCustomData9+ +### getCredential9+ -setAssociatedData(name: string, key: string, value: string, callback: AsyncCallback<void>): void +getCredential(name: string, credentialType: string, callback: AsyncCallback<string>): void -设置与此应用程序帐号关联的数据。使用callback异步回调。 +获取指定应用帐号的凭据。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | ----------------- | -| name | string | 是 | 应用帐号名称。 | -| key | string | 是 | 要设置的数据的键,密钥可以自定义。 | -| value | string | 是 | 要设置的数据的值。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当设置与此应用帐号关联的数据成功时,err为undefined,否则为错误对象。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------------- | --------------------------- | ---- | -------------- | +| name | string | 是 | 应用帐号的名称。 | +| credentialType | string | 是 | 凭据类型。 | +| callback | AsyncCallback<string> | 是 | 回调函数。当获取凭据成功时,err为null,data为指定应用帐号的凭据;否则为错误对象。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name, key or value. | - | 12300003 | the account indicated by name dose not exist. | - | 12400008 | the number of customized data has reached the upper limit. | +| 错误码ID | 错误信息 | +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or credentialType. | +| 12300003 | Account not found. | +| 12300102 | Credential not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.setCustomData("ZhangSan", "k001", "v001", (err) => { - console.log("setCustomData err: " + JSON.stringify(err)); - }); + appAccountManager.getCredential("ZhangSan", "PIN_SIX", (err, result) => { + if (err) { + console.log("getCredential failed, error: " + JSON.stringify(err)); + } else { + console.log('getCredential successfully, result: ' + result); + } + }); } catch (err) { - console.log("setCustomData err: " + JSON.stringify(err)); + console.log("getCredential err: " + JSON.stringify(err)); } ``` -### setCustomData9+ +### getCredential9+ -setAssociatedData(name: string, key: string, value: string): Promise<void> +getCredential(name: string, credentialType: string): Promise<string> -设置与此应用程序帐号关联的数据。使用Promise异步回调。 +获取指定应用帐号的凭据。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ----- | ------ | ---- | ----------------- | -| name | string | 是 | 应用帐号名称。 | -| key | string | 是 | 要设置的数据的键,密钥可以自定义。 | -| value | string | 是 | 要设置的数据的值。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------------- | ------ | ---- | ---------- | +| name | string | 是 | 应用帐号的名称。 | +| credentialType | string | 是 | 凭据类型。 | **返回值:** -| 类型 | 说明 | -| :------------------ | :-------------------- | -| Promise<void> | Promise对象。无返回结果的Promise对象。 | +| 类型 | 说明 | +| :-------------------- | :-------------------- | +| Promise<string> | Promise对象,返回指定应用帐号的凭据。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name, key or value. | - | 12300003 | the account indicated by name dose not exist. | - | 12400008 | the number of customized data has reached the upper limit. | +| 错误码ID | 错误信息 | +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or credentialType. | +| 12300003 | Account not found. | +| 12300102 | Credential not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.setCustomData("ZhangSan", "k001", "v001").then(() => { - console.log('setCustomData Success'); - }).catch((err) => { - console.log("setCustomData err: " + JSON.stringify(err)); - }); + appAccountManager.getCredential("ZhangSan", "PIN_SIX").then((credential) => { + console.log("getCredential successfully, credential: " + credential); + }).catch((err) => { + console.log("getCredential failed, error: " + JSON.stringify(err)); + }); } catch (err) { - console.log("setCustomData err: " + JSON.stringify(err)); + console.log("getCredential exception: " + JSON.stringify(err)); } ``` -### getAllAccounts9+ - -getAllAccounts(callback: AsyncCallback<Array<AppAccountInfo>>): void +### setCustomData9+ -获取全部应用已授权帐号信息。 +setCustomData(name: string, key: string, value: string, callback: AsyncCallback<void>): void -**需要权限:** ohos.permission.GET_ALL_APP_ACCOUNTS,仅系统应用可用。 +设置指定应用帐号的自定义数据。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | --------- | -| callback | AsyncCallback<Array<[AppAccountInfo](#appaccountinfo)>> | 是 | 应用帐号信息列表。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ----------------- | +| name | string | 是 | 应用帐号的名称。 | +| key | string | 是 | 自定义数据的键名。 | +| value | string | 是 | 自定义数据的取值。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当设置自定义数据成功时,err为null,否则为错误对象。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or key or value. | +| 12300003 | Account not found. | +| 12400003 | The number of custom data reaches the upper limit. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.getAllAccounts((err, data)=>{ - console.debug("getAllAccounts err:" + JSON.stringify(err)); - console.debug("getAllAccounts data:" + JSON.stringify(data)); - }); + appAccountManager.setCustomData("ZhangSan", "age", "12", (err) => { + if (err) { + console.log("setCustomData failed, error: " + JSON.stringify(err)); + } else { + console.log("setCustomData successfully"); + } + }); } catch (err) { - console.debug("getAllAccounts err:" + JSON.stringify(err)); + console.log("setCustomData exception: " + JSON.stringify(err)); } ``` -### getAllAccounts9+ - -getAllAccounts(): Promise<Array<AppAccountInfo>> +### setCustomData9+ -获取全部应用已授权帐号信息。 +setCustomData(name: string, key: string, value: string): Promise<void> -**需要权限:** ohos.permission.GET_ALL_APP_ACCOUNTS,仅系统应用可用。 +设置指定应用帐号的自定义数据。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | ----------------- | +| name | string | 是 | 应用帐号的名称。 | +| key | string | 是 | 自定义数据的键名。 | +| value | string | 是 | 自定义数据的取值。 | + **返回值:** -| 类型 | 说明 | -| ---------------------------------------- | --------------------- | -| Promise<Array<[AppAccountInfo](#appaccountinfo)>> | Promise对象。返回全部应用已授权帐号信息对象。 | +| 类型 | 说明 | +| :------------------ | :-------------------- | +| Promise<void> | Promise对象。无返回结果的Promise对象。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or key or value. | +| 12300003 | Account not found. | +| 12400003 | The number of custom data reaches the upper limit. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.getAllAccounts().then((data) => { - console.log('getAllAccounts: ' + data); - }).catch((err) => { - console.log("getAllAccounts err: " + JSON.stringify(err)); - }); + appAccountManager.setCustomData("ZhangSan", "age", "12").then(() => { + console.log("setCustomData successfully"); + }).catch((err) => { + console.log("setCustomData failed, error: " + JSON.stringify(err)); + }); } catch (err) { - console.log("getAllAccounts err: " + JSON.stringify(err)); + console.log("setCustomData exception: " + JSON.stringify(err)); } ``` -### getAccountsByOwner9+ - -getAccountsByOwner(owner: string, callback: AsyncCallback<Array<AppAccountInfo>>): void +### getCustomData9+ -获取指定应用全部帐号信息。 +getCustomData(name: string, key: string, callback: AsyncCallback<string>): void -**需要权限:** ohos.permission.GET_ALL_APP_ACCOUNTS,仅系统应用可用。 +根据指定键名获取特定应用帐号的自定义数据。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | --------- | -| owner | string | 是 | 应用包名称。 | -| callback | AsyncCallback<Array<[AppAccountInfo](#appaccountinfo)>> | 是 | 应用帐号信息列表。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------- | ----- | ------------------------ | +| name | string | 是 | 应用帐号的名称。 | +| key | string | 是 | 自定义数据的键名。 | +| callback | AsyncCallback<string> | 是 | 回调函数。当获取成功时,err为null,data为自定义数据的取值;否则为错误对象。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid owner. | - | 12300003 | the account indicated by owner dose not exist. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or key. | +| 12300003 | Account not found. | +| 12400002 | Custom data not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - const selfBundle = "com.example.actsgetallaaccounts"; + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.getAccountsByOwner(selfBundle, (err, data)=>{ - console.debug("getAccountsByOwner err:" + JSON.stringify(err)); - console.debug("getAccountsByOwner data:" + JSON.stringify(data)); - }); + appAccountManager.getCustomData("ZhangSan", "age", (err, data) => { + if (err) { + console.log('getCustomData failed, error: ' + err); + } else { + console.log("getCustomData successfully, data: " + data); + } + }); } catch (err) { - console.debug("getAccountsByOwner err:" + JSON.stringify(err)); + console.log("getCustomData exception: " + JSON.stringify(err)); } ``` -### getAccountsByOwner9+ - -getAccountsByOwner(owner: string): Promise<Array<AppAccountInfo>> +### getCustomData9+ -获取指定应用全部帐号信息。 +getCustomData(name: string, key: string): Promise<string> -**需要权限:** ohos.permission.GET_ALL_APP_ACCOUNTS,仅系统应用可用。 +根据指定键名获取特定应用帐号的自定义数据。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ----- | ------ | ---- | ------ | -| owner | string | 是 | 应用包名称。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---- | ------ | ---- | --------- | +| name | string | 是 | 应用帐号的名称。 | +| key | string | 是 | 自定义数据的键名。 | **返回值:** -| 类型 | 说明 | -| ---------------------------------------- | --------------------- | -| Promise<Array<[AppAccountInfo](#appaccountinfo)>> | Promise对象。返回指定应用全部帐号信息对象。 | +| 类型 | 说明 | +| --------------------- | --------------------- | +| Promise<string> | Promise对象,返回自定义数据的取值。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid owner. | - | 12300003 | the account indicated by owner dose not exist. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or key. | +| 12300003 | Account not found. | +| 12400002 | Custom data not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - const selfBundle = "com.example.actsgetallaaccounts"; + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.getAccountsByOwner(selfBundle).then((data) => { - console.log('getAccountsByOwner: ' + data); - }).catch((err) => { - console.log("getAccountsByOwner err: " + JSON.stringify(err)); - }); + appAccountManager.getCustomData("ZhangSan", "age").then((data) => { + console.log("getCustomData successfully, data: " + data); + }).catch((err) => { + console.log("getCustomData failed, error: " + JSON.stringify(err)); + }); } catch (err) { - console.log("getAccountsByOwner err: " + JSON.stringify(err)); + console.log("getCustomData exception: " + JSON.stringify(err)); } ``` -### getCredential9+ +### getCustomDataSync9+ -getCredential(name: string, credentialType: string, callback: AsyncCallback<string>): void +getCustomDataSync(name: string, key: string): string; -获取此应用帐号的凭据(如数字密码、人脸和PIN码等)。使用callback异步回调。 +根据指定键名获取特定应用帐号的自定义数据。使用同步方式返回结果。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------------- | --------------------------- | ---- | -------------- | -| name | string | 是 | 应用帐号名称。 | -| credentialType | string | 是 | 获取此应用帐号的凭据的类型。 | -| callback | AsyncCallback<string> | 是 | 回调函数。当获取此应用帐号的凭据成功时,err为undefined,data返回此应用帐号的凭据对象;否则为错误对象。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---- | ------ | ---- | --------- | +| name | string | 是 | 应用帐号的名称。 | +| key | string | 是 | 自定义数据的键名。 | + +**返回值:** + +| 类型 | 说明 | +| --------------------- | --------------------- | +| string | 自定义数据的取值。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name or credentialType. | - | 12300003 | the account indicated by name dose not exist. | - | 12300019 | credential does not exist. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or key. | +| 12300003 | Account not found. | +| 12400002 | Custom data not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.getCredential("ZhangSan", "credentialType001", (err, result) => { - console.log("getCredential err: " + JSON.stringify(err)); - console.log('getCredential result: ' + result); - }); + let value = appAccountManager.getCustomDataSync("ZhangSan", "age"); + console.info("getCustomDataSync successfully, vaue:" + value); } catch (err) { - console.log("getCredential err: " + JSON.stringify(err)); + console.error("getCustomDataSync failed, error: " + JSON.stringify(err)); } ``` -### getCredential9+ +### getAllAccounts9+ -getCredential(name: string, credentialType: string): Promise<string> +getAllAccounts(callback: AsyncCallback<Array<AppAccountInfo>>): void -获取此应用程序帐号的凭据。使用Promise异步回调。 +获取所有可访问的应用帐号信息。使用callback异步回调。 + +**需要权限:** ohos.permission.GET_ALL_APP_ACCOUNTS。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------------- | ------ | ---- | ---------- | -| name | string | 是 | 应用帐号名称。 | -| credentialType | string | 是 | 要获取的凭据的类型。 | - -**返回值:** - -| 类型 | 说明 | -| :-------------------- | :-------------------- | -| Promise<string> | Promise对象。返回此应用程序帐号的凭据对象。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | --------- | +| callback | AsyncCallback<Array<[AppAccountInfo](#appaccountinfo)>> | 是 | 回调函数。当查询成功时,err为null,data为获取到的应用帐号信息列表;否则为错误对象。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name or credentialType. | - | 12300003 | the account indicated by name dose not exist. | - | 12300019 | credential does not exist. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.getCredential("ZhangSan", "credentialType001").then((data) => { - console.log('getCredential, result: ' + data); - }).catch((err) => { - console.log("getCredential err: " + JSON.stringify(err)); - }); + appAccountManager.getAllAccounts((err, data) => { + if (err) { + console.debug("getAllAccounts failed, error:" + JSON.stringify(err)); + } else { + console.debug("getAllAccounts successfully"); + } + }); } catch (err) { - console.log("getCredential err: " + JSON.stringify(err)); + console.debug("getAllAccounts exception: " + JSON.stringify(err)); } ``` -### getCustomData9+ +### getAllAccounts9+ -getCustomData(name: string, key: string, callback: AsyncCallback<string>): void +getAllAccounts(): Promise<Array<AppAccountInfo>> -获取与此应用程序帐号关联的数据。使用callback异步回调。 +获取所有可访问的应用帐号信息。使用Promise异步回调。 + +**需要权限:** ohos.permission.GET_ALL_APP_ACCOUNTS。 **系统能力:** SystemCapability.Account.AppAccount -**参数:** +**返回值:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------- | ---- | ----------------- | -| name | string | 是 | 应用帐号名称。 | -| key | string | 是 | 要获取的数据的键。 | -| callback | AsyncCallback<string> | 是 | 回调函数。当获取与此应用程序帐号关联的数据成功时,err为undefined,data返回与此应用程序帐号关联的数据对象;否则为错误对象。 | +| 类型 | 说明 | +| ---------------------------------------- | --------------------- | +| Promise<Array<[AppAccountInfo](#appaccountinfo)>> | Promise对象,返回全部应用已授权帐号信息对象。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name or key. | - | 12300003 | the account indicated by name dose not exist. | - | 12400009 | the customData does not exist. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.getCustomData("ZhangSan", "k001", (err, result) => { - console.log("getCustomData err: " + JSON.stringify(err)); - console.log('getCustomData result: ' + result); - }); + appAccountManager.getAllAccounts().then((data) => { + console.debug("getAllAccounts successfully"); + }).catch((err) => { + console.debug("getAllAccounts failed, error:" + JSON.stringify(err)); + }); } catch (err) { - console.log("getCustomData err: " + JSON.stringify(err)); + console.debug("getAllAccounts exception: " + JSON.stringify(err)); } ``` -### getCustomData9+ +### getAccountsByOwner9+ -getCustomData(name: string, key: string): Promise<string> +getAccountsByOwner(owner: string, callback: AsyncCallback<Array<AppAccountInfo>>): void -获取与此应用程序帐号关联的数据。使用Promise异步回调。 +根据应用帐号所有者获取调用方可访问的应用帐号列表。使用callback异步回调。 + +**需要权限:** ohos.permission.GET_ALL_APP_ACCOUNTS。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---- | ------ | ---- | --------- | -| name | string | 是 | 应用帐号名称。 | -| key | string | 是 | 要获取的数据的键。 | - -**返回值:** - -| 类型 | 说明 | -| :-------------------- | :-------------------- | -| Promise<string> | Promise对象。返回与此应用程序帐号关联的数据对象。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | --------- | +| owner | string | 是 | 应用帐号所有者的包名。 | +| callback | AsyncCallback<Array<[AppAccountInfo](#appaccountinfo)>> | 是 | 回调函数。如果获取成功,err为null,data为获取到的应用帐号列表;否则为错误对象。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name or key. | - | 12300003 | the account indicated by name dose not exist. | - | 12400009 | the customData does not exist. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid owner. | +| 12400001 | Application not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.getCustomData("ZhangSan", "k001").then((data) => { - console.log('getCustomData: ' + data); - }).catch((err) => { - console.log("getCustomData err: " + JSON.stringify(err)); - }); + appAccountManager.getAccountsByOwner("com.example.accountjsdemo2", (err, data) => { + if (err) { + console.debug("getAccountsByOwner failed, error:" + JSON.stringify(err)); + } else { + console.debug("getAccountsByOwner successfully, data:" + JSON.stringify(data)); + } + }); } catch (err) { - console.log("getCustomData err: " + JSON.stringify(err)); + console.debug("getAccountsByOwner exception:" + JSON.stringify(err)); } ``` -### getCustomDataSync9+ +### getAccountsByOwner9+ + +getAccountsByOwner(owner: string): Promise<Array<AppAccountInfo>> -getCustomDataSync(name: string, key: string): string; +根据应用帐号所有者获取调用方可访问的应用帐号列表。使用Promise异步回调。 -获取与此应用程序帐号关联的数据,使用同步方式返回结果。 +**需要权限:** ohos.permission.GET_ALL_APP_ACCOUNTS。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---- | ------ | ---- | --------- | -| name | string | 是 | 应用帐号名称。 | -| key | string | 是 | 要获取的数据的键。 | +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | ------ | +| owner | string | 是 | 应用帐号所有者的包名。 | **返回值:** -| 类型 | 说明 | -| :-------------------- | :-------------------- | -| string | 目标关联数据的取值。 | +| 类型 | 说明 | +| ---------------------------------------- | --------------------- | +| Promise<Array<[AppAccountInfo](#appaccountinfo)>> | Promise对象,返回获取到的应用帐号列表。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name or key. | - | 12300003 | the account indicated by name dose not exist. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid owner. | +| 12400001 | Application not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - var backData = appAccountManager.getCustomDataSync("ZhangSan", "k001"); - console.info("getCustomDataSync backData:" + JSON.stringify(backData)); + appAccountManager.getAccountsByOwner("com.example.accountjsdemo2").then((data) => { + console.debug("getAccountsByOwner successfully, data:" + JSON.stringify(data)); + }).catch((err) => { + console.debug("getAccountsByOwner failed, error:" + JSON.stringify(err)); + }); } catch (err) { - console.error(`getCustomDataSync err, code is ${e.code}, message is ${e.message}`); + console.debug("getAccountsByOwner exception:" + JSON.stringify(err)); } ``` @@ -1241,7 +1275,7 @@ getCustomDataSync(name: string, key: string): string; on(type: 'accountChange', owners: Array<string>, callback: Callback<Array<AppAccountInfo>>): void -订阅指定帐号所有者的帐户变更事件。使用callback异步回调。 +订阅指定应用的帐号信息变更事件。 **系统能力:** SystemCapability.Account.AppAccount @@ -1249,31 +1283,30 @@ on(type: 'accountChange', owners: Array<string>, callback: Callback<Arr | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ------------------------------ | -| type | 'accountChange' | 是 | 事件回调类型,支持的事件为'accountChange',当帐号所有者更新帐号时,触发该事件。 | -| owners | Array<string> | 是 | 指示帐号的所有者。 | -| callback | Callback<Array<[AppAccountInfo](#appaccountinfo)>> | 是 | 回调函数。返回指定帐号所有者更新的帐号信息对象数组。 | +| type | 'accountChange' | 是 | 事件回调类型,支持的事件为'accountChange',当目标应用更新帐号信息时,触发该事件。 | +| owners | Array<string> | 是 | 应用帐号所有者的包名列表。 | +| callback | Callback<Array<[AppAccountInfo](#appaccountinfo)>> | 是 | 回调函数,返回信息发生变更的应用帐号列表。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid type or owners. | - | 12300003 | the account indicated by owners dose not exist. | - | 12300005 | the listener has been registered. | +| 错误码ID | 错误信息 | +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid type or owners. | +| 12300011 | Callback has been registered. | +| 12400001 | Application not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); function changeOnCallback(data){ - console.debug("receive change data:" + JSON.stringify(data)); + console.log("receive change data:" + JSON.stringify(data)); } try{ - appAccountManager.on('accountChange', ["com.example.actsaccounttest"], changeOnCallback); - } - catch(err){ - console.error("on accountOnOffDemo err:" + JSON.stringify(err)); + appAccountManager.on("accountChange", ["com.example.actsaccounttest"], changeOnCallback); + } catch(err) { + console.error("on accountChange failed, error:" + JSON.stringify(err)); } ``` @@ -1281,7 +1314,7 @@ on(type: 'accountChange', owners: Array<string>, callback: Callback<Arr off(type: 'accountChange', callback?: Callback>): void -取消订阅帐号事件。使用callback异步回调。 +取消订阅帐号信息变更事件。 **系统能力:** SystemCapability.Account.AppAccount @@ -1289,32 +1322,34 @@ off(type: 'accountChange', callback?: Callback>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------------- | ---- | ------------ | -| type | 'accountChange' | 是 | 事件回调类型,支持的事件为'accountChange',当帐号所有者更新帐号时,触发该事件。 | -| callback | Callback> | 否 | 回调函数,返回指定帐号所有者更新的帐号信息数组。 | +| type | 'accountChange' | 是 | 事件回调类型,支持的事件为'accountChange',当帐号所有者更新帐号信息时,触发该事件。 | +| callback | Callback> | 否 | 回调函数,返回信息发生变更的应用帐号列表。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid type. | - | 12300005 | the listener has been registered. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid type. | +| 12300012 | Callback has not been registered. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); function changeOnCallback(data){ - console.debug("receive change data:" + JSON.stringify(data)); - appAccountManager.off('accountChange', function(){ - console.debug("off finish"); - }) + console.log("receive change data:" + JSON.stringify(data)); + } + try{ + appAccountManager.on("accountChange", ["com.example.actsaccounttest"], changeOnCallback); + } catch(err) { + console.error("on accountChange failed, error:" + JSON.stringify(err)); } try{ - appAccountManager.on('accountChange', ["com.example.actsaccounttest"], changeOnCallback); + appAccountManager.off('accountChange', changeOnCallback); } catch(err){ - console.error("on accountOnOffDemo err:" + JSON.stringify(err)); + console.error("off accountChange failed, error:" + JSON.stringify(err)); } ``` @@ -1322,7 +1357,7 @@ off(type: 'accountChange', callback?: Callback>): void auth(name: string, owner: string, authType: string, callback: AuthCallback): void -对应用帐户进行鉴权以获取Auth令牌。使用callback异步回调。 +对应用帐号进行鉴权以获取授权令牌。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -1330,48 +1365,47 @@ auth(name: string, owner: string, authType: string, callback: AuthCallback): voi | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------- | ---- | --------------- | -| name | string | 是 | 要鉴权的应用帐号名称。 | -| owner | string | 是 | 要鉴权的应用帐号所有者包名。 | +| name | string | 是 | 应用帐号的名称。 | +| owner | string | 是 | 应用帐号所有者的包名。 | | authType | string | 是 | 鉴权类型。 | -| callback | [AuthCallback](#authcallback9) | 是 | 回调函数。返回鉴权结果对象。 | +| callback | [AuthCallback](#authcallback9) | 是 | 回调对象,返回鉴权结果。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name, owner, authType or options. | - | 12300003 | the account indicated by owner dose not exist. | - | 12300016 | authentication timeout. | - | 12300017 | authentication service is busy. | - | 12300018 | authentication service is locked. | - | 12400001 | the application indicated by name does not exist. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner or authType. | +| 12300003 | Account not found. | +| 12300010 | Account service busy. | +| 12300113 | Authenticator service not found. | +| 12300114 | Authenticator service exception. | **示例:** ```js import featureAbility from '@ohos.ability.featureAbility'; - function onResultCallback(code, result) { - console.log("resultCode: " + code); - console.log("result: " + JSON.stringify(result)); + function onResultCallback(code, authResult) { + console.log("resultCode: " + code); + console.log("authResult: " + JSON.stringify(authResult)); } function onRequestRedirectedCallback(request) { - let abilityStartSetting = {want: request}; - featureAbility.startAbility(abilityStartSetting, (err)=>{ - console.log("startAbility err: " + JSON.stringify(err)); - }); + let abilityStartSetting = {want: request}; + featureAbility.startAbility(abilityStartSetting, (err) => { + console.log("startAbility err: " + JSON.stringify(err)); + }); } - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.auth("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", { - onResult: onResultCallback, - onRequestRedirected: onRequestRedirectedCallback - }); + appAccountManager.auth("LiSi", "com.example.accountjsdemo", "getSocialData", { + onResult: onResultCallback, + onRequestRedirected: onRequestRedirectedCallback + }); } catch (err) { - console.log("auth err: " + JSON.stringify(err)); + console.log("auth exception: " + JSON.stringify(err)); } ``` @@ -1379,7 +1413,7 @@ auth(name: string, owner: string, authType: string, callback: AuthCallback): voi auth(name: string, owner: string, authType: string, options: {[key: string]: Object}, callback: AuthCallback): void -对应用帐户进行鉴权以获取OAuth令牌。使用callback异步回调。 +对应用帐号进行鉴权以获取授权令牌。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -1387,49 +1421,51 @@ auth(name: string, owner: string, authType: string, options: {[key: string]: Obj | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------- | ---- | --------------- | -| name | string | 是 | 要鉴权的应用帐号名称。 | -| owner | string | 是 | 要鉴权的应用帐号所有者包名。 | +| name | string | 是 | 应用帐号的名称。 | +| owner | string | 是 | 应用帐号所有者的包名。 | | authType | string | 是 | 鉴权类型。 | | options | {[key: string]: Object} | 是 | 鉴权所需的可选项。 | -| callback | [AuthCallback](#authcallback9) | 是 | 回调函数。返回鉴权结果对象。 | +| callback | [AuthCallback](#authcallback9) | 是 | 回调对象,返回鉴权结果。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name, owner, authType or options. | - | 12300003 | the account indicated by owner dose not exist. | - | 12300016 | authentication timeout. | - | 12300017 | authentication service is busy. | - | 12300018 | authentication service is locked. | - | 12400001 | the application indicated by name does not exist. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner or authType. | +| 12300003 | Account not exist. | +| 12300010 | Account service busy. | +| 12300113 | Authenticator service not found. | +| 12300114 | Authenticator service exception. | **示例:** ```js import featureAbility from '@ohos.ability.featureAbility'; - function onResultCallback(code, result) { - console.log("resultCode: " + code); - console.log("result: " + JSON.stringify(result)); + function onResultCallback(code, authResult) { + console.log("resultCode: " + code); + console.log("authResult: " + JSON.stringify(authResult)); } function onRequestRedirectedCallback(request) { - let abilityStartSetting = {want: request}; - featureAbility.startAbility(abilityStartSetting, (err)=>{ - console.log("startAbility err: " + JSON.stringify(err)); - }); + let abilityStartSetting = {want: request}; + featureAbility.startAbility(abilityStartSetting, (err) => { + console.log("startAbility err: " + JSON.stringify(err)); + }); } - const appAccountManager = account_appAccount.createAppAccountManager(); + let options = { + "password": "xxxx", + }; + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.auth("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", {}, { - onResult: onResultCallback, - onRequestRedirected: onRequestRedirectedCallback - }); + appAccountManager.auth("LiSi", "com.example.accountjsdemo", "getSocialData", options, { + onResult: onResultCallback, + onRequestRedirected: onRequestRedirectedCallback + }); } catch (err) { - console.log("auth err: " + JSON.stringify(err)); + console.log("auth exception: " + JSON.stringify(err)); } ``` @@ -1437,7 +1473,7 @@ auth(name: string, owner: string, authType: string, options: {[key: string]: Obj getAuthToken(name: string, owner: string, authType: string, callback: AsyncCallback<string>): void -获取指定应用帐号和鉴权类型的Auth令牌。使用callback异步回调。 +获取指定应用帐号的特定鉴权类型的授权令牌。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -1446,31 +1482,33 @@ getAuthToken(name: string, owner: string, authType: string, callback: AsyncCallb | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------- | ---- | ----------- | | name | string | 是 | 应用帐号的名称。 | -| owner | string | 是 | 应用帐号的所有者包名。 | +| owner | string | 是 | 应用帐号所有者的包名。 | | authType | string | 是 | 鉴权类型。 | -| callback | AsyncCallback<string> | 是 | 回调函数。当获取指定应用帐号和鉴权类型的Auth令牌成功时,err为undefined,data返回Auth令牌对象;否则为错误对象。 | +| callback | AsyncCallback<string> | 是 | 回调函数。当获取成功时,err为null,data为授权令牌值;否则为错误对象。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name, owner or authType. | - | 12300003 | the account indicated by owner dose not exist. | - | 12300015 | the authType is not supported on current device. | - | 12400001 | the application indicated by name does not exist. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name, owner or authType. | +| 12300003 | Account not found. | +| 12300107 | AuthType not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.getAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", (err, data) => { - console.log('getAuthToken err: ' + JSON.stringify(err)); - console.log('getAuthToken token: ' + data); - }); + appAccountManager.getAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", (err, token) => { + if (err) { + console.log("getAuthToken failed, error: " + JSON.stringify(err)); + } else { + console.log("getAuthToken successfully, token: " + token); + } + }); } catch (err) { - console.log('getAuthToken err: ' + JSON.stringify(err)); + console.log("getAuthToken exception: " + JSON.stringify(err)); } ``` @@ -1478,7 +1516,7 @@ getAuthToken(name: string, owner: string, authType: string, callback: AsyncCallb getAuthToken(name: string, owner: string, authType: string): Promise<string> -获取指定应用帐户和鉴权类型的Auth令牌。使用Promise异步回调。 +获取指定应用帐号的特定鉴权类型的授权令牌。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -1487,37 +1525,36 @@ getAuthToken(name: string, owner: string, authType: string): Promise<string&g | 参数名 | 类型 | 必填 | 说明 | | -------- | ------ | ---- | ----------- | | name | string | 是 | 应用帐号的名称。 | -| owner | string | 是 | 应用帐号的所有者包名。 | +| owner | string | 是 | 应用帐号所有者的包名。 | | authType | string | 是 | 鉴权类型。 | **返回值:** -| 类型 | 说明 | +| 类型 | 说明 | | --------------------- | --------------------- | -| Promise<string> | Promise对象。返回指定应用帐户和鉴权类型的Auth令牌对象。 | +| Promise<string> | Promise对象,返回授权令牌。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name, owner or authType. | - | 12300003 | the account indicated by owner dose not exist. | - | 12300015 | the authType is not supported on current device. | - | 12400001 | the application indicated by name does not exist. | +| 错误码ID | 错误信息 | +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner or authType. | +| 12300003 | Account not found. | +| 12300107 | AuthType not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.getAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData").then((data) => { - console.log('getAuthToken token: ' + data); - }).catch((err) => { - console.log("getAuthToken err: " + JSON.stringify(err)); - }); + appAccountManager.getAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData").then((token) => { + console.log("getAuthToken successfully, token: " + token); + }).catch((err) => { + console.log("getAuthToken failed, error: " + JSON.stringify(err)); + }); } catch (err) { - console.log("getAuthToken err: " + JSON.stringify(err)); + console.log("getAuthToken exception: " + JSON.stringify(err)); } ``` @@ -1525,7 +1562,7 @@ getAuthToken(name: string, owner: string, authType: string): Promise<string&g setAuthToken(name: string, authType: string, token: string, callback: AsyncCallback<void>): void -设置指定应用帐号和鉴权类型的Auth令牌。使用callback异步回调。 +为指定应用帐号设置特定鉴权类型的授权令牌。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -1535,30 +1572,32 @@ setAuthToken(name: string, authType: string, token: string, callback: AsyncCallb | -------- | ------------------------- | ---- | -------- | | name | string | 是 | 应用帐号的名称。 | | authType | string | 是 | 鉴权类型。 | -| token | string | 是 | Auth令牌。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当设置指定应用帐号和鉴权类型的Auth令牌成功时,err为undefined;否则为错误对象。 | +| token | string | 是 | 授权令牌。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当设置成功时,err为null;否则为错误对象。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name, owner, authType or token. | - | 12300003 | the account indicated by name dose not exist. | - | 12300015 | the authType is not supported on current device. | - | 12300019 | credential does not exist. | - | 12400007 | the number of token has reached the upper limit. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or authType or token. | +| 12300003 | Account not found. | +| 12400004 | The number of token reaches the upper limit. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.setAuthToken("LiSi", "getSocialData", "xxxx", (err) => { - console.log('setAuthToken err: ' + JSON.stringify(err)); - }); + appAccountManager.setAuthToken("LiSi", "getSocialData", "xxxx", (err) => { + if (err) { + console.log("setAuthToken failed, error: " + JSON.stringify(err)); + } else { + console.log("setAuthToken successfully"); + } + }); } catch (err) { - console.log('setAuthToken err: ' + JSON.stringify(err)); + console.log('setAuthToken exception: ' + JSON.stringify(err)); } ``` @@ -1566,7 +1605,7 @@ setAuthToken(name: string, authType: string, token: string, callback: AsyncCallb setAuthToken(name: string, authType: string, token: string): Promise<void> -设置指定应用帐户和鉴权类型的Auth令牌。使用Promise异步回调。 +为指定应用帐号设置特定鉴权类型的授权令牌。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -1576,7 +1615,7 @@ setAuthToken(name: string, authType: string, token: string): Promise<void> | -------- | ------ | ---- | -------- | | name | string | 是 | 应用帐号的名称。 | | authType | string | 是 | 鉴权类型。 | -| token | string | 是 | Auth令牌。 | +| token | string | 是 | 授权令牌。 | **返回值:** @@ -1586,27 +1625,25 @@ setAuthToken(name: string, authType: string, token: string): Promise<void> **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name, owner, authType or token. | - | 12300003 | the account indicated by name dose not exist. | - | 12300015 | the authType is not supported on current device. | - | 12300019 | credential does not exist. | - | 12400007 | the number of token has reached the upper limit. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or authType or token. | +| 12300003 | Account not found. | +| 12400004 | The number of token reaches the upper limit. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.setAuthToken("LiSi", "getSocialData", "xxxx").then(() => { - console.log('setAuthToken successfully'); - }).catch((err) => { - console.log('setAuthToken err: ' + JSON.stringify(err)); - }); + appAccountManager.setAuthToken("LiSi", "getSocialData", "xxxx").then(() => { + console.log("setAuthToken successfully"); + }).catch((err) => { + console.log("setAuthToken failed, error: " + JSON.stringify(err)); + }); } catch (err) { - console.log('setAuthToken err: ' + JSON.stringify(err)); + console.log("setAuthToken exception: " + JSON.stringify(err)); } ``` @@ -1614,7 +1651,7 @@ setAuthToken(name: string, authType: string, token: string): Promise<void> deleteAuthToken(name: string, owner: string, authType: string, token: string, callback: AsyncCallback<void>): void -删除指定应用帐户和鉴权类型的Auth令牌。使用callback异步回调。 +删除指定应用帐号的特定鉴权类型的授权令牌。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -1623,31 +1660,34 @@ deleteAuthToken(name: string, owner: string, authType: string, token: string, ca | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ------------ | | name | string | 是 | 应用帐号的名称。 | -| owner | string | 是 | 应用帐号的所有者包名。 | +| owner | string | 是 | 应用帐号所有者的包名。 | | authType | string | 是 | 鉴权类型。 | -| token | string | 是 | 要删除的Auth令牌。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当删除指定应用帐户和鉴权类型的Auth令牌成功时,err为undefined;否则为错误对象。 | +| token | string | 是 | 授权令牌。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当删除成功时,err为null;否则为错误对象。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name, owner, authType or token. | - | 12300003 | the account indicated by name dose not exist. | - | 12300015 | the authType is not supported on current device. | - | 12300019 | credential does not exist. | +| 错误码ID | 错误信息 | +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner or authType or token. | +| 12300003 | Account not found. | +| 12300107 | AuthType not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.deleteAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", "xxxxx", (err) => { - console.log('deleteAuthToken err: ' + JSON.stringify(err)); + appAccountManager.deleteAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", "xxxxx", (err) => { + if (err) { + console.log('deleteAuthToken failed, error: ' + JSON.stringify(err)); + } else { + console.log("deleteAuthToken successfully"); + } }); } catch (err) { - console.log('deleteAuthToken err: ' + JSON.stringify(err)); + console.log('deleteAuthToken exception: ' + JSON.stringify(err)); } ``` @@ -1655,7 +1695,7 @@ deleteAuthToken(name: string, owner: string, authType: string, token: string, ca deleteAuthToken(name: string, owner: string, authType: string, token: string): Promise<void> -删除指定应用帐户和鉴权类型的Auth令牌。使用Promise异步回调。 +删除指定应用帐号的特定鉴权类型的授权令牌。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -1664,9 +1704,9 @@ deleteAuthToken(name: string, owner: string, authType: string, token: string): P | 参数名 | 类型 | 必填 | 说明 | | -------- | ------ | ---- | ------------ | | name | string | 是 | 应用帐号的名称。 | -| owner | string | 是 | 应用帐号的所有者包名。 | +| owner | string | 是 | 应用帐号所有者的包名。 | | authType | string | 是 | 鉴权类型。 | -| token | string | 是 | 要删除的Auth令牌。 | +| token | string | 是 | 授权令牌。 | **返回值:** @@ -1676,26 +1716,25 @@ deleteAuthToken(name: string, owner: string, authType: string, token: string): P **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name, owner, authType or token. | - | 12300003 | the account indicated by name dose not exist. | - | 12300015 | the authType is not supported on current device. | - | 12300019 | credential does not exist. | +| 错误码ID | 错误信息 | +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner or authType or token. | +| 12300003 | Account not found. | +| 12300107 | AuthType not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.deleteAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", "xxxxx").then(() => { - console.log('deleteAuthToken successfully'); - }).catch((err) => { - console.log("deleteAuthToken err: " + JSON.stringify(err)); - }); + appAccountManager.deleteAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", "xxxxx").then(() => { + console.log("deleteAuthToken successfully"); + }).catch((err) => { + console.log('deleteAuthToken failed, error: ' + JSON.stringify(err)); + }); } catch (err) { - console.log("deleteAuthToken err: " + JSON.stringify(err)); + console.log('deleteAuthToken exception: ' + JSON.stringify(err)); } ``` @@ -1703,7 +1742,7 @@ deleteAuthToken(name: string, owner: string, authType: string, token: string): P setAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean, callback: AsyncCallback<void>): void -设置指定鉴权类型的Auth令牌对特定应用的可见性。使用callback异步回调。 +设置指定帐号的特定鉴权类型的授权令牌对指定应用的可见性。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -1714,29 +1753,34 @@ setAuthTokenVisibility(name: string, authType: string, bundleName: string, isVis | name | string | 是 | 应用帐号的名称。 | | authType | string | 是 | 鉴权类型。 | | bundleName | string | 是 | 被设置可见性的应用包名。 | -| isVisible | boolean | 是 | 是否可见。当设置成true可见,false不可见。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当设置指定鉴权类型的Auth令牌对特定应用的可见性成功时,err为undefined;否则为错误对象。 | +| isVisible | boolean | 是 | 是否可见。true表示可见,false表示不可见。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当设置成功时,err为null;否则为错误对象。| **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name, authType or bundleName. | - | 12300003 | the account indicated by name dose not exist. | - | 12300015 | the authType is not supported on current device. | - | 12300019 | credential does not exist. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or authType or bundleName. | +| 12300003 | Account not found. | +| 12300107 | AuthType not found. | +| 12400001 | Application not found. | +| 12400005 | The size of authorization list reaches the upper limit. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.setAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", true, (err) => { - console.log('setAuthTokenVisibility err: ' + JSON.stringify(err)); + appAccountManager.setAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", true, (err) => { + if (err) { + console.log("setAuthTokenVisibility failed, error: " + JSON.stringify(err)); + } else { + console.log("setAuthTokenVisibility successfully"); + } }); } catch (err) { - console.log('setAuthTokenVisibility err: ' + JSON.stringify(err)); + console.log("setAuthTokenVisibility exception: " + JSON.stringify(err)); } ``` @@ -1744,18 +1788,18 @@ setAuthTokenVisibility(name: string, authType: string, bundleName: string, isVis setAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean): Promise<void> -设置指定鉴权类型的OAuth令牌对特定应用的可见性。使用Promise异步回调。 +设置指定帐号的特定鉴权类型的授权令牌对指定应用的可见性。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------- | ---- | ------------ | -| name | string | 是 | 应用帐号的名称。 | -| authType | string | 是 | 鉴权类型。 | -| bundleName | string | 是 | 被设置可见性的应用包名。 | -| isVisible | boolean | 是 | 是否可见。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------- | ---- | ------------------------- | +| name | string | 是 | 应用帐号的名称。 | +| authType | string | 是 | 鉴权类型。 | +| bundleName | string | 是 | 被设置可见性的应用包名。 | +| isVisible | boolean | 是 | 是否可见。true表示可见,false表示不可见。 | **返回值:** @@ -1765,26 +1809,27 @@ setAuthTokenVisibility(name: string, authType: string, bundleName: string, isVis **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name, authType or bundleName. | - | 12300003 | the account indicated by name dose not exist. | - | 12300015 | the authType is not supported on current device. | - | 12300019 | credential does not exist. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or authType or bundleName. | +| 12300003 | Account not found. | +| 12300107 | AuthType not found. | +| 12400001 | Application not found. | +| 12400005 | The size of authorization list reaches the upper limit. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.setAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", true).then(() => { - console.log('setAuthTokenVisibility successfully'); - }).catch((err) => { - console.log('setAuthTokenVisibility err: ' + JSON.stringify(err)); - }); + appAccountManager.setAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", true).then(() => { + console.log("setAuthTokenVisibility successfully"); + }).catch((err) => { + console.log("setAuthTokenVisibility failed, error: " + JSON.stringify(err)); + }); } catch (err) { - console.log('setAuthTokenVisibility err: ' + JSON.stringify(err)); + console.log("setAuthTokenVisibility exception: " + JSON.stringify(err)); } ``` @@ -1792,7 +1837,7 @@ setAuthTokenVisibility(name: string, authType: string, bundleName: string, isVis checkAuthTokenVisibility(name: string, authType: string, bundleName: string, callback: AsyncCallback<boolean>): void -检查指定鉴权类型的Auth令牌对特定应用的可见性。使用callback异步回调。 +检查指定应用帐号的特定鉴权类型的授权令牌对指定应用的可见性。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -1803,29 +1848,32 @@ checkAuthTokenVisibility(name: string, authType: string, bundleName: string, cal | name | string | 是 | 应用帐号的名称。 | | authType | string | 是 | 鉴权类型。 | | bundleName | string | 是 | 检查可见性的应用包名。 | -| callback | AsyncCallback<boolean> | 是 | 回调函数。当检查指定鉴权类型的Auth令牌对特定应用的可见性时,err为undefined,data为true表示可见,data为false表示不可见;否则为错误对象。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。当检查成功时,err为null,data为true表示可见,data为false表示不可见;否则为错误对象。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name, authType or bundleName. | - | 12300003 | the account indicated by name dose not exist. | - | 12300015 | the authType is not supported on current device. | - | 12300019 | credential does not exist. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or authType or bundleName. | +| 12300003 | Account not found. | +| 12300107 | AuthType not found. | +| 12400001 | Application not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.checkAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", (err, data) => { - console.log('checkAuthTokenVisibility err: ' + JSON.stringify(err)); - console.log('checkAuthTokenVisibility isVisible: ' + data); - }); + appAccountManager.checkAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", (err, isVisible) => { + if (err) { + console.log("checkAuthTokenVisibility failed, error: " + JSON.stringify(err)); + } else { + console.log("checkAuthTokenVisibility successfully, isVisible: " + isVisible); + } + }); } catch (err) { - console.log('checkAuthTokenVisibility err: ' + JSON.stringify(err)); + console.log("checkAuthTokenVisibility exception: " + JSON.stringify(err)); } ``` @@ -1833,7 +1881,7 @@ checkAuthTokenVisibility(name: string, authType: string, bundleName: string, cal checkAuthTokenVisibility(name: string, authType: string, bundleName: string): Promise<boolean> -检查指定鉴权类型的Auth令牌对特定应用的可见性。使用Promise异步回调。 +检查指定应用帐号的特定鉴权类型的授权令牌对指定应用的可见性。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -1849,38 +1897,38 @@ checkAuthTokenVisibility(name: string, authType: string, bundleName: string): Pr | 类型 | 说明 | | ---------------------- | --------------------- | -| Promise<boolean> | Promise对象。返回true表示指定鉴权类型的Auth令牌对特定应用的可见,返回false表示不可见。 | +| Promise<boolean> | Promise对象,返回true表示授权令牌对指定应用的可见,返回false表示不可见。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name, authType or bundleName. | - | 12300003 | the account indicated by name dose not exist. | - | 12300015 | the authType is not supported on current device. | - | 12300019 | credential does not exist. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or authType or bundleName. | +| 12300003 | Account not found. | +| 12300107 | AuthType not found. | +| 12400001 | Application not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.checkAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo").then((data) => { - console.log('checkAuthTokenVisibility isVisible: ' + data); - }).catch((err) => { - console.log('checkAuthTokenVisibility err: ' + JSON.stringify(err)); - }); + appAccountManager.checkAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo").then((isVisible) => { + console.log("checkAuthTokenVisibility successfully, isVisible: " + isVisible); + }).catch((err) => { + console.log("checkAuthTokenVisibility failed, error: " + JSON.stringify(err)); + }); } catch (err) { - console.log('checkAuthTokenVisibility err: ' + JSON.stringify(err)); + console.log("checkAuthTokenVisibility exception: " + JSON.stringify(err)); } ``` ### getAllAuthTokens9+ -getAllAuthTokens(name: string, owner: string, callback: AsyncCallback<Array<OAuthTokenInfo>>): void +getAllAuthTokens(name: string, owner: string, callback: AsyncCallback<Array<AuthTokenInfo>>): void -获取指定应用对调用方全部可见的Auth令牌。使用callback异步回调。 +获取指定帐号对调用方可见的所有授权令牌。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -1889,29 +1937,31 @@ getAllAuthTokens(name: string, owner: string, callback: AsyncCallback<Array&l | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ----------- | | name | string | 是 | 应用帐号的名称。 | -| owner | string | 是 | 应用帐号的所有者包名。 | -| callback | AsyncCallback<Array< [AuthTokenInfo](#authtokeninfo9)>> | 是 | 回调函数。当获取指定应用对调 -用方全部可见的Auth令牌成功时,err为undefined,data为全部可见的Auth令牌数组;否则为错误对象。 | +| owner | string | 是 | 应用帐号所有者的包名。 | +| callback | AsyncCallback<Array<[AuthTokenInfo](#authtokeninfo9)>> | 是 | 回调函数。当获取成功时,err为null,data为授权令牌数组;否则为错误对象。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name or owner. | - | 12300003 | the account indicated by name dose not exist. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner. | +| 12300003 | Account not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.getAllAuthTokens("LiSi", "com.example.ohos.accountjsdemo", (err, data) => { - console.log("getAllAuthTokens err: " + JSON.stringify(err)); - console.log('getAllAuthTokens data: ' + JSON.stringify(data)); - }); + appAccountManager.getAllAuthTokens("LiSi", "com.example.accountjsdemo", (err, tokenArr) => { + if (err) { + console.log("getAllAuthTokens failed, error: " + JSON.stringify(err)); + } else { + console.log('getAllAuthTokens successfully, tokenArr: ' + tokenArr); + } + }); } catch (err) { - console.log("getAllAuthTokens err: " + JSON.stringify(err)); + console.log("getAllAuthTokens exception: " + JSON.stringify(err)); } ``` @@ -1919,7 +1969,7 @@ getAllAuthTokens(name: string, owner: string, callback: AsyncCallback<Array&l getAllAuthTokens(name: string, owner: string): Promise<Array<AuthTokenInfo>> -获取指定应用帐户对调用方可见的全部Auth令牌。使用Promise异步回调。 +获取指定帐号对调用方可见的所有授权令牌。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -1928,34 +1978,34 @@ getAllAuthTokens(name: string, owner: string): Promise<Array<AuthTokenInfo | 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------- | | name | string | 是 | 应用帐号的名称。 | -| owner | string | 是 | 应用帐号的所有者包名。 | +| owner | string | 是 | 应用帐号所有者的包名。 | **返回值:** | 类型 | 说明 | | ---------------------------------------- | --------------------- | -| Promise<Array< [AuthTokenInfo](#authtokeninfo9)>> | Promise对象。返回指定应用帐户对调用方可见的全部Auth令牌对象。 | +| Promise<Array<[AuthTokenInfo](#authtokeninfo9)>> | Promise对象,返回授权令牌数组。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name or owner. | - | 12300003 | the account indicated by name dose not exist. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner. | +| 12300003 | Account not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.getAllAuthTokens("LiSi", "com.example.ohos.accountjsdemo").then((data) => { - console.log('getAllAuthTokens data: ' + JSON.stringify(data)); - }).catch((err) => { - console.log("getAllAuthTokens err: " + JSON.stringify(err)); - }); + appAccountManager.getAllAuthTokens("LiSi", "com.example.accountjsdemo").then((tokenArr) => { + console.log('getAllAuthTokens successfully, tokenArr: ' + JSON.stringify(tokenArr)); + }).catch((err) => { + console.log("getAllAuthTokens failed, error: " + JSON.stringify(err)); + }); } catch (err) { - console.log("getAllAuthTokens err: " + JSON.stringify(err)); + console.log("getAllAuthTokens exception: " + JSON.stringify(err)); } ``` @@ -1963,7 +2013,7 @@ getAllAuthTokens(name: string, owner: string): Promise<Array<AuthTokenInfo getAuthList(name: string, authType: string, callback: AsyncCallback<Array<string>>): void -获取指定应用帐户和鉴权类型的Auth令牌的授权列表。使用callback异步回调。 +获取指定应用帐号的特定鉴权类型的授权列表,即被授权的包名数组(令牌的授权列表通过[setAuthTokenVisibility](#setauthtokenvisibility9)来设置)。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -1972,30 +2022,32 @@ getAuthList(name: string, authType: string, callback: AsyncCallback<Array< | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ----------------------- | | name | string | 是 | 应用帐号的名称。 | -| authType | string | 是 | 应用帐号的鉴权类型的Auth令牌的授权列表。 | -| callback | AsyncCallback<Array<string>> | 是 | 回调函数。当获取指定应用帐户和鉴权类型的Auth令牌的授权列表成功时,err为undefined,data为Auth令牌的授权列表;否则为错误对象。 | +| authType | string | 是 | 鉴权类型。 | +| callback | AsyncCallback<Array<string>> | 是 | 回调函数。当获取成功时,err为null,data为被授权的包名数组;否则为错误对象。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name or authType. | - | 12300003 | the account indicated by name dose not exist. | - | 12300015 | the authType is not supported on current device. | - | 12300019 | credential does not exist. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or authType. | +| 12300003 | Account not found. | +| 12300107 | AuthType not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.getAuthList("com.example.ohos.accountjsdemo", "getSocialData", (err, data) => { - console.log('getAuthList err: ' + JSON.stringify(err)); - console.log('getAuthList data: ' + JSON.stringify(data)); - }); + appAccountManager.getAuthList("com.example.accountjsdemo", "getSocialData", (err, authList) => { + if (err) { + console.log("getAuthList failed, error: " + JSON.stringify(err)); + } else { + console.log("getAuthList successfully, authList: " + authList); + } + }); } catch (err) { - console.log('getAuthList err: ' + JSON.stringify(err)); + console.log('getAuthList exception: ' + JSON.stringify(err)); } ``` @@ -2003,45 +2055,44 @@ getAuthList(name: string, authType: string, callback: AsyncCallback<Array< getAuthList(name: string, authType: string): Promise<Array<string>> -获取指定应用帐户和鉴权类型的Auth令牌的授权列表。使用Promise异步回调。 +获取指定应用帐号的特定鉴权类型的授权列表,即被授权的包名数组(令牌的授权列表通过[setAuthTokenVisibility](#setauthtokenvisibility9)来设置)。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** | 参数名 | 类型 | 必填 | 说明 | -| -------- | ------ | ---- | ----------------------- | +| -------- | ------ | ---- | ------------------------------ | | name | string | 是 | 应用帐号的名称。 | -| authType | string | 是 | 应用帐号的鉴权类型的Auth令牌的授权列表。 | +| authType | string | 是 | 鉴权类型。 | **返回值:** | 类型 | 说明 | | ---------------------------------- | --------------------- | -| Promise<Array<string>> | Promise对象。返回指定应用帐户和鉴权类型的Auth令牌的授权列表对象。 | +| Promise<Array<string>> | Promise对象,返回被授权的包名数组。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name or authType. | - | 12300003 | the account indicated by name dose not exist. | - | 12300015 | the authType is not supported on current device. | - | 12300019 | credential does not exist. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or authType. | +| 12300003 | Account not found. | +| 12300107 | AuthType not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.getAuthList("com.example.ohos.accountjsdemo", "getSocialData").then((data) => { - console.log('getAuthList data: ' + JSON.stringify(data)); - }).catch((err) => { - console.log("getAuthList err: " + JSON.stringify(err)); - }); + appAccountManager.getAuthList("com.example.accountjsdemo", "getSocialData").then((authList) => { + console.log("getAuthList successfully, authList: " + authList); + }).catch((err) => { + console.log("getAuthList failed, error: " + JSON.stringify(err)); + }); } catch (err) { - console.log("getAuthList err: " + JSON.stringify(err)); + console.log("getAuthList exception: " + JSON.stringify(err)); } ``` @@ -2049,7 +2100,7 @@ getAuthList(name: string, authType: string): Promise<Array<string>> getAuthCallback(sessionId: string, callback: AsyncCallback<AuthCallback>): void -获取鉴权会话的认证器回调。使用callback异步回调。 +获取鉴权会话的认证器回调对象。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -2058,37 +2109,44 @@ getAuthCallback(sessionId: string, callback: AsyncCallback<AuthCallback>): | 参数名 | 类型 | 必填 | 说明 | | --------- | ---------------------------------------- | ---- | -------- | | sessionId | string | 是 | 鉴权会话的标识。 | -| callback | AsyncCallback<[AuthCallback](#authcallback9)> | 是 | 回调函数。当获取鉴权会话的认证器回调函数成功时,err为undefined,data为认证器回调函数;否则为错误对象。 | +| callback | AsyncCallback<[AuthCallback](#authcallback9)> | 是 | 回调函数。当获取成功时,err为null,data为鉴权会话的认证器回调对象;否则为错误对象。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12400005 | the session indicated by sessionId does not exist. | +| 错误码ID | 错误信息 | +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid sessionId. | +| 12300108 | Session not found. | **示例:** ```js import featureAbility from '@ohos.ability.featureAbility'; - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); featureAbility.getWant((err, want) => { - var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; - try { - appAccountManager.getAuthCallback(sessionId, (err, callback) => { - if (err.code != account_appAccount.ResultCode.SUCCESS) { - console.log("getAuthCallback err: " + JSON.stringify(err)); - return; - } - var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi", - [account_appAccount.Constants.KEY_OWNER]: "com.example.ohos.accountjsdemo", - [account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData", - [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; - callback.onResult(account_appAccount.ResultCode.SUCCESS, result); - }); - } catch (err) { - console.log("getAuthCallback err: " + JSON.stringify(err)); - } + var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; + try { + appAccountManager.getAuthCallback(sessionId, (err, callback) => { + if (err.code != account_appAccount.ResultCode.SUCCESS) { + console.log("getAuthCallback err: " + JSON.stringify(err)); + return; + } + var result = { + accountInfo: { + name: "Lisi", + owner: "com.example.accountjsdemo", + }, + tokenInfo: { + token: "xxxxxx", + authType: "getSocialData" + } + }; + callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + }); + } catch (err) { + console.log("getAuthCallback exception: " + JSON.stringify(err)); + } }); ``` @@ -2096,7 +2154,7 @@ getAuthCallback(sessionId: string, callback: AsyncCallback<AuthCallback>): getAuthCallback(sessionId: string): Promise<AuthCallback> -获取鉴权会话的认证器回调。使用Promise异步回调。 +获取鉴权会话的认证器回调对象。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -2110,33 +2168,42 @@ getAuthCallback(sessionId: string): Promise<AuthCallback> | 类型 | 说明 | | ------------------------------------ | --------------------- | -| Promise<[AuthCallback](#authcallback9)> | Promise对象。返回鉴权会话的认证器回调对象。 | +| Promise<[AuthCallback](#authcallback9)> | Promise对象,返回鉴权会话的认证器回调对象。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12400005 | the session indicated by sessionId does not exist. | +| 错误码ID | 错误信息 | +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid sessionId. | +| 12300108 | Session not found. | **示例:** ```js import featureAbility from '@ohos.ability.featureAbility'; - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); featureAbility.getWant().then((want) => { var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; try { - appAccountManager.getAuthCallback(sessionId).then((callback) => { - var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi", - [account_appAccount.Constants.KEY_OWNER]: "com.example.ohos.accountjsdemo", - [account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData", - [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; - callback.onResult(account_appAccount.ResultCode.SUCCESS, result); - }).catch((err) => { - console.log("getAuthCallback err: " + JSON.stringify(err)); - }); + appAccountManager.getAuthCallback(sessionId).then((callback) => { + var result = { + accountInfo: { + name: "Lisi", + owner: "com.example.accountjsdemo", + }, + tokenInfo: { + token: "xxxxxx", + authType: "getSocialData" + } + }; + callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + }).catch((err) => { + console.log("getAuthCallback err: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("getAuthCallback exception: " + JSON.stringify(err)); } }).catch((err) => { console.log("getWant err: " + JSON.stringify(err)); @@ -2147,7 +2214,7 @@ getAuthCallback(sessionId: string): Promise<AuthCallback> queryAuthenticatorInfo(owner: string, callback: AsyncCallback<AuthenticatorInfo>): void -获取指定应用帐号的认证器信息。使用callback异步回调。 +获取指定应用的认证器信息。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -2155,28 +2222,31 @@ queryAuthenticatorInfo(owner: string, callback: AsyncCallback<AuthenticatorIn | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------------------- | ---- | ----------- | -| owner | string | 是 | 应用帐号的所有者包名。 | -| callback | AsyncCallback<[AuthenticatorInfo](#authenticatorinfo8)> | 是 | 回调函数。当获取指定应用帐号的认证器信息成功时,err为undefined,data为认证器信息对象;否则为错误对象。 | +| owner | string | 是 | 应用包名。 | +| callback | AsyncCallback<[AuthenticatorInfo](#authenticatorinfo8)> | 是 | 回调函数。当获取成功时,err为null,data为认证器信息对象;否则为错误对象。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid owner. | - | 12300003 | the account indicated by owner dose not exist. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid owner. | +| 12300113 | Authenticator service not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.queryAuthenticatorInfo("com.example.ohos.accountjsdemo", (err, data) => { - console.log("queryAuthenticatorInfo err: " + JSON.stringify(err)); - console.log('queryAuthenticatorInfo data: ' + JSON.stringify(data)); - }); + appAccountManager.queryAuthenticatorInfo("com.example.accountjsdemo", (err, info) => { + if (err) { + console.log("queryAuthenticatorInfo failed, error: " + JSON.stringify(err)); + } else { + console.log('queryAuthenticatorInfo successfully, info: ' + JSON.stringify(info)); + } + }); } catch (err) { - console.log("queryAuthenticatorInfo err: " + JSON.stringify(err)); + console.log("queryAuthenticatorInfo exception: " + JSON.stringify(err)); } ``` @@ -2184,7 +2254,7 @@ queryAuthenticatorInfo(owner: string, callback: AsyncCallback<AuthenticatorIn queryAuthenticatorInfo(owner: string): Promise<AuthenticatorInfo> -获取指定应用帐户的认证器信息。使用Promise异步回调。 +获取指定应用的认证器信息。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -2192,34 +2262,34 @@ queryAuthenticatorInfo(owner: string): Promise<AuthenticatorInfo> | 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------- | -| owner | string | 是 | 应用帐号的所有者包名。 | +| owner | string | 是 | 应用包名。 | **返回值:** | 类型 | 说明 | | -------------------------------- | --------------------- | -| Promise<[AuthenticatorInfo](#authenticatorinfo8)> | Promise对象。返回指定应用帐户的认证器信息对象。 | +| Promise<[AuthenticatorInfo](#authenticatorinfo8)> | Promise对象,返回指定应用的认证器信息对象。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid owner. | - | 12300003 | the account indicated by owner dose not exist. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid owner. | +| 12300113 | Authenticator service not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.queryAuthenticatorInfo("com.example.ohos.accountjsdemo").then((data) => { - console.log('queryAuthenticatorInfo: ' + JSON.stringify(data)); - }).catch((err) => { - console.log("queryAuthenticatorInfo err: " + JSON.stringify(err)); - }); + appAccountManager.queryAuthenticatorInfo("com.example.accountjsdemo").then((info) => { + console.log("queryAuthenticatorInfo successfully, info: " + JSON.stringify(info)); + }).catch((err) => { + console.log("queryAuthenticatorInfo failed, error: " + JSON.stringify(err)); + }); } catch (err) { - console.log("queryAuthenticatorInfo err: " + JSON.stringify(err)); + console.log("queryAuthenticatorInfo exception: " + JSON.stringify(err)); } ``` @@ -2227,7 +2297,7 @@ queryAuthenticatorInfo(owner: string): Promise<AuthenticatorInfo> checkAccountLabels(name: string, owner: string, labels: Array<string>, callback: AsyncCallback<boolean>): void; -检查指定帐户是否具有特定的标签集合。使用callback异步回调。 +检查指定应用帐号是否满足特定的标签集合。使用callback异步回调。该方法依赖目标应用的认证器提供标签检查的能力。 **系统能力:** SystemCapability.Account.AppAccount @@ -2235,32 +2305,37 @@ checkAccountLabels(name: string, owner: string, labels: Array<string>, cal | 参数名 | 类型 | 必填 | 说明 | | -------------- | ------------------------- | ----- | --------------- | -| name | string | 是 | 应用帐户的名称。 | -| owner | string | 是 | 应用帐户的所有者。| +| name | string | 是 | 应用帐号的名称。 | +| owner | string | 是 | 应用帐号的所有者。| | labels | Array<string> | 是 | 标签数组。 | -| callback | AsyncCallback<boolean> | 是 | 回调函数。当检查指定帐户是否具有特定的标签集合成功时,err为undefined,data为true表示具有特定标签,data为false表示不具有特定标签;否则为错误对象。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。当检查成功时,err为null,data为true表示满足特定的标签集合,data为false表示不满足;否则为错误对象。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name or owner. | - | 12300003 | the account indicated by owner dose not exist. | - | 12400001 | the application indicated by name does not exist. | +| 错误码ID | 错误信息 | +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner or labels. | +| 12300003 | Account not found. | +| 12300010 | Account service busy. | +| 12300113 | Authenticator service not found. | +| 12300114 | Authenticator service exception. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - var labels = ["student"]; + let appAccountManager = account_appAccount.createAppAccountManager(); + let labels = ["student"]; try { - appAccountManager.checkAccountLabels("zhangsan", "com.example.ohos.accountjsdemo", labels, (err, data) => { - console.log('checkAccountLabels: ' + JSON.stringify(data)); - console.log("checkAccountLabels err: " + JSON.stringify(err)); - }); + appAccountManager.checkAccountLabels("zhangsan", "com.example.accountjsdemo", labels, (err, hasAllLabels) => { + if (err) { + console.log("checkAccountLabels failed, error: " + JSON.stringify(err)); + } else { + console.log("checkAccountLabels successfully, hasAllLabels: " + hasAllLabels); + } + }); } catch (err) { - console.log("checkAccountLabels err: " + JSON.stringify(err)); + console.log("checkAccountLabels exception: " + JSON.stringify(err)); } ``` @@ -2268,7 +2343,7 @@ checkAccountLabels(name: string, owner: string, labels: Array<string>, cal checkAccountLabels(name: string, owner: string, labels: Array<string>): Promise<boolean> -检查指定帐户是否具有特定的标签集合。使用Promise异步回调。 +检查指定应用帐号是否满足特定的标签集合。使用Promise异步回调。该方法依赖目标应用的认证器提供标签检查的能力。 **系统能力:** SystemCapability.Account.AppAccount @@ -2276,38 +2351,40 @@ checkAccountLabels(name: string, owner: string, labels: Array<string>): Pr | 参数名 | 类型 | 必填 | 说明 | | -------------- | ------------------------- | ----- | --------------- | -| name | string | 是 | 应用帐户的名称。 | -| owner | string | 是 | 应用帐户的所有者。| +| name | string | 是 | 应用帐号的名称。 | +| owner | string | 是 | 应用帐号的所有者。| | labels | Array<string> | 是 | 标签数组。 | **返回值:** | 类型 | 说明 | | ------------------- | -------------------------------- | -| Promise<boolean> | Promise对象。返回true表示指定帐户具有特定的标签集合,返回false表示不具有特性的标签集合。 | +| Promise<boolean> | Promise对象,返回true表示指定帐号满足特定的标签集合,返回false表示不满足。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name or owner. | - | 12300003 | the account indicated by owner dose not exist. | - | 12400001 | the application indicated by name does not exist. | +| 错误码ID | 错误信息 | +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner or labels. | +| 12300003 | Account not found. | +| 12300010 | Account service busy. | +| 12300113 | Authenticator service not found. | +| 12300114 | Authenticator service exception. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - var labels = ["student"]; + let appAccountManager = account_appAccount.createAppAccountManager(); + let labels = ["student"]; try { - appAccountManager.checkAccountLabels("zhangsan", "com.example.ohos.accountjsdemo", labels).then((data) => { - console.log('checkAccountLabels: ' + JSON.stringify(data)); - }).catch((err) => { - console.log("checkAccountLabels err: " + JSON.stringify(err)); - }); + appAccountManager.checkAccountLabels("zhangsan", "com.example.accountjsdemo", labels).then((hasAllLabels) => { + console.log('checkAccountLabels successfully: ' + hasAllLabels); + }).catch((err) => { + console.log("checkAccountLabels failed, error: " + JSON.stringify(err)); + }); } catch (err) { - console.log("checkAccountLabels err: " + JSON.stringify(err)); + console.log("checkAccountLabels exception: " + JSON.stringify(err)); } ``` @@ -2315,7 +2392,7 @@ checkAccountLabels(name: string, owner: string, labels: Array<string>): Pr deleteCredential(name: string, credentialType: string, callback: AsyncCallback<void>): void -删除指定应用帐户的指定类型的凭据信息。使用callback异步回调。 +删除指定应用帐号的特定类型的凭据信息。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -2323,30 +2400,33 @@ deleteCredential(name: string, credentialType: string, callback: AsyncCallback&l | 参数名 | 类型 | 必填 | 说明 | | -------------- | ------------------------- | ----- | -------------- | -| name | string | 是 | 应用帐户的名称。 | +| name | string | 是 | 应用帐号的名称。 | | credentialType | string | 是 | 凭据类型。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当删除指定应用帐户的指定类型的凭据信息成功时,err为undefined;否则为错误对象。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当删除成功时,err为null;否则为错误对象。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name or credentialType. | - | 12300019 | credential does not exist. | - | 12400001 | the application indicated by name does not exist. | +| 错误码ID | 错误信息 | +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or credentialType. | +| 12300003 | Account not found. | +| 12300102 | Credential not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.deleteCredential("zhangsan", "pin", (err, data) => { - console.log('deleteCredential: ' + JSON.stringify(data)); - console.log("deleteCredential err: " + JSON.stringify(err)); - }); + appAccountManager.deleteCredential("zhangsan", "PIN_SIX", (err) => { + if (err) { + console.log("deleteCredential failed, error: " + JSON.stringify(err)); + } else { + console.log("deleteCredential successfully"); + } + }); } catch (err) { - console.log("deleteCredential err: " + JSON.stringify(err)); + console.log("deleteCredential exception: " + JSON.stringify(err)); } ``` @@ -2354,7 +2434,7 @@ deleteCredential(name: string, credentialType: string, callback: AsyncCallback&l deleteCredential(name: string, credentialType: string): Promise<void> -删除指定应用帐户的指定类型的凭据信息。使用Promise异步回调。 +删除指定应用帐号的特定类型的凭据信息。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -2362,7 +2442,7 @@ deleteCredential(name: string, credentialType: string): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | -------------- | ------ | ----- | --------------- | -| name | string | 是 | 应用帐户的名称。 | +| name | string | 是 | 应用帐号的名称。 | | credentialType | string | 是 | 凭据类型。 | **返回值:** @@ -2373,33 +2453,33 @@ deleteCredential(name: string, credentialType: string): Promise<void> **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name or credentialType. | - | 12300019 | credential does not exist. | - | 12400001 | the application indicated by name does not exist. | +| 错误码ID | 错误信息 | +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or credentialType. | +| 12300003 | Account not found. | +| 12300102 | Credential not found. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.deleteCredential("zhangsan", "pin").then((data) => { - console.log('deleteCredential: ' + JSON.stringify(data)); - }).catch((err) => { - console.log("deleteCredential err: " + JSON.stringify(err)); - }); + appAccountManager.deleteCredential("zhangsan", "PIN_SIX").then(() => { + console.log("deleteCredential successfully"); + }).catch((err) => { + console.log("deleteCredential failed, error: " + JSON.stringify(err)); + }); } catch (err) { - console.log("deleteCredential err: " + JSON.stringify(err)); + console.log("deleteCredential exception: " + JSON.stringify(err)); } ``` ### selectAccountsByOptions9+ -selectAccountsByOptions(options: SelectAccountsOptions, callback: AsyncCallback<Array<AppAccountInfo>>); +selectAccountsByOptions(options: SelectAccountsOptions, callback: AsyncCallback<Array<AppAccountInfo>>): void -根据选项选择请求方可访问的帐号列表。使用callback异步回调。 +根据选项选择调用方可访问的帐号列表。使用callback异步回调。如果选项中包含标签约束,则该方法依赖目标应用的认证器提供标签检查的能力。 **系统能力:** SystemCapability.Account.AppAccount @@ -2407,30 +2487,36 @@ selectAccountsByOptions(options: SelectAccountsOptions, callback: AsyncCallback& | 参数名 | 类型 | 必填 | 说明 | | -------------- | ----------------------------------- | ----- | --------------- | -| options | SelectAccountsOptions | 是 | 选择帐户的选项。 | -| callback | AsyncCallback<[AppAccountInfo](#appaccountinfo)> | 是 | 回调函数。当根据选项选择请求方可访问的帐号列表时,err为undefined,data为可访问的帐号信息对象;否则为错误对象。 | +| options | SelectAccountsOptions | 是 | 选择帐号的选项。 | +| callback | AsyncCallback<[AppAccountInfo](#appaccountinfo)> | 是 | 回调函数。当根据选项选择请求方可访问的帐号列表时,err为null,data为可访问的帐号信息对象;否则为错误对象。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid options. | +| 错误码ID | 错误信息 | +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid options. | +| 12300010 | Account service busy. | +| 12300114 | Authenticator service exception. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - var options = { - allowedOwners: ["com.example.ohos.accountjsdemo"] + let appAccountManager = account_appAccount.createAppAccountManager(); + let options = { + allowedOwners: [ "com.example.accountjsdemo" ], + requiredLabels: [ "student" ] }; try { - appAccountManager.selectAccountsByOptions(options, (err, data) => { - console.log('selectAccountsByOptions: ' + JSON.stringify(data)); - console.log("selectAccountsByOptions err: " + JSON.stringify(err)); - }); + appAccountManager.selectAccountsByOptions(options, (err, accountArr) => { + if (err) { + console.log("selectAccountsByOptions failed, error: " + JSON.stringify(err)); + } else { + console.log("selectAccountsByOptions successfully, accountArr: " + JSON.stringify(accountArr)); + } + }); } catch (err) { - console.log("selectAccountsByOptions err: " + JSON.stringify(err)); + console.log("selectAccountsByOptions exception: " + JSON.stringify(err)); } ``` @@ -2438,7 +2524,7 @@ selectAccountsByOptions(options: SelectAccountsOptions, callback: AsyncCallback& selectAccountsByOptions(options: SelectAccountsOptions): Promise<Array<AppAccountInfo>> -根据选项选择请求方可访问的帐户列表。使用Promise异步回调。 +根据选项选择调用方可访问的帐号列表。使用Promise异步回调。如果选项中包含标签约束,则该方法依赖目标应用的认证器提供标签检查的能力。 **系统能力:** SystemCapability.Account.AppAccount @@ -2446,44 +2532,46 @@ selectAccountsByOptions(options: SelectAccountsOptions): Promise<Array<App | 参数名 | 类型 | 必填 | 说明 | | -------------- | ------------------------- | ----- | --------------- | -| options | [SelectAccountsOptions](#selectaccountsoptions9) | 是 | 选择帐户的选项。 | +| options | [SelectAccountsOptions](#selectaccountsoptions9) | 是 | 选择帐号的选项。 | **返回值:** | 类型 | 说明 | | ------------------- | -------------------------------- | -| Promise<[AppAccountInfo](#appaccountinfo)> | Promise对象。返回请求方可访问的帐户对象。 | +| Promise<[AppAccountInfo](#appaccountinfo)> | Promise对象,返回调用方可访问的帐号列表。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid options. | +| 错误码ID | 错误信息 | +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid options. | +| 12300010 | Account service busy. | +| 12300114 | Authenticator service exception. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - var options = { - allowedOwners: ["com.example.ohos.accountjsdemo"] + let appAccountManager = account_appAccount.createAppAccountManager(); + let options = { + allowedOwners: ["com.example.accountjsdemo"] }; try { - appAccountManager.selectAccountsByOptions(options).then((data) => { - console.log('selectAccountsByOptions: ' + JSON.stringify(data)); - }).catch((err) => { - console.log("selectAccountsByOptions err: " + JSON.stringify(err)); - }); + appAccountManager.selectAccountsByOptions(options).then((accountArr) => { + console.log("selectAccountsByOptions successfully, accountArr: " + JSON.stringify(accountArr)); + }).catch((err) => { + console.log("selectAccountsByOptions failed, error: " + JSON.stringify(err)); + }); } catch (err) { - console.log("selectAccountsByOptions err: " + JSON.stringify(err)); + console.log("selectAccountsByOptions exception: " + JSON.stringify(err)); } ``` ### verifyCredential9+ -verifyCredential(name: string, owner: string, callback: AuthenticatorCallback): void; +verifyCredential(name: string, owner: string, callback: AuthCallback): void; -验证用户凭据。使用callback异步回调。 +验证指定帐号的凭据。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -2491,26 +2579,27 @@ verifyCredential(name: string, owner: string, callback: AuthenticatorCallback): | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------- | ----- | ----------------------- | -| name | string | 是 | 应用帐户的名称。 | -| owner | string | 是 | 应用帐户的所有者。 | -| callback | [AuthenticatorCallback](#authenticatorcallbackdeprecated) | 是 | 回调函数。返回认证结果回调函数。 | +| name | string | 是 | 应用帐号的名称。 | +| owner | string | 是 | 应用帐号所有者的包名。 | +| callback | [AuthCallback](#authcallback9) | 是 | 回调函数,返回验证结果。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name, owner or options. | - | 12300003 | the account indicated by owner dose not exist. | - | 12400001 | the application indicated by name does not exist. | - | 12400002 | the account authenticator service does not exist. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner. | +| 12300003 | Account not found. | +| 12300010 | Account service busy. | +| 12300113 | Authenticator service not found. | +| 12300114 | Authenticator service exception. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.verifyCredential("zhangsan", "com.example.ohos.accountjsdemo", { + appAccountManager.verifyCredential("zhangsan", "com.example.accountjsdemo", { onResult: (resultCode, result) => { console.log("verifyCredential onResult, resultCode:" + JSON.stringify(resultCode)); console.log("verifyCredential onResult, result:" + JSON.stringify(result)); @@ -2526,7 +2615,7 @@ verifyCredential(name: string, owner: string, callback: AuthenticatorCallback): ### verifyCredential9+ -verifyCredential(name: string, owner: string, options: VerifyCredentialOptions, callback: AuthenticatorCallback): void; +verifyCredential(name: string, owner: string, options: VerifyCredentialOptions, callback: AuthCallback): void; 验证用户凭据。使用callback异步回调。 @@ -2536,39 +2625,40 @@ verifyCredential(name: string, owner: string, options: VerifyCredentialOptions, | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ----- | ----------------------- | -| name | string | 是 | 应用帐户的名称。 | -| owner | string | 是 | 应用帐户的所有者。 | +| name | string | 是 | 应用帐号的名称。 | +| owner | string | 是 | 应用帐号所有者的包名。 | | options | [VerifyCredentialOptions](#verifycredentialoptions9) | 是 | 验证凭据的选项。 | -| callback | [AuthenticatorCallback](#authenticatorcallbackdeprecated) | 是 | 回调函数。返回认证结果回调函数。 | +| callback | [AuthCallback](#authcallback9) | 是 | 回调函数,返回验证结果。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid name, owner or options. | - | 12300003 | the account indicated by owner dose not exist. | - | 12400001 | the application indicated by name does not exist. | - | 12400002 | the account authenticator service does not exist. | +| 错误码ID | 错误信息| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner or options. | +| 12300003 | Account not found. | +| 12300010 | Account service busy. | +| 12300113 | Authenticator service not found. | +| 12300114 | Authenticator service exception. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - var options = { + let appAccountManager = account_appAccount.createAppAccountManager(); + let options = { credentialType: "pin", credential: "123456" }; try { - appAccountManager.verifyCredential("zhangsan", "com.example.ohos.accountjsdemo", options, { - onResult: (resultCode, result) => { - console.log("verifyCredential onResult, resultCode:" + JSON.stringify(resultCode)); - console.log("verifyCredential onResult, result:" + JSON.stringify(result)); - }, - onRequestRedirected: (request) => { - console.log("verifyCredential onRequestRedirected, request:" + JSON.stringify(request)); - } - }); + appAccountManager.verifyCredential("zhangsan", "com.example.accountjsdemo", options, { + onResult: (resultCode, result) => { + console.log("verifyCredential onResult, resultCode:" + JSON.stringify(resultCode)); + console.log("verifyCredential onResult, result:" + JSON.stringify(result)); + }, + onRequestRedirected: (request) => { + console.log("verifyCredential onRequestRedirected, request:" + JSON.stringify(request)); + } + }); } catch (err) { console.log("verifyCredential err: " + JSON.stringify(err)); } @@ -2578,7 +2668,7 @@ verifyCredential(name: string, owner: string, options: VerifyCredentialOptions, setAuthenticatorProperties(owner: string, callback: AuthCallback): void; -设置认证器属性。使用callback异步回调。 +设置指定应用的认证器属性。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -2587,33 +2677,34 @@ setAuthenticatorProperties(owner: string, callback: AuthCallback): void; | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------- | ----- | ----------------------- | | owner | string | 是 | 认证器的所有者。 | -| callback | [AuthCallback](#authcallback9) | 是 | 回调函数。返回设置属性结果回调函数。 | +| callback | [AuthCallback](#authcallback9) | 是 | 回调函数,返回设置属性的结果。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid owner or options. | - | 12300003 | the account indicated by owner dose not exist. | - | 12400002 | the account authenticator service does not exist. | +| 错误码ID | 错误信息 | +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid owner. | +| 12300010 | Account service busy. | +| 12300113 | Authenticator service not found. | +| 12300114 | Authenticator service exception. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.setAuthenticatorProperties("com.example.ohos.accountjsdemo", { - onResult: (resultCode, result) => { - console.log("setAuthenticatorProperties onResult, resultCode:" + JSON.stringify(resultCode)); - console.log("setAuthenticatorProperties onResult, result:" + JSON.stringify(result)); - }, - onRequestRedirected: (request) => { - console.log("setAuthenticatorProperties onRequestRedirected, request:" + JSON.stringify(request)); - } - }); + appAccountManager.setAuthenticatorProperties("com.example.accountjsdemo", { + onResult: (resultCode, result) => { + console.log("setAuthenticatorProperties onResult, resultCode:" + JSON.stringify(resultCode)); + console.log("setAuthenticatorProperties onResult, result:" + JSON.stringify(result)); + }, + onRequestRedirected: (request) => { + console.log("setAuthenticatorProperties onRequestRedirected, request:" + JSON.stringify(request)); + } + }); } catch (err) { - console.log("setAuthenticatorProperties err: " + JSON.stringify(err)); + console.log("setAuthenticatorProperties err: " + JSON.stringify(err)); } ``` @@ -2631,36 +2722,37 @@ setAuthenticatorProperties(owner: string, options: SetPropertiesOptions, callbac | -------- | --------------------- | ----- | ----------------------- | | owner | string | 是 | 认证器的所有者。 | | options | [SetPropertiesOptions](#setpropertiesoptions9) | 是 | 设置属性的选项。 | -| callback | [AuthCallback](#authcallback9) | 是 | 认证器回调,返回设置属性结果回调函数。 | +| callback | [AuthCallback](#authcallback9) | 是 | 认证器回调,返回设置属性的结果。 | **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 12300001 | system service exception. | - | 12300002 | invalid owner or options. | - | 12300003 | the account indicated by owner dose not exist. | - | 12400002 | the account authenticator service does not exist. | +| 错误码ID | 错误信息 | +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid owner or options. | +| 12300010 | Account service busy. | +| 12300113 | Authenticator service not found. | +| 12300114 | Authenticator service exception. | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - var options = { + let appAccountManager = account_appAccount.createAppAccountManager(); + let options = { properties: {"prop1": "value1"} }; try { - appAccountManager.setAuthenticatorProperties("com.example.ohos.accountjsdemo", options, { - onResult: (resultCode, result) => { - console.log("setAuthenticatorProperties onResult, resultCode:" + JSON.stringify(resultCode)); - console.log("setAuthenticatorProperties onResult, result:" + JSON.stringify(result)); - }, - onRequestRedirected: (request) => { - console.log("setAuthenticatorProperties onRequestRedirected, request:" + JSON.stringify(request)); - } - }); + appAccountManager.setAuthenticatorProperties("com.example.accountjsdemo", options, { + onResult: (resultCode, result) => { + console.log("setAuthenticatorProperties onResult, resultCode:" + JSON.stringify(resultCode)); + console.log("setAuthenticatorProperties onResult, result:" + JSON.stringify(result)); + }, + onRequestRedirected: (request) => { + console.log("setAuthenticatorProperties onRequestRedirected, request:" + JSON.stringify(request)); + } + }); } catch (err) { - console.log("setAuthenticatorProperties err: " + JSON.stringify(err)); + console.log("setAuthenticatorProperties err: " + JSON.stringify(err)); } ``` @@ -2669,7 +2761,7 @@ setAuthenticatorProperties(owner: string, options: SetPropertiesOptions, callbac addAccount(name: string, callback: AsyncCallback<void>): void -将此应用的帐号名添加到帐号管理服务中。使用callback异步回调。 +根据帐号名添加应用帐号。使用callback异步回调。 > **说明:** > 从API version 9开始废弃, 建议使用[createAccount](#createaccount9)替代 @@ -2682,13 +2774,13 @@ addAccount(name: string, callback: AsyncCallback<void>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | -------------------- | -| name | string | 是 | 要添加的应用帐号名称。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当此应用的帐号名添加到帐号管理服务成功时,err为undefined,否则为错误对象。 | +| name | string | 是 | 应用帐号的名称。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当创建成功时,err为null,否则为错误对象。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.addAccount("WangWu", (err) => { console.log("addAccount err: " + JSON.stringify(err)); }); @@ -2698,7 +2790,7 @@ addAccount(name: string, callback: AsyncCallback<void>): void addAccount(name: string, extraInfo: string, callback: AsyncCallback<void>): void -将此应用程序的帐号名和额外信息(能转换string类型的其它信息,如token)添加到帐号管理服务中。使用callback异步回调。 +根据帐号名和额外信息添加应用帐号。使用callback异步回调。 > **说明:** > 从API version 9开始废弃, 建议使用[createAccount](#createaccount9-1)替代 > 从 API version 7开始支持。 @@ -2709,16 +2801,16 @@ addAccount(name: string, extraInfo: string, callback: AsyncCallback<void>) | 参数名 | 类型 | 必填 | 说明 | | --------- | ------------------------- | ---- | ---------------------------------------- | -| name | string | 是 | 要添加的应用帐号名称。 | -| extraInfo | string | 是 | 要添加的应用帐号的额外信息(能转换string类型的其它信息,如token等),额外信息不能是应用帐号的敏感信息(如应用账号密码)。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当此应用程序的帐号名和额外信息添加到帐号管理服务成功时,err为undefined,否则为错误对象。 | +| name | string | 是 | 应用帐号的名称。 | +| extraInfo | string | 是 | 额外信息(能转换string类型的其它信息),额外信息不能是应用帐号的敏感信息(如应用账号密码、token等)。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当创建成功时,err为null,否则为错误对象。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.addAccount("LiSi", "token101", (err) => { - console.log("addAccount err: " + JSON.stringify(err)); + console.log("addAccount err: " + JSON.stringify(err)); }); ``` @@ -2726,7 +2818,7 @@ addAccount(name: string, extraInfo: string, callback: AsyncCallback<void>) addAccount(name: string, extraInfo?: string): Promise<void> -将此应用的帐号名或额外信息(能转换成string类型的其它信息)添加到帐号管理服务中。使用Promise异步回调。 +根据帐号名和额外信息添加应用帐号。使用callback异步回调。使用Promise异步回调。 > **说明:** > 从API version 9开始废弃, 建议使用[createAccount](#createaccount9-2)替代 > 从 API version 7开始支持。 @@ -2737,8 +2829,8 @@ addAccount(name: string, extraInfo?: string): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | --------- | ------ | ---- | ---------------------------------------- | -| name | string | 是 | 要添加的应用帐号名称。 | -| extraInfo | string | 否 | 要添加的应用帐号的额外信息(能转换成string类型的其它信息),额外信息不能是应用帐号的敏感信息(如应用账号密码)。 | +| name | string | 是 | 应用帐号的名称。 | +| extraInfo | string | 否 | 额外信息(能转换string类型的其它信息),额外信息不能是应用帐号的敏感信息(如应用账号密码、token等)。 | **返回值:** @@ -2749,11 +2841,11 @@ addAccount(name: string, extraInfo?: string): Promise<void> **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.addAccount("LiSi", "token101").then(()=> { - console.log('addAccount Success'); + console.log('addAccount Success'); }).catch((err) => { - console.log("addAccount err: " + JSON.stringify(err)); + console.log("addAccount err: " + JSON.stringify(err)); }); ``` @@ -2761,7 +2853,7 @@ addAccount(name: string, extraInfo?: string): Promise<void> addAccountImplicitly(owner: string, authType: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void -根据指定的帐号所有者、鉴权类型和可选项隐式地添加应用帐号,并使用callback回调异步返回结果。 +根据指定的帐号所有者隐式地添加应用帐号。使用callback异步回调。 > **说明:** 从API version 9开始废弃, 建议使用[createAccountImplicitly](#createaccountimplicitly9)替代。 > @@ -2773,10 +2865,10 @@ addAccountImplicitly(owner: string, authType: string, options: {[key: string]: a | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------- | ---- | ----------------------- | -| owner | string | 是 | 要添加的应用帐号所有者包名。 | -| authType | string | 是 | 要添加的应用帐号鉴权类型。鉴权类型为自定义。 | +| owner | string | 是 | 应用帐号所有者的包名。 | +| authType | string | 是 | 鉴权类型。鉴权类型为自定义。 | | options | {[key: string]: any} | 是 | 鉴权所需要的可选项。可选项可根据自己需要设置。 | -| callback | [AuthenticatorCallback](#authenticatorcallbackdeprecated) | 是 | 认证器回调,用于返回鉴权结果。 | +| callback | [AuthenticatorCallback](#authenticatorcallbackdeprecated) | 是 | 认证器回调对象,返回添加结果。 | **示例:** @@ -2784,21 +2876,21 @@ addAccountImplicitly(owner: string, authType: string, options: {[key: string]: a import featureAbility from '@ohos.ability.featureAbility'; function onResultCallback(code, result) { - console.log("resultCode: " + code); - console.log("result: " + JSON.stringify(result)); + console.log("resultCode: " + code); + console.log("result: " + JSON.stringify(result)); } function onRequestRedirectedCallback(request) { - let abilityStartSetting = {want: request}; - featureAbility.startAbility(abilityStartSetting, (err)=>{ - console.log("startAbility err: " + JSON.stringify(err)); - }); + let abilityStartSetting = {want: request}; + featureAbility.startAbility(abilityStartSetting, (err)=>{ + console.log("startAbility err: " + JSON.stringify(err)); + }); } - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.addAccountImplicitly("com.example.ohos.accountjsdemo", "getSocialData", {}, { - onResult: onResultCallback, - onRequestRedirected: onRequestRedirectedCallback + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.addAccountImplicitly("com.example.accountjsdemo", "getSocialData", {}, { + onResult: onResultCallback, + onRequestRedirected: onRequestRedirectedCallback }); ``` @@ -2806,7 +2898,7 @@ addAccountImplicitly(owner: string, authType: string, options: {[key: string]: a deleteAccount(name: string, callback: AsyncCallback<void>): void -从帐号管理服务中删除应用帐号。使用callback异步回调。 +删除应用帐号。使用callback异步回调。 > **说明:** 从API version 9开始废弃, 建议使用[removeAccount](#removeaccount9)替代。 > @@ -2818,13 +2910,13 @@ deleteAccount(name: string, callback: AsyncCallback<void>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ---------------- | -| name | string | 是 | 要删除的应用帐号名称。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当帐号管理服务中删除应用帐号成功时,err为undefined,否则为错误对象。 | +| name | string | 是 | 应用帐号的名称。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当删除成功时,err为null,否则为错误对象。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.deleteAccount("ZhaoLiu", (err) => { console.log("deleteAccount err: " + JSON.stringify(err)); }); @@ -2834,7 +2926,7 @@ deleteAccount(name: string, callback: AsyncCallback<void>): void deleteAccount(name: string): Promise<void> -从帐号管理服务中删除应用帐号。使用Promise异步回调。 +删除应用帐号。使用Promise异步回调。 > **说明:** 从API version 9开始废弃, 建议使用[removeAccount](#removeaccount9)替代。 > @@ -2846,7 +2938,7 @@ deleteAccount(name: string): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | ---- | ------ | ---- | ----------- | -| name | string | 是 | 要删除的应用帐号名称。 | +| name | string | 是 | 应用帐号的名称。 | **返回值:** @@ -2857,7 +2949,7 @@ deleteAccount(name: string): Promise<void> **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.deleteAccount("ZhaoLiu").then(() => { console.log('deleteAccount Success'); }).catch((err) => { @@ -2880,15 +2972,15 @@ disableAppAccess(name: string, bundleName: string, callback: AsyncCallback<vo | 参数名 | 类型 | 必填 | 说明 | | ---------- | ------------------------- | ---- | --------------------------------- | -| name | string | 是 | 要禁用访问的第三方应用帐号名称。 | +| name | string | 是 | 应用帐号的名称。 | | bundleName | string | 是 | 第三方应用的包名。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当禁止指定第三方应用帐号名称对指定包名称的第三方应用进行访问设置成功时,err为undefined,否则为错误对象。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当禁止指定第三方应用帐号名称对指定包名称的第三方应用进行访问设置成功时,err为null,否则为错误对象。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.disableAppAccess("ZhangSan", "com.example.ohos.accountjsdemo", (err) => { + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.disableAppAccess("ZhangSan", "com.example.accountjsdemo", (err) => { console.log("disableAppAccess err: " + JSON.stringify(err)); }); ``` @@ -2909,7 +3001,7 @@ disableAppAccess(name: string, bundleName: string): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | ---------- | ------ | ---- | ---------------- | -| name | string | 是 | 要禁用访问的第三方应用帐号名称。 | +| name | string | 是 | 要禁用访问的第三方应用帐号的名称。 | | bundleName | string | 是 | 第三方应用的包名。 | **返回值:** @@ -2921,8 +3013,8 @@ disableAppAccess(name: string, bundleName: string): Promise<void> **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.disableAppAccess("ZhangSan", "com.example.ohos.accountjsdemo").then(() => { + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.disableAppAccess("ZhangSan", "com.example.accountjsdemo").then(() => { console.log('disableAppAccess Success'); }).catch((err) => { console.log("disableAppAccess err: " + JSON.stringify(err)); @@ -2945,15 +3037,15 @@ enableAppAccess(name: string, bundleName: string, callback: AsyncCallback<voi | 参数名 | 类型 | 必填 | 说明 | | ---------- | ------------------------- | ---- | --------------------------------- | -| name | string | 是 | 应用帐号名称。 | +| name | string | 是 | 应用帐号的名称。 | | bundleName | string | 是 | 第三方应用的包名。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当允许指定第三方应用帐号名称对指定包名称的第三方应用进行访问设置成功时,err为undefined,否则为错误对象。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当允许指定第三方应用帐号名称对指定包名称的第三方应用进行访问设置成功时,err为null,否则为错误对象。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.enableAppAccess("ZhangSan", "com.example.ohos.accountjsdemo", (err) => { + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.enableAppAccess("ZhangSan", "com.example.accountjsdemo", (err) => { console.log("enableAppAccess: " + JSON.stringify(err)); }); ``` @@ -2974,7 +3066,7 @@ enableAppAccess(name: string, bundleName: string): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | ---------- | ------ | ---- | --------- | -| name | string | 是 | 应用帐号名称。 | +| name | string | 是 | 应用帐号的名称。 | | bundleName | string | 是 | 第三方应用的包名。 | **返回值:** @@ -2986,8 +3078,8 @@ enableAppAccess(name: string, bundleName: string): Promise<void> **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.enableAppAccess("ZhangSan", "com.example.ohos.accountjsdemo").then(() => { + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.enableAppAccess("ZhangSan", "com.example.accountjsdemo").then(() => { console.log('enableAppAccess Success'); }).catch((err) => { console.log("enableAppAccess err: " + JSON.stringify(err)); @@ -2998,7 +3090,7 @@ enableAppAccess(name: string, bundleName: string): Promise<void> checkAppAccountSyncEnable(name: string, callback: AsyncCallback<boolean>): void -检查指定应用帐号是否允许应用数据同步。使用callback异步回调。 +检查指定应用帐号是否开启数据同步功能。使用callback异步回调。 > **说明:** 从API version 9开始废弃。建议使用[checkDataSyncEnabled](#checkdatasyncenabled9)替代。 > @@ -3012,13 +3104,13 @@ checkAppAccountSyncEnable(name: string, callback: AsyncCallback<boolean>): | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------- | ---- | --------------------- | -| name | string | 是 | 应用帐号名称。 | -| callback | AsyncCallback<boolean> | 是 | 回调函数。当检查指定应用帐号是否允许应用数据同步成功,err为undefined,data返回true表示指定应用帐号允许应用数据同步,data返回false表示指定应用帐号不允许应用数据同步;否则为错误对象。 | +| name | string | 是 | 应用帐号的名称。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。返回true表示指定应用帐号已开启数据同步功能;返回false表示未开启。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.checkAppAccountSyncEnable("ZhangSan", (err, result) => { console.log("checkAppAccountSyncEnable err: " + JSON.stringify(err)); console.log('checkAppAccountSyncEnable result: ' + result); @@ -3029,7 +3121,7 @@ checkAppAccountSyncEnable(name: string, callback: AsyncCallback<boolean>): checkAppAccountSyncEnable(name: string): Promise<boolean> -检查指定应用帐号是否允许应用数据同步。使用Promise异步回调。 +检查指定应用帐号是否开启数据同步功能。使用Promise异步回调。 > **说明:** 从API version 9开始废弃。建议使用[checkDataSyncEnabled](#checkdatasyncenabled9-1)替代。 > @@ -3043,18 +3135,18 @@ checkAppAccountSyncEnable(name: string): Promise<boolean> | 参数名 | 类型 | 必填 | 说明 | | ---- | ------ | ---- | ------- | -| name | string | 是 | 应用帐号名称。 | +| name | string | 是 | 应用帐号的名称。 | **返回值:** | 类型 | 说明 | -| :--------------------- | :-------------------- | -| Promise<boolean> | Promise对象。返回true表示允许应用数据同步;返回false表示不允许应用数据同步。 | +| ---------------------- | --------------------- | +| Promise<boolean> | Promise对象,返回true表示指定应用帐号已开启数据同步功能;返回false表示未开启。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.checkAppAccountSyncEnable("ZhangSan").then((data) => { console.log('checkAppAccountSyncEnable, result: ' + data); }).catch((err) => { @@ -3066,7 +3158,7 @@ checkAppAccountSyncEnable(name: string): Promise<boolean> setAccountCredential(name: string, credentialType: string, credential: string,callback: AsyncCallback<void>): void -设置此应用程序帐号的凭据。使用callback异步回调。 +设置指定应用帐号的凭据。使用callback异步回调。 > **说明:** 从API version 9开始废弃,建议使用[setCredential](#setcredential9)替代。 > @@ -3078,15 +3170,15 @@ setAccountCredential(name: string, credentialType: string, credential: string,ca | 参数名 | 类型 | 必填 | 说明 | | -------------- | ------------------------- | ---- | ------------- | -| name | string | 是 | 应用程序帐号名称。 | -| credentialType | string | 是 | 要设置的凭据类型。 | -| credential | string | 是 | 要设置的凭据。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当设置此应用程序帐号的凭据成功时,err为undefined,否则为错误对象。 | +| name | string | 是 | 应用帐号的名称。 | +| credentialType | string | 是 | 凭据类型。 | +| credential | string | 是 | 凭据取值。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当设置此应用程序帐号的凭据成功时,err为null,否则为错误对象。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.setAccountCredential("ZhangSan", "credentialType001", "credential001", (err) => { console.log("setAccountCredential err: " + JSON.stringify(err)); }); @@ -3096,7 +3188,7 @@ setAccountCredential(name: string, credentialType: string, credential: string,ca setAccountCredential(name: string, credentialType: string, credential: string): Promise<void> -设置此应用程序帐号的凭据。使用Promise异步回调。 +设置指定应用帐号的凭据。使用Promise异步回调。 > **说明:** 从API version 9开始废弃,建议使用[setCredential](#setcredential9-1)替代。 > @@ -3109,8 +3201,8 @@ setAccountCredential(name: string, credentialType: string, credential: string): | 参数名 | 类型 | 必填 | 说明 | | -------------- | ------ | ---- | ---------- | | name | string | 是 | 应用帐号的名称。 | -| credentialType | string | 是 | 要设置的凭据的类型。 | -| credential | string | 是 | 要设置的凭据。 | +| credentialType | string | 是 | 凭据类型。 | +| credential | string | 是 | 凭据取值。 | **返回值:** @@ -3121,7 +3213,7 @@ setAccountCredential(name: string, credentialType: string, credential: string): **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.setAccountCredential("ZhangSan", "credentialType001", "credential001").then(() => { console.log('setAccountCredential Success'); }).catch((err) => { @@ -3133,9 +3225,9 @@ setAccountCredential(name: string, credentialType: string, credential: string): setAccountExtraInfo(name: string, extraInfo: string, callback: AsyncCallback<void>): void -设置此应用程序帐号的额外信息。使用callback异步回调。 +设置指定应用帐号的额外信息。使用callback异步回调。 -> **说明:** 从API version 9开始废弃。 +> **说明:** 从API version 9开始废弃,建议使用[setCustomData](#setcustomdata9)替代。 > > 从 API version 7开始支持。 @@ -3146,14 +3238,14 @@ setAccountExtraInfo(name: string, extraInfo: string, callback: AsyncCallback< | 参数名 | 类型 | 必填 | 说明 | | --------- | ------------------------- | ---- | --------------- | -| name | string | 是 | 应用帐号名称。 | -| extraInfo | string | 是 | 要设置的额外信息。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当设置此应用程序帐号的额外信息成功时,err为undefined,否则为错误对象。 | +| name | string | 是 | 应用帐号的名称。 | +| extraInfo | string | 是 | 额外信息(能转换string类型的其它信息),额外信息不能是应用帐号的敏感信息(如应用账号密码、token等)。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当设置成功时,err为null,否则为错误对象。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.setAccountExtraInfo("ZhangSan", "Tk002", (err) => { console.log("setAccountExtraInfo err: " + JSON.stringify(err)); }); @@ -3165,7 +3257,7 @@ setAccountExtraInfo(name: string, extraInfo: string): Promise<void> 设置此应用程序帐号的额外信息。使用Promise异步回调。 -> **说明:** 从API version 9开始废弃。 +> **说明:** 从API version 9开始废弃,建议使用[setCustomData](#setcustomdata9-1)替代。 > > 从 API version 7开始支持。 @@ -3176,8 +3268,8 @@ setAccountExtraInfo(name: string, extraInfo: string): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | --------- | ------ | ---- | --------- | -| name | string | 是 | 应用帐号名称。 | -| extraInfo | string | 是 | 要设置的额外信息。 | +| name | string | 是 | 应用帐号的名称。 | +| extraInfo | string | 是 | 额外信息(能转换string类型的其它信息),额外信息不能是应用帐号的敏感信息(如应用账号密码、token等)。 | **返回值:** @@ -3188,7 +3280,7 @@ setAccountExtraInfo(name: string, extraInfo: string): Promise<void> **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.setAccountExtraInfo("ZhangSan", "Tk002").then(() => { console.log('setAccountExtraInfo Success'); }).catch((err) => { @@ -3200,7 +3292,7 @@ setAccountExtraInfo(name: string, extraInfo: string): Promise<void> setAppAccountSyncEnable(name: string, isEnable: boolean, callback: AsyncCallback<void>): void -设置指定的应用程序帐号是否允许应用程序数据同步。使用callback异步回调。 +开启或禁止指定应用帐号的数据同步功能。使用callback异步回调。 > **说明:** 从API version 9开始废弃, 建议使用[setDataSyncEnabled](#setdatasyncenabled9)替代。 > @@ -3214,14 +3306,14 @@ setAppAccountSyncEnable(name: string, isEnable: boolean, callback: AsyncCallback | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ------------------------- | -| name | string | 是 | 应用帐号名称。 | -| isEnable | boolean | 是 | 是否允许应用数据同步。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当设置指定的应用帐号是否允许应用程序数据同步成功时,err为undefined,否则为错误对象。 | +| name | string | 是 | 应用帐号的名称。 | +| isEnable | boolean | 是 | 是否开启数据同步。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当开启或禁止成功时,err为null,否则为错误对象。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.setAppAccountSyncEnable("ZhangSan", true, (err) => { console.log("setAppAccountSyncEnable err: " + JSON.stringify(err)); }); @@ -3231,7 +3323,7 @@ setAppAccountSyncEnable(name: string, isEnable: boolean, callback: AsyncCallback setAppAccountSyncEnable(name: string, isEnable: boolean): Promise<void> -设置指定的应用程序帐号是否允许应用程序数据同步。使用Promise异步回调。 +开启或禁止指定应用帐号的数据同步功能。使用Promise异步回调。 > **说明:** 从API version 9开始废弃, 建议使用[setDataSyncEnabled](#setdatasyncenabled9-1)替代。 > @@ -3245,8 +3337,8 @@ setAppAccountSyncEnable(name: string, isEnable: boolean): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | -------- | ------- | ---- | ----------- | -| name | string | 是 | 应用帐号名称。 | -| isEnable | boolean | 是 | 是否允许应用数据同步。 | +| name | string | 是 | 应用帐号的名称。 | +| isEnable | boolean | 是 | 是否开启数据同步。 | **返回值:** @@ -3257,7 +3349,7 @@ setAppAccountSyncEnable(name: string, isEnable: boolean): Promise<void> **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager .setAppAccountSyncEnable("ZhangSan", true).then(() => { console.log('setAppAccountSyncEnable Success'); }).catch((err) => { @@ -3269,7 +3361,7 @@ setAppAccountSyncEnable(name: string, isEnable: boolean): Promise<void> setAssociatedData(name: string, key: string, value: string, callback: AsyncCallback<void>): void -设置与此应用程序帐号关联的数据。使用callback异步回调。 +设置指定应用帐号的关联数据。使用callback异步回调。 > **说明:** 从API version 9开始废弃, 建议使用[setCustomData](#setcustomdata9)替代。 > @@ -3282,15 +3374,15 @@ setAssociatedData(name: string, key: string, value: string, callback: AsyncCallb | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ----------------- | -| name | string | 是 | 应用帐号名称。 | -| key | string | 是 | 要设置的数据的键,密钥可以自定义。 | -| value | string | 是 | 要设置的数据的值。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当设置与此应用帐号关联的数据成功时,err为undefined,否则为错误对象。 | +| name | string | 是 | 应用帐号的名称。 | +| key | string | 是 | 关联数据的键名。 | +| value | string | 是 | 关联数据的取值。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当设置与此应用帐号关联的数据成功时,err为null,否则为错误对象。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.setAssociatedData("ZhangSan", "k001", "v001", (err) => { console.log("setAssociatedData err: " + JSON.stringify(err)); }); @@ -3300,7 +3392,7 @@ setAssociatedData(name: string, key: string, value: string, callback: AsyncCallb setAssociatedData(name: string, key: string, value: string): Promise<void> -设置与此应用程序帐号关联的数据。使用Promise异步回调。 +设置指定应用帐号的关联数据。使用Promise异步回调。 > **说明:** 从API version 9开始废弃, 建议使用[setCustomData](#setcustomdata9-1)替代。 > @@ -3313,9 +3405,9 @@ setAssociatedData(name: string, key: string, value: string): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------- | -| name | string | 是 | 应用帐号名称。 | -| key | string | 是 | 要设置的数据的键,密钥可以自定义。 | -| value | string | 是 | 要设置的数据的值。 | +| name | string | 是 | 应用帐号的名称。 | +| key | string | 是 | 关联数据的键名。 | +| value | string | 是 | 关联数据的取值。 | **返回值:** @@ -3326,7 +3418,7 @@ setAssociatedData(name: string, key: string, value: string): Promise<void> **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.setAssociatedData("ZhangSan", "k001", "v001").then(() => { console.log('setAssociatedData Success'); }).catch((err) => { @@ -3338,13 +3430,13 @@ setAssociatedData(name: string, key: string, value: string): Promise<void> getAllAccessibleAccounts(callback: AsyncCallback<Array<AppAccountInfo>>): void -获取全部应用已授权帐号信息。 +获取所有可访问的应用帐号信息。使用callback异步回调。 > **说明:** 从API version 9开始废弃, 建议使用[getAllAccounts](#getallaccounts9)替代。 > > 从 API version 7开始支持。 -**需要权限:** ohos.permission.GET_ALL_APP_ACCOUNTS,仅系统应用可用。 +**需要权限:** ohos.permission.GET_ALL_APP_ACCOUNTS。 **系统能力:** SystemCapability.Account.AppAccount @@ -3352,12 +3444,12 @@ getAllAccessibleAccounts(callback: AsyncCallback<Array<AppAccountInfo>& | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | --------- | -| callback | AsyncCallback<Array<[AppAccountInfo](#appaccountinfo)>> | 是 | 应用帐号信息列表。 | +| callback | AsyncCallback<Array<[AppAccountInfo](#appaccountinfo)>> | 是 | 回调函数。当查询成功时,err为null,data为获取到的应用帐号信息列表;否则为错误对象。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.getAllAccessibleAccounts((err, data)=>{ console.debug("getAllAccessibleAccounts err:" + JSON.stringify(err)); console.debug("getAllAccessibleAccounts data:" + JSON.stringify(data)); @@ -3368,13 +3460,13 @@ getAllAccessibleAccounts(callback: AsyncCallback<Array<AppAccountInfo>& getAllAccessibleAccounts(): Promise<Array<AppAccountInfo>> -获取全部应用已授权帐号信息。 +获取所有可访问的应用帐号信息。使用Promise异步回调。 > **说明:** 从API version 9开始废弃, 建议使用[getAllAccounts](#getallaccounts9-1)替代。 > > 从 API version 7开始支持。 -**需要权限:** ohos.permission.GET_ALL_APP_ACCOUNTS,仅系统应用可用。 +**需要权限:** ohos.permission.GET_ALL_APP_ACCOUNTS。 **系统能力:** SystemCapability.Account.AppAccount @@ -3382,12 +3474,12 @@ getAllAccessibleAccounts(): Promise<Array<AppAccountInfo>> | 类型 | 说明 | | ---------------------------------------- | --------------------- | -| Promise<Array<[AppAccountInfo](#appaccountinfo)>> | Promise对象。返回全部应用已授权帐号信息对象。 | +| Promise<Array<[AppAccountInfo](#appaccountinfo)>> | Promise对象,返回全部应用已授权帐号信息对象。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.getAllAccessibleAccounts().then((data) => { console.log('getAllAccessibleAccounts: ' + data); }).catch((err) => { @@ -3399,13 +3491,13 @@ getAllAccessibleAccounts(): Promise<Array<AppAccountInfo>> getAllAccounts(owner: string, callback: AsyncCallback<Array<AppAccountInfo>>): void -获取指定应用全部帐号信息。 +根据应用帐号所有者获取调用方可访问的应用帐号列表。使用callback异步回调。 -> **说明:** 从API version 9开始废弃, 建议使用[getAccountsByOwner]替代。 +> **说明:** 从API version 9开始废弃, 建议使用[getAccountsByOwner](#getaccountsbyowner9)替代。 > > 从 API version 7开始支持。 -**需要权限:** ohos.permission.GET_ALL_APP_ACCOUNTS,仅系统应用可用。 +**需要权限:** ohos.permission.GET_ALL_APP_ACCOUNTS。 **系统能力:** SystemCapability.Account.AppAccount @@ -3413,13 +3505,13 @@ getAllAccounts(owner: string, callback: AsyncCallback<Array<AppAccountInfo | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | --------- | -| owner | string | 是 | 应用包名称。 | +| owner | string | 是 | 应用帐号所有者的包名。 | | callback | AsyncCallback<Array<[AppAccountInfo](#appaccountinfo)>> | 是 | 应用帐号信息列表。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); const selfBundle = "com.example.actsgetallaaccounts"; appAccountManager.getAllAccounts(selfBundle, (err, data)=>{ console.debug("getAllAccounts err:" + JSON.stringify(err)); @@ -3431,7 +3523,7 @@ getAllAccounts(owner: string, callback: AsyncCallback<Array<AppAccountInfo getAllAccounts(owner: string): Promise<Array<AppAccountInfo>> -获取指定应用全部帐号信息。 +根据应用帐号所有者获取调用方可访问的应用帐号列表。使用Promise异步回调。 > **说明:** 从API version 9开始废弃, 建议使用[getAccountsByOwner](#getaccountsbyowner9-1)替代。 > @@ -3451,12 +3543,12 @@ getAllAccounts(owner: string): Promise<Array<AppAccountInfo>> | 类型 | 说明 | | ---------------------------------------- | --------------------- | -| Promise<Array<[AppAccountInfo](#appaccountinfo)>> | Promise对象。返回指定应用全部帐号信息对象。 | +| Promise<Array<[AppAccountInfo](#appaccountinfo)>> | Promise对象,返回指定应用全部帐号信息对象。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); const selfBundle = "com.example.actsgetallaaccounts"; appAccountManager.getAllAccounts(selfBundle).then((data) => { console.log('getAllAccounts: ' + data); @@ -3469,7 +3561,7 @@ getAllAccounts(owner: string): Promise<Array<AppAccountInfo>> getAccountCredential(name: string, credentialType: string, callback: AsyncCallback<string>): void -获取此应用帐号的凭据(如数字密码、人脸和PIN码等)。使用callback异步回调。 +获取指定应用帐号的凭据。使用callback异步回调。 > **说明:** 从API version 9开始废弃, 建议使用[getCredential](#getcredential9)替代。 > @@ -3481,14 +3573,14 @@ getAccountCredential(name: string, credentialType: string, callback: AsyncCallba | 参数名 | 类型 | 必填 | 说明 | | -------------- | --------------------------- | ---- | -------------- | -| name | string | 是 | 应用帐号名称。 | -| credentialType | string | 是 | 获取此应用帐号的凭据的类型。 | -| callback | AsyncCallback<string> | 是 | 回调函数。当获取此应用帐号的凭据成功时,err为undefined,data返回此应用帐号的凭据对象;否则为错误对象。 | +| name | string | 是 | 应用帐号的名称。 | +| credentialType | string | 是 | 凭据类型。 | +| callback | AsyncCallback<string> | 是 | 回调函数。当获取凭据成功时,err为null,data为指定应用帐号的凭据;否则为错误对象。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.getAccountCredential("ZhangSan", "credentialType001", (err, result) => { console.log("getAccountCredential err: " + JSON.stringify(err)); console.log('getAccountCredential result: ' + result); @@ -3499,7 +3591,7 @@ getAccountCredential(name: string, credentialType: string, callback: AsyncCallba getAccountCredential(name: string, credentialType: string): Promise<string> -获取此应用程序帐号的凭据。使用Promise异步回调。 +获取指定应用帐号的凭据。使用Promise异步回调。 > **说明:** 从API version 9开始废弃, 建议使用[getCredential](#getcredential9-1)替代。 > @@ -3511,19 +3603,19 @@ getAccountCredential(name: string, credentialType: string): Promise<string> | 参数名 | 类型 | 必填 | 说明 | | -------------- | ------ | ---- | ---------- | -| name | string | 是 | 应用帐号名称。 | -| credentialType | string | 是 | 要获取的凭据的类型。 | +| name | string | 是 | 应用帐号的名称。 | +| credentialType | string | 是 | 凭据类型。 | **返回值:** | 类型 | 说明 | | :-------------------- | :-------------------- | -| Promise<string> | Promise对象。返回此应用程序帐号的凭据对象。 | +| Promise<string> | Promise对象,返回指定应用帐号的凭据。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.getAccountCredential("ZhangSan", "credentialType001").then((data) => { console.log('getAccountCredential, result: ' + data); }).catch((err) => { @@ -3535,9 +3627,9 @@ getAccountCredential(name: string, credentialType: string): Promise<string> getAccountExtraInfo(name: string, callback: AsyncCallback<string>): void -获取此应用帐号的额外信息(能转换成string类型的其它信息)。使用callback异步回调。 +获取指定应用帐号的额外信息(能转换成string类型的其它信息)。使用callback异步回调。 -> **说明:** 从API version 9开始废弃。 +> **说明:** 从API version 9开始废弃, 建议使用[getCustomData](#getcustomdata9)替代。 > > 从 API version 7开始支持。 @@ -3547,13 +3639,13 @@ getAccountExtraInfo(name: string, callback: AsyncCallback<string>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------- | ---- | --------------- | -| name | string | 是 | 应用帐号名称。 | -| callback | AsyncCallback<string> | 是 | 回调函数。当获取此应用帐号的额外信息成功时,err为undefined,data返回此应用帐号的额外信息对象;否则为错误对象。 | +| name | string | 是 | 应用帐号的名称。 | +| callback | AsyncCallback<string> | 是 | 回调函数。当获取此应用帐号的额外信息成功时,err为null,data返回此应用帐号的额外信息对象;否则为错误对象。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.getAccountExtraInfo("ZhangSan", (err, result) => { console.log("getAccountExtraInfo err: " + JSON.stringify(err)); console.log('getAccountExtraInfo result: ' + result); @@ -3564,9 +3656,9 @@ getAccountExtraInfo(name: string, callback: AsyncCallback<string>): void getAccountExtraInfo(name: string): Promise<string> -获取此应用程序帐号的额外信息。使用Promise异步回调。 +获取指定应用帐号的额外信息(能转换成string类型的其它信息)。使用Promise异步回调。 -> **说明:** 从API version 9开始废弃。 +> **说明:** 从API version 9开始废弃, 建议使用[getCustomData](#getcustomdata9-1)替代。 > > 从 API version 7开始支持。 @@ -3576,18 +3668,18 @@ getAccountExtraInfo(name: string): Promise<string> | 参数名 | 类型 | 必填 | 说明 | | ---- | ------ | ---- | ------- | -| name | string | 是 | 应用帐号名称。 | +| name | string | 是 | 应用帐号的名称。 | **返回值:** | 类型 | 说明 | | :-------------------- | :-------------------- | -| Promise<string> | Promise对象。返回此应用程序帐号的额外信息对象。 | +| Promise<string> | Promise对象,返回此应用程序帐号的额外信息对象。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.getAccountExtraInfo("ZhangSan").then((data) => { console.log('getAccountExtraInfo, result: ' + data); }).catch((err) => { @@ -3599,7 +3691,7 @@ getAccountExtraInfo(name: string): Promise<string> getAssociatedData(name: string, key: string, callback: AsyncCallback<string>): void -获取与此应用程序帐号关联的数据。使用callback异步回调。 +根据指定键名获取特定应用帐号的关联数据。使用callback异步回调。 > **说明:** 从API version 9开始废弃, 建议使用[getCustomData](#getcustomdata9)替代。 > @@ -3611,14 +3703,14 @@ getAssociatedData(name: string, key: string, callback: AsyncCallback<string&g | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------- | ---- | ----------------- | -| name | string | 是 | 应用帐号名称。 | -| key | string | 是 | 要获取的数据的键。 | -| callback | AsyncCallback<string> | 是 | 回调函数。当获取与此应用程序帐号关联的数据成功时,err为undefined,data返回与此应用程序帐号关联的数据对象;否则为错误对象。 | +| name | string | 是 | 应用帐号的名称。 | +| key | string | 是 | 关联数据的键名。 | +| callback | AsyncCallback<string> | 是 | 回调函数。当获取成功时,err为null,data为关联数据的取值;否则为错误对象。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.getAssociatedData("ZhangSan", "k001", (err, result) => { console.log("getAssociatedData err: " + JSON.stringify(err)); console.log('getAssociatedData result: ' + result); @@ -3641,19 +3733,19 @@ getAssociatedData(name: string, key: string): Promise<string> | 参数名 | 类型 | 必填 | 说明 | | ---- | ------ | ---- | --------- | -| name | string | 是 | 应用帐号名称。 | -| key | string | 是 | 要获取的数据的键。 | +| name | string | 是 | 应用帐号的名称。 | +| key | string | 是 | 关联数据的键名。 | **返回值:** | 类型 | 说明 | | :-------------------- | :-------------------- | -| Promise<string> | Promise对象。返回与此应用程序帐号关联的数据对象。 | +| Promise<string> | Promise对象,返回关联数据的取值。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.getAssociatedData("ZhangSan", "k001").then((data) => { console.log('getAssociatedData: ' + data); }).catch((err) => { @@ -3665,7 +3757,7 @@ getAssociatedData(name: string, key: string): Promise<string> on(type: 'change', owners: Array<string>, callback: Callback<Array<AppAccountInfo>>): void -订阅指定帐号所有者的帐户变更事件。使用callback异步回调。 +订阅指定应用的帐号信息变更事件。 > **说明:** 从API version 9开始废弃, 建议使用[on('accountChange')](#onaccountchange9)替代。 > @@ -3677,14 +3769,14 @@ on(type: 'change', owners: Array<string>, callback: Callback<Array<A | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ------------------------------ | -| type | 'change' | 是 | 事件回调类型,支持的事件为'change',当帐号所有者更新帐号时,触发该事件。 | -| owners | Array<string> | 是 | 指示帐号的所有者。 | -| callback | Callback<Array<[AppAccountInfo](#appaccountinfo)>> | 是 | 回调函数。返回指定帐号所有者更新的帐号信息数组。 | +| type | 'change' | 是 | 事件回调类型,支持的事件为'change',当帐号所有者更新帐号信息时,触发该事件。 | +| owners | Array<string> | 是 | 应用帐号所有者的包名列表。 | +| callback | Callback<Array<[AppAccountInfo](#appaccountinfo)>> | 是 | 回调函数,返回信息发生变更的应用帐号列表。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); function changeOnCallback(data){ console.debug("receive change data:" + JSON.stringify(data)); } @@ -3700,7 +3792,7 @@ on(type: 'change', owners: Array<string>, callback: Callback<Array<A off(type: 'change', callback?: Callback>): void -取消订阅帐号事件。使用callback异步回调。 +取消订阅帐号信息变更事件。 > **说明:** 从API version 9开始废弃, 建议使用[off('accountChange')](#offaccountchange9)替代。 > @@ -3712,13 +3804,13 @@ off(type: 'change', callback?: Callback>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------------- | ---- | ------------ | -| type | 'change' | 是 | 事件回调类型,支持的事件为'change',当帐号所有者更新帐号时,触发该事件。 | -| callback | Callback> | 否 | 回调函数,返回指定帐号所有者更新的帐号信息数组。 | +| type | 'change' | 是 | 事件回调类型,支持的事件为'change',当帐号所有者更新帐号信息时,触发该事件。 | +| callback | Callback> | 否 | 回调函数,返回信息发生变更的应用帐号列表。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); function changeOnCallback(data){ console.debug("receive change data:" + JSON.stringify(data)); appAccountManager.off('change', function(){ @@ -3737,7 +3829,7 @@ off(type: 'change', callback?: Callback>): void authenticate(name: string, owner: string, authType: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void -对应用帐户进行鉴权以获取OAuth令牌。使用callback异步回调。 +对应用帐号进行鉴权以获取授权令牌。使用callback异步回调。 > **说明:** 从API version 9开始废弃, 建议使用[auth](#auth9)替代。 > @@ -3749,11 +3841,11 @@ authenticate(name: string, owner: string, authType: string, options: {[key: stri | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------- | ---- | --------------- | -| name | string | 是 | 要鉴权的应用帐号名称。 | -| owner | string | 是 | 要鉴权的应用帐号所有者包名。 | +| name | string | 是 | 应用帐号的名称。 | +| owner | string | 是 | 应用帐号所有者的包名。 | | authType | string | 是 | 鉴权类型。 | | options | {[key: string]: any} | 是 | 鉴权所需的可选项。 | -| callback | [AuthenticatorCallback](#authenticatorcallbackdeprecated) | 是 | 回调函数。返回鉴权结果对象。 | +| callback | [AuthenticatorCallback](#authenticatorcallbackdeprecated) | 是 | 回调对象,返回鉴权结果。 | **示例:** @@ -3772,8 +3864,8 @@ authenticate(name: string, owner: string, authType: string, options: {[key: stri }); } - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.authenticate("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", {}, { + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.authenticate("LiSi", "com.example.accountjsdemo", "getSocialData", {}, { onResult: onResultCallback, onRequestRedirected: onRequestRedirectedCallback }); @@ -3783,7 +3875,7 @@ authenticate(name: string, owner: string, authType: string, options: {[key: stri getOAuthToken(name: string, owner: string, authType: string, callback: AsyncCallback<string>): void -获取指定应用帐号和鉴权类型的OAuth令牌。使用callback异步回调。 +获取指定应用帐号的特定鉴权类型的授权令牌。使用callback异步回调。 > **说明:** 从API version 9开始废弃, 建议使用[getAuthToken](#getauthtoken9)替代。 > @@ -3796,15 +3888,15 @@ getOAuthToken(name: string, owner: string, authType: string, callback: AsyncCall | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------- | ---- | ----------- | | name | string | 是 | 应用帐号的名称。 | -| owner | string | 是 | 应用帐号的所有者包名。 | +| owner | string | 是 | 应用帐号所有者的包名。 | | authType | string | 是 | 鉴权类型。 | -| callback | AsyncCallback<string> | 是 | 回调函数。当获取指定应用帐号和鉴权类型的Auth令牌成功时,err为undefined,data返回Auth令牌对象;否则为错误对象。 | +| callback | AsyncCallback<string> | 是 | 回调函数。当获取成功时,err为null,data为授权令牌值;否则为错误对象。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", (err, data) => { + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getOAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", (err, data) => { console.log('getOAuthToken err: ' + JSON.stringify(err)); console.log('getOAuthToken token: ' + data); }); @@ -3814,7 +3906,7 @@ getOAuthToken(name: string, owner: string, authType: string, callback: AsyncCall getOAuthToken(name: string, owner: string, authType: string): Promise<string> -获取指定应用帐户和鉴权类型的OAuth令牌。使用Promise异步回调。 +获取指定应用帐号的特定鉴权类型的授权令牌。使用Promise异步回调。 > **说明:** 从API version 9开始废弃, 建议使用[getAuthToken](#getauthtoken9-1)替代。 > @@ -3827,20 +3919,20 @@ getOAuthToken(name: string, owner: string, authType: string): Promise<string& | 参数名 | 类型 | 必填 | 说明 | | -------- | ------ | ---- | ----------- | | name | string | 是 | 应用帐号的名称。 | -| owner | string | 是 | 应用帐号的所有者包名。 | +| owner | string | 是 | 应用帐号所有者的包名。 | | authType | string | 是 | 鉴权类型。 | **返回值:** | 类型 | 说明 | | --------------------- | --------------------- | -| Promise<string> | Promise对象。返回指定应用帐户和鉴权类型的OAuth令牌对象。 | +| Promise<string> | Promise对象,返回授权令牌。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData").then((data) => { + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getOAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData").then((data) => { console.log('getOAuthToken token: ' + data); }).catch((err) => { console.log("getOAuthToken err: " + JSON.stringify(err)); @@ -3851,7 +3943,7 @@ getOAuthToken(name: string, owner: string, authType: string): Promise<string& setOAuthToken(name: string, authType: string, token: string, callback: AsyncCallback<void>): void -设置指定应用帐号和鉴权类型的OAuth令牌。使用callback异步回调。 +为指定应用帐号设置特定鉴权类型的授权令牌。使用callback异步回调。 > **说明:** 从API version 9开始废弃, 建议使用[setAuthToken](#setauthtoken9)替代。 > @@ -3865,13 +3957,13 @@ setOAuthToken(name: string, authType: string, token: string, callback: AsyncCall | -------- | ------------------------- | ---- | -------- | | name | string | 是 | 应用帐号的名称。 | | authType | string | 是 | 鉴权类型。 | -| token | string | 是 | OAuth令牌。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当设置指定应用帐号和鉴权类型的OAuth令牌成功时,err为undefined;否则为错误对象。 | +| token | string | 是 | 授权令牌。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当设置成功时,err为null;否则为错误对象。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.setOAuthToken("LiSi", "getSocialData", "xxxx", (err) => { console.log('setOAuthToken err: ' + JSON.stringify(err)); }); @@ -3881,7 +3973,7 @@ setOAuthToken(name: string, authType: string, token: string, callback: AsyncCall setOAuthToken(name: string, authType: string, token: string): Promise<void> -设置指定应用帐户和鉴权类型的OAuth令牌。使用Promise异步回调。 +为指定应用帐号设置特定鉴权类型的授权令牌。使用Promise异步回调。 > **说明:** 从API version 9开始废弃, 建议使用[setAuthToken](#setauthtoken9-1)替代。 > @@ -3895,7 +3987,7 @@ setOAuthToken(name: string, authType: string, token: string): Promise<void> | -------- | ------ | ---- | -------- | | name | string | 是 | 应用帐号的名称。 | | authType | string | 是 | 鉴权类型。 | -| token | string | 是 | OAuth令牌。 | +| token | string | 是 | 授权令牌。 | **返回值:** @@ -3906,7 +3998,7 @@ setOAuthToken(name: string, authType: string, token: string): Promise<void> **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.setOAuthToken("LiSi", "getSocialData", "xxxx").then(() => { console.log('setOAuthToken successfully'); }).catch((err) => { @@ -3918,7 +4010,7 @@ setOAuthToken(name: string, authType: string, token: string): Promise<void> deleteOAuthToken(name: string, owner: string, authType: string, token: string, callback: AsyncCallback<void>): void -删除指定应用帐户和鉴权类型的OAuth令牌。使用callback异步回调。 +删除指定应用帐号的特定鉴权类型的授权令牌。使用callback异步回调。 > **说明:** 从API version 9开始废弃, 建议使用[deleteAuthToken](#deleteauthtoken9)替代。 > @@ -3931,16 +4023,16 @@ deleteOAuthToken(name: string, owner: string, authType: string, token: string, c | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ------------ | | name | string | 是 | 应用帐号的名称。 | -| owner | string | 是 | 应用帐号的所有者包名。 | +| owner | string | 是 | 应用帐号所有者的包名。 | | authType | string | 是 | 鉴权类型。 | -| token | string | 是 | 要删除的OAuth令牌。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当删除指定应用帐户和鉴权类型的OAuth令牌成功时,err为undefined;否则为错误对象。 | +| token | string | 是 | 授权令牌。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当删除成功时,err为null;否则为错误对象。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.deleteOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", "xxxxx", (err) => { + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.deleteOAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", "xxxxx", (err) => { console.log('deleteOAuthToken err: ' + JSON.stringify(err)); }); ``` @@ -3949,9 +4041,9 @@ deleteOAuthToken(name: string, owner: string, authType: string, token: string, c deleteOAuthToken(name: string, owner: string, authType: string, token: string): Promise<void> -删除指定应用帐户和鉴权类型的OAuth令牌。使用Promise异步回调。 +删除指定应用帐号的特定鉴权类型的授权令牌。使用Promise异步回调。 -> **说明:** 从API version 9开始废弃, 建议使用[setAuthToken](#setauthtoken9-1)替代。 +> **说明:** 从API version 9开始废弃, 建议使用[deleteAuthToken](#deleteauthtoken9-1)替代。 > > 从 API version 8开始支持。 @@ -3962,9 +4054,9 @@ deleteOAuthToken(name: string, owner: string, authType: string, token: string): | 参数名 | 类型 | 必填 | 说明 | | -------- | ------ | ---- | ------------ | | name | string | 是 | 应用帐号的名称。 | -| owner | string | 是 | 应用帐号的所有者包名。 | +| owner | string | 是 | 应用帐号所有者的包名。 | | authType | string | 是 | 鉴权类型。 | -| token | string | 是 | 要删除的OAuth令牌。 | +| token | string | 是 | 授权令牌。 | **返回值:** @@ -3975,8 +4067,8 @@ deleteOAuthToken(name: string, owner: string, authType: string, token: string): **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.deleteOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", "xxxxx").then(() => { + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.deleteOAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", "xxxxx").then(() => { console.log('deleteOAuthToken successfully'); }).catch((err) => { console.log("deleteOAuthToken err: " + JSON.stringify(err)); @@ -3987,7 +4079,7 @@ deleteOAuthToken(name: string, owner: string, authType: string, token: string): setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean, callback: AsyncCallback<void>): void -设置指定鉴权类型的Auth令牌对特定应用的可见性。使用callback异步回调。 +设置指定帐号的特定鉴权类型的授权令牌对指定应用的可见性。使用callback异步回调。 > **说明:** 从API version 9开始废弃, 建议使用[setAuthTokenVisibility](#setauthtokenvisibility9)替代。 > @@ -4002,14 +4094,14 @@ setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVi | name | string | 是 | 应用帐号的名称。 | | authType | string | 是 | 鉴权类型。 | | bundleName | string | 是 | 被设置可见性的应用包名。 | -| isVisible | boolean | 是 | 是否可见。当设置成true可见,false不可见。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当设置指定鉴权类型的Auth令牌对特定应用的可见性成功时,err为undefined;否则为错误对象。 | +| isVisible | boolean | 是 | 是否可见。true表示可见,false表示不可见。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当设置成功时,err为null;否则为错误对象。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setOAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", true, (err) => { + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setOAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", true, (err) => { console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err)); }); ``` @@ -4018,7 +4110,7 @@ setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVi setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean): Promise<void> -设置指定鉴权类型的OAuth令牌对特定应用的可见性。使用Promise异步回调。 +设置指定帐号的特定鉴权类型的授权令牌对指定应用的可见性。使用Promise异步回调。 > **说明:** 从API version 9开始废弃, 建议使用[setAuthTokenVisibility](#setauthtokenvisibility9-1)替代。 > @@ -4033,7 +4125,7 @@ setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVi | name | string | 是 | 应用帐号的名称。 | | authType | string | 是 | 鉴权类型。 | | bundleName | string | 是 | 被设置可见性的应用包名。 | -| isVisible | boolean | 是 | 是否可见。 | +| isVisible | boolean | 是 | 是否可见。true表示可见,false表示不可见。 | **返回值:** @@ -4044,8 +4136,8 @@ setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVi **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setOAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", true).then(() => { + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setOAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", true).then(() => { console.log('setOAuthTokenVisibility successfully'); }).catch((err) => { console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err)); @@ -4056,7 +4148,7 @@ setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVi checkOAuthTokenVisibility(name: string, authType: string, bundleName: string, callback: AsyncCallback<boolean>): void -检查指定鉴权类型的OAuth令牌对特定应用的可见性。使用callback异步回调。 +检查指定应用帐号的特定鉴权类型的授权令牌对指定应用的可见性。使用callback异步回调。 > **说明:** 从API version 9开始废弃, 建议使用[checkAuthTokenVisibility](#checkauthtokenvisibility9)替代。 > @@ -4071,13 +4163,13 @@ checkOAuthTokenVisibility(name: string, authType: string, bundleName: string, ca | name | string | 是 | 应用帐号的名称。 | | authType | string | 是 | 鉴权类型。 | | bundleName | string | 是 | 检查可见性的应用包名。 | -| callback | AsyncCallback<boolean> | 是 | 回调函数。检查指定鉴权类型的OAuth令牌对特定应用的可见性时,err为undefined,data为true表示可见,data为false表示不可见;否则为错误对象。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。当检查成功时,err为null,data为true表示可见,data为false表示不可见;否则为错误对象。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.checkOAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", (err, data) => { + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.checkOAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", (err, data) => { console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err)); console.log('checkOAuthTokenVisibility isVisible: ' + data); }); @@ -4087,7 +4179,7 @@ checkOAuthTokenVisibility(name: string, authType: string, bundleName: string, ca checkOAuthTokenVisibility(name: string, authType: string, bundleName: string): Promise<boolean> -检查指定鉴权类型的OAuth令牌对特定应用的可见性。使用Promise异步回调。 +检查指定应用帐号的特定鉴权类型的授权令牌对指定应用的可见性。使用Promise异步回调。 > **说明:** 从API version 9开始废弃, 建议使用[checkAuthTokenVisibility](#checkauthtokenvisibility9-1)替代。 > @@ -4107,13 +4199,13 @@ checkOAuthTokenVisibility(name: string, authType: string, bundleName: string): P | 类型 | 说明 | | ---------------------- | --------------------- | -| Promise<boolean> | Promise对象。返回true表示指定鉴权类型的OAuth令牌对特定应用的可见,返回false表示不可见。 | +| Promise<boolean> | Promise对象,返回true表示指定鉴权类型的OAuth令牌对特定应用的可见,返回false表示不可见。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.checkOAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo").then((data) => { + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.checkOAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo").then((data) => { console.log('checkOAuthTokenVisibility isVisible: ' + data); }).catch((err) => { console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err)); @@ -4124,7 +4216,7 @@ checkOAuthTokenVisibility(name: string, authType: string, bundleName: string): P getAllOAuthTokens(name: string, owner: string, callback: AsyncCallback<Array<OAuthTokenInfo>>): void -获取指定应用对调用方全部可见的OAuth令牌。使用callback异步回调。 +获取指定帐号对调用方可见的所有授权令牌。使用callback异步回调。 > **说明:** 从API version 9开始废弃, 建议使用[getAllAuthTokens](#getallauthtokens9)替代。 > @@ -4137,14 +4229,14 @@ getAllOAuthTokens(name: string, owner: string, callback: AsyncCallback<Array& | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ----------- | | name | string | 是 | 应用帐号的名称。 | -| owner | string | 是 | 应用帐号的所有者包名。 | -| callback | AsyncCallback<Array< [OAuthTokenInfo](#oauthtokeninfodeprecated)>> | 是 | 回调函数。当获取指定应用对调用方全部可见的OAuth令牌成功时,err为undefined,data为全部可见的OAuth令牌数组;否则为错误对象。 | +| owner | string | 是 | 应用帐号所有者的包名。 | +| callback | AsyncCallback<Array< [OAuthTokenInfo](#oauthtokeninfodeprecated)>> | 是 | 回调函数。当获取成功时,err为null,data为授权令牌数组;否则为错误对象。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAllOAuthTokens("LiSi", "com.example.ohos.accountjsdemo", (err, data) => { + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAllOAuthTokens("LiSi", "com.example.accountjsdemo", (err, data) => { console.log("getAllOAuthTokens err: " + JSON.stringify(err)); console.log('getAllOAuthTokens data: ' + JSON.stringify(data)); }); @@ -4154,7 +4246,7 @@ getAllOAuthTokens(name: string, owner: string, callback: AsyncCallback<Array& getAllOAuthTokens(name: string, owner: string): Promise<Array<OAuthTokenInfo>> -获取指定应用帐户对调用方可见的全部OAuth令牌。使用Promise异步回调。 +获取指定帐号对调用方可见的所有授权令牌。使用Promise异步回调。 > **说明:** 从API version 9开始废弃, 建议使用[getAllAuthTokens](#getallauthtokens9-1)替代。 > @@ -4167,19 +4259,19 @@ getAllOAuthTokens(name: string, owner: string): Promise<Array<OAuthTokenIn | 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------- | | name | string | 是 | 应用帐号的名称。 | -| owner | string | 是 | 应用帐号的所有者包名。 | +| owner | string | 是 | 应用帐号所有者的包名。 | **返回值:** | 类型 | 说明 | | ---------------------------------------- | --------------------- | -| Promise<Array< [OAuthTokenInfo](#oauthtokeninfodeprecated)>> | Promise对象。返回指定应用帐户对调用方可见的全部OAuth令牌对象。 | +| Promise<Array< [OAuthTokenInfo](#oauthtokeninfodeprecated)>> | Promise对象,返回授权令牌数组。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAllOAuthTokens("LiSi", "com.example.ohos.accountjsdemo").then((data) => { + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAllOAuthTokens("LiSi", "com.example.accountjsdemo").then((data) => { console.log('getAllOAuthTokens data: ' + JSON.stringify(data)); }).catch((err) => { console.log("getAllOAuthTokens err: " + JSON.stringify(err)); @@ -4190,7 +4282,7 @@ getAllOAuthTokens(name: string, owner: string): Promise<Array<OAuthTokenIn getOAuthList(name: string, authType: string, callback: AsyncCallback<Array<string>>): void -获取指定应用帐户和鉴权类型的OAuth令牌的授权列表。使用callback异步回调。 +获取指定应用帐号的特定鉴权类型的授权列表,即被授权的包名数组(令牌的授权列表通过setOAuthTokenVisibility(#setoauthtokenvisibilitydeprecated)来设置)。使用callback异步回调。 > **说明:** 从API version 9开始废弃, 建议使用[getAuthList](#getauthlist9)替代。 > @@ -4203,16 +4295,16 @@ getOAuthList(name: string, authType: string, callback: AsyncCallback<Array< | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ----------------------- | | name | string | 是 | 应用帐号的名称。 | -| authType | string | 是 | 应用帐号的鉴权类型的OAuth令牌的授权列表。 | -| callback | AsyncCallback<Array<string>> | 是 | 回调函数。当获取指定应用帐户和鉴权类型的OAuth令牌的授权列表成功时,err为undefined,data为OAuth令牌的授权列表;否则为错误对象。 | +| authType | string | 是 | 鉴权类型。 | +| callback | AsyncCallback<Array<string>> | 是 | 回调函数。当获取成功时,err为null,data为被授权的包名数组;否则为错误对象。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getOAuthList("com.example.ohos.accountjsdemo", "getSocialData", (err, data) => { - console.log('getOAuthList err: ' + JSON.stringify(err)); - console.log('getOAuthList data: ' + JSON.stringify(data)); + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getOAuthList("com.example.accountjsdemo", "getSocialData", (err, data) => { + console.log('getOAuthList err: ' + JSON.stringify(err)); + console.log('getOAuthList data: ' + JSON.stringify(data)); }); ``` @@ -4220,7 +4312,7 @@ getOAuthList(name: string, authType: string, callback: AsyncCallback<Array< getOAuthList(name: string, authType: string): Promise<Array<string>> -获取指定应用帐户和鉴权类型的OAuth令牌的授权列表。使用Promise异步回调。 +获取指定应用帐号的特定鉴权类型的授权列表,即被授权的包名数组(令牌的授权列表通过setOAuthTokenVisibility(#setoauthtokenvisibilitydeprecated)来设置)。使用Promise异步回调。 > **说明:** 从API version 9开始废弃, 建议使用[getAuthList](#getauthlist9-1)替代。 > @@ -4233,19 +4325,19 @@ getOAuthList(name: string, authType: string): Promise<Array<string>> | 参数名 | 类型 | 必填 | 说明 | | -------- | ------ | ---- | ----------------------- | | name | string | 是 | 应用帐号的名称。 | -| authType | string | 是 | 应用帐号的鉴权类型的OAuth令牌的授权列表。 | +| authType | string | 是 | 鉴权类型。 | **返回值:** | 类型 | 说明 | | ---------------------------------- | --------------------- | -| Promise<Array<string>> | Promise对象。返回指定应用帐户和鉴权类型的OAuth令牌的授权列表对象。 | +| Promise<Array<string>> | Promise对象,返回被授权的包名数组。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getOAuthList("com.example.ohos.accountjsdemo", "getSocialData").then((data) => { + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getOAuthList("com.example.accountjsdemo", "getSocialData").then((data) => { console.log('getOAuthList data: ' + JSON.stringify(data)); }).catch((err) => { console.log("getOAuthList err: " + JSON.stringify(err)); @@ -4269,13 +4361,13 @@ getAuthenticatorCallback(sessionId: string, callback: AsyncCallback<Authentic | 参数名 | 类型 | 必填 | 说明 | | --------- | ---------------------------------------- | ---- | -------- | | sessionId | string | 是 | 鉴权会话的标识。 | -| callback | AsyncCallback<[AuthenticatorCallback](#authenticatorcallbackdeprecated)> | 是 | 回调函数。当获取鉴权会话的认证器回调函数成功时,err为undefined,data为认证器回调函数;否则为错误对象。 | +| callback | AsyncCallback<[AuthenticatorCallback](#authenticatorcallbackdeprecated)> | 是 | 回调函数。当获取鉴权会话的认证器回调函数成功时,err为null,data为认证器回调函数;否则为错误对象。 | **示例:** ```js import featureAbility from '@ohos.ability.featureAbility'; - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); featureAbility.getWant((err, want) => { var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; appAccountManager.getAuthenticatorCallback(sessionId, (err, callback) => { @@ -4284,7 +4376,7 @@ getAuthenticatorCallback(sessionId: string, callback: AsyncCallback<Authentic return; } var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi", - [account_appAccount.Constants.KEY_OWNER]: "com.example.ohos.accountjsdemo", + [account_appAccount.Constants.KEY_OWNER]: "com.example.accountjsdemo", [account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData", [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; callback.onResult(account_appAccount.ResultCode.SUCCESS, result); @@ -4314,19 +4406,19 @@ getAuthenticatorCallback(sessionId: string): Promise<AuthenticatorCallback> | 类型 | 说明 | | ------------------------------------ | --------------------- | -| Promise<[AuthenticatorCallback](#authenticatorcallbackdeprecated)> | Promise对象。返回鉴权会话的认证器回调对象。 | +| Promise<[AuthenticatorCallback](#authenticatorcallbackdeprecated)> | Promise对象,返回鉴权会话的认证器回调对象。 | **示例:** ```js import featureAbility from '@ohos.ability.featureAbility'; - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); featureAbility.getWant().then((want) => { var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => { var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi", - [account_appAccount.Constants.KEY_OWNER]: "com.example.ohos.accountjsdemo", + [account_appAccount.Constants.KEY_OWNER]: "com.example.accountjsdemo", [account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData", [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; callback.onResult(account_appAccount.ResultCode.SUCCESS, result); @@ -4342,7 +4434,7 @@ getAuthenticatorCallback(sessionId: string): Promise<AuthenticatorCallback> getAuthenticatorInfo(owner: string, callback: AsyncCallback<AuthenticatorInfo>): void -获取指定应用帐号的认证器信息。使用callback异步回调。 +获取指定应用的认证器信息。使用callback异步回调。 > **说明:** 从API version 9开始废弃, 建议使用[queryAuthenticatorInfo](#queryauthenticatorinfo9)替代。 > @@ -4354,14 +4446,14 @@ getAuthenticatorInfo(owner: string, callback: AsyncCallback<AuthenticatorInfo | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------------------- | ---- | ----------- | -| owner | string | 是 | 应用帐号的所有者包名。 | -| callback | AsyncCallback<[AuthenticatorInfo](#authenticatorinfo8)> | 是 | 回调函数。当获取指定应用帐号的认证器信息成功时,err为undefined,data为认证器信息对象;否则为错误对象。 | +| owner | string | 是 | 应用帐号所有者的包名。 | +| callback | AsyncCallback<[AuthenticatorInfo](#authenticatorinfo8)> | 是 | 回调函数。当获取成功时,err为null,data为认证器信息对象;否则为错误对象。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAuthenticatorInfo("com.example.ohos.accountjsdemo", (err, data) => { + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAuthenticatorInfo("com.example.accountjsdemo", (err, data) => { console.log("getAuthenticatorInfo err: " + JSON.stringify(err)); console.log('getAuthenticatorInfo data: ' + JSON.stringify(data)); }); @@ -4371,7 +4463,7 @@ getAuthenticatorInfo(owner: string, callback: AsyncCallback<AuthenticatorInfo getAuthenticatorInfo(owner: string): Promise<AuthenticatorInfo> -获取指定应用帐户的认证器信息。使用Promise异步回调。 +获取指定应用的认证器信息。使用Promise异步回调。 > **说明:** 从API version 9开始废弃, 建议使用[queryAuthenticatorInfo](#queryauthenticatorinfo9-1)替代。 > @@ -4383,19 +4475,19 @@ getAuthenticatorInfo(owner: string): Promise<AuthenticatorInfo> | 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------- | -| owner | string | 是 | 应用帐号的所有者包名。 | +| owner | string | 是 | 应用帐号所有者的包名。 | **返回值:** | 类型 | 说明 | | -------------------------------- | --------------------- | -| Promise<[AuthenticatorInfo](#authenticatorinfo8)> | Promise对象。返回指定应用帐户的认证器信息对象。 | +| Promise<[AuthenticatorInfo](#authenticatorinfo8)> | Promise对象,返回指定应用的认证器信息对象。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAuthenticatorInfo("com.example.ohos.accountjsdemo").then((data) => { + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAuthenticatorInfo("com.example.accountjsdemo").then((data) => { console.log('getAuthenticatorInfo: ' + JSON.stringify(data)); }).catch((err) => { console.log("getAuthenticatorInfo err: " + JSON.stringify(err)); @@ -4410,7 +4502,7 @@ getAuthenticatorInfo(owner: string): Promise<AuthenticatorInfo> | 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------- | -| owner | string | 是 | 应用帐号的所有者包名。 | +| owner | string | 是 | 应用帐号所有者的包名。 | | name | string | 是 | 应用帐号的名称。 | ## AuthTokenInfo9+ @@ -4464,16 +4556,6 @@ getAuthenticatorInfo(owner: string): Promise<AuthenticatorInfo> | account | [AppAccountInfo](#appaccountinfo) | 否 | 令牌所属的帐号信息。 | | tokenInfo | [AuthTokenInfo](#authtokeninfo9) | 否 | 令牌信息。 | -## AuthOptions9+ - -表示认证的选项。 - -**系统能力:** 以下各项对应的系统能力均为SystemCapability.Account.AppAccount。 - -| 参数名 | 类型 | 必填 | 说明 | -| ------- | ------ | ---- | ---------- | -| parameters | {[key:string]: Object} | 否 | 自定义参数对象。 | - ## CreateAccountOptions9+ 表示创建账号的选项。 @@ -4543,7 +4625,9 @@ getAuthenticatorInfo(owner: string): Promise<AuthenticatorInfo> | ACTION_AUTHENTICATE(deprecated) | "authenticate" | 表示操作,鉴权。 | | ACTION_CREATE_ACCOUNT_IMPLICITLY9+ | "createAccountImplicitly" | 表示操作,隐式创建帐号。 | | ACTION_AUTH9+ | "auth" | 表示操作,鉴权。 | -| KEY_NAME | "name" | 表示键名,应用帐号名称。 | +| ACTION_VERIFY_CREDENTIAL9+ | "verifyCredential" | 表示操作,验证凭据。 | +| ACTION_SET_AUTHENTICATOR_PROPERTIES9+ | "setAuthenticatorProperties" | 表示操作,设置认证器属性。 | +| KEY_NAME | "name" | 表示键名,应用帐号的名称。 | | KEY_OWNER | "owner" | 表示键名,应用帐号所有者。| | KEY_TOKEN | "token" | 表示键名,令牌。 | | KEY_ACTION | "action" | 表示键名,操作。 | @@ -4585,11 +4669,11 @@ getAuthenticatorInfo(owner: string): Promise<AuthenticatorInfo> ## AuthCallback9+ -认证回调接口。 +认证器回调类。 ### onResult9+ -onResult: (code: number, result: {[key: string]: any}) => void +onResult: (code: number, result?: AuthResult) => void 通知请求结果。 @@ -4600,16 +4684,16 @@ onResult: (code: number, result: {[key: string]: any}) => void | 参数名 | 类型 | 必填 | 说明 | | ------ | -------------------- | ---- | ------ | | code | number | 是 | 鉴权结果码。 | -| result | {[key: string]: any} | 否 | 鉴权结果。 | +| result | [AuthResult](#authresult9) | 否 | 鉴权结果。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); var sessionId = "1234"; appAccountManager.getAuthCallback(sessionId).then((callback) => { var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi", - [account_appAccount.Constants.KEY_OWNER]: "com.example.ohos.accountjsdemo", + [account_appAccount.Constants.KEY_OWNER]: "com.example.accountjsdemo", [account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData", [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; callback.onResult(account_appAccount.ResultCode.SUCCESS, result); @@ -4638,8 +4722,8 @@ onRequestRedirected: (request: Want) => void class MyAuthenticator extends account_appAccount.Authenticator { createAccountImplicitly(options, callback) { callback.onRequestRedirected({ - bundleName: "com.example.ohos.accountjsdemo", - abilityName: "com.example.ohos.accountjsdemo.LoginAbility", + bundleName: "com.example.accountjsdemo", + abilityName: "com.example.accountjsdemo.LoginAbility", }); } @@ -4663,7 +4747,7 @@ onRequestContinued?: () => void **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); var sessionId = "1234"; appAccountManager.getAuthCallback(sessionId).then((callback) => { callback.onRequestContinued(); @@ -4698,11 +4782,11 @@ onResult: (code: number, result: {[key: string]: any}) => void **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); var sessionId = "1234"; appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => { var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi", - [account_appAccount.Constants.KEY_OWNER]: "com.example.ohos.accountjsdemo", + [account_appAccount.Constants.KEY_OWNER]: "com.example.accountjsdemo", [account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData", [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; callback.onResult(account_appAccount.ResultCode.SUCCESS, result); @@ -4731,8 +4815,8 @@ onRequestRedirected: (request: Want) => void class MyAuthenticator extends account_appAccount.Authenticator { addAccountImplicitly(authType, callerBundleName, options, callback) { callback.onRequestRedirected({ - bundleName: "com.example.ohos.accountjsdemo", - abilityName: "com.example.ohos.accountjsdemo.LoginAbility", + bundleName: "com.example.accountjsdemo", + abilityName: "com.example.accountjsdemo.LoginAbility", }); } @@ -4756,7 +4840,7 @@ onRequestContinued?: () => void **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); var sessionId = "1234"; appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => { callback.onRequestContinued(); @@ -4769,11 +4853,30 @@ onRequestContinued?: () => void 认证器基类。 -### addAccountImplicitly8+ +### createAccountImplicitly9+ + +createAccountImplicitly(options: CreateAccountImplicitlyOptions, callback: AuthCallback): void + +根据指定的帐号所有者隐式地创建应用帐号,并使用callback异步回调返回结果。 + +**系统能力:** SystemCapability.Account.AppAccount + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------------- | --------------------- | ---- | --------------- | +| options | {[key: string]: any} | 是 | 隐式创建账号的选项。 | +| callback | [AuthCallback](#authcallback9) | 是 | 认证器回调对象,用于返回创建结果。 | + +### addAccountImplicitlydeprecated addAccountImplicitly(authType: string, callerBundleName: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void -根据指定的鉴权类型和可选项,隐式地添加应用帐户,并使用callback回调异步返回结果。 +根据指定的鉴权类型和可选项,隐式地添加应用帐号,并使用callback异步回调返回结果。 + +> **说明:** 从API version 9开始废弃。 +> +> 从 API version 8开始支持, 建议使用[createAccountImplicitly](#createaccountimplicitly9-2)替代。 **系统能力:** SystemCapability.Account.AppAccount @@ -4786,11 +4889,33 @@ addAccountImplicitly(authType: string, callerBundleName: string, options: {[key: | options | {[key: string]: any} | 是 | 鉴权所需要的可选项。 | | callback | [AuthenticatorCallback](#authenticatorcallbackdeprecated) | 是 | 认证器回调,用于返回鉴权结果。 | -### authenticate8+ +### auth9+ + +auth(name: string, authType: string, options: {[key:string]: Object}, callback: AuthCallback): void + +对应用帐号进行鉴权以获取授权令牌,并使用callback异步回调返回结果。 + +**系统能力:** SystemCapability.Account.AppAccount + +**参数:** + +| 接口名 | 类型 | 必填 | 说明 | +| ---------------- | --------------------- | ---- | --------------- | +| name | string | 是 | 应用帐号的名称。 | +| authType | string | 是 | 应用帐号的鉴权类型。 | +| callerBundleName | string | 是 | 鉴权类型。 | +| options | {[key: string]: any} | 是 | 鉴权所需要的可选项。 | +| callback | [AuthCallback](#authcallback9) | 是 | 回调对象,用于返回鉴权结果。 | + +### authenticatedeprecated authenticate(name: string, authType: string, callerBundleName: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void -对应用帐户进行鉴权,获取OAuth令牌,并使用callback回调异步返回结果。 +对应用帐号进行鉴权,获取OAuth令牌,并使用callback异步回调返回结果。 + +> **说明:** 从API version 9开始废弃。 +> +> 从 API version 8开始支持, 建议使用[auth](#auth9-2)替代。 **系统能力:** SystemCapability.Account.AppAccount @@ -4806,9 +4931,9 @@ authenticate(name: string, authType: string, callerBundleName: string, options: ### verifyCredential9+ -verifyCredential(name: string, options: VerifyCredentialOptions, callback: AuthenticatorCallback): void; +verifyCredential(name: string, options: VerifyCredentialOptions, callback: AuthCallback): void; -验证应用帐户的凭据,并使用callback回调异步返回结果。 +验证应用帐号的凭据,并使用callback异步回调返回结果。 **系统能力:** SystemCapability.Account.AppAccount @@ -4818,13 +4943,13 @@ verifyCredential(name: string, options: VerifyCredentialOptions, callback: Authe | ---------------- | --------------------- | ---- | --------------- | | name | string | 是 | 应用帐号的名称。 | | options | [VerifyCredentialOptions](#verifycredentialoptions9) | 是 | 验证凭据的可选项。 | -| callback | [AuthenticatorCallback](#authenticatorcallbackdeprecated) | 是 | 认证器回调,用于返回验证结果。 | +| callback | [AuthCallback](#authcallback9) | 是 | 认证器回调,用于返回验证结果。 | ### setProperties9+ -setProperties(options: SetPropertiesOptions, callback: AuthenticatorCallback): void; +setProperties(options: SetPropertiesOptions, callback: AuthCallback): void; -设置认证器属性,并使用callback回调异步返回结果。 +设置认证器属性,并使用callback异步回调返回结果。 **系统能力:** SystemCapability.Account.AppAccount @@ -4833,13 +4958,13 @@ setProperties(options: SetPropertiesOptions, callback: AuthenticatorCallback): v | 接口名 | 类型 | 必填 | 说明 | | ---------------- | --------------------- | ---- | --------------- | | options | [SetPropertiesOptions](#setpropertiesoptions9) | 是 | 设置属性的可选项。 | -| callback | [AuthenticatorCallback](#authenticatorcallbackdeprecated) | 是 | 认证器回调,用于返回设置结果。 | +| callback | [AuthCallback](#authcallback9) | 是 | 认证器回调,用于返回设置结果。 | ### checkAccountLabels9+ -checkAccountLabels(name: string, labels: Array<string>, callback: AuthenticatorCallback): void; +checkAccountLabels(name: string, labels: Array<string>, callback: AuthCallback): void; -检查帐号标签,并使用callback回调异步返回结果。 +检查帐号标签,并使用callback异步回调返回结果。 **系统能力:** SystemCapability.Account.AppAccount @@ -4849,13 +4974,13 @@ checkAccountLabels(name: string, labels: Array<string>, callback: Authenti | ---------------- | --------------------- | ---- | --------------- | | name | string | 是 | 应用帐号的名称。 | | labels | Array<string> | 是 | 标签数组。 | -| callback | [AuthenticatorCallback](#authenticatorcallbackdeprecated) | 是 | 认证器回调,用于返回检查结果。 | +| callback | [AuthCallback](#authcallback9) | 是 | 认证器回调,用于返回检查结果。 | ### isAccountRemovable9+ -isAccountRemovable(name: string, callback: AuthenticatorCallback): void; +isAccountRemovable(name: string, callback: AuthCallback): void; -判断帐号是否可以删除,并使用callback回调异步返回结果。 +判断帐号是否可以删除,并使用callback异步回调返回结果。 **系统能力:** SystemCapability.Account.AppAccount @@ -4864,7 +4989,7 @@ isAccountRemovable(name: string, callback: AuthenticatorCallback): void; | 接口名 | 类型 | 必填 | 说明 | | ---------------- | --------------------- | ---- | --------------- | | name | string | 是 | 应用帐号的名称。 | -| callback | [AuthenticatorCallback](#authenticatorcallbackdeprecated) | 是 | 认证器回调,用于返回判断结果。 | +| callback | [AuthCallback](#authcallback9) | 是 | 认证器回调,用于返回判断结果。 | ### getRemoteObject9+ @@ -4878,49 +5003,49 @@ getRemoteObject(): rpc.RemoteObject; ```js class MyAuthenticator extends account_appAccount.Authenticator { - addAccountImplicitly(authType, callerBundleName, options, callback) { - callback.onRequestRedirected({ - bundleName: "com.example.ohos.accountjsdemo", - abilityName: "com.example.ohos.accountjsdemo.LoginAbility", - }); - } - - authenticate(name, authType, callerBundleName, options, callback) { - var result = {[account_appAccount.Constants.KEY_NAME]: name, - [account_appAccount.Constants.KEY_AUTH_TYPE]: authType, - [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; - callback.onResult(account_appAccount.ResultCode.SUCCESS, result); - } + addAccountImplicitly(authType, callerBundleName, options, callback) { + callback.onRequestRedirected({ + bundleName: "com.example.accountjsdemo", + abilityName: "com.example.accountjsdemo.LoginAbility", + }); + } - verifyCredential(name, options, callback) { - callback.onRequestRedirected({ - bundleName: "com.example.ohos.accountjsdemo", - abilityName: "com.example.ohos.accountjsdemo.VerifyAbility", - parameters: { - name: name - } - }); - } + authenticate(name, authType, callerBundleName, options, callback) { + var result = {[account_appAccount.Constants.KEY_NAME]: name, + [account_appAccount.Constants.KEY_AUTH_TYPE]: authType, + [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; + callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + } + + verifyCredential(name, options, callback) { + callback.onRequestRedirected({ + bundleName: "com.example.accountjsdemo", + abilityName: "com.example.accountjsdemo.VerifyAbility", + parameters: { + name: name + } + }); + } - setProperties(options, callback) { - callback.onResult(account_appAccount.ResultCode.SUCCESS, {}); - } + setProperties(options, callback) { + callback.onResult(account_appAccount.ResultCode.SUCCESS, {}); + } - checkAccountLabels(name, labels, callback) { - var result = {[account_appAccount.Constants.KEY_BOOLEAN_RESULT]: false}; - callback.onResult(account_appAccount.ResultCode.SUCCESS, result); - } - - isAccountRemovable(name, callback) { - var result = {[account_appAccount.Constants.KEY_BOOLEAN_RESULT]: true}; - callback.onResult(account_appAccount.ResultCode.SUCCESS, result); - } + checkAccountLabels(name, labels, callback) { + var result = {[account_appAccount.Constants.KEY_BOOLEAN_RESULT]: false}; + callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + } + + isAccountRemovable(name, callback) { + var result = {[account_appAccount.Constants.KEY_BOOLEAN_RESULT]: true}; + callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + } } var authenticator = null; export default { - onConnect(want) { - authenticator = new MyAuthenticator(); - return authenticator.getRemoteObject(); - } + onConnect(want) { + authenticator = new MyAuthenticator(); + return authenticator.getRemoteObject(); + } } ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-buffer.md b/zh-cn/application-dev/reference/apis/js-apis-buffer.md index 8f9dc2da74965af2331a49fe01a98cb8332d1118..e96a0be8ea126341ca717dc3293c9919f4031415 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-buffer.md +++ b/zh-cn/application-dev/reference/apis/js-apis-buffer.md @@ -25,6 +25,40 @@ import buffer from '@ohos.buffer'; | buffer | ArrayBuffer | 是 | 否 | ArrayBuffer对象。 | | byteOffset | number | 是 | 否 | 当前buffer所在内存池的偏移量。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200013 | Cannot set property ${propertyName} of Buffer which has only a getter. | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from("1236"); +try { + buf.length = 10; +} catch (err) { + console.log("set length exception: " + JSON.stringify(err)); +} + +let buf1 = buffer.from("123"); +try { + buf.buffer = buf1; +} catch (err) { + console.log("set buffer exception: " + JSON.stringify(err)); +} + +try { + buf.byteOffset = 3; +} catch (err) { + console.log("set byteOffset exception: " + JSON.stringify(err)); +} +``` + ### alloc alloc(size: number, fill?: string | Buffer | number, encoding?: BufferEncoding): Buffer @@ -55,6 +89,12 @@ import buffer from '@ohos.buffer'; let buf1 = buffer.alloc(5); let buf2 = buffer.alloc(5, 'a'); let buf3 = buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + +try { + let buf = buffer.alloc(-5); +} catch (err) { + console.log("alloc exception: " + JSON.stringify(err)); +} ``` ### allocUninitializedFromPool @@ -85,6 +125,12 @@ import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(10); buf.fill(0); + +try { + let buf = buffer.allocUninitializedFromPool(-5); +} catch (err) { + console.log("allocUninitializedFromPool exception: " + JSON.stringify(err)); +} ``` ### allocUninitialized @@ -114,6 +160,12 @@ import buffer from '@ohos.buffer'; let buf = buffer.allocUninitialized(10); buf.fill(0); + +try { + let buf = buffer.allocUninitialized(-5); +} catch (err) { + console.log("allocUninitialized exception: " + JSON.stringify(err)); +} ``` ### byteLength @@ -145,6 +197,12 @@ import buffer from '@ohos.buffer'; let str = '\u00bd + \u00bc = \u00be'; console.log(`${str}: ${str.length} characters, ${buffer.byteLength(str, 'utf-8')} bytes`); // 打印: ½ + ¼ = ¾: 9 characters, 12 bytes + +try { + let byteLen = buffer.byteLength(10); +} catch (err) { + console.log("byteLength exception: " + JSON.stringify(err)); +} ``` ### compare @@ -180,6 +238,12 @@ let res = buf1.compare(buf2); console.log(Number(res).toString()); // 打印 1 + +try { + let res = buffer.compare(10, buf2); +} catch (err) { + console.log("compare exception: " + JSON.stringify(err)); +} ``` ### concat @@ -203,6 +267,14 @@ concat(list: Buffer[] | Uint8Array[], totalLength?: number): Buffer | -------- | -------- | | Buffer | 返回新Buffer的实例。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "totalLength" is out of range. | + **示例:** ```ts @@ -212,6 +284,18 @@ let buf1 = buffer.from("1234"); let buf2 = buffer.from("abcd"); let buf = buffer.concat([buf1, buf2]); console.log(buf.toString('hex')); // 3132333461626364 + +try { + buf = buffer.concat("test string"); +} catch (err) { + console.log("concat exception: " + JSON.stringify(err)); +} + +try { + buf = buffer.concat([buf1, buf2], -1); +} catch (err) { + console.log("concat exception: " + JSON.stringify(err)); +} ``` ### from @@ -241,6 +325,12 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); console.log(buf.toString('hex')); // 627566666572 + +try { + const buf = buffer.from(10); +} catch (err) { + console.log("from exception: " + JSON.stringify(err)); +} ``` ### from @@ -265,6 +355,14 @@ from(arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number, length?: | -------- | -------- | | Buffer | 返回一个共享内存的Buffer实例。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "[byteOffset/length]" is out of range. | + **示例:** ```ts @@ -272,6 +370,12 @@ import buffer from '@ohos.buffer'; let ab = new ArrayBuffer(10); let buf = buffer.from(ab, 0, 2); + +try { + const buf = buffer.from(arrayBuffer, 6, 1); +} catch (err) { + console.log("from exception: " + JSON.stringify(err)); +} ``` ### from @@ -301,6 +405,12 @@ import buffer from '@ohos.buffer'; let buf1 = buffer.from('buffer'); let buf2 = buffer.from(buf1); + +try { + const buf = buffer.from(10); +} catch (err) { + console.log("from exception: " + JSON.stringify(err)); +} ``` ### from @@ -331,6 +441,12 @@ from(object: Object, offsetOrEncoding: number | string, length: number): Buffer import buffer from '@ohos.buffer'; let buf = buffer.from(new String('this is a test')); + +try { + const buf = buffer.from(10, 0, 1); +} catch (err) { + console.log("from exception: " + JSON.stringify(err)); +} ``` ### from @@ -364,6 +480,12 @@ let buf2 = buffer.from('7468697320697320612074c3a97374', 'hex'); console.log(buf1.toString()); // 打印: this is a test console.log(buf2.toString()); + +try { + const buf = buffer.from("test string", "utf9"); +} catch (err) { + console.log("from exception: " + JSON.stringify(err)); +} ``` @@ -465,6 +587,13 @@ let buf2 = buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); console.log(buf1.compare(buf2, 5, 9, 0, 4).toString()); // 打印: 0 console.log(buf1.compare(buf2, 0, 6, 4).toString()); // 打印: -1 console.log(buf1.compare(buf2, 5, 6, 5).toString()); // 打印: 1 + +let buf = buffer.from("1236"); +try { + let res = buf.compare(10); +} catch (err) { + console.log("compare exception: " + JSON.stringify(err)); +} ``` ### copy @@ -490,6 +619,14 @@ copy(target: Buffer| Uint8Array, targetStart?: number, sourceStart?: number, sou | -------- | -------- | | number | 复制的字节总长度。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "[targetStart/sourceStart/sourceEnd]" is out of range. | + **示例:** ```ts @@ -505,6 +642,21 @@ for (let i = 0; i < 26; i++) { buf1.copy(buf2, 8, 16, 20); console.log(buf2.toString('ascii', 0, 25)); // 打印: !!!!!!!!qrst!!!!!!!!!!!!! + +let buf3 = buffer.from("123656"); +try { + let num = buf3.copy(10); +} catch (err) { + console.log("copy exception: " + JSON.stringify(err)); +} + +let buf4 = buffer.from("123656"); +let buf5 = buffer.from("1235"); +try { + let num = buf4.copy(buf5, -1); +} catch (err) { + console.log("copy exception: " + JSON.stringify(err)); +} ``` ### entries @@ -558,6 +710,11 @@ let buf3 = buffer.from('ABCD'); console.log(buf1.equals(buf2).toString()); // 打印: true console.log(buf1.equals(buf3).toString()); // 打印: false +try { + let res = buf1.equals("1236"); +} catch (err) { + console.log("equals exception: " + JSON.stringify(err)); +} ``` ### fill @@ -583,6 +740,14 @@ fill(value: string | Buffer | Uint8Array | number, offset?: number, end?: number | -------- | -------- | | Buffer | 填充后的Buffer实例。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "[offset/end]" is out of range. | + **示例:** ```ts @@ -590,6 +755,12 @@ import buffer from '@ohos.buffer'; let b = buffer.allocUninitializedFromPool(50).fill('h'); console.log(b.toString()); + +try { + let buf = buffer.alloc(3).fill("$*$", -1); +} catch (err) { + console.log("fill exception: " + JSON.stringify(err)); +} ``` @@ -623,6 +794,13 @@ import buffer from '@ohos.buffer'; let buf = buffer.from('this is a buffer'); console.log(buf.includes('this').toString()); // 打印: true console.log(buf.includes('be').toString()); // 打印: false + +let buf1 = buffer.from("13236"); +try { + let flag = buf1.includes(true); +} catch (err) { + console.log("includes exception: " + JSON.stringify(err)); +} ``` ### indexOf @@ -655,6 +833,19 @@ import buffer from '@ohos.buffer'; let buf = buffer.from('this is a buffer'); console.log(buf.indexOf('this').toString()); // 打印: 0 console.log(buf.indexOf('is').toString()); // 打印: 2 + +let buf1 = buffer.from("13236"); +try { + let index = buf1.indexOf(true); +} catch (err) { + console.log("indexOf exception: " + JSON.stringify(err)); +} + +try { + let index1 = buf1.indexOf("a", "utf9"); +} catch (err) { + console.log("indexOf exception: " + JSON.stringify(err)); +} ``` ### keys @@ -712,6 +903,20 @@ import buffer from '@ohos.buffer'; let buf = buffer.from('this buffer is a buffer'); console.log(buf.lastIndexOf('this').toString()); // 打印: 0 console.log(buf.lastIndexOf('buffer').toString()); // 打印: 17 + +let buf1 = buffer.from("13236"); +try { + let index = buf1.lastIndexOf(true); +} catch (err) { + console.log("lastIndexOf exception: " + JSON.stringify(err)); +} + +try { + let index1 = buf1.lastIndexOf("a", "utf9"); +} catch (err) { + console.log("lastIndexOf exception: " + JSON.stringify(err)); +} + ``` @@ -735,6 +940,14 @@ readBigInt64BE(offset?: number): bigint | -------- | -------- | | bigint | 读取出的内容。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **示例:** ```ts @@ -743,6 +956,14 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78]); console.log(buf.readBigInt64BE(0).toString()); + +let buf1 = buffer.allocUninitializedFromPool(8); +buf1.writeBigInt64BE(0x0102030405060708n, 0); +try { + let ref = buf1.readBigInt64BE(1).toString(16); +} catch (err) { + console.log("readBigInt64BE exception: " + JSON.stringify(err)); +} ``` ### readBigInt64LE @@ -765,6 +986,14 @@ readBigInt64LE(offset?: number): bigint | -------- | -------- | | bigint | 读取出的内容。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **示例:** ```ts @@ -773,6 +1002,14 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78]); console.log(buf.readBigInt64LE(0).toString()); + +let buf1 = buffer.allocUninitializedFromPool(8); +buf1.writeBigInt64BE(0x0102030405060708n, 0); +try { + let ref = buf1.readBigInt64LE(1).toString(16); +} catch (err) { + console.log("readBigInt64LE exception: " + JSON.stringify(err)); +} ``` ### readBigUInt64BE @@ -795,6 +1032,14 @@ readBigUInt64BE(offset?: number): bigint | -------- | -------- | | bigint | 读取出的内容。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **示例:** ```ts @@ -803,6 +1048,14 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78]); console.log(buf.readBigUInt64BE(0).toString()); + +let buf1 = buffer.allocUninitializedFromPool(8); +buf1.writeBigUInt64BE(0xdecafafecacefaden, 0); +try { + let ref = buf1.readBigUInt64BE(1).toString(16); +} catch (err) { + console.log("readBigUInt64BE exception: " + JSON.stringify(err)); +} ``` ### readBigUInt64LE @@ -825,6 +1078,14 @@ readBigUInt64LE(offset?: number): bigint | -------- | -------- | | bigint | 读取出的内容。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **示例:** ```ts @@ -833,6 +1094,14 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78]); console.log(buf.readBigUInt64LE(0).toString()); + +let buf1 = buffer.allocUninitializedFromPool(8); +buf1.writeBigUInt64BE(0xdecafafecacefaden, 0); +try { + let ref = buf1.readBigUInt64LE(1).toString(16); +} catch (err) { + console.log("readBigUInt64LE exception: " + JSON.stringify(err)); +} ``` ### readDoubleBE @@ -855,6 +1124,14 @@ readDoubleBE(offset?: number): number | -------- | -------- | | number | 读取出的内容。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **示例:** ```ts @@ -862,6 +1139,14 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); console.log(buf.readDoubleBE(0).toString()); + +let buf1 = buffer.allocUninitializedFromPool(8); +buf1.writeDoubleBE(123.456, 0); +try { + let ref = buf1.readDoubleBE(1); +} catch (err) { + console.log("readDoubleBE exception: " + JSON.stringify(err)); +} ``` ### readDoubleLE @@ -884,6 +1169,14 @@ readDoubleLE(offset?: number): number | -------- | -------- | | number | 读取出的内容。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **示例:** ```ts @@ -891,6 +1184,14 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); console.log(buf.readDoubleLE(0).toString()); + +let buf1 = buffer.allocUninitializedFromPool(8); +buf1.writeDoubleLE(123.456, 0); +try { + let ref = buf1.readDoubleLE(1); +} catch (err) { + console.log("readDoubleLE exception: " + JSON.stringify(err)); +} ``` ### readFloatBE @@ -913,6 +1214,14 @@ readFloatBE(offset?: number): number | -------- | -------- | | number | 读取出的内容。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **示例:** ```ts @@ -920,6 +1229,14 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); console.log(buf.readFloatBE(0).toString()); + +let buf1 = buffer.allocUninitializedFromPool(4); +buf1.writeFloatBE(0xcabcbcbc, 0); +try { + let ref = buf1.readFloatBE(1).toString(16); +} catch (err) { + console.log("readFloatBE exception: " + JSON.stringify(err)); +} ``` ### readFloatLE @@ -942,6 +1259,14 @@ readFloatLE(offset?: number): number | -------- | -------- | | number | 读取出的内容。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **示例:** ```ts @@ -949,6 +1274,14 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); console.log(buf.readFloatLE(0).toString()); + +let buf1 = buffer.allocUninitializedFromPool(4); +buf1.writeFloatLE(0xcabcbcbc, 0); +try { + let ref = buf1.readFloatLE(1).toString(16); +} catch (err) { + console.log("readFloatLE exception: " + JSON.stringify(err)); +} ``` ### readInt8 @@ -971,6 +1304,14 @@ readInt8(offset?: number): number | -------- | -------- | | number | 读取出的内容。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **示例:** ```ts @@ -979,6 +1320,14 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([-1, 5]); console.log(buf.readInt8(0).toString()); // 打印: -1 console.log(buf.readInt8(1).toString()); // 打印: 5 + +let buf1 = buffer.allocUninitializedFromPool(2); +buf1.writeInt8(0x12); +try { + let ref = buf1.readInt8(2).toString(16); +} catch (err) { + console.log("readInt8 exception: " + JSON.stringify(err)); +} ``` ### readInt16BE @@ -1001,6 +1350,14 @@ readInt16BE(offset?: number): number | -------- | -------- | | number | 读取出的内容。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **示例:** ```ts @@ -1008,6 +1365,14 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([0, 5]); console.log(buf.readInt16BE(0).toString()); // 打印: 5 + +let buf1 = buffer.alloc(2); +buf1.writeInt16BE(0x1234, 0); +try { + let ref = buf1.readInt16BE(1).toString(16); +} catch (err) { + console.log("readInt16BE exception: " + JSON.stringify(err)); +} ``` ### readInt16LE @@ -1030,6 +1395,14 @@ readInt16LE(offset?: number): number | -------- | -------- | | number | 读取出的内容。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **示例:** ```ts @@ -1037,6 +1410,14 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([0, 5]); console.log(buf.readInt16LE(0).toString()); // 打印: 1280 + +let buf1 = buffer.alloc(2); +buf1.writeInt16BE(0x1234, 0); +try { + let ref = buf1.readInt16LE(1); +} catch (err) { + console.log("readInt16LE exception: " + JSON.stringify(err)); +} ``` ### readInt32BE @@ -1059,6 +1440,14 @@ readInt32BE(offset?: number): number | -------- | -------- | | number | 读取出的内容。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **示例:** ```ts @@ -1066,6 +1455,14 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([0, 0, 0, 5]); console.log(buf.readInt32BE(0).toString()); // 打印: 5 + +let buf1 = buffer.alloc(4); +buf1.writeInt32BE(0x12345678, 0); +try { + let ref = buf1.readInt32BE(1); +} catch (err) { + console.log("readInt32BE exception: " + JSON.stringify(err)); +} ``` ### readInt32LE @@ -1088,6 +1485,14 @@ readInt32LE(offset?: number): number | -------- | -------- | | number | 读取出的内容。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **示例:** ```ts @@ -1095,6 +1500,14 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([0, 0, 0, 5]); console.log(buf.readInt32LE(0).toString()); // 打印: 83886080 + +let buf1 = buffer.alloc(4); +buf1.writeInt32BE(0x12345678, 0); +try { + let ref = buf1.readInt32LE(1); +} catch (err) { + console.log("readInt32LE exception: " + JSON.stringify(err)); +} ``` ### readIntBE @@ -1119,6 +1532,14 @@ readIntBE(offset: number, byteLength: number): number | -------- | -------- | | number | 读取的内容。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "[offset/byteLength]" is out of range. | + **示例:** ```ts @@ -1127,6 +1548,14 @@ import buffer from '@ohos.buffer'; let buf = buffer.from("ab"); let num = buf.readIntBE(0, 1); console.log(num.toString()); // 97 + +let buf1 = buffer.allocUninitializedFromPool(6); +buf1.writeIntBE(0x123456789011, 0, 6); +try { + let ref = buf1.readIntBE(2, 5).toString(16); +} catch (err) { + console.log("readIntBE exception: " + JSON.stringify(err)); +} ``` @@ -1152,6 +1581,14 @@ readIntLE(offset: number, byteLength: number): number | -------- | -------- | | number | 读取出的内容。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "[offset/byteLength]" is out of range. | + **示例:** ```ts @@ -1159,6 +1596,14 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); console.log(buf.readIntLE(0, 6).toString(16)); + +let buf1 = buffer.allocUninitializedFromPool(6); +buf1.writeIntLE(0x123456789011, 0, 6); +try { + let ref = buf1.readIntLE(2, 5).toString(16); +} catch (err) { + console.log("readIntBE exception: " + JSON.stringify(err)); +} ``` ### readUInt8 @@ -1182,6 +1627,14 @@ readUInt8(offset?: number): number | -------- | -------- | | number | 读取出的内容。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **示例:** ```ts @@ -1190,6 +1643,14 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([1, -2]); console.log(buf.readUInt8(0).toString()); console.log(buf.readUInt8(1).toString()); + +let buf = buffer.allocUninitializedFromPool(4); +buf.writeUInt8(0x42); +try { + let ref = buf.readUInt8(4).toString(16); +} catch (err) { + console.log("readUInt8 exception: " + JSON.stringify(err)); +} ``` ### readUInt16BE @@ -1213,6 +1674,14 @@ readUInt16BE(offset?: number): number | -------- | -------- | | number | 读取出的内容。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **示例:** ```ts @@ -1221,6 +1690,14 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([0x12, 0x34, 0x56]); console.log(buf.readUInt16BE(0).toString(16)); console.log(buf.readUInt16BE(1).toString(16)); + +let buf1 = buffer.allocUninitializedFromPool(4); +buf1.writeUInt16BE(0x1234, 0); +try { + let ref = buf1.readUInt16BE(3).toString(16); +} catch (err) { + console.log("readUInt16BE exception: " + JSON.stringify(err)); +} ``` ### readUInt16LE @@ -1244,6 +1721,14 @@ readUInt16LE(offset?: number): number | -------- | -------- | | number | 读取出的内容。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **示例:** ```ts @@ -1252,6 +1737,14 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([0x12, 0x34, 0x56]); console.log(buf.readUInt16LE(0).toString(16)); console.log(buf.readUInt16LE(1).toString(16)); + +let buf1 = buffer.allocUninitializedFromPool(4); +buf1.writeUInt16LE(0x1234, 0); +try { + let ref = buf1.readUInt16LE(3).toString(16); +} catch (err) { + console.log("readUInt16LE exception: " + JSON.stringify(err)); +} ``` ### readUInt32BE @@ -1275,6 +1768,14 @@ readUInt32BE(offset?: number): number | -------- | -------- | | number | 读取出的内容。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **示例:** ```ts @@ -1282,6 +1783,14 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([0x12, 0x34, 0x56, 0x78]); console.log(buf.readUInt32BE(0).toString(16)); + +let buf1 = buffer.allocUninitializedFromPool(4); +buf1.writeUInt32BE(0x12345678, 0); +try { + let ref = buf1.readUInt32BE(1).toString(16); +} catch (err) { + console.log("readUInt32BE exception: " + JSON.stringify(err)); +} ``` ### readUInt32LE @@ -1305,6 +1814,14 @@ readUInt32LE(offset?: number): number | -------- | -------- | | number | 读取出的内容。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **示例:** ```ts @@ -1312,6 +1829,14 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([0x12, 0x34, 0x56, 0x78]); console.log(buf.readUInt32LE(0).toString(16)); + +let buf1 = buffer.allocUninitializedFromPool(4); +buf1.writeUInt32LE(0x12345678, 0); +try { + let ref = buf1.readUInt32LE(1).toString(16); +} catch (err) { + console.log("readUInt32LE exception: " + JSON.stringify(err)); +} ``` ### readUIntBE @@ -1336,6 +1861,14 @@ readUIntBE(offset: number, byteLength: number): number | -------- | -------- | | number | 读取出的内容。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "[offset/byteLength]" is out of range. | + **示例:** ```ts @@ -1343,6 +1876,14 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); console.log(buf.readUIntBE(0, 6).toString(16)); + +let buf1 = buffer.allocUninitializedFromPool(4); +buf1.writeUIntBE(0x13141516, 0, 4); +try { + let ref = buf1.readUIntBE(2, 3).toString(16); +} catch (err) { + console.log("readUIntBE exception: " + JSON.stringify(err)); +} ``` ### readUIntLE @@ -1367,6 +1908,14 @@ readUIntLE(offset: number, byteLength: number): number | -------- | -------- | | number | 读取出的内容。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "[offset/byteLength]" is out of range. | + **示例:** ```ts @@ -1374,6 +1923,14 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); console.log(buf.readUIntLE(0, 6).toString(16)); + +let buf1 = buffer.allocUninitializedFromPool(4); +buf1.writeUIntLE(0x13141516, 0, 4); +try { + let ref = buf1.readUIntLE(2, 3).toString(16); +} catch (err) { + console.log("readUIntLE exception: " + JSON.stringify(err)); +} ``` ### subarray @@ -1427,6 +1984,14 @@ swap16(): Buffer | -------- | -------- | | Buffer | 交换之后的Buffer实例。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200009 | Buffer size must be a multiple of 16-bits | + **示例:** ```ts @@ -1437,6 +2002,13 @@ console.log(buf1.toString('hex')); // 打印: 0102030405060708 buf1.swap16(); console.log(buf1.toString('hex')); // 打印: 0201040306050807 + +let buf2 = buffer.from("132"); +try { + buf2.swap16(); +} catch (err) { + console.log("swap16 exception: " + JSON.stringify(err)); +} ``` ### swap32 @@ -1454,6 +2026,14 @@ swap32(): Buffer | -------- | -------- | | Buffer | 交换之后的Buffer实例。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200009 | Buffer size must be a multiple of 32-bits | + **示例:** ```ts @@ -1464,6 +2044,13 @@ console.log(buf1.toString('hex')); // 打印: 0102030405060708 buf1.swap32(); console.log(buf1.toString('hex')); // 打印: 0403020108070605 + +let buf2 = buffer.from("132"); +try { + buf2.swap32(); +} catch (err) { + console.log("swap32 exception: " + JSON.stringify(err)); +} ``` ### swap64 @@ -1481,6 +2068,14 @@ swap64(): Buffer | -------- | -------- | | Buffer | 交换之后的Buffer实例。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200009 | Buffer size must be a multiple of 64-bits | + **示例:** ```ts @@ -1490,6 +2085,13 @@ let buf1 = buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); console.log(buf1.toString('hex')); // 打印: 0102030405060708 buf1.swap64(); console.log(buf1.toString('hex')); // 打印: 0807060504030201 + +let buf2 = buffer.from("1234567"); +try { + buf2.swap64(); +} catch (err) { + console.log("swap64 exception: " + JSON.stringify(err)); +} ``` ### toJSON @@ -1551,6 +2153,13 @@ for (let i = 0; i < 26; i++) { } console.log(buf1.toString('utf-8')); // 打印: abcdefghijklmnopqrstuvwxyz + +let buf2 = buffer.from("abc"); +try { + let str = buf2.toString("utf9"); +} catch (err) { + console.log("toString exception: " + JSON.stringify(err)); +} ``` ### values @@ -1602,6 +2211,14 @@ write(str: string, offset?: number, length?: number, encoding?: string): number | -------- | -------- | | number | 返回写入的字节数。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "[offset/length]" is out of range. | + **示例:** ```ts @@ -1614,6 +2231,27 @@ console.log(`${len} bytes: ${buf.toString('utf-8', 0, len)}`); let buffer1 = buffer.alloc(10); let length = buffer1.write('abcd', 8); + +let buf1 = buffer.alloc(8); +try { + let offset1 = buf1.write("abcde", "utf9"); +} catch (err) { + console.log("write exception: " + JSON.stringify(err)); +} + +let buf2 = buffer.alloc(8); +try { + let offset2 = buf2.write(10); +} catch (err) { + console.log("write exception: " + JSON.stringify(err)); +} + +let buf3 = buffer.alloc(8); +try { + let offset3 = buf3.write("abcde", -1); +} catch (err) { + console.log("write exception: " + JSON.stringify(err)); +} ``` ### writeBigInt64BE @@ -1638,6 +2276,14 @@ writeBigInt64BE(value: bigint, offset?: number): number | -------- | -------- | | number | 写入的字节数。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **示例:** ```ts @@ -1645,6 +2291,13 @@ import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(8); buf.writeBigInt64BE(0x0102030405060708n, 0); + +let buf1 = buffer.allocUninitializedFromPool(8); +try { + let ref = buf1.writeBigInt64BE(0x0102030405060708n, 1); +} catch (err) { + console.log("writeBigInt64BE exception: " + JSON.stringify(err)); +} ``` ### writeBigInt64LE @@ -1669,6 +2322,14 @@ writeBigInt64LE(value: bigint, offset?: number): number | -------- | -------- | | number | 写入的字节数。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **示例:** ```ts @@ -1676,6 +2337,13 @@ import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(8); buf.writeBigInt64LE(0x0102030405060708n, 0); + +let buf1 = buffer.allocUninitializedFromPool(8); +try { + let ref = buf1.writeBigInt64LE(0x0102030405060708n, 1); +} catch (err) { + console.log("writeBigInt64LE exception: " + JSON.stringify(err)); +} ``` ### writeBigUInt64BE @@ -1700,6 +2368,14 @@ writeBigUInt64BE(value: bigint, offset?: number): number | -------- | -------- | | number | 写入的字节数。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **示例:** ```ts @@ -1707,6 +2383,13 @@ import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(8); buf.writeBigUInt64BE(0xdecafafecacefaden, 0); + +let buf1 = buffer.allocUninitializedFromPool(8); +try { + let ref = buf1.writeBigUInt64BE(0xdecafafecacefaden, 1); +} catch (err) { + console.log("writeBigUInt64BE exception: " + JSON.stringify(err)); +} ``` ### writeBigUInt64LE @@ -1731,6 +2414,14 @@ writeBigUInt64LE(value: bigint, offset?: number): number | -------- | -------- | | number | 写入的字节数。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **示例:** ```ts @@ -1738,6 +2429,13 @@ import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(8); buf.writeBigUInt64LE(0xdecafafecacefaden, 0); + +let buf = buffer.allocUninitializedFromPool(8); +try { + let ref = buf.writeBigUInt64LE(0xdecafafecacefaden, 1); +} catch (err) { + console.log("writeBigUInt64LE exception: " + JSON.stringify(err)); +} ``` ### writeDoubleBE @@ -1762,6 +2460,14 @@ writeDoubleBE(value: number, offset?: number): number | -------- | -------- | | number | 写入的字节数。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **示例:** ```ts @@ -1769,6 +2475,13 @@ import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(8); buf.writeDoubleBE(123.456, 0); + +let buf1 = buffer.allocUninitializedFromPool(8); +try { + let ref = buf1.writeDoubleBE(123.456, 1); +} catch (err) { + console.log("writeDoubleBE exception: " + JSON.stringify(err)); +} ``` ### writeDoubleLE @@ -1793,6 +2506,14 @@ writeDoubleLE(value: number, offset?: number): number | -------- | -------- | | number | 写入的字节数。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **示例:** ```ts @@ -1800,6 +2521,13 @@ import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(8); buf.writeDoubleLE(123.456, 0); + +let buf = buffer.allocUninitializedFromPool(8); +try { + let ref = buf.writeDoubleLE(123.456, 1); +} catch (err) { + console.log("writeDoubleLE exception: " + JSON.stringify(err)); +} ``` ### writeFloatBE @@ -1824,6 +2552,14 @@ writeFloatBE(value: number, offset?: number): number | -------- | -------- | | number | 写入的字节数。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **示例:** ```ts @@ -1831,6 +2567,13 @@ import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(8); buf.writeFloatBE(0xcafebabe, 0); + +let buf1 = buffer.allocUninitializedFromPool(4); +try { + let ref = buf1.writeFloatBE(0xcabcbcbc, 5); +} catch (err) { + console.log("writeFloatBE exception: " + JSON.stringify(err)); +} ``` @@ -1856,6 +2599,14 @@ writeFloatLE(value: number, offset?: number): number | -------- | -------- | | number | 写入的字节数。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **示例:** ```ts @@ -1863,6 +2614,13 @@ import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(8); buf.writeFloatLE(0xcafebabe, 0); + +let buf1 = buffer.allocUninitializedFromPool(4); +try { + let ref = buf1.writeFloatLE(0xcabcbcbc, 5); +} catch (err) { + console.log("writeFloatLE exception: " + JSON.stringify(err)); +} ``` ### writeInt8 @@ -1887,6 +2645,14 @@ writeInt8(value: number, offset?: number): number | -------- | -------- | | number | 写入的字节数。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **示例:** ```ts @@ -1895,6 +2661,13 @@ import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(2); buf.writeInt8(2, 0); buf.writeInt8(-2, 1); + +let buf1 = buffer.allocUninitializedFromPool(2); +try { + let ref = buf1.writeInt8(2, -1); +} catch (err) { + console.log("writeInt8 exception: " + JSON.stringify(err)); +} ``` @@ -1920,6 +2693,14 @@ writeInt16BE(value: number, offset?: number): number | -------- | -------- | | number | 写入的字节数。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **示例:** ```ts @@ -1927,6 +2708,13 @@ import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(2); buf.writeInt16BE(0x0102, 0); + +let buf1 = buffer.alloc(2); +try { + let ref = buf1.writeInt16BE(0x7bca, -1); +} catch (err) { + console.log("writeInt16BE exception: " + JSON.stringify(err)); +} ``` @@ -1952,6 +2740,14 @@ writeInt16LE(value: number, offset?: number): number | -------- | -------- | | number | 写入的字节数。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **示例:** ```ts @@ -1959,6 +2755,13 @@ import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(2); buf.writeInt16LE(0x0304, 0); + +let buf1 = buffer.alloc(2); +try { + let ref = buf1.writeInt16LE(0x7bca, -1); +} catch (err) { + console.log("writeInt16LE exception: " + JSON.stringify(err)); +} ``` ### writeInt32BE @@ -1983,6 +2786,14 @@ writeInt32BE(value: number, offset?: number): number | -------- | -------- | | number | 写入的字节数。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **示例:** ```ts @@ -1990,6 +2801,13 @@ import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(4); buf.writeInt32BE(0x01020304, 0); + +let buf1 = buffer.alloc(4); +try { + let ref = buf1.writeInt32BE(0x12345678, -1); +} catch (err) { + console.log("writeInt32BE exception: " + JSON.stringify(err)); +} ``` @@ -2015,6 +2833,14 @@ writeInt32LE(value: number, offset?: number): number | -------- | -------- | | number | 写入的字节数。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **示例:** ```ts @@ -2022,6 +2848,13 @@ import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(4); buf.writeInt32LE(0x05060708, 0); + +let buf1 = buffer.alloc(4); +try { + let ref = buf1.writeInt32LE(0x12345678, -1); +} catch (err) { + console.log("writeInt32LE exception: " + JSON.stringify(err)); +} ``` ### writeIntBE @@ -2047,6 +2880,14 @@ writeIntBE(value: number, offset: number, byteLength: number): number | -------- | -------- | | number | 写入的字节数。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "[value/offset/byteLength]" is out of range. | + **示例:** ```ts @@ -2054,6 +2895,13 @@ import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(6); buf.writeIntBE(0x1234567890ab, 0, 6); + +let buf1 = buffer.allocUninitializedFromPool(6); +try { + let ref = buf1.writeIntBE(0x1234567890ab, 1, 6); +} catch (err) { + console.log("writeIntBE exception: " + JSON.stringify(err)); +} ``` @@ -2080,6 +2928,14 @@ writeIntLE(value: number, offset: number, byteLength: number): number | -------- | -------- | | number | 写入的字节数。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "[value/offset/byteLength]" is out of range. | + **示例:** ```ts @@ -2087,6 +2943,13 @@ import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(6); buf.writeIntLE(0x1234567890ab, 0, 6); + +let buf1 = buffer.allocUninitializedFromPool(6); +try { + let ref = buf1.writeIntLE(0x1234567890ab, 1, 6); +} catch (err) { + console.log("writeIntLE exception: " + JSON.stringify(err)); +} ``` ### writeUInt8 @@ -2111,6 +2974,14 @@ writeUInt8(value: number, offset?: number): number | -------- | -------- | | number | 写入的字节数。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **示例:** ```ts @@ -2121,6 +2992,13 @@ buf.writeUInt8(0x3, 0); buf.writeUInt8(0x4, 1); buf.writeUInt8(0x23, 2); buf.writeUInt8(0x42, 3); + +let buf1 = buffer.allocUninitializedFromPool(4); +try { + let ref = buf1.writeUInt8(0x42, -1); +} catch (err) { + console.log("writeUInt8 exception: " + JSON.stringify(err)); +} ``` ### writeUInt16BE @@ -2145,6 +3023,14 @@ writeUInt16BE(value: number, offset?: number): number | -------- | -------- | | number | 写入的字节数。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **示例:** ```ts @@ -2153,6 +3039,13 @@ import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(4); buf.writeUInt16BE(0xdead, 0); buf.writeUInt16BE(0xbeef, 2); + +let buf1 = buffer.allocUninitializedFromPool(4); +try { + let ref = buf1.writeUInt16BE(0xdeadfc, 0); +} catch (err) { + console.log("writeUInt16BE exception: " + JSON.stringify(err)); +} ``` ### writeUInt16LE @@ -2177,6 +3070,14 @@ writeUInt16LE(value: number, offset?: number): number | -------- | -------- | | number | 写入的字节数。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **示例:** ```ts @@ -2185,6 +3086,13 @@ import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(4); buf.writeUInt16LE(0xdead, 0); buf.writeUInt16LE(0xbeef, 2); + +let buf1 = buffer.allocUninitializedFromPool(4); +try { + let ref = buf1.writeUInt16LE(0xdeadfc, 0); +} catch (err) { + console.log("writeUInt16LE exception: " + JSON.stringify(err)); +} ``` ### writeUInt32BE @@ -2209,6 +3117,14 @@ writeUInt32BE(value: number, offset?: number): number | -------- | -------- | | number | 写入的字节数。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **示例:** ```ts @@ -2216,6 +3132,13 @@ import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(4); buf.writeUInt32BE(0xfeedface, 0); + +let buf1 = buffer.allocUninitializedFromPool(4); +try { + let ref = buf1.writeUInt32BE(0xfeedface, -1); +} catch (err) { + console.log("writeUInt32BE exception: " + JSON.stringify(err)); +} ``` ### writeUInt32LE @@ -2240,6 +3163,14 @@ writeUInt32LE(value: number, offset?: number): number | -------- | -------- | | number | 写入的字节数。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **示例:** ```ts @@ -2247,6 +3178,13 @@ import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(4); buf.writeUInt32LE(0xfeedface, 0); + +let buf1 = buffer.allocUninitializedFromPool(4); +try { + let ref = buf1.writeUInt32LE(0xfeedface, -1); +} catch (err) { + console.log("writeUInt32LE exception: " + JSON.stringify(err)); +} ``` ### writeUIntBE @@ -2272,6 +3210,14 @@ writeUIntBE(value: number, offset: number, byteLength: number): number | -------- | -------- | | number | 写入的字节数。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "[value/offset/byteLength]" is out of range. | + **示例:** ```ts @@ -2279,6 +3225,13 @@ import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(6); buf.writeUIntBE(0x1234567890ab, 0, 6); + +let buf1 = buffer.allocUninitializedFromPool(4); +try { + let ref = buf1.writeUIntBE(0x13141516, 0, 1); +} catch (err) { + console.log("writeUIntBE exception: " + JSON.stringify(err)); +} ``` ### writeUIntLE @@ -2304,6 +3257,14 @@ writeUIntLE(value: number, offset: number, byteLength: number): number | -------- | -------- | | number | 写入的字节数。 | +**错误码:** + +以下错误码的详细介绍请参见[buffer错误码](../errorcodes/errorcode-buffer.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 10200001 | The value of "[value/offset/byteLength]" is out of range. | + **示例:** ```ts @@ -2311,6 +3272,13 @@ import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(6); buf.writeUIntLE(0x1234567890ab, 0, 6); + +let buf1 = buffer.allocUninitializedFromPool(4); +try { + let ref = buf1.writeUIntLE(0x13141516, 0, 1); +} catch (err) { + console.log("writeUIntLE exception: " + JSON.stringify(err)); +} ``` ### transcode @@ -2343,6 +3311,25 @@ import buffer from '@ohos.buffer'; let buf = buffer.alloc(50); let newBuf = buffer.transcode(buffer.from('€'), 'utf-8', 'ascii'); console.log(newBuf.toString('ascii')); + +try { + let buf1 = buffer.transcode(10, "utf8", "ucs2"); +} catch (err) { + console.log("transcode exception: " + JSON.stringify(err)); +} + +let buf2 = buffer.from("测试"); +try { + let buf3 = buffer.transcode(buf2, 0, "ucs2"); +} catch (err) { + console.log("transcode exception: " + JSON.stringify(err)); +} + +try { + let buf3 = buffer.transcode(buf2, "utf8", 0); +} catch (err) { + console.log("transcode exception: " + JSON.stringify(err)); +} ``` ## Blob @@ -2373,13 +3360,24 @@ Blob的构造函数。 **示例:** + ```ts + import buffer from '@ohos.buffer'; -```ts -import buffer from '@ohos.buffer'; - -let blob = new buffer.Blob(['a', 'b', 'c']); -let blob1 = new buffer.Blob(['a', 'b', 'c'], {endings:'native', type: 'MIME'}); -``` + let blob = new buffer.Blob(['a', 'b', 'c']); + let blob1 = new buffer.Blob(['a', 'b', 'c'], {endings:'native', type: 'MIME'}); + + try { + let blob1 = new buffer.Blob(["a", "b", "c"], 10); + } catch (err) { + console.log("Blob constructor exception: " + JSON.stringify(err)); + } + + try { + let blob2 = new buffer.Blob("abc", { type: "new type", endings: "transparent" }); + } catch (err) { + console.log("Blob constructor exception: " + JSON.stringify(err)); + } + ``` ### encode diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundle-defaultAppManager.md b/zh-cn/application-dev/reference/apis/js-apis-bundle-defaultAppManager.md index 7e2f8e3deede69d1204b7b91589a4f5d7a73167d..1508fd7c192fc20c0c38699176d3fe0b6c1206c3 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundle-defaultAppManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundle-defaultAppManager.md @@ -15,18 +15,18 @@ import defaultAppMgr from '@ohos.bundle.defaultAppManager' 应用类型 -**系统能力:** SystemCapability.BundleManager.BundleFramework - -| 名称 | 类型 | 说明 | -| -------- | -------- | -------------------------------------- | -| BROWSER | string | 默认浏览器。 | -| IMAGE | string | 默认图片查看器。 | -| AUDIO | string | 默认音频播放器。 | -| VIDEO | string | 默认视频播放器。 | -| PDF | string | 默认PDF文档查看器。 | -| WORD | string | 默认WORD文档查看器。 | -| EXCEL | string | 默认EXCEL文档查看器。 | -| PPT | string | 默认PPT文档查看器。 | +**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultAppManager + +| 名称 | 类型 | 值 | 说明 | +| -------- | -------- | -------------------------------------- | -------------------------------------- | +| BROWSER | string | Web Browser | 默认浏览器。 | +| IMAGE | string | Image Gallery | 默认图片查看器。 | +| AUDIO | string | Audio Player | 默认音频播放器。 | +| VIDEO | string | Video Player | 默认视频播放器。 | +| PDF | string | PDF Viewer | 默认PDF文档查看器。 | +| WORD | string | Word Viewer | 默认WORD文档查看器。 | +| EXCEL | string | Excel Viewer | 默认EXCEL文档查看器。 | +| PPT | string | PPT Viewer | 默认PPT文档查看器。 | ## defaultAppMgr.isDefaultApplication @@ -34,7 +34,7 @@ isDefaultApplication(type: string): Promise\ 以异步方法根据系统已定义的应用类型判断当前应用是否是该应用类型的默认应用,使用Promise形式返回结果。 -**系统能力:** SystemCapability.BundleManager.BundleFramework +**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultAppManager **参数:** @@ -65,7 +65,7 @@ isDefaultApplication(type: string, callback: AsyncCallback\): void 以异步方法根据系统已定义的应用类型判断当前应用是否是该应用类型的默认应用,使用callback形式返回结果。 -**系统能力:** SystemCapability.BundleManager.BundleFramework +**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultAppManager **参数:** @@ -94,7 +94,7 @@ getDefaultApplication(type: string, userId?: number): Promise\ **需要权限:** ohos.permission.GET_DEFAULT_APPLICATION -**系统能力:** SystemCapability.BundleManager.BundleFramework +**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultAppManager **系统API:** 此接口为系统接口,三方应用不支持调用 @@ -111,6 +111,14 @@ getDefaultApplication(type: string, userId?: number): Promise\ | ------------------------- | ------------------ | | Promise\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Promise形式返回默认应用包信息。 | +**错误码:** + +| 错误码ID | 错误码信息 | +| -------- | ----------------------------------------- | +| 17700004 | The specified user id is not found. | +| 17700023 | The specified default app does not exist. | +| 17700025 | The specified type is invalid. | + **示例:** ```js @@ -139,7 +147,7 @@ getDefaultApplication(type: string, userId: number, callback: AsyncCallback\ | 是 | 程序启动作为入参的回调函数,返回包信息。 | +**错误码:** + +| 错误码ID | 错误码信息 | +| -------- | ----------------------------------------- | +| 17700004 | The specified user id is not found. | +| 17700023 | The specified default app does not exist. | +| 17700025 | The specified type is invalid. | + **示例:** ```js @@ -179,7 +195,7 @@ getDefaultApplication(type: string, callback: AsyncCallback\) : void **需要权限:** ohos.permission.GET_DEFAULT_APPLICATION -**系统能力:** SystemCapability.BundleManager.BundleFramework +**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultAppManager **系统API:** 此接口为系统接口,三方应用不支持调用 @@ -190,6 +206,14 @@ getDefaultApplication(type: string, callback: AsyncCallback\) : void | type | string | 是 | 要查询的应用类型,取[ApplicationType](#defaultappmgrapplicationtype)中的值,或者符合媒体类型格式的文件类型。 | | callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | 是 | 程序启动作为入参的回调函数,返回包信息。 | +**错误码:** + +| 错误码ID | 错误码信息 | +| -------- | ----------------------------------------- | +| 17700004 | The specified user id is not found. | +| 17700023 | The specified default app does not exist. | +| 17700025 | The specified type is invalid. | + **示例:** ```js @@ -218,7 +242,7 @@ setDefaultApplication(type: string, elementName: ElementName, userId?: number): **需要权限:** ohos.permission.SET_DEFAULT_APPLICATION -**系统能力:** SystemCapability.BundleManager.BundleFramework +**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultAppManager.defaultAppManager **系统API:** 此接口为系统接口,三方应用不支持调用 @@ -230,6 +254,14 @@ setDefaultApplication(type: string, elementName: ElementName, userId?: number): | elementName | [ElementName](js-apis-bundle-ElementName.md) | 是 | 要设置为默认应用的组件信息。 | | userId | number | 否 | 用户ID。默认值:调用方所在用户。 | +**错误码:** + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------------- | +| 17700004 | The specified user id is not found. | +| 17700025 | The specified type is invalid. | +| 17700028 | The specified ability and type does not match. | + **示例:** ```js @@ -266,7 +298,7 @@ setDefaultApplication(type: string, elementName: ElementName, userId: number, ca **需要权限:** ohos.permission.SET_DEFAULT_APPLICATION -**系统能力:** SystemCapability.BundleManager.BundleFramework +**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultAppManager.defaultAppManager **系统API:** 此接口为系统接口,三方应用不支持调用 @@ -279,6 +311,14 @@ setDefaultApplication(type: string, elementName: ElementName, userId: number, ca | userId | number | 是 | 用户ID。 | | callback | AsyncCallback\ | 是 | 程序启动作为入参的回调函数。 | +**错误码:** + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------------- | +| 17700004 | The specified user id is not found. | +| 17700025 | The specified type is invalid. | +| 17700028 | The specified ability and type does not match. | + **示例:** ```js @@ -315,7 +355,7 @@ setDefaultApplication(type: string, elementName: ElementName, callback: AsyncCal **需要权限:** ohos.permission.SET_DEFAULT_APPLICATION -**系统能力:** SystemCapability.BundleManager.BundleFramework +**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultAppManager.defaultAppManager **系统API:** 此接口为系统接口,三方应用不支持调用 @@ -327,6 +367,14 @@ setDefaultApplication(type: string, elementName: ElementName, callback: AsyncCal | elementName | [ElementName](js-apis-bundle-ElementName.md) | 是 | 要设置为默认应用的组件信息。 | | callback | AsyncCallback\ | 是 | 程序启动作为入参的回调函数。 | +**错误码:** + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------------- | +| 17700004 | The specified user id is not found. | +| 17700025 | The specified type is invalid. | +| 17700028 | The specified ability and type does not match. | + **示例:** ```js @@ -363,7 +411,7 @@ resetDefaultApplication(type: string, userId?: number): Promise\ **需要权限:** ohos.permission.SET_DEFAULT_APPLICATION -**系统能力:** SystemCapability.BundleManager.BundleFramework +**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultAppManager.defaultAppManager **系统API:** 此接口为系统接口,三方应用不支持调用 @@ -374,6 +422,13 @@ resetDefaultApplication(type: string, userId?: number): Promise\ | type | string | 是 | 要重置的应用类型,取[ApplicationType](#defaultappmgrapplicationtype)中的值,或者符合媒体类型格式的文件类型。 | | userId | number | 否 | 用户ID。默认值:调用方所在用户。 | +**错误码:** + +| 错误码ID | 错误码信息 | +| -------- | ----------------------------------- | +| 17700004 | The specified user id is not found. | +| 17700025 | The specified type is invalid. | + **示例:** ```js @@ -402,7 +457,7 @@ resetDefaultApplication(type: string, userId: number, callback: AsyncCallback\ | 是 | 程序启动作为入参的回调函数。 | +**错误码:** + +| 错误码ID | 错误码信息 | +| -------- | ----------------------------------- | +| 17700004 | The specified user id is not found. | +| 17700025 | The specified type is invalid. | + **示例:** ```js @@ -442,7 +504,7 @@ resetDefaultApplication(type: string, callback: AsyncCallback\) : void; **需要权限:** ohos.permission.SET_DEFAULT_APPLICATION -**系统能力:** SystemCapability.BundleManager.BundleFramework +**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultAppManager.defaultAppManager **系统API:** 此接口为系统接口,三方应用不支持调用 @@ -453,6 +515,13 @@ resetDefaultApplication(type: string, callback: AsyncCallback\) : void; | type | string | 是 | 要重置的应用类型,取[ApplicationType](#defaultappmgrapplicationtype)中的值,或者符合媒体类型格式的文件类型。 | | callback | AsyncCallback\ | 是 | 程序启动作为入参的回调函数。 | +**错误码:** + +| 错误码ID | 错误码信息 | +| -------- | ----------------------------------- | +| 17700004 | The specified user id is not found. | +| 17700025 | The specified type is invalid. | + **示例:** ```js diff --git a/zh-cn/application-dev/reference/apis/js-apis-call.md b/zh-cn/application-dev/reference/apis/js-apis-call.md index 5fb798aceeb9d3e5b08efcec6484ec8df3018743..cc9679e4d6a085fea6c55236632694b200acddad 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-call.md +++ b/zh-cn/application-dev/reference/apis/js-apis-call.md @@ -664,6 +664,8 @@ hangup\(callback: AsyncCallback\): void 此接口为系统接口。 +**需要权限**:ohos.permission.ANSWER_CALL + **系统能力**:SystemCapability.Telephony.CallManager **参数:** @@ -689,6 +691,8 @@ hangup\(callId: number, callback: AsyncCallback\): void 此接口为系统接口。 +**需要权限**:ohos.permission.ANSWER_CALL + **系统能力**:SystemCapability.Telephony.CallManager **参数:** @@ -715,6 +719,8 @@ hangup\(callId?: number\): Promise 此接口为系统接口。 +**需要权限**:ohos.permission.ANSWER_CALL + **系统能力**:SystemCapability.Telephony.CallManager **参数:** @@ -748,6 +754,8 @@ reject\(callback: AsyncCallback\): void 此接口为系统接口。 +**需要权限**:ohos.permission.ANSWER_CALL + **系统能力**:SystemCapability.Telephony.CallManager **参数:** @@ -773,6 +781,8 @@ reject\(options: RejectMessageOptions, callback: AsyncCallback\): void 此接口为系统接口。 +**需要权限**:ohos.permission.ANSWER_CALL + **系统能力**:SystemCapability.Telephony.CallManager **参数:** @@ -802,6 +812,8 @@ reject(callId: number, callback: AsyncCallback\): void 此接口为系统接口。 +**需要权限**:ohos.permission.ANSWER_CALL + **系统能力**:SystemCapability.Telephony.CallManager **参数:** @@ -827,6 +839,8 @@ reject\(callId: number, options: RejectMessageOptions, callback: AsyncCallback 此接口为系统接口。 +**需要权限**:ohos.permission.ANSWER_CALL + **系统能力**:SystemCapability.Telephony.CallManager **参数:** @@ -894,6 +910,8 @@ holdCall\(callId: number, callback: AsyncCallback\): void 此接口为系统接口。 +**需要权限**:ohos.permission.ANSWER_CALL + **系统能力**:SystemCapability.Telephony.CallManager **参数:** @@ -920,6 +938,8 @@ holdCall\(callId: number\): Promise 此接口为系统接口。 +**需要权限**:ohos.permission.ANSWER_CALL + **系统能力**:SystemCapability.Telephony.CallManager **参数:** @@ -953,6 +973,8 @@ unHoldCall\(callId: number, callback: AsyncCallback\): void 此接口为系统接口。 +**需要权限**:ohos.permission.ANSWER_CALL + **系统能力**:SystemCapability.Telephony.CallManager **参数:** @@ -979,6 +1001,8 @@ unHoldCall\(callId: number\): Promise 此接口为系统接口。 +**需要权限**:ohos.permission.ANSWER_CALL + **系统能力**:SystemCapability.Telephony.CallManager **参数:** @@ -1012,6 +1036,8 @@ switchCall\(callId: number, callback: AsyncCallback\): void 此接口为系统接口。 +**需要权限**:ohos.permission.ANSWER_CALL + **系统能力**:SystemCapability.Telephony.CallManager **参数:** @@ -1038,6 +1064,8 @@ switchCall\(callId: number\): Promise 此接口为系统接口。 +**需要权限**:ohos.permission.ANSWER_CALL + **系统能力**:SystemCapability.Telephony.CallManager **参数:** @@ -1307,6 +1335,8 @@ getCallWaitingStatus\(slotId: number, callback: AsyncCallback 此接口为系统接口。 +**需要权限**:ohos.permission.GET_TELEPHONY_STATE + **系统能力**:SystemCapability.Telephony.CallManager **参数:** @@ -1366,6 +1398,8 @@ setCallWaiting\(slotId: number, activate: boolean, callback: AsyncCallback 此接口为系统接口。 +**需要权限**:ohos.permission.SET_TELEPHONY_STATE + **系统能力**:SystemCapability.Telephony.CallManager **参数:** @@ -1603,6 +1639,8 @@ on\(type: 'callDetailsChange', callback: Callback\): void 此接口为系统接口。 +**需要权限**:ohos.permission.SET_TELEPHONY_STATE + **系统能力**:SystemCapability.Telephony.CallManager **参数:** @@ -1628,6 +1666,8 @@ on\(type: 'callEventChange', callback: Callback\): void 此接口为系统接口。 +**需要权限**:ohos.permission.SET_TELEPHONY_STATE + **系统能力**:SystemCapability.Telephony.CallManager **参数:** @@ -1653,6 +1693,8 @@ on\(type: 'callDisconnectedCause', callback: Callback): vo 此接口为系统接口。 +**需要权限**:ohos.permission.SET_TELEPHONY_STATE + **系统能力**:SystemCapability.Telephony.CallManager **参数:** @@ -1678,6 +1720,8 @@ on\(type: 'mmiCodeResult', callback: Callback\): void 此接口为系统接口。 +**需要权限**:ohos.permission.SET_TELEPHONY_STATE + **系统能力**:SystemCapability.Telephony.CallManager **参数:** @@ -1703,6 +1747,8 @@ off\(type: 'callDetailsChange', callback?: Callback\): vo 此接口为系统接口。 +**需要权限**:ohos.permission.SET_TELEPHONY_STATE + **系统能力**:SystemCapability.Telephony.CallManager **参数:** @@ -1728,6 +1774,8 @@ off\(type: 'callEventChange', callback?: Callback\): void 此接口为系统接口。 +**需要权限**:ohos.permission.SET_TELEPHONY_STATE + **系统能力**:SystemCapability.Telephony.CallManager **参数:** @@ -1753,6 +1801,8 @@ off\(type: 'callDisconnectedCause', callback?: Callback\): 此接口为系统接口。 +**需要权限**:ohos.permission.SET_TELEPHONY_STATE + **系统能力**:SystemCapability.Telephony.CallManager **参数:** @@ -1778,6 +1828,8 @@ off\(type: 'mmiCodeResult', callback?: Callback\): void 此接口为系统接口。 +**需要权限**:ohos.permission.SET_TELEPHONY_STATE + **系统能力**:SystemCapability.Telephony.CallManager **参数:** @@ -1914,6 +1966,8 @@ getCallRestrictionStatus\(slotId: number, type: CallRestrictionType, callback: A 此接口为系统接口。 +**需要权限**:ohos.permission.GET_TELEPHONY_STATE + **系统能力**:SystemCapability.Telephony.CallManager **参数:** @@ -1941,6 +1995,8 @@ getCallRestrictionStatus\(slotId: number, type: CallRestrictionType\): Promise 此接口为系统接口。 +**需要权限**:ohos.permission.SET_TELEPHONY_STATE + **系统能力**:SystemCapability.Telephony.CallManager **参数:** @@ -2046,6 +2106,8 @@ getCallTransferInfo\(slotId: number, type: CallTransferType, callback: AsyncCall 此接口为系统接口。 +**需要权限**:ohos.permission.GET_TELEPHONY_STATE + **系统能力**:SystemCapability.Telephony.CallManager **参数:** @@ -2073,6 +2135,8 @@ getCallTransferInfo\(slotId: number, type: CallTransferType): Promise 此接口为系统接口。 +**需要权限**:ohos.permission.SET_TELEPHONY_STATE + **系统能力**:SystemCapability.Telephony.CallManager **参数:** @@ -2557,6 +2625,8 @@ enableImsSwitch(slotId: number, callback: AsyncCallback): void 此接口为系统接口。 +**需要权限**:ohos.permission.SET_TELEPHONY_STATE + **系统能力**:SystemCapability.Telephony.CallManager **参数:** @@ -2582,6 +2652,8 @@ enableImsSwitch(slotId: number): Promise 此接口为系统接口。 +**需要权限**:ohos.permission.SET_TELEPHONY_STATE + **系统能力**:SystemCapability.Telephony.CallManager **参数:** @@ -2615,6 +2687,8 @@ disableImsSwitch(slotId: number, callback: AsyncCallback): void 此接口为系统接口。 +**需要权限**:ohos.permission.SET_TELEPHONY_STATE + **系统能力**:SystemCapability.Telephony.CallManager **参数:** @@ -2640,6 +2714,8 @@ disableImsSwitch(slotId: number): Promise 此接口为系统接口。 +**需要权限**:ohos.permission.SET_TELEPHONY_STATE + **系统能力**:SystemCapability.Telephony.CallManager **参数:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-camera.md b/zh-cn/application-dev/reference/apis/js-apis-camera.md index 1d7ecedb9bf69cf520049f33f1a3bfd780c1243b..42d5c951e39b7a8f7ea28c82c5454770271c7369 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-camera.md +++ b/zh-cn/application-dev/reference/apis/js-apis-camera.md @@ -20,9 +20,9 @@ getCameraManager(context: Context, callback: AsyncCallback): voi **参数:** -| 名称 | 类型 | 必填 | 说明 | +| 名称 | 类型 | 必填 | 说明 | | -------- | ----------------------------------------------- | ---- | ---------------------------- | -| context | Context | 是 | 应用上下文。 | +| context | [Context](../../ability/context-userguide.md) | 是 | 应用上下文。 | | callback | AsyncCallback<[CameraManager](#cameramanager)\> | 是 | 回调函数,用于获取相机管理器实例。 | **示例:** @@ -49,7 +49,7 @@ getCameraManager(context: Context): Promise | 名称 | 类型 | 必填 | 说明 | | ------- | ------- | ---- | ------------ | -| context | Context | 是 | 应用上下文。 | +| context | [Context](../../ability/context-userguide.md) | 是 | 应用上下文。 | **返回值:** @@ -194,7 +194,7 @@ getSupportedOutputCapability(camera:CameraDevice, callback: AsyncCallback { +cameraManager.getSupportedOutputCapability(cameradevice, (err, cameras) => { if (err) { console.error(`Failed to get the cameras. ${err.message}`); return; @@ -939,7 +939,7 @@ on(type: 'error', camera:CameraDevice, callback: ErrorCallback { +cameraInput.on('error', camera, (cameraInputError) => { console.log(`Camera input error code: ${cameraInputError.code}`); }) ``` @@ -995,7 +995,7 @@ cameraInput.on('error', (cameraInputError) => { | EXPOSURE_MODE_AUTO | 1 | 自动曝光模式。 | | EXPOSURE_MODE_CONTINUOUS_AUTO | 2 | 连续自动曝光。 | -## FocusMode + ## FocusMode 枚举,焦距模式。 @@ -1735,7 +1735,7 @@ isExposureModeSupported(aeMode: ExposureMode, callback: AsyncCallback) **示例:** ```js -captureSession.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKEN,(err) => { +captureSession.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKED,(err) => { if (err) { console.log(`Failed to check exposure mode supported ${err.message}`); return ; @@ -1838,7 +1838,7 @@ setExposureMode(aeMode: ExposureMode, callback: AsyncCallback): void **示例:** ```js -captureSession.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKEN,(err) => { +captureSession.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKED,(err) => { if (err) { console.log(`Failed to set the exposure mode ${err.message}`); return ; @@ -2622,7 +2622,7 @@ captureSession.isVideoStabilizationModeSupported(camera.VideoStabilizationMode.O console.error(`Failed to check whether video stabilization mode supported. ${err.message}`); return; } - console.log(`Callback returned with the successful execution of isVideoStabilizationModeSupported: ${status}`); + console.log(`Callback returned with the successful execution of isVideoStabilizationModeSupported`); }) ``` @@ -3386,7 +3386,7 @@ photoOutput.on('error', (err, photoOutputError) => { | 名称 | 类型 | 说明 | | ---- | ------------------------------------- | ----------------------- | -| code | [PhotoOutputError](#photooutputerror) | PhotoOutput中的错误码。 | +| code | [PhotoOutputErrorCode](#photooutputerrorcode) | PhotoOutput中的错误码。 | ## VideoOutput @@ -3577,7 +3577,7 @@ videoOutput.on('error', (VideoOutputError) => { | 名称 | 类型 | 说明 | | ---- | ------------------------------------- | ----------------------- | -| code | [PhotoOutputError](#photooutputerror) | VideoOutput中的错误码。 | +| code | [PhotoOutputErrorCode](#photooutputerrorcode) | VideoOutput中的错误码。 | ## MetadataObjectType diff --git a/zh-cn/application-dev/reference/apis/js-apis-configuration.md b/zh-cn/application-dev/reference/apis/js-apis-configuration.md index 0f82948b512e9bd6b497befe3953562bcdb69c63..d8a1dc478279b66b1ab73f2b12b3d7269fd04aac 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-configuration.md +++ b/zh-cn/application-dev/reference/apis/js-apis-configuration.md @@ -3,7 +3,7 @@ Configuration模块提供环境变化信息的能力。 > **说明:** -> +> > 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 ## 导入模块 @@ -16,12 +16,12 @@ import Configuration from '@ohos.application.Configuration'; **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase - | 名称 | 参数类型 | 可读 | 可写 | 说明 | + | 名称 | 参数类型 | 可读 | 可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | -| language | string | 是 | 是 | 表示应用程序的当前语言。 | -| colorMode | [ColorMode](js-apis-configurationconstant.md) | 是 | 是 | 表示深浅色模式,取值范围:浅色模式(COLOR_MODE_LIGHT),深色模式(COLOR_MODE_DARK)。默认为浅色。 | -| direction9+ | Direction | 是 | 否 | 表示屏幕方向,取值范围:水平方向(DIRECTION_HORIZONTAL),垂直方向(DIRECTION_VERTICAL)。 | -| screenDensity9+ | ScreenDensity | 是 | 否 | 表示屏幕分辨率,取值范围:SCREEN_DENSITY_SDPI(120)、SCREEN_DENSITY_MDPI(160)、SCREEN_DENSITY_LDPI(240)、SCREEN_DENSITY_XLDPI(320)、SCREEN_DENSITY_XXLDPI(480)、SCREEN_DENSITY_XXXLDPI(640)。 | -| displayId9+ | number | 是 | 否 | 表示应用所在的displayId。 | -| hasPointerDevice9+ | boolean | 是 | 否 | 指示指针类型设备是否已连接。 | +| language | string | 是 | 是 | 表示应用程序的当前语言。 | +| colorMode | [ColorMode](js-apis-configurationconstant.md) | 是 | 是 | 表示深浅色模式,取值范围:浅色模式(COLOR_MODE_LIGHT),深色模式(COLOR_MODE_DARK)。默认为浅色。 | +| direction9+ | Direction | 是 | 否 | 表示屏幕方向,取值范围:水平方向(DIRECTION_HORIZONTAL),垂直方向(DIRECTION_VERTICAL)。 | +| screenDensity9+ | ScreenDensity | 是 | 否 | 表示屏幕分辨率,取值范围:SCREEN_DENSITY_SDPI(120)、SCREEN_DENSITY_MDPI(160)、SCREEN_DENSITY_LDPI(240)、SCREEN_DENSITY_XLDPI(320)、SCREEN_DENSITY_XXLDPI(480)、SCREEN_DENSITY_XXXLDPI(640)。 | +| displayId9+ | number | 是 | 否 | 表示应用所在的物理屏幕Id。 | +| hasPointerDevice9+ | boolean | 是 | 否 | 指示指针类型设备是否已连接,如键鼠、触控板等。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-continuation-continuationManager.md b/zh-cn/application-dev/reference/apis/js-apis-continuation-continuationManager.md index 28646100317913a0d82f2fbe740c7fa647e4f491..0e05d31270de26c1943eabbe95bdee8cfb036b64 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-continuation-continuationManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-continuation-continuationManager.md @@ -155,6 +155,8 @@ registerContinuation(callback: AsyncCallback\): void; 注册流转管理服务,并获取对应的注册token,无过滤条件,使用AsyncCallback方式作为异步方法。 +**需要权限**:ohos.permission.DISTRIBUTED_DATASYNC + **系统能力**:SystemCapability.Ability.DistributedAbilityManager **参数:** @@ -197,6 +199,8 @@ registerContinuation(options: ContinuationExtraParams, callback: AsyncCallback\< 连接流转管理服务,并获取对应的注册token,使用AsyncCallback方式作为异步方法。 +**需要权限**:ohos.permission.DISTRIBUTED_DATASYNC + **系统能力**:SystemCapability.Ability.DistributedAbilityManager **参数:** @@ -243,6 +247,8 @@ registerContinuation(options?: ContinuationExtraParams): Promise\; 连接流转管理服务,并获取对应的注册token,使用Promise方式作为异步方法。 +**需要权限**:ohos.permission.DISTRIBUTED_DATASYNC + **系统能力**:SystemCapability.Ability.DistributedAbilityManager **参数:** @@ -295,7 +301,7 @@ on(type: "deviceConnect", callback: Callback\): void; 异步方法,监听设备连接状态,使用Callback形式返回连接的设备信息。 -> 从API Version 9开始不再维护,建议使用[on](#continuationmanagerondeviceconnect9)替代。 +> 从API Version 9开始不再维护,建议使用[on](#continuationmanagerondeviceselected9)替代。 **系统能力**:SystemCapability.Ability.DistributedAbilityManager @@ -334,7 +340,7 @@ on(type: "deviceDisconnect", callback: Callback\): void; 异步方法,监听设备断开状态,使用Callback形式返回断开的设备信息。 -> 从API Version 9开始不再维护,建议使用[on](#continuationmanagerondevicedisconnect9)替代。 +> 从API Version 9开始不再维护,建议使用[on](#continuationmanagerondeviceunselected9)替代。 **系统能力**:SystemCapability.Ability.DistributedAbilityManager @@ -371,7 +377,7 @@ off(type: "deviceConnect", callback?: Callback\): void; 异步方法,取消监听设备连接状态,使用Callback形式返回连接的设备信息。 -> 从API Version 9开始不再维护,建议使用[off](#continuationmanageroffdeviceconnect9)替代。 +> 从API Version 9开始不再维护,建议使用[off](#continuationmanageroffdeviceselected9)替代。 **系统能力**:SystemCapability.Ability.DistributedAbilityManager @@ -410,7 +416,7 @@ off(type: "deviceDisconnect", callback?: Callback\): void; 异步方法,取消监听设备断开状态,使用Callback形式返回连接的设备信息。 -> 从API Version 9开始不再维护,建议使用[off](#continuationmanageroffdevicedisconnect9)替代。 +> 从API Version 9开始不再维护,建议使用[off](#continuationmanageroffdeviceunselected9)替代。 **系统能力**:SystemCapability.Ability.DistributedAbilityManager @@ -441,19 +447,21 @@ off(type: "deviceDisconnect", callback?: Callback\): void; }); ``` -## continuationManager.on("deviceConnect")9+ +## continuationManager.on("deviceSelected")9+ -on(type: "deviceConnect", token: number, callback: Callback\>): void; +on(type: "deviceSelected", token: number, callback: Callback\>): void; 异步方法,监听设备连接状态,使用Callback形式返回连接的设备信息。 +**需要权限**:ohos.permission.DISTRIBUTED_DATASYNC + **系统能力**:SystemCapability.Ability.DistributedAbilityManager **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | type | string | 是 | 监听的事件类型,固定值"deviceConnect"。 | + | type | string | 是 | 监听的事件类型,固定值"deviceSelected"。 | | token | number | 是 | 注册后的token。 | | callback | Callback\> | 是 | 当用户从设备选择模块中选择设备时调用,返回设备ID、设备类型和设备名称供开发者使用。 | @@ -473,12 +481,12 @@ on(type: "deviceConnect", token: number, callback: Callback\ { - console.info('onDeviceConnect len: ' + data.length); + continuationManager.on("deviceSelected", token, (data) => { + console.info('onDeviceSelected len: ' + data.length); for (let i = 0; i < data.length; i++) { - console.info('onDeviceConnect deviceId: ' + JSON.stringify(data[i].id)); - console.info('onDeviceConnect deviceType: ' + JSON.stringify(data[i].type)); - console.info('onDeviceConnect deviceName: ' + JSON.stringify(data[i].name)); + console.info('onDeviceSelected deviceId: ' + JSON.stringify(data[i].id)); + console.info('onDeviceSelected deviceType: ' + JSON.stringify(data[i].type)); + console.info('onDeviceSelected deviceName: ' + JSON.stringify(data[i].name)); } }); } catch (err) { @@ -486,21 +494,23 @@ on(type: "deviceConnect", token: number, callback: Callback\9+
+## continuationManager.on("deviceUnselected")9+ -on(type: "deviceDisconnect", token: number, callback: Callback\>): void; +on(type: "deviceUnselected", token: number, callback: Callback\>): void; 异步方法,监听设备断开状态,使用Callback形式返回断开的设备信息。 +**需要权限**:ohos.permission.DISTRIBUTED_DATASYNC + **系统能力**:SystemCapability.Ability.DistributedAbilityManager **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | type | string | 是 | 监听的事件类型,固定值"deviceDisconnect"。 | + | type | string | 是 | 监听的事件类型,固定值"deviceUnselected"。 | | token | number | 是 | 注册后的token。 | - | callback | Callback\> | 是 | 当用户从设备选择模块中断开设备时调用,返回设备ID供开发者使用。 | + | callback | Callback\> | 是 | 当用户从设备选择模块中断开设备时调用,返回设备ID、设备类型和设备名称供开发者使用。 | **错误码:** @@ -518,31 +528,35 @@ on(type: "deviceDisconnect", token: number, callback: Callback\>) ```ts let token = 1; try { - continuationManager.on("deviceDisconnect", token, (data) => { - console.info('onDeviceDisconnect len: ' + data.length); + continuationManager.on("deviceUnselected", token, (data) => { + console.info('onDeviceUnselected len: ' + data.length); for (let i = 0; i < data.length; i++) { - console.info('onDeviceDisconnect deviceId: ' + JSON.stringify(data[i])); + console.info('onDeviceUnselected deviceId: ' + JSON.stringify(data[i].id)); + console.info('onDeviceUnselected deviceType: ' + JSON.stringify(data[i].type)); + console.info('onDeviceUnselected deviceName: ' + JSON.stringify(data[i].name)); } - console.info('onDeviceDisconnect finished.'); + console.info('onDeviceUnselected finished.'); }); } catch (err) { console.error('on failed, cause: ' + JSON.stringify(err)); } ``` -## continuationManager.off("deviceConnect")9+ +## continuationManager.off("deviceSelected")9+ -off(type: "deviceConnect", token: number): void; +off(type: "deviceSelected", token: number): void; 取消监听设备连接状态。 +**需要权限**:ohos.permission.DISTRIBUTED_DATASYNC + **系统能力**:SystemCapability.Ability.DistributedAbilityManager **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | type | string | 是 | 取消监听的事件类型,固定值"deviceConnect"。 | + | type | string | 是 | 取消监听的事件类型,固定值"deviceSelected"。 | | token | number | 是 | 注册后的token。 | **错误码:** @@ -561,25 +575,27 @@ off(type: "deviceConnect", token: number): void; ```ts let token = 1; try { - continuationManager.off("deviceConnect", token); + continuationManager.off("deviceSelected", token); } catch (err) { console.error('off failed, cause: ' + JSON.stringify(err)); } ``` -## continuationManager.off("deviceDisconnect")9+ +## continuationManager.off("deviceUnselected")9+ -off(type: "deviceDisconnect", token: number): void; +off(type: "deviceUnselected", token: number): void; 取消监听设备断开状态。 +**需要权限**:ohos.permission.DISTRIBUTED_DATASYNC + **系统能力**:SystemCapability.Ability.DistributedAbilityManager **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | type | string | 是 | 取消监听的事件类型,固定值"deviceDisconnect"。 | + | type | string | 是 | 取消监听的事件类型,固定值"deviceUnselected"。 | | token | number | 是 | 注册后的token。 | **错误码:** @@ -598,7 +614,7 @@ off(type: "deviceDisconnect", token: number): void; ```ts let token = 1; try { - continuationManager.off("deviceDisconnect", token); + continuationManager.off("deviceUnselected", token); } catch (err) { console.error('off failed, cause: ' + JSON.stringify(err)); } @@ -610,7 +626,7 @@ startDeviceManager(token: number, callback: AsyncCallback\): void; 拉起设备选择模块,可显示组网内可选择设备列表信息,无过滤条件,使用AsyncCallback方式作为异步方法。 -> 从API Version 9开始不再维护,建议使用[startContinuationDeviceManager](#continuationmanagerondeviceconnect9)替代。 +> 从API Version 9开始不再维护,建议使用[startContinuationDeviceManager](#continuationmanagerstartcontinuationdevicemanager9)替代。 **系统能力**:SystemCapability.Ability.DistributedAbilityManager @@ -752,6 +768,8 @@ startContinuationDeviceManager(token: number, callback: AsyncCallback\): v 拉起设备选择模块,可显示组网内可选择设备列表信息,无过滤条件,使用AsyncCallback方式作为异步方法。 +**需要权限**:ohos.permission.DISTRIBUTED_DATASYNC + **系统能力**:SystemCapability.Ability.DistributedAbilityManager **参数:** @@ -794,6 +812,8 @@ startContinuationDeviceManager(token: number, options: ContinuationExtraParams, 拉起设备选择模块,可显示组网内可选择设备列表信息,使用AsyncCallback方式作为异步方法。 +**需要权限**:ohos.permission.DISTRIBUTED_DATASYNC + **系统能力**:SystemCapability.Ability.DistributedAbilityManager **参数:** @@ -840,6 +860,8 @@ startContinuationDeviceManager(token: number, options?: ContinuationExtraParams) 拉起设备选择模块,可显示组网内可选择设备列表信息,使用Promise方式作为异步方法。 +**需要权限**:ohos.permission.DISTRIBUTED_DATASYNC + **系统能力**:SystemCapability.Ability.DistributedAbilityManager **参数:** @@ -988,6 +1010,8 @@ updateContinuationState(token: number, deviceId: string, status: DeviceConnectSt 通知设备选择模块,更新当前的连接状态,使用AsyncCallback方式作为异步方法。 +**需要权限**:ohos.permission.DISTRIBUTED_DATASYNC + **系统能力**:SystemCapability.Ability.DistributedAbilityManager **参数:** @@ -1033,6 +1057,8 @@ updateContinuationState(token: number, deviceId: string, status: DeviceConnectSt 通知设备选择模块,更新当前的连接状态,使用Promise方式作为异步方法。 +**需要权限**:ohos.permission.DISTRIBUTED_DATASYNC + **系统能力**:SystemCapability.Ability.DistributedAbilityManager **参数:** @@ -1169,6 +1195,8 @@ unregisterContinuation(token: number, callback: AsyncCallback\): void; 解注册流转管理服务,传入注册时获取的token进行解注册,使用AsyncCallback方式作为异步方法。 +**需要权限**:ohos.permission.DISTRIBUTED_DATASYNC + **系统能力**:SystemCapability.Ability.DistributedAbilityManager **参数:** @@ -1211,6 +1239,8 @@ unregisterContinuation(token: number): Promise\; 解注册流转管理服务,传入注册时获取的token进行解注册,使用Promise方式作为异步方法。 +**需要权限**:ohos.permission.DISTRIBUTED_DATASYNC + **系统能力**:SystemCapability.Ability.DistributedAbilityManager **参数:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-distributedobject.md b/zh-cn/application-dev/reference/apis/js-apis-data-distributedobject.md index 5917976c58a5840152786573c551932c20749eb8..79c474b00aa1c9e77c25a6ea710df58815c0069a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-distributedobject.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-distributedobject.md @@ -13,35 +13,57 @@ import distributedObject from '@ohos.data.distributedDataObject'; ``` -## distributedDataObject.createDistributedObject - -createDistributedObject(source: object): DistributedObject +## distributedObject.create9+ +create(context: Context, source: object): DistributedObjectV9 创建一个分布式数据对象。 -**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject。 +**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | + | context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-Context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | | source | object | 是 | 设置分布式数据对象的属性。 | - + **返回值:** | 类型 | 说明 | | -------- | -------- | -| [DistributedObject](#distributedobject) | 创建完成的分布式数据对象。 | +| [DistributedObjectV9](#distributedobjectv9) | 创建完成的分布式数据对象。 | **示例:** +FA模型示例: + ```js +// 导入模块 import distributedObject from '@ohos.data.distributedDataObject'; -// 创建对象,对象包含4个属性类型,string,number,boolean和Object -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +import featureAbility from '@ohos.ability.featureAbility'; +// 获取context +let context = featureAbility.getContext(); +// 创建对象,该对象包含4个属性类型,string,number,boolean和Object +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); ``` +Stage模型示例: + +```ts +// 导入模块 +import distributedObject from '@ohos.data.distributedDataObject'; +import Ability from '@ohos.application.Ability'; +// 获取context +let context; +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context + } +} +// 创建对象,该对象包含4个属性类型,string,number,boolean和Object +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +``` ## distributedObject.genSessionId @@ -49,7 +71,7 @@ genSessionId(): string 随机创建一个sessionId。 -**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject。 +**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject **返回值:** @@ -61,14 +83,14 @@ genSessionId(): string ```js import distributedObject from '@ohos.data.distributedDataObject'; -var sessionId = distributedObject.genSessionId(); +let sessionId = distributedObject.genSessionId(); ``` ## SaveSuccessResponse9+ save接口回调信息。 -**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject。 +**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject | 名称 | 类型 | 说明 | | -------- | -------- | -------- | @@ -80,25 +102,150 @@ save接口回调信息。 revokeSave接口回调信息。 -**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject。 +**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject | 名称 | 类型 | 说明 | | -------- | -------- | -------- | | sessionId | string | 多设备协同的唯一标识。 | -## DistributedObject +## DistributedObjectV9 表示一个分布式数据对象。 -### setSessionId +### setSessionId9+ -setSessionId(sessionId?: string): boolean +setSessionId(sessionId: string, callback: AsyncCallback<void>): void 设置同步的sessionId,当可信组网中有多个设备时,多个设备间的对象如果设置为同一个sessionId,就能自动同步。 **需要权限:** ohos.permission.DISTRIBUTED_DATASYNC。 -**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject。 +**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**参数:** + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | sessionId | string | 是 | 分布式数据对象在可信组网中的标识ID。| + | callback | AsyncCallback<void> | 是 | 加入session的异步回调。| + +**错误码:** + + 以下错误码的详细介绍参见[分布式数据对象错误码](../errorcodes/errorcode-distributed-data_object.md)。 + + | 类型 | 说明 | + | -------- | -------- | + | 15400001 | 创建内存数据库失败。| + +**示例:** + +FA模型示例 + +```js +import distributedObject from '@ohos.data.distributedDataObject'; +import featureAbility from '@ohos.ability.featureAbility'; +// 获取context +let context = featureAbility.getContext(); +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +// g_object加入分布式组网 +g_object.setSessionId(distributedObject.genSessionId(), ()=>{ + console.log("join session"); +}); +``` +Stage模型示例 + +```ts +import distributedObject from '@ohos.data.distributedDataObject'; +import Ability from '@ohos.application.Ability'; +// 获取context +let context; +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context + } +} +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +// g_object加入分布式组网 +g_object.setSessionId(distributedObject.genSessionId(), ()=>{ + console.log("join session"); +}); +``` + +### setSessionId9+ + +setSessionId(callback: AsyncCallback<void>): void + +退出所有已加入的session。 + +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC。 + +**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**参数:** + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | 是 | 退出所有已加入session的异步回调。 | + +**错误码:** + + 以下错误码的详细介绍参见[分布式数据对象错误码](../errorcodes/errorcode-distributed-data_object.md)。 + + | 类型 | 说明 | + | -------- | -------- | + | 15400001 | 创建内存数据库失败。| + +**示例:** + +FA模型示例 + +```js +import distributedObject from '@ohos.data.distributedDataObject'; +import featureAbility from '@ohos.ability.featureAbility'; +// 获取context +let context = featureAbility.getContext(); +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +// g_object加入分布式组网 +g_object.setSessionId(distributedObject.genSessionId(), ()=>{ + console.log("join session"); +}); +// 退出分布式组网 +g_object.setSessionId(() => { + console.log("leave all lession."); +}); +``` +Stage模型示例 + +```ts +import distributedObject from '@ohos.data.distributedDataObject'; +import Ability from '@ohos.application.Ability'; +// 获取context +let context; +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context + } +} +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +// g_object加入分布式组网 +g_object.setSessionId(distributedObject.genSessionId(), ()=>{ + console.log("join session"); +}); +// 退出分布式组网 +g_object.setSessionId(() => { + console.log("leave all lession."); +}); +``` + +### setSessionId9+ + +setSessionId(sessionId?: string): Promise<void> + +设置同步的sessionId,当可信组网中有多个设备时,多个设备间的对象如果设置为同一个sessionId,就能自动同步。 + +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC。 + +**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject **参数:** @@ -108,28 +255,75 @@ setSessionId(sessionId?: string): boolean **返回值:** +| 类型 | 说明 | +| -------- | -------- | +| Promise<void> | Promise对象。| + +**错误码:** + + 以下错误码的详细介绍参见[分布式数据对象错误码](../errorcodes/errorcode-distributed-data_object.md)。 + | 类型 | 说明 | | -------- | -------- | - | boolean | true:标识设置sessionId成功。
false:标识设置sessionId失败。 | + | 15400001 | 创建内存数据库失败。| **示例:** +FA模型示例 + ```js import distributedObject from '@ohos.data.distributedDataObject'; -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});; +import featureAbility from '@ohos.ability.featureAbility'; +// 获取context +let context = featureAbility.getContext(); +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); // g_object加入分布式组网 -g_object.setSessionId(distributedObject.genSessionId()); -// 设置为""退出分布式组网 -g_object.setSessionId(""); +g_object.setSessionId(distributedObject.genSessionId()).then (()=>{ + console.log("join session."); + }).catch((error)=>{ + console.info("error:" + error.code + error.message); +}); +// 退出分布式组网 +g_object.setSessionId().then (()=>{ + console.log("leave all lession."); + }).catch((error)=>{ + console.info("error:" + error.code + error.message); +}); +``` +Stage模型示例 + +```ts +import distributedObject from '@ohos.data.distributedDataObject'; +import Ability from '@ohos.application.Ability'; +// 获取context +let context; +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context + } +} +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +// g_object加入分布式组网 +g_object.setSessionId(distributedObject.genSessionId()).then (()=>{ + console.info("join session."); + }).catch((error)=>{ + console.info("error:" + error.code + error.message); +}); +// 退出分布式组网 +g_object.setSessionId().then (()=>{ + console.log("leave all lession."); + }).catch((error)=>{ + console.info("error:" + error.code + error.message); +}); ``` -### on('change') +### on('change')9+ on(type: 'change', callback: Callback<{ sessionId: string, fields: Array<string> }>): void -监听分布式数据对象的变更。 +监听分布式数据对象的数据变更。 -**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject。 +**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject **参数:** @@ -140,9 +334,14 @@ on(type: 'change', callback: Callback<{ sessionId: string, fields: Array<stri **示例:** +FA模型示例 + ```js -import distributedObject from '@ohos.data.distributedDataObject'; -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +import distributedObject from '@ohos.data.distributedDataObject'; +import featureAbility from '@ohos.ability.featureAbility'; +// 获取context +let context = featureAbility.getContext(); +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); globalThis.changeCallback = (sessionId, changeData) => { console.info("change" + sessionId); if (changeData != null && changeData != undefined) { @@ -154,13 +353,37 @@ globalThis.changeCallback = (sessionId, changeData) => { g_object.on("change", globalThis.changeCallback); ``` -### off('change') +Stage模型示例 + +```ts +import distributedObject from '@ohos.data.distributedDataObject'; +import Ability from '@ohos.application.Ability'; +// 获取context +let context; +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context + } +} +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +globalThis.changeCallback = (sessionId, changeData) => { + console.info("change" + sessionId); + if (changeData != null && changeData != undefined) { + changeData.forEach(element => { + console.info("changed !" + element + " " + g_object[element]); + }); + } +} +g_object.on("change", globalThis.changeCallback); +``` + +### off('change')9+ off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array<string> }>): void 当不再进行数据变更监听时,使用此接口删除对象的变更监听。 -**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject。 +**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject **参数:** @@ -172,22 +395,46 @@ off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array<st **示例:** +FA模型示例 + ```js -import distributedObject from '@ohos.data.distributedDataObject'; -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +import distributedObject from '@ohos.data.distributedDataObject'; +import featureAbility from '@ohos.ability.featureAbility'; +// 获取context +let context = featureAbility.getContext(); +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); // 删除数据变更回调changeCallback g_object.off("change", globalThis.changeCallback); // 删除所有的数据变更回调 g_object.off("change"); ``` -### on('status') +Stage模型示例 + +```ts +import distributedObject from '@ohos.data.distributedDataObject'; +import Ability from '@ohos.application.Ability'; +// 获取context +let context; +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context + } +} +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +// 删除数据变更回调changeCallback +g_object.off("change", globalThis.changeCallback); +// 删除所有的数据变更回调 +g_object.off("change"); +``` + +### on('status')9+ on(type: 'status', callback: Callback<{ sessionId: string, networkId: string, status: 'online' | 'offline' }>): void 监听分布式数据对象的上下线。 -**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject。 +**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject **参数:** @@ -198,22 +445,46 @@ on(type: 'status', callback: Callback<{ sessionId: string, networkId: string, st **示例:** +FA模型示例 + ```js import distributedObject from '@ohos.data.distributedDataObject'; +import featureAbility from '@ohos.ability.featureAbility'; +// 获取context +let context = featureAbility.getContext(); +globalThis.statusCallback = (sessionId, networkId, status) => { + globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; +} +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +g_object.on("status", globalThis.statusCallback); +``` + +Stage模型示例 + +```ts +import distributedObject from '@ohos.data.distributedDataObject'; +import Ability from '@ohos.application.Ability'; +// 获取context +let context; +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context + } +} globalThis.statusCallback = (sessionId, networkId, status) => { globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; } -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); g_object.on("status", globalThis.statusCallback); ``` -### off('status') +### off('status')9+ off(type: 'status', callback?: Callback<{ sessionId: string, deviceId: string, status: 'online' | 'offline' }>): void 当不再进行对象上下线监听时,使用此接口删除对象的上下线监听。 -**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject。 +**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject **参数:** @@ -225,9 +496,36 @@ off(type: 'status', callback?: Callback<{ sessionId: string, deviceId: string, s **示例:** +FA模型示例 + ```js import distributedObject from '@ohos.data.distributedDataObject'; -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +import featureAbility from '@ohos.ability.featureAbility'; +// 获取context +let context = featureAbility.getContext(); +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +globalThis.statusCallback = (sessionId, networkId, status) => { + globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; +} +// 删除上下线回调changeCallback +g_object.off("status",globalThis.statusCallback); +// 删除所有的上下线回调 +g_object.off("status"); +``` + +Stage模型示例 + +```ts +import distributedObject from '@ohos.data.distributedDataObject'; +import Ability from '@ohos.application.Ability'; +// 获取context +let context; +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context + } +} +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); globalThis.statusCallback = (sessionId, networkId, status) => { globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; } @@ -251,7 +549,7 @@ save(deviceId: string, callback: AsyncCallback<SaveSuccessResponse>): void - 应用卸载。 - 成功恢复数据之后。 -**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject。 +**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject **参数:** @@ -264,7 +562,31 @@ save(deviceId: string, callback: AsyncCallback<SaveSuccessResponse>): void ```js import distributedObject from '@ohos.data.distributedDataObject'; -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); +import featureAbility from '@ohos.ability.featureAbility'; +// 获取context +let context = featureAbility.getContext(); +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false}); +g_object.setSessionId("123456"); +g_object.save("local", (status, result) => { + console.log("save status = " + status); + console.log("save callback"); + console.info("save sessionId: " + result.sessionId); + console.info("save version: " + result.version); + console.info("save deviceId: " + result.deviceId); +}); +``` + +```js +import distributedObject from '@ohos.data.distributedDataObject'; +import Ability from '@ohos.application.Ability'; +// 获取context +let context; +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context + } +} +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false}); g_object.setSessionId("123456"); g_object.save("local", (status, result) => { console.log("save status = " + status); @@ -289,7 +611,7 @@ save(deviceId: string): Promise<SaveSuccessResponse> - 应用卸载。 - 成功恢复数据之后。 -**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject。 +**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject **参数:** @@ -307,7 +629,32 @@ save(deviceId: string): Promise<SaveSuccessResponse> ```js import distributedObject from '@ohos.data.distributedDataObject'; -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); +import featureAbility from '@ohos.ability.featureAbility'; +// 获取context +let context = featureAbility.getContext(); +let g_object = distributedObject.create({name:"Amy", age:18, isVis:false}); +g_object.setSessionId("123456"); +g_object.save("local").then((result) => { + console.log("save callback"); + console.info("save sessionId " + result.sessionId); + console.info("save version " + result.version); + console.info("save deviceId " + result.deviceId); +}, () => { + console.error("save failed"); +}); +``` + +```js +import distributedObject from '@ohos.data.distributedDataObject'; +import Ability from '@ohos.application.Ability'; +// 获取context +let context; +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context + } +} +let g_object = distributedObject.create({name:"Amy", age:18, isVis:false}); g_object.setSessionId("123456"); g_object.save("local").then((result) => { console.log("save callback"); @@ -328,7 +675,7 @@ revokeSave(callback: AsyncCallback<RevokeSaveSuccessResponse>): void 如果对象保存在本地设备,那么将删除所有受信任设备上所保存的数据。 如果对象保存在其他设备,那么将删除本地设备上的数据。 -**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject。 +**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject **参数:** @@ -338,9 +685,38 @@ revokeSave(callback: AsyncCallback<RevokeSaveSuccessResponse>): void **示例:** +FA模型示例 + ```js import distributedObject from '@ohos.data.distributedDataObject'; -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); +import featureAbility from '@ohos.ability.featureAbility'; +// 获取context +let context = featureAbility.getContext(); +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false}); +g_object.setSessionId("123456"); +g_object.save("local").then((result) => { + console.log("save callback"); + console.info("save sessionId " + result.sessionId); + console.info("save version " + result.version); + console.info("save deviceId " + result.deviceId); +}, () => { + console.error("save failed"); +}); +``` + +Stage模型示例 + +```ts +import distributedObject from '@ohos.data.distributedDataObject'; +import Ability from '@ohos.application.Ability'; +// 获取context +let context; +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context + } +} +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false}); g_object.setSessionId("123456"); g_object.revokeSave((result, data) => { console.log("revokeSave callback"); @@ -356,7 +732,7 @@ revokeSave(): Promise<RevokeSaveSuccessResponse> 如果对象保存在本地设备,那么将删除所有受信任设备上所保存的数据。 如果对象保存在其他设备,那么将删除本地设备上的数据。 -**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject。 +**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject **返回值:** @@ -366,9 +742,14 @@ revokeSave(): Promise<RevokeSaveSuccessResponse> **示例:** +FA模型示例 + ```js import distributedObject from '@ohos.data.distributedDataObject'; -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); +import featureAbility from '@ohos.ability.featureAbility'; +// 获取context +let context = featureAbility.getContext(); +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false}); g_object.setSessionId("123456"); g_object.revokeSave().then((result) => { console.log("revokeSave callback"); @@ -377,3 +758,231 @@ g_object.revokeSave().then((result) => { console.error("revokeSave failed"); }); ``` + +Stage模型示例 + +```ts +import distributedObject from '@ohos.data.distributedDataObject'; +import Ability from '@ohos.application.Ability'; +// 获取context +let context; +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context + } +} +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false}); +g_object.setSessionId("123456"); +g_object.save("local").then((result) => { + console.log("save callback"); + console.info("save sessionId " + result.sessionId); + console.info("save version " + result.version); + console.info("save deviceId " + result.deviceId); +}, () => { + console.error("save failed"); +}); +``` + +## distributedObject.createDistributedObject(deprecated) + +createDistributedObject(source: object): DistributedObject + + +创建一个分布式数据对象。 + +> **说明:** +> +> 从 API Version 8 开始支持,从 API Version 9 开始废弃,建议使用distributedObject.create替代。 + +**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**参数:** + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | source | object | 是 | 设置分布式数据对象的属性。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| [DistributedObject](#distributedobjectdeprecated) | 创建完成的分布式数据对象。 | + +**示例:** + +```js +import distributedObject from '@ohos.data.distributedDataObject'; +// 创建对象,对象包含4个属性类型,string,number,boolean和Object +let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +``` + +## DistributedObject(deprecated) + +表示一个分布式数据对象。 + +### setSessionId(deprecated) + +setSessionId(sessionId?: string): boolean + +设置同步的sessionId,当可信组网中有多个设备时,多个设备间的对象如果设置为同一个sessionId,就能自动同步。 + +> **说明:** +> +> 从 API Version 8 开始支持,从 API Version 9 开始废弃,建议使用[setSessionId](#setsessionid9)替代。 + +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC。 + +**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**参数:** + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | sessionId | string | 否 | 分布式数据对象在可信组网中的标识ID。如果要退出分布式组网,设置为""或不设置均可。 | + +**返回值:** + + | 类型 | 说明 | + | -------- | -------- | + | boolean | true:标识设置sessionId成功。
false:标识设置sessionId失败。 | + +**示例:** + +```js +import distributedObject from '@ohos.data.distributedDataObject'; +let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});; +// g_object加入分布式组网 +g_object.setSessionId(distributedObject.genSessionId()); +// 设置为""退出分布式组网 +g_object.setSessionId(""); +``` + +### on('change')(deprecated) + +on(type: 'change', callback: Callback<{ sessionId: string, fields: Array<string> }>): void + +监听分布式数据对象的变更。 + +> **说明:** +> +> 从 API Version 8 开始支持,从 API Version 9 开始废弃,建议使用[on('change')](#onchange9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**参数:** + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | type | string | 是 | 事件类型,固定为'change',表示数据变更。 | + | callback | Callback<{ sessionId: string, fields: Array<string> }> | 是 | 变更回调对象实例。
sessionId:标识变更对象的sessionId;
fields:标识对象变更的属性名。 | + +**示例:** + +```js +import distributedObject from '@ohos.data.distributedDataObject'; +let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +globalThis.changeCallback = (sessionId, changeData) => { + console.info("change" + sessionId); + if (changeData != null && changeData != undefined) { + changeData.forEach(element => { + console.info("changed !" + element + " " + g_object[element]); + }); + } +} +g_object.on("change", globalThis.changeCallback); +``` + +### off('change')(deprecated) + +off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array<string> }>): void + +当不再进行数据变更监听时,使用此接口删除对象的变更监听。 + +> **说明:** +> +> 从 API Version 8 开始支持,从 API Version 9 开始废弃,建议使用[off('change')](#offchange9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**参数:** + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | type | string | 是 | 事件类型,固定为'change',表示数据变更。 | + | callback | Callback<{ sessionId: string, fields: Array<string> }> | 否 | 需要删除的数据变更回调,若不设置则删除该对象所有的数据变更回调。
sessionId:标识变更对象的sessionId;
fields:标识对象变更的属性名。 | + + +**示例:** + +```js +import distributedObject from '@ohos.data.distributedDataObject'; +let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +// 删除数据变更回调changeCallback +g_object.off("change", globalThis.changeCallback); +// 删除所有的数据变更回调 +g_object.off("change"); +``` + +### on('status')(deprecated) + +on(type: 'status', callback: Callback<{ sessionId: string, networkId: string, status: 'online' | 'offline' }>): void + +监听分布式数据对象的上下线。 + +> **说明:** +> +> 从 API Version 8 开始支持,从 API Version 9 开始废弃,建议使用[on('status')](#onstatus9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**参数:** + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | type | string | 是 | 事件类型,固定为'status',表示对象上下线。 | + | callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | 是 | 监听上下线回调实例。
sessionId:标识变更对象的sessionId;
networkId:标识对象设备,即deviceId;
status:标识对象为'online'(上线)或'offline'(下线)的状态。 | + +**示例:** + +```js +import distributedObject from '@ohos.data.distributedDataObject'; +globalThis.statusCallback = (sessionId, networkId, status) => { + globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; +} +let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +g_object.on("status", globalThis.statusCallback); +``` + +### off('status')(deprecated) + +off(type: 'status', callback?: Callback<{ sessionId: string, deviceId: string, status: 'online' | 'offline' }>): void + +当不再进行对象上下线监听时,使用此接口删除对象的上下线监听。 + +> **说明:** +> +> 从 API Version 8 开始支持,从 API Version 9 开始废弃,建议使用[off('status')](#offstatus9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**参数:** + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | type | string | 是 | 事件类型,固定为'status',表示对象上下线。 | + | callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | 否 | 需要删除的上下线回调,若不设置则删除该对象所有的上下线回调。
sessionId:标识变更对象的sessionId;
deviceId:标识变更对象的deviceId;
status:标识对象为'online'(上线)或'offline'(下线)的状态。 | + + +**示例:** + +```js +import distributedObject from '@ohos.data.distributedDataObject'; +let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +globalThis.statusCallback = (sessionId, networkId, status) => { + globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; +} +// 删除上下线回调changeCallback +g_object.off("status",globalThis.statusCallback); +// 删除所有的上下线回调 +g_object.off("status"); +``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-display.md b/zh-cn/application-dev/reference/apis/js-apis-display.md index 16f4b444dfab57746ef9839190eade2c246007c7..9a81d184706a40168d702b300e4823c53245bfed 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-display.md +++ b/zh-cn/application-dev/reference/apis/js-apis-display.md @@ -414,7 +414,7 @@ promise.then((data) => { | alive | boolean | 是 | 否 | 显示设备是否启用。| | state | [DisplayState](#displaystate) | 是 | 否 | 显示设备的状态。| | refreshRate | number | 是 | 否 | 显示设备的刷新率。| -| rotation | number | 是 | 否 | 显示设备的屏幕旋转角度。| +| rotation | number | 是 | 否 | 显示设备的屏幕旋转角度。
值为0时,表示显示设备屏幕旋转为0°;
值为1时,表示显示设备屏幕旋转为90°;
值为2时,表示显示设备屏幕旋转为180°;
值为3时,表示显示设备屏幕旋转为270°。| | width | number | 是 | 否 | 显示设备的宽度,单位为像素。| | height | number | 是 | 否 | 显示设备的高度,单位为像素。| | densityDPI | number | 是 | 否 | 显示设备的屏幕密度,单位为DPI。| diff --git a/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md b/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md index 5d62db3f113c60af609aa15ce4aa6990fb079ab3..eca0200f6b2aac960d82d6195642d6d2ab26ef07 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md +++ b/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md @@ -54,20 +54,18 @@ getOsAccountDistributedInfo(callback: AsyncCallback<DistributedInfo>): voi **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 201 | permission denied. | - | 401 | the parameter check failed. | - | 12300001 | system service exception. | +| 错误码ID | 错误信息| +| -------- | ------------------- | +| 12300001 | System service exception. | **示例:** ```js const accountAbility = account_distributedAccount.getDistributedAccountAbility(); try { accountAbility.getOsAccountDistributedInfo((err, data) => { - console.log("getOsAccountDistributedInfo err: " + JSON.stringify(err)); - console.log('Query account info name: ' + data.name); - console.log('Query account info id: ' + data.id); + console.log("getOsAccountDistributedInfo err: " + JSON.stringify(err)); + console.log('Query account info name: ' + data.name); + console.log('Query account info id: ' + data.id); }); } catch (e) { console.log("getOsAccountDistributedInfo exception: " + JSON.stringify(e)); @@ -92,11 +90,9 @@ getOsAccountDistributedInfo(): Promise<DistributedInfo> **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 201 | permission denied. | - | 401 | the parameter check failed. | - | 12300001 | system service exception. | +| 错误码ID | 错误信息| +| -------- | ------------------- | +| 12300001 | System service exception. | **示例:** ```js @@ -146,6 +142,7 @@ queryOsAccountDistributedInfo(callback: AsyncCallback<DistributedInfo>): v queryOsAccountDistributedInfo(): Promise<DistributedInfo> 获取分布式帐号信息。使用Promise异步回调。 + > **说明:** 从API version 9开始废弃,建议使用[getOsAccountDistributedInfo](#getosaccountdistributedinfo9-1) > > 从 API version 7开始支持。 @@ -190,12 +187,10 @@ setOsAccountDistributedInfo(accountInfo: DistributedInfo, callback: AsyncCallbac **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 201 | permission denied. | - | 401 | the parameter check failed. | - | 12300001 | system service exception. | - | 12300002 | invalid accountInfo. | +| 错误码ID | 错误信息| +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | invalid accountInfo. | **示例:** ```js @@ -234,12 +229,10 @@ setOsAccountDistributedInfo(accountInfo: DistributedInfo): Promise<void> **错误码:** - | 错误码ID | 错误信息| - | ------- | -------| - | 201 | permission denied. | - | 401 | the parameter check failed. | - | 12300001 | system service exception. | - | 12300002 | invalid accountInfo. | +| 错误码ID | 错误信息| +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | invalid accountInfo. | **示例:** ```js @@ -260,6 +253,7 @@ setOsAccountDistributedInfo(accountInfo: DistributedInfo): Promise<void> updateOsAccountDistributedInfo(accountInfo: DistributedInfo, callback: AsyncCallback<void>): void 更新分布式帐号信息。使用callback异步回调。 + > **说明:** 从API version 9开始废弃,建议使用[setOsAccountDistributedInfo](#setosaccountdistributedinfo9) > > 从 API version 7开始支持。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-fileio.md b/zh-cn/application-dev/reference/apis/js-apis-fileio.md index dd484ad1a6b14a1e24be7dfb9d208c9f65be0eb1..a69af688341e87c3628ce0ef8b07b92e41919644 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-fileio.md +++ b/zh-cn/application-dev/reference/apis/js-apis-fileio.md @@ -29,7 +29,7 @@ class MainAbility extends Ability { } ``` - Stage模型context的具体获取方法参见[Stage模型](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-ability-context.md#abilitycontext)。 + Stage模型context的具体获取方法参见[Stage模型](js-apis-ability-context.md#abilitycontext)。 **FA模型** @@ -41,7 +41,7 @@ class MainAbility extends Ability { }) ``` - FA模型context的具体获取方法参见[FA模型](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-Context.md#context%E6%A8%A1%E5%9D%97)。 + FA模型context的具体获取方法参见[FA模型](js-apis-Context.md#Context模块)。 ## fileio.stat diff --git a/zh-cn/application-dev/reference/apis/js-apis-huks.md b/zh-cn/application-dev/reference/apis/js-apis-huks.md index ee703cf1686bba0bef5f11d287da62e6cc9b02e6..49c7126b86a04983f27ba36299d4c2ef5e3e5278 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-huks.md +++ b/zh-cn/application-dev/reference/apis/js-apis-huks.md @@ -2596,7 +2596,7 @@ finish(handle: number, options: HuksOptions) : Promise\ finish操作密钥接口,使用Promise方式异步返回结果。huks.init, huks.update, huks.finish为三段式接口,需要一起使用。 -> **说明:** 从API Version 9开始废弃,建议使用[huks.updateSession9+](#huksfinishsession9-1)替代。 +> **说明:** 从API Version 9开始废弃,建议使用[huks.finishSession9+](#huksfinishsession9-1)替代。 **系统能力**:SystemCapability.Security.Huks diff --git a/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md b/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md index 90a611d1bb4452fc73fddb95d6866e1b189043af..c9be6f2af616711ec5ce4c69ed98def44f71cb1f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md +++ b/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md @@ -660,7 +660,7 @@ mediaLibrary.getMediaLibrary().storeMediaAsset(option).then((value) => { startImagePreview(images: Array<string>, index: number, callback: AsyncCallback<void>): void -启动图片预览界面并限定预览开始显示的图片。可以预览指定序号的单张本地图片(dataability://),也可以预览列表中的所有网络图片(https://)。使用callback方式进行异步回调。 +启动图片预览界面并限定预览开始显示的图片。可以预览指定序号的单张本地图片(datashare://),也可以预览列表中的所有网络图片(https://)。使用callback方式进行异步回调。 > **说明**:
从API Version 9开始废弃。建议使用[Image组件](../arkui-ts/ts-basic-components-image.md)替代。
Image组件,可用于本地图片和网络图片的渲染展示。 @@ -670,7 +670,7 @@ startImagePreview(images: Array<string>, index: number, callback: AsyncCal | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ---------------------------------------- | -| images | Array<string> | 是 | 预览的图片URI("https://","dataability://")列表。 | +| images | Array<string> | 是 | 预览的图片URI("https://","datashare://")列表。 | | index | number | 是 | 开始显示的图片序号。 | | callback | AsyncCallback<void> | 是 | 图片预览回调,失败时返回错误信息。 | @@ -678,8 +678,8 @@ startImagePreview(images: Array<string>, index: number, callback: AsyncCal ```js let images = [ - "dataability:///media/xxxx/2", - "dataability:///media/xxxx/3" + "datashare:///media/xxxx/2", + "datashare:///media/xxxx/3" ]; /* 网络图片使用方式 let images = [ @@ -702,7 +702,7 @@ mediaLibrary.getMediaLibrary().startImagePreview(images, index, (err) => { startImagePreview(images: Array<string>, callback: AsyncCallback<void>): void -启动图片预览界面,可以预览列表中首张本地图片(dataability://),也可以预览列表中的所有网络图片(https://)。使用callback方式进行异步回调。 +启动图片预览界面,可以预览列表中首张本地图片(datashare://),也可以预览列表中的所有网络图片(https://)。使用callback方式进行异步回调。 > **说明**:
从API Version 9开始废弃。建议使用[Image组件](../arkui-ts/ts-basic-components-image.md)替代。
Image组件,可用于本地图片和网络图片的渲染展示。 @@ -712,15 +712,15 @@ startImagePreview(images: Array<string>, callback: AsyncCallback<void&g | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ---------------------------------------- | -| images | Array<string> | 是 | 预览的图片URI("https://","dataability://")列表。 | +| images | Array<string> | 是 | 预览的图片URI("https://","datashare://")列表。 | | callback | AsyncCallback<void> | 是 | 图片预览回调,失败时返回错误信息。 | **示例:** ```js let images = [ - "dataability:///media/xxxx/2", - "dataability:///media/xxxx/3" + "datashare:///media/xxxx/2", + "datashare:///media/xxxx/3" ]; /* 网络图片使用方式 let images = [ @@ -742,7 +742,7 @@ mediaLibrary.getMediaLibrary().startImagePreview(images, (err) => { startImagePreview(images: Array<string>, index?: number): Promise<void> -启动图片预览界面并限定预览开始显示的图片。可以预览指定序号的单张本地图片(dataability://),也可以预览列表中的所有网络图片(https://)。使用Promise方式进行异步回调。 +启动图片预览界面并限定预览开始显示的图片。可以预览指定序号的单张本地图片(datashare://),也可以预览列表中的所有网络图片(https://)。使用Promise方式进行异步回调。 > **说明**:
从API Version 9开始废弃。建议使用[Image组件](../arkui-ts/ts-basic-components-image.md)替代。
Image组件,可用于本地图片和网络图片的渲染展示。 @@ -752,7 +752,7 @@ startImagePreview(images: Array<string>, index?: number): Promise<void& | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------------- | ---- | ---------------------------------------- | -| images | Array<string> | 是 | 预览的图片URI("https://","dataability://")列表。 | +| images | Array<string> | 是 | 预览的图片URI("https://","datashare://")列表。 | | index | number | 否 | 开始显示的图片序号,不选择时默认为0。 | **返回值:** @@ -765,8 +765,8 @@ startImagePreview(images: Array<string>, index?: number): Promise<void& ```js let images = [ - "dataability:///media/xxxx/2", - "dataability:///media/xxxx/3" + "datashare:///media/xxxx/2", + "datashare:///media/xxxx/3" ]; /* 网络图片使用方式 let images = [ @@ -798,7 +798,7 @@ startMediaSelect(option: MediaSelectOption, callback: AsyncCallback<Array< | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ------------------------------------ | | option | [MediaSelectOption](#mediaselectoptiondeprecated) | 是 | 媒体选择选项。 | -| callback | AsyncCallback<Array<string>> | 是 | 媒体选择回调,返回选择的媒体URI(dataability://)列表。 | +| callback | AsyncCallback<Array<string>> | 是 | 媒体选择回调,返回选择的媒体URI(datashare://)列表。 | **示例:** @@ -838,7 +838,7 @@ startMediaSelect(option: MediaSelectOption): Promise<Array<string>> | 类型 | 说明 | | ---------------------------------- | ---------------------------------------- | -| Promise<Array<string>> | Promise实例,用于异步获取选择的媒体URI(dataability://)列表。 | +| Promise<Array<string>> | Promise实例,用于异步获取选择的媒体URI(datashare://)列表。 | **示例:** @@ -1015,7 +1015,7 @@ async function example() { | 名称 | 类型 | 可读 | 可写 | 说明 | | ------------------------- | ------------------------ | ---- | ---- | ------------------------------------------------------ | | id | number | 是 | 否 | 文件资源编号 | -| uri | string | 是 | 否 | 文件资源uri(如:dataability:///media/image/2) | +| uri | string | 是 | 否 | 文件资源uri(如:datashare:///media/image/2) | | mimeType | string | 是 | 否 | 文件扩展属性 | | mediaType8+ | [MediaType](#mediatype8) | 是 | 否 | 媒体类型 | | displayName | string | 是 | 是 | 显示文件名,包含后缀名 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-net-policy.md b/zh-cn/application-dev/reference/apis/js-apis-net-policy.md index 8bffaf0ea66260cdb6f5a405c3cc72545a9b0056..b64c21fb78a1b77ed0e7f6c67a9148ddb2deba48 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-net-policy.md +++ b/zh-cn/application-dev/reference/apis/js-apis-net-policy.md @@ -155,7 +155,7 @@ policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.cur setPolicyByUid(uid: number, policy: NetUidPolicy): Promise\; -设置对应uid应用的访问计量网络的策略,使用callback方式作为异步方法。 +设置对应uid应用的访问计量网络的策略,使用Promise方式作为异步方法。 **需要权限**:ohos.permission.CONNECTIVITY_INTERNAL @@ -871,6 +871,7 @@ policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number }); ``` + ## policy.updateRemindPolicy updateRemindPolicy(netType: NetBearType, iccid: string, remindType: RemindType): Promise\; @@ -1059,8 +1060,8 @@ policy.on('netBackgroundPolicyChange', (data) => { | 参数名 | 类型 | 说明 | | ----------------------- | ----------------------------------- | ------------------------------------------------------------ | | netType | [NetBearType](js-apis-net-connection.md#netbeartype) | 网络类型。 | -| iccid | string | 计量蜂窝网络的SIM卡的标识值。以太网,wify网络不会用到 | -| ident | string | 计量蜂窝网络中配合iccid联合使用。以太网,wify网络单独使用。用于标记类型。 | +| iccid | string | 计量蜂窝网络的SIM卡的标识值。以太网,wifi网络不会用到 | +| ident | string | 计量蜂窝网络中配合iccid联合使用。以太网,wifi网络单独使用。用于标记类型。 | | periodDuration | string | 计量开始时间。 | | warningBytes | number | 发出警告的流量阈值。 | | limitBytes | number | 流量设置的配额。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-net-sharing.md b/zh-cn/application-dev/reference/apis/js-apis-net-sharing.md index f19a5f42023b2a16c589e19dc16509de079ba336..09eb27279de84db7a500e367a3a0da4a0dce78cb 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-net-sharing.md +++ b/zh-cn/application-dev/reference/apis/js-apis-net-sharing.md @@ -26,7 +26,7 @@ isSharingSupported(callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------------- | ---- | ---------- | -| callback | AsyncCallback\ | 是 | 回调函数,返回ture代表支持网络共享。 | +| callback | AsyncCallback\ | 是 | 回调函数,返回true代表支持网络共享。 | **示例:** @@ -77,7 +77,7 @@ isSharing(callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------------- | ---- | ---------- | -| callback | AsyncCallback\ | 是 | 回调函数,返回ture代表网络共享中。 | +| callback | AsyncCallback\ | 是 | 回调函数,返回true代表网络共享中。 | **示例:** @@ -102,7 +102,7 @@ isSharing(): Promise\ | 类型 | 说明 | | --------------------------------- | ------------------------------------- | -| Promise\ | 以Promise形式返回网络共享状态结果,返回ture代表网络共享中。 | +| Promise\ | 以Promise形式返回网络共享状态结果,返回true代表网络共享中。 | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-osAccount.md b/zh-cn/application-dev/reference/apis/js-apis-osAccount.md index b8c557185193c2f1ca58fcd399d54a2a69d5a7b1..a9a1c265c231ec3b93bf0e3a55a302c4ceb6a94f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-osAccount.md +++ b/zh-cn/application-dev/reference/apis/js-apis-osAccount.md @@ -70,9 +70,11 @@ activateOsAccount(localId: number, callback: AsyncCallback<void>): void | 错误码ID | 错误信息 | | -------- | ------------------- | +| 12300001 | System service exception. | | 12300002 | Invalid localId. | -| 12300003 | Account not exists. | -| 12300004 | Restricted Account. | +| 12300003 | Account not found. | +| 12300008 | Restricted Account. | +| 12300009 | Account has been activated. | **示例:** 激活ID为100的系统帐号 ```js @@ -112,16 +114,18 @@ activateOsAccount(localId: number): Promise<void> **返回值:** | 类型 | 说明 | -| :------------------ | :----------------------------------- | +| ------------------- | ------------------------------------ | | Promise<void> | Promise对象。无返回结果的Promise对象。 | **错误码:** | 错误码ID | 错误信息 | | -------- | ------------------- | +| 12300001 | System service exception. | | 12300002 | Invalid localId. | -| 12300003 | Account not exists. | -| 12300004 | Restricted Account. | +| 12300003 | Account not found. | +| 12300008 | Restricted Account. | +| 12300009 | Account has been activated. | **示例:** 激活ID为100的系统帐号 ```js @@ -152,12 +156,18 @@ checkMultiOsAccountEnabled(callback: AsyncCallback<boolean>): void | -------- | ---------------------------- | ---- | ------------------------------------------------------ | | callback | AsyncCallback<boolean> | 是 | 回调函数。返回true表示支持多系统帐号;返回false表示不支持。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------- | +| 12300001 | System service exception. | + **示例:** ```js let accountManager = account_osAccount.getAccountManager(); try { - accountManager.checkMultiOsAccountEnabled((err, isEnalbed) => { + accountManager.checkMultiOsAccountEnabled((err, isEnabled) => { if (err) { console.log("checkMultiOsAccountEnabled failed, error: " + JSON.stringify(err)); } else { @@ -183,6 +193,12 @@ checkMultiOsAccountEnabled(): Promise<boolean> | :--------------------- | :--------------------------------------------------------- | | Promise<boolean> | Promise对象。返回true表示支持多系统帐号;返回false表示不支持。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------- | +| 12300001 | System service exception. | + **示例:** ```js @@ -219,16 +235,17 @@ checkOsAccountActivated(localId: number, callback: AsyncCallback<boolean>) | 错误码ID | 错误信息 | | -------- | ------------------- | +| 12300001 | System service exception. | | 12300002 | Invalid localId. | -| 12300003 | Account not exists. | +| 12300003 | Account not found. | **示例:** 判断ID为100的系统帐号是否处于激活状态 ```js let accountManager = account_osAccount.getAccountManager(); - let osLocalId = 100; + let localId = 100; try { - accountManager.checkOsAccountActivated(osLocalId, (err, isActivated)=>{ + accountManager.checkOsAccountActivated(localId, (err, isActivated) => { if (err) { console.log('checkOsAccountActivated failed, error:' + JSON.stringify(err)); } else { @@ -246,7 +263,7 @@ checkOsAccountActivated(localId: number): Promise<boolean> 判断指定系统帐号是否处于激活状态。使用Promise异步回调。 -**需要权限:** ohos.permission.MANAGE_LOCAL_ACCOUNTS +**需要权限:** ohos.permission.MANAGE_LOCAL_ACCOUNTS 或 ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS **系统能力:** SystemCapability.Account.OsAccount @@ -266,8 +283,9 @@ checkOsAccountActivated(localId: number): Promise<boolean> | 错误码ID | 错误信息 | | -------- | ------------------- | +| 12300001 | System service exception. | | 12300002 | Invalid localId. | -| 12300003 | Account not exists. | +| 12300003 | Account not found. | **示例:** 判断ID为100的系统帐号是否处于激活状态 @@ -291,7 +309,7 @@ checkConstraintEnabled(localId: number, constraint: string, callback: AsyncCallb 判断指定系统帐号是否具有指定约束。使用callback异步回调。 -**需要权限:** ohos.permission.MANAGE_LOCAL_ACCOUNTS。 +**需要权限:** ohos.permission.MANAGE_LOCAL_ACCOUNTS 或 ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS **系统能力:** SystemCapability.Account.OsAccount @@ -307,8 +325,9 @@ checkConstraintEnabled(localId: number, constraint: string, callback: AsyncCallb | 错误码ID | 错误信息 | | -------- | ------------------- | +| 12300001 | System service exception. | | 12300002 | Invalid localId. | -| 12300003 | Account not exists. | +| 12300003 | Account not found. | **示例:** 判断ID为100的系统帐号是否有禁止使用Wi-Fi的约束 @@ -356,8 +375,9 @@ checkConstraintEnabled(localId: number, constraint: string): Promise<boolean& | 错误码ID | 错误信息 | | -------- | ------------------- | +| 12300001 | System service exception. | | 12300002 | Invalid localId. | -| 12300003 | Account not exists. | +| 12300003 | Account not found. | **示例:** 判断ID为100的系统帐号是否有禁止使用Wi-Fi的约束 @@ -394,8 +414,7 @@ checkOsAccountTestable(callback: AsyncCallback<boolean>): void | 错误码ID | 错误信息 | | -------- | ------------------- | -| 12300002 | Invalid localId. | -| 12300003 | Account not exists. | +| 12300001 | System service exception. | **示例:** @@ -432,8 +451,7 @@ checkOsAccountTestable(): Promise<boolean> | 错误码ID | 错误信息 | | -------- | ------------------- | -| 12300002 | Invalid localId. | -| 12300003 | Account not exists. | +| 12300001 | System service exception. | **示例:** @@ -470,8 +488,9 @@ checkOsAccountVerified(callback: AsyncCallback<boolean>): void | 错误码ID | 错误信息 | | -------- | ------------------- | +| 12300001 | System service exception. | | 12300002 | Invalid localId. | -| 12300003 | Account not exists. | +| 12300003 | Account not found. | **示例:** @@ -511,8 +530,9 @@ checkOsAccountVerified(localId: number, callback: AsyncCallback<boolean>): | 错误码ID | 错误信息 | | -------- | ------------------- | +| 12300001 | System service exception. | | 12300002 | Invalid localId. | -| 12300003 | Account not exists. | +| 12300003 | Account not found. | **示例:** @@ -520,7 +540,7 @@ checkOsAccountVerified(localId: number, callback: AsyncCallback<boolean>): let accountManager = account_osAccount.getAccountManager(); let localId = 100; try { - accountManager.checkOsAccountVerified(localId, (err, result) => { + accountManager.checkOsAccountVerified(localId, (err, isVerified) => { if (err) { console.log("checkOsAccountVerified failed, error: " + JSON.stringify(err)); } else { @@ -558,8 +578,9 @@ checkOsAccountVerified(localId?: number): Promise<boolean> | 错误码ID | 错误信息 | | -------- | ------------------- | +| 12300001 | System service exception. | | 12300002 | Invalid localId. | -| 12300003 | Account not exists. | +| 12300003 | Account not found. | **示例:** @@ -573,7 +594,7 @@ checkOsAccountVerified(localId?: number): Promise<boolean> console.log("checkOsAccountVerified failed, error: " + JSON.stringify(err)); }); } catch (err) { - console.log('checkOsAccountVerified exception: ' + JSON.stringify(e)); + console.log('checkOsAccountVerified exception: ' + JSON.stringify(err)); } ``` @@ -600,9 +621,10 @@ removeOsAccount(localId: number, callback: AsyncCallback<void>): void | 错误码ID | 错误信息 | | -------- | ------------------- | +| 12300001 | System service exception. | | 12300002 | Invalid localId. | -| 12300003 | Account not exists. | -| 12300004 | Restricted Account. | +| 12300003 | Account not found. | +| 12300008 | Restricted Account. | **示例:** @@ -652,9 +674,10 @@ removeOsAccount(localId: number): Promise<void> | 错误码ID | 错误信息 | | -------- | ------------------- | +| 12300001 | System service exception. | | 12300002 | Invalid localId. | -| 12300003 | Account not exists. | -| 12300004 | Restricted Account. | +| 12300003 | Account not found. | +| 12300008 | Restricted Account. | **示例:** @@ -699,9 +722,10 @@ setOsAccountConstraints(localId: number, constraints: Array<string>, enabl | 错误码ID | 错误信息 | | -------- | ------------------- | +| 12300001 | System service exception. | | 12300002 | Invalid localId. | -| 12300003 | Account not exists. | -| 12300004 | Restricted Account. | +| 12300003 | Account not found. | +| 12300008 | Restricted Account. | **示例:** 给ID为100的系统帐号设置禁止使用Wi-Fi的约束 @@ -752,9 +776,10 @@ setOsAccountConstraints(localId: number, constraints: Array<string>, enabl | 错误码ID | 错误信息 | | -------- | ------------------- | +| 12300001 | System service exception. | | 12300002 | Invalid localId. | -| 12300003 | Account not exists. | -| 12300004 | Restricted Account. | +| 12300003 | Account not found. | +| 12300008 | Restricted Account. | **示例:** 删除ID为100的系统帐号的禁止使用Wi-Fi的约束 @@ -796,9 +821,10 @@ setOsAccountName(localId: number, localName: string, callback: AsyncCallback< | 错误码ID | 错误信息 | | -------- | ------------------- | -| 12300002 | Invalid parameters. | -| 12300003 | Account not exists. | -| 12300004 | Restricted Account. | +| 12300001 | System service exception. | +| 12300002 | Invalid localId or localName. | +| 12300003 | Account not found. | +| 12300008 | Restricted Account. | **示例:** 将ID为100的系统帐号的帐号名设置成demoName @@ -841,16 +867,17 @@ setOsAccountName(localId: number, localName: string): Promise<void> **返回值:** | 类型 | 说明 | -| :------------------ | :----------------------------------- | +| ------------------- | ------------------------------------ | | Promise<void> | Promise对象。无返回结果的Promise对象。 | **错误码:** | 错误码ID | 错误信息 | | -------- | ------------------- | -| 12300002 | Invalid localId. | -| 12300003 | Account not exists. | -| 12300004 | Restricted Account. | +| 12300001 | System service exception. | +| 12300002 | Invalid localId or localName. | +| 12300003 | Account not found. | +| 12300008 | Restricted Account. | **示例:** 将ID为100的系统帐号的帐号名设置成demoName @@ -885,6 +912,12 @@ getOsAccountCount(callback: AsyncCallback<number>): void | -------- | --------------------------- | ---- | -------------------------------------------------------------------------- | | callback | AsyncCallback<number> | 是 | 回调函数。当获取成功时,err为null,data为已创建的系统帐号的数量;否则为错误对象。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------- | +| 12300001 | System service exception. | + **示例:** ```js @@ -918,6 +951,12 @@ getOsAccountCount(): Promise<number> | --------------------- | -------------------------------------- | | Promise<number> | Promise对象,返回已创建的系统帐号的数量。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------- | +| 12300001 | System service exception. | + **示例:** ```js @@ -947,6 +986,12 @@ queryOsAccountLocalIdFromProcess(callback: AsyncCallback<number>): void | -------- | --------------------------- | ---- | ---------------------------------------------------------------------------- | | callback | AsyncCallback<number> | 是 | 回调函数。当获取成功时,err为null,data为当前进程所属的系统帐号ID;否则为错误对象。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------- | +| 12300001 | System service exception. | + **示例:** ```js @@ -975,9 +1020,15 @@ queryOsAccountLocalIdFromProcess(): Promise<number> **返回值:** | 类型 | 说明 | -| :-------------------- | :--------------------------------------- | +| --------------------- | ---------------------------------------- | | Promise<number> | Promise对象,返回当前进程所属的系统帐号ID。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------- | +| 12300001 | System service exception. | + **示例:** ```js @@ -1008,10 +1059,11 @@ queryOsAccountLocalIdFromUid(uid: number, callback: AsyncCallback<number>) | uid | number | 是 | 进程uid。 | | callback | AsyncCallback<number> | 是 | 回调函数。如果查询成功,err为null,data为对应的系统帐号ID;否则为错误对象。 | - **错误码:** | 错误码ID | 错误信息 | +| -------- | --------------- | +| 12300001 | System service exception. | | 12300002 | Invalid uid. | **示例:** 查询值为12345678的uid所属的系统帐号的帐号ID @@ -1054,6 +1106,8 @@ queryOsAccountLocalIdFromUid(uid: number): Promise<number> **错误码:** | 错误码ID | 错误信息 | +| -------- | ------------- | +| 12300001 | System service exception. | | 12300002 | Invalid uid. | **示例:** 查询值为12345678的uid所属的系统帐号ID @@ -1074,7 +1128,7 @@ queryOsAccountLocalIdFromUid(uid: number): Promise<number> ### queryOsAccountLocalIdFromDomain9+ -getOsAccountLocalIdFromDomain(domainInfo: DomainAccountInfo, callback: AsyncCallback<number>): void +queryOsAccountLocalIdFromDomain(domainInfo: DomainAccountInfo, callback: AsyncCallback<number>): void 根据域帐号信息,获取与其关联的系统帐号ID。使用callback异步回调。 @@ -1089,6 +1143,13 @@ getOsAccountLocalIdFromDomain(domainInfo: DomainAccountInfo, callback: AsyncCall | domainInfo | [DomainAccountInfo](#domainaccountinfo8) | 是 | 域帐号信息。 | | callback | AsyncCallback<number> | 是 | 回调函数。如果查询成功,err为null,data为域帐号关联的系统帐号ID;否则为错误对象。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid domainInfo. | + **示例:** ```js @@ -1129,6 +1190,13 @@ queryOsAccountLocalIdFromDomain(domainInfo: DomainAccountInfo): Promise<numbe | :-------------------- | :------------------------------------- | | Promise<number> | Promise对象,返回域帐号关联的系统帐号ID。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid domainInfo. | + **示例:** ```js @@ -1161,6 +1229,12 @@ queryMaxOsAccountNumber(callback: AsyncCallback<number>): void | -------- | --------------------------- | ---- | -------------------------------------------------------------------------------- | | callback | AsyncCallback<number> | 是 | 回调函数,如果查询成功,err为null,data为允许创建的系统帐号的最大数量;否则为错误对象。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------- | +| 12300001 | System service exception. | + **示例:** ```js @@ -1194,6 +1268,12 @@ queryMaxOsAccountNumber(): Promise<number> | --------------------- | ------------------------------------------- | | Promise<number> | Promise对象,返回允许创建的系统帐号的最大数量。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------- | +| 12300001 | System service exception. | + **示例:** ```js @@ -1230,8 +1310,9 @@ getOsAccountConstraints(localId: number, callback: AsyncCallback<Array<str | 错误码ID | 错误信息 | | -------- | ------------------- | +| 12300001 | System service exception. | | 12300002 | Invalid localId. | -| 12300003 | Account not exists. | +| 12300003 | Account not found. | **示例:** 获取ID为100的系统帐号的全部约束 @@ -1277,8 +1358,9 @@ getOsAccountConstraints(localId: number): Promise<Array<string>> | 错误码ID | 错误信息 | | -------- | ------------------- | +| 12300001 | System service exception. | | 12300002 | Invalid localId. | -| 12300003 | Account not exists. | +| 12300003 | Account not found. | **示例:** 获取ID为100的系统帐号的全部约束 @@ -1314,6 +1396,12 @@ queryAllCreatedOsAccounts(callback: AsyncCallback<Array<OsAccountInfo>& | -------- | ------------------------------------------------------------ | ---- | -------------------------------------------------- | | callback | AsyncCallback<Array<[OsAccountInfo](#osaccountinfo)>> | 是 | 回调函数。如果查询成功,err为null,data为已创建的所有系统帐号的信息列表;否则为错误对象。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------- | +| 12300001 | System service exception. | + **示例:** ```js @@ -1346,6 +1434,12 @@ queryAllCreatedOsAccounts(): Promise<Array<OsAccountInfo>> | ----------------------------------------------------------- | --------------------------------------------- | | Promise<Array<[OsAccountInfo](#osaccountinfo)>> | Promise对象,返回已创建的所有系统帐号的信息列表。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------- | +| 12300001 | System service exception. | + **示例:** ```js @@ -1375,6 +1469,12 @@ getActivatedOsAccountIds(callback: AsyncCallback<Array<number>>): vo | -------- | ---------------------------------------- | ---- | ------------------------------------------------------ | | callback | AsyncCallback<Array<number>> | 是 | 回调函数。如果查询成功,err为null,data为当前处于激活状态的系统帐号的ID列表;否则为错误对象。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------- | +| 12300001 | System service exception. | + **示例:** ```js @@ -1406,6 +1506,12 @@ getActivatedOsAccountIds(): Promise<Array<number>> | :--------------------------------- | :------------------------------------------------ | | Promise<Array<number>> | Promise对象,返回当前处于激活状态的系统帐号的ID列表。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------- | +| 12300001 | System service exception. | + **示例:** ```js @@ -1442,8 +1548,14 @@ createOsAccount(localName: string, type: OsAccountType, callback: AsyncCallback& | callback | AsyncCallback<[OsAccountInfo](#osaccountinfo)> | 是 | 回调函数。如果创建成功,err为null,data为新创建的系统帐号的信息;否则为错误对象。 | **错误码:** -| 错误码ID | 错误信息 | + +| 错误码ID | 错误信息 | +| -------- | ------------------------- | +| 12300001 | System service exception. | | 12300002 | Invalid localName or type. | +| 12300005 | Multi-user not supported. | +| 12300006 | Unsupported account type. | +| 12300007 | The number of account reaches the upper limit. | **示例:** @@ -1485,8 +1597,14 @@ createOsAccount(localName: string, type: OsAccountType): Promise<OsAccountInf | Promise<[OsAccountInfo](#osaccountinfo)> | Promis对象,返回新创建的系统帐号的信息。 | **错误码:** -| 错误码ID | 错误信息 | + +| 错误码ID | 错误信息 | +| -------- | ------------------------- | +| 12300001 | System service exception. | | 12300002 | Invalid localName or type. | +| 12300005 | Multi-user not supported. | +| 12300006 | Unsupported account type. | +| 12300007 | The number of account reaches the upper limit. | **示例:** @@ -1518,14 +1636,20 @@ createOsAccountForDomain(type: OsAccountType, domainInfo: DomainAccountInfo, cal **参数:** | 参数名 | 类型 | 必填 | 说明 | -| :--------- | ---------------------------------------------------- | ---- | -------------------------------------------------------------------------- | +| ---------- | ---------------------------------------------------- | ---- | -------------------------------------------------------------------------- | | type | [OsAccountType](#osaccounttype) | 是 | 创建的系统帐号的类型。 | | domainInfo | [DomainAccountInfo](#domainaccountinfo8) | 是 | 域帐号信息。 | | callback | AsyncCallback<[OsAccountInfo](#osaccountinfo)> | 是 | 回调函数。如果创建成功,err为null,data为新创建的系统帐号的信息;否则为错误对象。 | **错误码:** + | 错误码ID | 错误信息 | +| -------- | ------------------- | +| 12300001 | System service exception. | | 12300002 | Invalid type or domainInfo. | +| 12300005 | Multi-user not supported. | +| 12300006 | Unsupported account type. | +| 12300007 | The number of account reaches the upper limit. | **示例:** @@ -1568,8 +1692,14 @@ createOsAccountForDomain(type: OsAccountType, domainInfo: DomainAccountInfo): Pr | Promise<[OsAccountInfo](#osaccountinfo)> | Promise对象,返回新创建的系统帐号的信息。 | **错误码:** + | 错误码ID | 错误信息 | +| -------- | ------------------- | +| 12300001 | System service exception. | | 12300002 | Invalid type or domainInfo. | +| 12300005 | Multi-user not supported. | +| 12300006 | Unsupported account type. | +| 12300007 | The number of account reaches the upper limit. | **示例:** @@ -1603,6 +1733,12 @@ getCurrentOsAccount(callback: AsyncCallback<OsAccountInfo>): void | -------- | ---------------------------------------------------- | ---- | ---------------------------------------------- | | callback | AsyncCallback<[OsAccountInfo](#osaccountinfo)> | 是 | 回调函数。如果查询成功,err为null,data为当前进程所属的系统帐号信息;否则为错误对象。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------- | +| 12300001 | System service exception. | + **示例:** ```js @@ -1633,6 +1769,12 @@ getCurrentOsAccount(): Promise<OsAccountInfo> | ---------------------------------------------- | ----------------------------------------- | | Promise<[OsAccountInfo](#osaccountinfo)> | Promise对象,返回当前进程所属的系统帐号信息。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------- | +| 12300001 | System service exception. | + **示例:** ```js @@ -1668,10 +1810,12 @@ queryOsAccountById(localId: number, callback: AsyncCallback<OsAccountInfo> | callback | AsyncCallback<[OsAccountInfo](#osaccountinfo)> | 是 | 回调函数。如果查询成功,err为null,data为查到的系统帐号的信息;否则为错误对象。 | **错误码:** + | 错误码ID | 错误信息 | | -------- | ------------------- | +| 12300001 | System service exception. | | 12300002 | Invalid localId. | -| 12300003 | Account not exists. | +| 12300003 | Account not found. | **示例:** 查询ID为100的系统帐号信息 @@ -1713,10 +1857,12 @@ queryOsAccountById(localId: number): Promise<OsAccountInfo> | Promise<[OsAccountInfo](#osaccountinfo)> | Promise对象,返回查到的系统帐号的信息。 | **错误码:** + | 错误码ID | 错误信息 | | -------- | ------------------- | +| 12300001 | System service exception. | | 12300002 | Invalid localId. | -| 12300003 | Account not exists. | +| 12300003 | Account not found. | **示例:** 查询ID为100的系统帐号信息 @@ -1748,6 +1894,12 @@ getOsAccountType(callback: AsyncCallback<OsAccountType>): void | -------- | ---------------------------------------------------- | ---- | ---------------------------------------------------- | | callback | AsyncCallback<[OsAccountType](#osaccounttype)> | 是 | 回调函数。如果查询成功,err为null,data为当前进程所属的系统帐号的帐号类型;否则为错误对象。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------- | +| 12300001 | System service exception. | + **示例:** ```js @@ -1776,6 +1928,12 @@ getOsAccountType(): Promise<OsAccountType> | ---------------------------------------------- | ----------------------------------------------- | | Promise<[OsAccountType](#osaccounttype)> | Promise对象,返回当前进程所属的系统帐号的帐号类型。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------- | +| 12300001 | System service exception. | + **示例:** ```js @@ -1797,7 +1955,7 @@ queryDistributedVirtualDeviceId(callback: AsyncCallback<string>): void 获取分布式虚拟设备ID。使用callback异步回调。 -**需要权限:** ohos.permission.MANAGE_LOCAL_ACCOUNTS +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC or ohos.permission.MANAGE_LOCAL_ACCOUNTS **系统能力:** SystemCapability.Account.OsAccount @@ -1807,6 +1965,12 @@ queryDistributedVirtualDeviceId(callback: AsyncCallback<string>): void | -------- | --------------------------- | ---- | --------------------------------------------------------------------- | | callback | AsyncCallback<string> | 是 | 回调函数。如果获取成功,err为null,data为分布式虚拟设备ID;否则为错误对象。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------- | +| 12300001 | System service exception. | + **示例:** ```js @@ -1827,7 +1991,7 @@ queryDistributedVirtualDeviceId(): Promise<string> 获取分布式虚拟设备ID。使用Promise异步回调。 -**需要权限:** ohos.permission.MANAGE_LOCAL_ACCOUNTS +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC or ohos.permission.MANAGE_LOCAL_ACCOUNTS **系统能力:** SystemCapability.Account.OsAccount @@ -1837,6 +2001,12 @@ queryDistributedVirtualDeviceId(): Promise<string> | --------------------- | --------------------------------- | | Promise<string> | Promise对象,返回分布式虚拟设备ID。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------- | +| 12300001 | System service exception. | + **示例:** ```js @@ -1872,10 +2042,12 @@ getOsAccountProfilePhoto(localId: number, callback: AsyncCallback<string>) | callback | AsyncCallback<string> | 是 | 回调函数。如果获取成功,err为null,data为指定系统帐号的头像信息;否则为错误对象。 | **错误码:** + | 错误码ID | 错误信息 | | -------- | ------------------- | +| 12300001 | System service exception. | | 12300002 | Invalid localId. | -| 12300003 | Account not exists. | +| 12300003 | Account not found. | **示例:** 获取ID为100的系统帐号的头像 @@ -1917,10 +2089,12 @@ getOsAccountProfilePhoto(localId: number): Promise<string> | Promise<string> | Promise对象,返回指定系统帐号的头像信息。 | **错误码:** + | 错误码ID | 错误信息 | | -------- | ------------------- | +| 12300001 | System service exception. | | 12300002 | Invalid localId. | -| 12300003 | Account not exists. | +| 12300003 | Account not found. | **示例:** 获取ID为100的系统帐号的头像 @@ -1959,11 +2133,13 @@ setOsAccountProfilePhoto(localId: number, photo: string, callback: AsyncCallback | callback | AsyncCallback<void> | 是 | 回调结果。 | **错误码:** + | 错误码ID | 错误信息 | | -------- | ------------------- | -| 12300002 | Invalid localId. | -| 12300003 | Account not exists. | -| 12300004 | Restricted Account. | +| 12300001 | System service exception. | +| 12300002 | Invalid localId or photo. | +| 12300003 | Account not found. | +| 12300008 | Restricted Account. | **示例:** 给ID为100的系统帐号设置头像 @@ -2005,15 +2181,17 @@ setOsAccountProfilePhoto(localId: number, photo: string): Promise<void> **返回值:** | 类型 | 说明 | -| :------------------ | :----------------------------------- | +| ------------------- | ------------------------------------ | | Promise<void> | Promise对象。无返回结果的Promise对象。 | **错误码:** + | 错误码ID | 错误信息 | | -------- | ------------------- | -| 12300002 | Invalid localId. | -| 12300003 | Account not exists. | -| 12300004 | Restricted Account. | +| 12300001 | System service exception. | +| 12300002 | Invalid localId or photo. | +| 12300003 | Account not found. | +| 12300008 | Restricted Account. | **示例:** 给ID为100的系统帐号设置头像 @@ -2051,8 +2229,12 @@ queryOsAccountLocalIdBySerialNumber(serialNumber: number, callback: AsyncCallbac | callback | AsyncCallback<number> | 是 | 回调函数。如果成功,err为null,data为与SN码关联的系统帐号的帐号ID;否则为错误对象。 | **错误码:** + | 错误码ID | 错误信息 | +| -------- | ------------------- | +| 12300001 | System service exception. | | 12300002 | Invalid serialNumber. | +| 12300003 | Account not found. | **示例:** 查询与SN码12345关联的系统帐号的ID @@ -2086,12 +2268,16 @@ queryOsAccountLocalIdBySerialNumber(serialNumber: number): Promise<number> **返回值:** | 类型 | 说明 | -| :-------------------- | :------------------- ----------------------- | +| --------------------- | -------------------------------------------- | | Promise<number> | Promise对象,返回与SN码关联的系统帐号的帐号ID。 | **错误码:** + | 错误码ID | 错误信息 | +| -------- | ------------------- | +| 12300001 | System service exception. | | 12300002 | Invalid serialNumber. | +| 12300003 | Account not found. | **示例:** 查询与SN码12345关联的系统帐号的ID @@ -2128,8 +2314,9 @@ querySerialNumberByOsAccountLocalId(localId: number, callback: AsyncCallback< | 错误码ID | 错误信息 | | -------- | ------------------- | +| 12300001 | System service exception. | | 12300002 | Invalid localId. | -| 12300003 | Account not exists. | +| 12300003 | Account not found. | **示例:** 获取ID为100的系统帐号关联的SN码 @@ -2170,8 +2357,9 @@ querySerialNumberByOsAccountLocalId(localId: number): Promise<number> | 错误码ID | 错误信息 | | -------- | ------------------- | +| 12300001 | System service exception. | | 12300002 | Invalid localId. | -| 12300003 | Account not exists. | +| 12300003 | Account not found. | **示例:** 获取ID为100的系统帐号关联的SN码 @@ -2209,6 +2397,14 @@ on(type: 'activate' | 'activating', name: string, callback: Callback<number&g | name | string | 是 | 订阅名称,可自定义,要求非空且长度不超过1024字节。 | | callback | Callback<number> | 是 | 订阅系统帐号变动信息的回调,表示当前事件对应的系统帐号ID。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid type or name. | +| 12300011 | Callback has been registered. | + **示例:** ```js @@ -2243,6 +2439,14 @@ off(type: 'activate' | 'activating', name: string, callback?: Callback<number | name | string | 是 | 订阅名称,可自定义,,要求非空且长度不超过1024字节,需要与订阅接口传入的值保持一致。 | | callback | Callback<number> | 否 | 取消订阅系统帐号变化的回调,默认返回0。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid type or name. | +| 12300012 | Callback has not been registered. | + **示例:** ```js @@ -2274,6 +2478,13 @@ getBundleIdFromUid(uid: number, callback: AsyncCallback<number>): void; | uid | number | 是 | 进程uid。 | | callback | AsyncCallback<number> | 是 | 回调函数。如果查询成功,err为null,data为与uid对应的bundleId;否则为错误对象。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid uid. | + **示例:** ```js @@ -2310,6 +2521,13 @@ getBundleIdFromUid(uid: number): Promise<number>; | --------------------- | ------------------------------------ | | Promise<number> | Promise对象,返回与uid对应的bundleId。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid uid. | + **示例:** ```js @@ -2344,6 +2562,12 @@ isMainOsAccount(callback: AsyncCallback<boolean>): void; | -------- | ---------------------------- | ---- | ----------------------------------------------------------------- | | callback | AsyncCallback<boolean> | 是 | 回调函数,返回true表示当前帐号为主帐号,返回false表示当前帐号非主帐号。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------- | +| 12300001 | System service exception. | + **示例:** ```js @@ -2375,6 +2599,12 @@ isMainOsAccount(): Promise<boolean>; | ---------------------- | --------------------------------------------------------------------- | | Promise<boolean> | Promise对象,返回true表示当前帐号为主帐号,返回false表示当前帐号非主帐号。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------- | +| 12300001 | System service exception. | + **示例:** ```js @@ -2409,6 +2639,14 @@ queryOsAccountConstraintSourceTypes(localId: number, constraint: string, callbac | constraint | string | 是 | 要查询的[约束](#系统帐号约束列表)名称 | | callback | AsyncCallback<Array<[ConstraintSourceTypeInfo](#constraintsourcetypeinfo)>> | 是 | 回调函数。如果成功,err为null,data为指定系统帐号的指定[约束](#系统帐号约束列表)来源信息;否则为错误对象。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid localId or constraint. | +| 12300003 | Account not found. | + **示例:** ```js @@ -2445,9 +2683,17 @@ queryOsAccountConstraintSourceTypes(localId: number, constraint: string): Promis **返回值:** | 类型 | 说明 | -| :-------------------- | :----------------------------------------------------------- | +| --------------------- | ------------------------------------------------------------ | | Promise<Array<[ConstraintSourceTypeInfo](#constraintsourcetypeinfo)>> | Promise对象,返回指定系统帐号的指定[约束](#系统帐号约束列表)来源信息。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid localId or constraint. | +| 12300003 | Account not found. | + **示例:** ```js @@ -2485,7 +2731,7 @@ isMultiOsAccountEnable(callback: AsyncCallback<boolean>): void ```js let accountManager = account_osAccount.getAccountManager(); - accountManager.isMultiOsAccountEnable((err, isEnalbed) => { + accountManager.isMultiOsAccountEnable((err, isEnabled) => { if (err) { console.log("isMultiOsAccountEnable failed, error: " + JSON.stringify(err)); } else { @@ -2744,6 +2990,8 @@ isOsAccountVerified(callback: AsyncCallback<boolean>): void > > 从 API version 7开始支持。 +**需要权限:** ohos.permission.MANAGE_LOCAL_ACCOUNTS 或 ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + **系统能力:** SystemCapability.Account.OsAccount **参数:** @@ -3361,7 +3609,7 @@ getDistributedVirtualDeviceId(callback: AsyncCallback<string>): void > > 从 API version 7开始支持。 -**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC 或 ohos.permission.MANAGE_LOCAL_ACCOUNTS **系统能力:** SystemCapability.Account.OsAccount @@ -3391,7 +3639,7 @@ getDistributedVirtualDeviceId(): Promise<string> > > 从 API version 7开始支持。 -**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC 或 ohos.permission.MANAGE_LOCAL_ACCOUNTS **系统能力:** SystemCapability.Account.OsAccount @@ -3565,7 +3813,6 @@ constructor() let userAuth = new account_osAccount.UserAuth(); ``` - ### getVersion8+ getVersion(): number; @@ -3593,7 +3840,7 @@ getVersion(): number; getAvailableStatus(authType: AuthType, authTrustLevel: AuthTrustLevel): number; -检查身份认证功能是否可用。 +获取指定认证类型和认证可信等级的认证能力的可用状态。 **系统接口:** 此接口为系统接口。 @@ -3603,16 +3850,23 @@ getAvailableStatus(authType: AuthType, authTrustLevel: AuthTrustLevel): number; **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| --------------- | -----------------------------------------------| ---- | ------------------------- | -| authType | [AuthType](#authtype8) | 是 | 指示用于认证的凭据类型。 | -| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | 是 | 表示身份验证结果的信任级别。 | +| 参数名 | 类型 | 必填 | 说明 | +| --------------- | -----------------------------------| ---- | ------------------------- | +| authType | [AuthType](#authtype8) | 是 | 认证类型。 | +| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | 是 | 认证的可信等级。 | **返回值:** -| 类型 | 说明 | -| :----- | :---------------------------------------- | -| number | 返回验证[结果](#resultcode8)。 | +| 类型 | 说明 | +| ------ | ----------------------------- | +| number | 返回认证能力的可用状态。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | --------------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid authType or authTrustLevel. | **示例:** ```js @@ -3642,9 +3896,16 @@ getProperty(request: GetPropertyRequest, callback: AsyncCallback<ExecutorProp **参数:** | 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------------------------------------------------------- | ---- | ---------------------------------- | +| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------ | | request | [GetPropertyRequest](#getpropertyrequest8) | 是 | 请求信息,包括认证类型和属性类型列表。 | -| callback | AsyncCallback<[ExecutorProperty](#executorproperty8)> | 是 | 回调函数。如果获取成功,err为null,data为执行器属性信息;否则为错误对象。 | +| callback | AsyncCallback<[ExecutorProperty](#executorproperty8)> | 是 | 回调函数。如果获取成功,err为null,data为执行器属性信息;否则为错误对象。| + +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | --------------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid request. | **示例:** ```js @@ -3692,6 +3953,13 @@ getProperty(request: GetPropertyRequest): Promise<ExecutorProperty>; | :---------------------------------------------------------------- | :-------------------------------------------------- | | Promise<[ExecutorProperty](#executorproperty8)> | Promise对象,返回执行者属性信息。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | --------------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid request. | + **示例:** ```js let userAuth = new account_osAccount.UserAuth(); @@ -3734,6 +4002,13 @@ setProperty(request: SetPropertyRequest, callback: AsyncCallback<number>): | request | [SetPropertyRequest](#setpropertyrequest8)| 是 | 请求信息,包括认证类型和要设置的密钥值。 | | callback | AsyncCallback<number> | 是 | 回调函数。如果设置成功,err为null,data为一个[数值](#resultcode8),指示属性设置是否成功;否则为错误对象。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | --------------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid request. | + **示例:** ```js let userAuth = new account_osAccount.UserAuth(); @@ -3776,6 +4051,13 @@ setProperty(request: SetPropertyRequest): Promise<number>; | :-------------------- | :------------------------------------------------------------ | | Promise<number> | Promise对象,返回一个[数值](#resultcode8),指示属性设置是否成功。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | --------------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid request. | + **示例:** ```js let userAuth = new account_osAccount.UserAuth(); @@ -3809,20 +4091,32 @@ auth(challenge: Uint8Array, authType: AuthType, authTrustLevel: AuthTrustLevel, **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| --------------- | ---------------------------------------------------- | --- | ------------------------------------ | +| 参数名 | 类型 | 必填 | 说明 | +| --------------- | ---------------------------------------- | --- | ------------------------------------ | | challenge | Uint8Array | 是 | 指示挑战值,挑战值为一个随机数,用于提升安全性。| | authType | [AuthType](#authtype8) | 是 | 指示认证类型。 | | authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | 是 | 指示认证结果的信任级别。 | | callback | [IUserAuthCallback](#iuserauthcallback8) | 是 | 回调对象,返回认证结果。 | - **返回值:** | 类型 | 说明 | -| :--------- | :----------------- | +| ---------- | ------------------ | | Uint8Array | 返回取消的上下文ID。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | --------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid challenge or authType or authTrustLevel. | +| 12300101 | Credential is incorrect. | +| 12300105 | Unsupported authTrustLevel. | +| 12300106 | Unsupported authType. | +| 12300110 | Authentication locked. | +| 12300111 | Authentication timeout. | +| 12300112 | Authentication service busy. | + **示例:** ```js let userAuth = new account_osAccount.UserAuth(); @@ -3863,13 +4157,25 @@ authUser(userId: number, challenge: Uint8Array, authType: AuthType, authTrustLev | authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | 是 | 指示认证结果的信任级别。 | | callback | [IUserAuthCallback](#iuserauthcallback8) | 是 | 回调对象,返回认证结果。 | - **返回值:** | 类型 | 说明 | -| :--------- | :----------------- | +| ---------- | ------------------ | | Uint8Array | 返回取消的上下文ID。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | --------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid userId or challenge or authType or authTrustLevel. | +| 12300101 | Credential is incorrect. | +| 12300105 | Unsupported authTrustLevel. | +| 12300106 | Unsupported authType. | +| 12300110 | Authentication locked. | +| 12300111 | Authentication timeout. | +| 12300112 | Authentication service busy. | + **示例:** ```js let userAuth = new account_osAccount.UserAuth(); @@ -3880,8 +4186,8 @@ authUser(userId: number, challenge: Uint8Array, authType: AuthType, authTrustLev try { userAuth.authUser(userID, challenge, authType, authTrustLevel, { onResult: function(result,extraInfo){ - console.log('authUser result = ' + result); - console.log('authUser extraInfo = ' + JSON.stringify(extraInfo)); + console.log('authUser result = ' + result); + console.log('authUser extraInfo = ' + JSON.stringify(extraInfo)); } }); } catch (e) { @@ -3893,7 +4199,7 @@ authUser(userId: number, challenge: Uint8Array, authType: AuthType, authTrustLev cancelAuth(contextID: Uint8Array): void; -取消特定的认证。 +取消指定的认证操作。 **系统接口:** 此接口为系统接口。 @@ -3905,21 +4211,28 @@ cancelAuth(contextID: Uint8Array): void; | 参数名 | 类型 | 必填 | 说明 | | ----------| ---------- | ---- | ------------------------------------------ | -| contextID | Uint8Array | 是 | 指示身份验证上下文ID,此ID动态生成没有具体值。 | +| contextId | Uint8Array | 是 | 指示身份验证上下文ID,此ID动态生成没有具体值。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------ | +| 12300001 | System service exception. | +| 12300002 | Invalid contextId. | **示例:** ```js let userAuth = new account_osAccount.UserAuth(); let pinAuth = new account_osAccount.PINAuth(); let challenge = new Uint8Array([0]); - let contextID = userAuth.auth(challenge, account_osAccount.AuthType.PIN, account_osAccount.AuthTrustLevel.ATL1, { + let contextId = userAuth.auth(challenge, account_osAccount.AuthType.PIN, account_osAccount.AuthTrustLevel.ATL1, { onResult: (result, extraInfo) => { console.log('auth result = ' + result); console.log('auth extraInfo = ' + JSON.stringify(extraInfo)); } }); try { - userAuth.cancelAuth(contextID); + userAuth.cancelAuth(contextId); } catch (e) { console.log('cancelAuth exception = ' + JSON.stringify(e)); } @@ -3948,9 +4261,9 @@ constructor() ### registerInputer8+ -registerInputer(inputer: IInputer): boolean; +registerInputer(inputer: IInputer): void; -注册输入器。 +注册PIN码输入器。 **系统接口:** 此接口为系统接口。 @@ -3960,9 +4273,9 @@ registerInputer(inputer: IInputer): boolean; **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ----------| ----------------------------------- | --- | ------------------ | -| inputer | [IInputer](#iinputer8) | 是 | 指示密码输入框回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| ----------| ----------------------- | --- | -------------------------- | +| inputer | [IInputer](#iinputer8) | 是 | PIN码输入器,用于获取PIN码。 | **返回值:** @@ -3970,6 +4283,13 @@ registerInputer(inputer: IInputer): boolean; | :------ | :-------------------------------------------- | | boolean | 返回布尔值,true表示注册成功,false表示注册失败。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | --------------------------- | +| 12300001 | System service exception. | +| 12300103 | Inputer already registered. | + **示例:** ```js let pinAuth = new account_osAccount.PINAuth(); @@ -3990,7 +4310,7 @@ registerInputer(inputer: IInputer): boolean; unregisterInputer(): void; -卸载输入器。 +解注册PIN码输入器。 **系统接口:** 此接口为系统接口。 @@ -4014,7 +4334,7 @@ unregisterInputer(): void; constructor() -创建用户认证的实例。 +用户身份管理类的默认构造函数。 **系统接口:** 此接口为系统接口。 @@ -4029,7 +4349,7 @@ constructor() openSession(callback: AsyncCallback<Uint8Array>): void; -打开会话,启动IDM操作以获取挑战值。使用callback异步回调。 +打开会话,获取挑战值。使用callback异步回调。 **系统接口:** 此接口为系统接口。 @@ -4043,6 +4363,12 @@ openSession(callback: AsyncCallback<Uint8Array>): void; | -------- | -------------------------------- | ---- | -------------------------------------------------------------- | | callback | AsyncCallback<Uint8Array> | 是 | 回调函数。如果打开会话成功,err为null,data为挑战值;否则为错误对象。| +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | --------------------------- | +| 12300001 | System service exception. | + **示例:** ```js let userIDM = new account_osAccount.UserIdentityManager(); @@ -4060,7 +4386,7 @@ openSession(callback: AsyncCallback<Uint8Array>): void; openSession(): Promise<Uint8Array>; -打开会话,启动IDM操作以获取挑战值。使用Promise异步回调。 +打开会话,获取挑战值。使用Promise异步回调。 **系统接口:** 此接口为系统接口。 @@ -4074,6 +4400,12 @@ openSession(): Promise<Uint8Array>; | :------------------------ | ----------------------- | | Promise<Uint8Array> | Promise对象,返回挑战值。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | --------------------------- | +| 12300001 | System service exception. | + **示例:** ```js let userIDM = new account_osAccount.UserIdentityManager(); @@ -4103,10 +4435,19 @@ addCredential(credentialInfo: CredentialInfo, callback: IIdmCallback): void; **参数:** | 参数名 | 类型 | 必填 | 说明 | -| --------------- | ------------------------------ ----- | --- | ---------------------------- | +| --------------- | ------------------------------------ | --- | ---------------------------- | | credentialInfo | [CredentialInfo](#credentialinfo8) | 是 | 指示凭据信息。 | | callback | [IIdmCallback](#iidmcallback8) | 是 | 回调对象,返回添加凭据的结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid credentialInfo, i.e. authType or authSubType. | +| 12300101 | Token is invalid. | +| 12300106 | Unsupported authType. | + **示例:** ```js let password = new Uint8Array([0, 0, 0, 0, 0, 0]); @@ -4155,6 +4496,15 @@ updateCredential(credentialInfo: CredentialInfo, callback: IIdmCallback): void; | credentialInfo | [CredentialInfo](#credentialinfo8) | 是 | 指示凭据信息。 | | callback | [IIdmCallback](#iidmcallback8) | 是 | 回调对象,返回更新凭据的结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid credentialInfo, i.e. authType or authSubType or token. | +| 12300101 | Token is invalid. | +| 12300106 | Unsupported authType. | + **示例:** ```js let userIDM = new account_osAccount.UserIdentityManager(); @@ -4229,6 +4579,12 @@ cancel(challenge: Uint8Array): void; | -------- | ----------- | ---- | ----- | | challenge | Uint8Array | 是 | 挑战值。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid challenge. | **示例:** ```js @@ -4260,6 +4616,13 @@ delUser(token: Uint8Array, callback: IIdmCallback): void; | token | Uint8Array | 是 | 身份验证令牌。 | | callback | [IIdmCallback](#iidmcallback8) | 是 | 回调对象,返回删除用户的结果。| +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300101 | Token is invalid. | + **示例:** ```js let userIDM = new account_osAccount.UserIdentityManager(); @@ -4296,6 +4659,15 @@ delCred(credentialId: Uint8Array, token: Uint8Array, callback: IIdmCallback): vo | token | Uint8Array | 是 | 身份验证令牌。 | | callback | [IIdmCallback](#iidmcallback8) | 是 | 回调对象,返回删除凭据的结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid credentialId. | +| 12300101 | Token is invalid. | +| 12300102 | Credential not found. | + **示例:** ```js let userIDM = new account_osAccount.UserIdentityManager(); @@ -4331,6 +4703,12 @@ getAuthInfo(callback: AsyncCallback<Array<EnrolledCredInfo>>): void; | -------- | ------------------------------------------------------------------------ | ---- | --------------------------------------------- | | callback | AsyncCallback<Array<[EnrolledCredInfo](#enrolledcredinfo8)>> | 是 | 回调函数。如果成功,err为null,data为当前用户指定类型的所有已注册凭据信息;否则为错误对象。| +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | --------------------- | +| 12300001 | System service exception. | +| 12300102 | Credential not found. | **示例:** ```js @@ -4367,7 +4745,10 @@ getAuthInfo(authType: AuthType, callback: AsyncCallback<Array<EnrolledCred **错误码:** | 错误码ID | 错误信息 | -| 12300015 | Unsupported authType. | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid authType. | +| 12300102 | Credential not found. | **示例:** ```js @@ -4403,13 +4784,16 @@ getAuthInfo(authType?: AuthType): Promise<Array<EnrolledCredInfo>>; **返回值:** | 类型 | 说明 | -| :------------------------------------------- | :------------------------------------------------------------ ---------- | +| :------------------------------------------- | :----------------------------------------------------------------------- | | Promise<Array<[EnrolledCredInfo](#enrolledcredinfo8)>> | Promise对象,返回当前用户指定类型的所有已注册凭据信息。| **错误码:** | 错误码ID | 错误信息 | -| 12300015 | Unsupported authType. | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid authType. | +| 12300102 | Credential not found. | **示例:** ```js @@ -4703,7 +5087,7 @@ onAcquireInfo?: (module: number, acquire: number, extraInfo: any) => void; | ------------ | ---------------------------------------- | ----- | ----------------- | | credType | [AuthType](#authtype8) | 是 | 指示凭据类型。 | | credSubType | [AuthSubType](#authsubtype8) | 是 | 指示凭据子类型。 | -| token | Uint8Array | 是 | 指示认证令牌。 | +| token | Uint8Array | 是 | 指示认证令牌。 | ## RequestResult8+ diff --git a/zh-cn/application-dev/reference/apis/js-apis-privacyManager.md b/zh-cn/application-dev/reference/apis/js-apis-privacyManager.md index 038b1311f6fefab47e05daca0673c006cd410d86..ce88e784596cb6c4de0f0b2e30ff1a3c2b0a0d1c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-privacyManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-privacyManager.md @@ -15,7 +15,7 @@ import privacyManager from '@ohos.privacyManager'; ## privacyManager.addPermissionUsedRecord -addPermissionUsedRecord(tokenID: number, permissionName: string, successCount: number, failCount: number): Promise<void> +addPermissionUsedRecord(tokenID: number, permissionName: Permissions, successCount: number, failCount: number): Promise<void> 受应用权限保护的应用在被其他服务、应用调用时,可以使用该接口增加一条权限使用记录。使用Promise异步回调。 权限使用记录包括:调用方的应用身份标识、使用的应用权限名称,和其访问本应用成功、失败的次数。 @@ -29,7 +29,7 @@ addPermissionUsedRecord(tokenID: number, permissionName: string, successCount: n | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------- | ---- | ------------------------------------------ | | tokenID | number | 是 | 调用方的应用身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得。 | -| permissionName | string | 是 | 应用权限名称。 | +| permissionName | Permissions | 是 | 应用权限名称。 | | successCount | number | 是 | 访问成功的次数。 | | failCount | number | 是 | 访问失败的次数。 | @@ -67,7 +67,7 @@ try { ## privacyManager.addPermissionUsedRecord -addPermissionUsedRecord(tokenID: number, permissionName: string, successCount: number, failCount: number, callback: AsyncCallback<void>): void +addPermissionUsedRecord(tokenID: number, permissionName: Permissions, successCount: number, failCount: number, callback: AsyncCallback<void>): void 受应用权限保护的应用在被其他服务、应用调用时,可以使用该接口增加一条权限使用记录。使用callback异步回调。 权限使用记录包括:调用方的应用身份标识、使用的应用权限名称,和其访问本应用成功、失败的次数。 @@ -81,7 +81,7 @@ addPermissionUsedRecord(tokenID: number, permissionName: string, successCount: n | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------- | ---- | ------------------------------------------ | | tokenID | number | 是 | 调用方的应用身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得。 | -| permissionName | string | 是 | 应用权限名称。 | +| permissionName | Permissions | 是 | 应用权限名称。 | | successCount | number | 是 | 访问成功的次数。 | | failCount | number | 是 | 访问失败的次数。 | | callback | AsyncCallback<void> | 是 | 回调函数。当添加使用记录成功时,err为undefine;否则为错误对象。 | @@ -227,7 +227,7 @@ try { ## privacyManager.startUsingPermission -startUsingPermission(tokenID: number, permissionName: string): Promise<void> +startUsingPermission(tokenID: number, permissionName: Permissions): Promise<void> 应用开始使用某项权限,可监听应用在前后台使用权限,并将使用权限的记录落盘,由系统服务调用。使用Promise异步回调。 @@ -240,7 +240,7 @@ startUsingPermission(tokenID: number, permissionName: string): Promise<void&g | 参数名 | 类型 | 必填 | 说明 | | -------------- | ------ | ---- | ------------------------------------ | | tokenID | number | 是 | 调用方的应用身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得。 | -| permissionName | string | 是 | 需要使用的权限名。 | +| permissionName | Permissions | 是 | 需要使用的权限名。 | **返回值:** @@ -277,7 +277,7 @@ try { ## privacyManager.startUsingPermission -startUsingPermission(tokenID: number, permissionName: string, callback: AsyncCallback<void>): void +startUsingPermission(tokenID: number, permissionName: Permissions, callback: AsyncCallback<void>): void 应用开始使用某项权限,可监听应用在前后台使用权限,并将使用权限的记录落盘,由系统服务调用。使用callback异步回调。 @@ -290,7 +290,7 @@ startUsingPermission(tokenID: number, permissionName: string, callback: AsyncCal | 参数名 | 类型 | 必填 | 说明 | | -------------- | --------------------- | ---- | ------------------------------------ | | tokenID | number | 是 | 调用方的应用身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得。 | -| permissionName | string | 是 | 需要使用的权限名。 | +| permissionName | Permissions | 是 | 需要使用的权限名。 | | callback | AsyncCallback<void> | 是 | 回调函数。当开始使用权限成功时,err为undefine;否则为错误对象。 | **错误码:** @@ -337,7 +337,7 @@ stopUsingPermission(tokenID: number, permissionName: string): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | -------------- | ------ | ---- | ------------------------------------ | | tokenID | number | 是 | 调用方的应用身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得。 | -| permissionName | string | 是 | 需要使用的权限名。 | +| permissionName | Permissions | 是 | 需要使用的权限名。 | **返回值:** @@ -374,7 +374,7 @@ try { ## privacyManager.stopUsingPermission -stopUsingPermission(tokenID: number, permissionName: string, callback: AsyncCallback<void>): void +stopUsingPermission(tokenID: number, permissionName: Permissions, callback: AsyncCallback<void>): void 应用停止使用某项权限,与Start对应,由系统服务调用。使用callback异步回调。 @@ -387,7 +387,7 @@ stopUsingPermission(tokenID: number, permissionName: string, callback: AsyncCall | 参数名 | 类型 | 必填 | 说明 | | -------------- | --------------------- | ---- | ------------------------------------ | | tokenID | number | 是 | 调用方的应用身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得。 | -| permissionName | string | 是 | 需要使用的权限名。 | +| permissionName | Permissions | 是 | 需要使用的权限名。 | | callback | AsyncCallback<void> | 是 | 回调函数。当停止使用权限成功时,err为undefine;否则为错误对象。 | **错误码:** @@ -421,7 +421,7 @@ try { ## privacyManager.on -on(type: 'activeStateChange', permissionNameList: Array<string>, callback: Callback<ActiveChangeResponse>): void +on(type: 'activeStateChange', permissionNameList: Array<Permissions>, callback: Callback<ActiveChangeResponse>): void 订阅指定权限列表的权限使用状态变更事件。 @@ -434,7 +434,7 @@ on(type: 'activeStateChange', permissionNameList: Array<string>, callback: | 参数名 | 类型 | 必填 | 说明 | | ------------------ | --------------------- | ---- | ------------------------------------------------------------ | | type | string | 是 | 订阅事件类型,固定为'activeStateChange',权限使用状态变更事件。 | -| permissionNameList | Array<string> | 否 | 订阅的权限名列表,为空时表示订阅所有的权限使用状态变化。 | +| permissionNameList | Array<Permissions> | 否 | 订阅的权限名列表,为空时表示订阅所有的权限使用状态变化。 | | callback | Callback<[ActiveChangeResponse](#activechangeresponse)> | 是 | 订阅指定权限使用状态变更事件的回调。 | **错误码:** @@ -451,7 +451,7 @@ on(type: 'activeStateChange', permissionNameList: Array<string>, callback: ```js import privacyManager from '@ohos.privacyManager'; -let permissionNameList: Array = []; +let permissionNameList: Array = []; try { atManager.on('activeStateChange', permissionNameList, (data) => { console.debug("receive permission state change, data:" + JSON.stringify(data)); @@ -463,7 +463,7 @@ try { ## privacyManager.off -off(type: 'activeStateChange', permissionNameList: Array<string>, callback?: Callback<ActiveChangeResponse>): void; +off(type: 'activeStateChange', permissionNameList: Array<Permissions>, callback?: Callback<ActiveChangeResponse>): void; 取消订阅指定权限列表的权限使用状态变更事件。 @@ -476,7 +476,7 @@ off(type: 'activeStateChange', permissionNameList: Array<string>, callback | 参数名 | 类型 | 必填 | 说明 | | ------------------ | --------------------- | ---- | ------------------------------------------------------------ | | type | string | 是 | 订阅事件类型,固定为'activeStateChange',权限使用状态变更事件。 | -| permissionNameList | Array<string> | 否 | 订阅的权限名列表,为空时表示订阅所有的权限状态变化,必须与on的输入一致。 | +| permissionNameList | Array<Permissions> | 否 | 订阅的权限名列表,为空时表示订阅所有的权限状态变化,必须与on的输入一致。 | | callback | Callback<[ActiveChangeResponse](#activechangeresponse)> | 否 | 取消订阅指定tokenId与指定权限名状态变更事件的回调。| **错误码:** @@ -492,7 +492,7 @@ off(type: 'activeStateChange', permissionNameList: Array<string>, callback ```js import privacyManager from '@ohos.privacyManager'; -let permissionNameList: Array = []; +let permissionNameList: Array = []; try { privacyManager.off('activeStateChange', permissionNameList); }catch(err) { @@ -523,7 +523,7 @@ try { | isRemote | boolean | 否 | 默认值false。 | | deviceId | string | 否 | 目标应用所在设备的ID。 | | bundleName | string | 否 | 目标应用的包名。 | -| permissionNames | Array<string> | 否 | 需要查询的权限集合。 | +| permissionNames | Array<Permissions> | 否 | 需要查询的权限集合。 | | beginTime | number | 否 | 查询的起始时间,单位:ms,默认值0,不设定起始时间。 | | endTime | number | 否 | 查询的终止时间,单位:ms,默认值0,不设定终止时间。 | | flag | [PermissionUsageFlag](#permissionusageflag) | 是 | 查询方式,默认值FLAG_PERMISSION_USAGE_SUMMARY。 | @@ -562,7 +562,7 @@ try { | 名称 | 类型 | 必填 | 说明 | | -------- | -------------- | ---- | ---------------------------------------- | -| permissionName | string | 否 | 权限名。 | +| permissionName | Permissions | 否 | 权限名。 | | accessCount | number | 否 | 该权限访问总次数。 | | rejectCount | number | 否 | 该权限拒绝总次数。 | | lastAccessTime | number | 否 | 最后一次访问时间,单位:ms。 | @@ -604,6 +604,6 @@ try { | 名称 | 类型 | 可读 | 可写 | 说明 | | -------------- | ---------------------- | ---- | ---- | --------------------- | | tokenId | number | 是 | 否 | 被订阅的应用身份标识 | -| permissionName | string | 是 | 否 | 权限使用状态发生变化的权限名 | +| permissionName | Permissions | 是 | 否 | 权限使用状态发生变化的权限名 | | deviceId | string | 是 | 否 | 设备号 | | activeStatus | [PermissionActiveStatus](#permissionactivestatus) | 是 | 否 | 权限使用状态变化类型 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-prompt.md b/zh-cn/application-dev/reference/apis/js-apis-prompt.md index e27e59cc59adff21df45050006848f3d5824c852..34a7b312a997f8281a8a9098ef8f738781ae2060 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-prompt.md +++ b/zh-cn/application-dev/reference/apis/js-apis-prompt.md @@ -48,7 +48,7 @@ prompt.showToast({ | -------- | ---------------------------------------- | ---- | ---------------------------------------- | | message | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | 是 | 显示的文本信息。 | | duration | number | 否 | 默认值1500ms,取值区间:1500ms-10000ms。若小于1500ms则取默认值,若大于10000ms则取上限值10000ms。 | -| bottom | string\| number | 否 | 设置弹窗边框距离屏幕底部的位置。 | +| bottom | string\| number | 否 | 设置弹窗边框距离屏幕底部的位置,无上限值,默认单位vp。 | ## prompt.showDialog diff --git a/zh-cn/application-dev/reference/apis/js-apis-radio.md b/zh-cn/application-dev/reference/apis/js-apis-radio.md index c69f86e8f16c0f27b0d790c16dd044abbefd9832..766eaca47f8109fd04b94c8b4ddf52c87b299c6c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-radio.md +++ b/zh-cn/application-dev/reference/apis/js-apis-radio.md @@ -927,6 +927,8 @@ sendUpdateCellLocationRequest\(callback: AsyncCallback\): void 此接口为系统接口。 +**需要权限**:ohos.permission.LOCATION + **系统能力**:SystemCapability.Telephony.CoreService **参数:** @@ -951,6 +953,8 @@ sendUpdateCellLocationRequest\(slotId: number, callback: AsyncCallback\): 此接口为系统接口。 +**需要权限**:ohos.permission.LOCATION + **系统能力**:SystemCapability.Telephony.CoreService **参数:** @@ -977,6 +981,8 @@ sendUpdateCellLocationRequest\(slotId?: number): Promise 此接口为系统接口。 +**需要权限**:ohos.permission.LOCATION + **系统能力**:SystemCapability.Telephony.CoreService **参数:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-router.md b/zh-cn/application-dev/reference/apis/js-apis-router.md index 2a7401953f2f3442039ab871b698bf9f58eb5099..8cec7d2ea0514913aead0a9174aa094699ac0e24 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-router.md +++ b/zh-cn/application-dev/reference/apis/js-apis-router.md @@ -589,7 +589,7 @@ router.getParams(); | 名称 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------------------------------------------------------------ | | url | string | 是 | 表示目标页面的url,可以用以下两种格式:
- 页面绝对路径,由配置文件中pages列表提供,例如:
  - pages/index/index
  - pages/detail/detail
- 特殊值,如果url的值是"/",则跳转到首页。 | -| params | Object | 否 | 跳转时要同时传递到目标页面的数据,跳转到目标页面后,参数可以在页面中直接使用,如this.data1(data1为跳转时params参数中的key值)。如果目标页面中已有该字段,则其值会被传入的字段值覆盖。 | +| params | Object | 否 | 表示路由跳转时要同时传递到目标页面的数据。跳转到目标页面后,使用router.getParams()获取传递的参数,此外,在类web范式中,参数也可以在页面中直接使用,如this.keyValue(keyValue为跳转时params参数中的key值),如果目标页面中已有该字段,则其值会被传入的字段值覆盖。 | > **说明:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-rpc.md b/zh-cn/application-dev/reference/apis/js-apis-rpc.md index e8b88c0404bbe9d0b477551168012e76de16f728..600db31d22c1b9e08f00dc3fe461212e50e6c076 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-rpc.md +++ b/zh-cn/application-dev/reference/apis/js-apis-rpc.md @@ -3131,7 +3131,9 @@ readRawData(size: number): number[] ## MessageParcel(deprecated) -在RPC过程中,发送方可以使用MessageParcel提供的写方法,将待发送的数据以特定格式写入该对象。接收方可以使用MessageParcel提供的读方法从该对象中读取特定格式的数据。数据格式包括:基础类型及数组、IPC对象、接口描述符和自定义序列化对象。建议后续使用MessageSequence类替代。 +>从API version 9 开始不再维护,建议使用[MessageSequence](#messagesequence9)类替代。 + +在RPC过程中,发送方可以使用MessageParcel提供的写方法,将待发送的数据以特定格式写入该对象。接收方可以使用MessageParcel提供的读方法从该对象中读取特定格式的数据。数据格式包括:基础类型及数组、IPC对象、接口描述符和自定义序列化对象。 ### create @@ -4023,7 +4025,9 @@ writeString(val: string): boolean 将字符串值写入MessageParcel实例。 **系统能力**:SystemCapability.Communication.IPC.Core + **参数:** + | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ----------------------------------------- | | val | string | 是 | 要写入的字符串值,其长度应小于40960字节。 | @@ -4128,7 +4132,7 @@ readSequenceable(dataIn: Sequenceable) : boolean | 参数名 | 类型 | 必填 | 说明 | | ------ | ----------------------------- | ---- | --------------------------------------- | - | dataIn | [Sequenceable](#sequenceable) | 是 | 需要从MessageParcel读取成员变量的对象。 | + | dataIn | [Sequenceable](#sequenceabledeprecated) | 是 | 需要从MessageParcel读取成员变量的对象。 | **返回值:** @@ -5137,6 +5141,7 @@ readRemoteObjectArray(objects: IRemoteObject[]): void **系统能力**:SystemCapability.Communication.IPC.Core **参数:** + | 参数名 | 类型 | 必填 | 说明 | | ------- | --------------- | ---- | --------- | | objects | IRemoteObject[] | 是 | 从MessageParcel读取的IRemoteObject对象数组。 | @@ -5510,9 +5515,6 @@ readRawData(size: number): number[] ## Parcelable9+ -> **说明:** -> 本类从API version 9开始启用,代替Sequenceable类。 - 在进程间通信(IPC)期间,将类的对象写入MessageSequence并从MessageSequence中恢复它们。 ### marshalling @@ -5619,7 +5621,9 @@ unmarshalling(dataIn: MessageSequence) : boolean ## Sequenceable(deprecated) -在进程间通信(IPC)期间,将类的对象写入MessageParcel并从MessageParcel中恢复它们。后续使用Parcelable类替代。 +>从API version 9 开始不再维护,建议使用[Parcelable](#parcelable9)类替代。 + +在进程间通信(IPC)期间,将类的对象写入MessageParcel并从MessageParcel中恢复它们。 ### marshalling @@ -5633,7 +5637,7 @@ marshalling(dataOut: MessageParcel): boolean | 参数名 | 类型 | 必填 | 说明 | | ------- | ------------------------------- | ---- | ----------------------------------------- | - | dataOut | [MessageParcel](#messageparcel) | 是 | 可序列对象将被封送到的MessageParcel对象。 | + | dataOut | [MessageParcel](#messageparceldeprecated) | 是 | 可序列对象将被封送到的MessageParcel对象。 | **返回值:** @@ -5684,7 +5688,7 @@ unmarshalling(dataIn: MessageParcel) : boolean | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------------------------- | ---- | --------------------------------------------- | - | dataIn | [MessageParcel](#messageparcel) | 是 | 已将可序列对象封送到其中的MessageParcel对象。 | + | dataIn | [MessageParcel](#messageparceldeprecated) | 是 | 已将可序列对象封送到其中的MessageParcel对象。 | **返回值:** @@ -5793,25 +5797,27 @@ onRemoteDied(): void **系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.IPC.Core。 - | 参数: | 值 | 说明 | - | ------- | --------------- | ------------------------------------- | - | errCode | number | 错误码。 | - | code | number | 消息代码。 | - | data | MessageSequence | 发送给对端进程的MessageSequence对象。 | - | reply | MessageSequence | 对端进程返回的MessageSequence对象。 | + | 参数名 | 类型 | 必填 | 说明 | + | ------- | --------------- | ---- | ------------------------------------- | + | errCode | number | 是 | 错误码。 | + | code | number | 是 | 消息代码。 | + | data | MessageSequence | 是 | 发送给对端进程的MessageSequence对象。 | + | reply | MessageSequence | 是 | 对端进程返回的MessageSequence对象。 | ## SendRequestResult8+(deprecated) -发送请求的响应结果。后续使用RequestResult类替代。 +>从API version 9 开始不再维护,建议使用[RequestResult](#requestresult9)类替代。 + +发送请求的响应结果。 **系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.IPC.Core。 - | 参数: | 值 | 说明 | - | ------- | ------------- | ----------------------------------- | - | errCode | number | 错误码。 | - | code | number | 消息代码。 | - | data | MessageParcel | 发送给对端进程的MessageParcel对象。 | - | reply | MessageParcel | 对端进程返回的MessageParcel对象。 | + | 参数名 | 类型 | 必填 | 说明 | + | ------- | ------------- | ---- | ----------------------------------- | + | errCode | number | 是 | 错误码。 | + | code | number | 是 | 消息代码。 | + | data | MessageParcel | 是 | 发送给对端进程的MessageParcel对象。 | + | reply | MessageParcel | 是 | 对端进程返回的MessageParcel对象。 | ## IRemoteObject @@ -5839,9 +5845,11 @@ getLocalInterface(descriptor: string): IRemoteBroker ### queryLocalInterface(deprecated) +>从API version 9 开始不再维护,建议使用[getLocalInterface](#getlocalinterface9)类替代。 + queryLocalInterface(descriptor: string): IRemoteBroker -查询接口。后续使用getLocalInterface方法替代。 +查询接口。 **系统能力**:SystemCapability.Communication.IPC.Core @@ -5860,9 +5868,11 @@ queryLocalInterface(descriptor: string): IRemoteBroker ### sendRequest(deprecated) +>从API version 9 开始不再维护,建议使用[sendMessageRequest](#sendmessagerequest9)类替代。 + sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean -以同步或异步方式向对端进程发送MessageParcel消息。如果为选项设置了异步模式,则期约立即兑现,reply报文里没有内容。如果为选项设置了同步模式,则期约将在sendRequest返回时兑现,回复内容在reply报文里。建议使用sendMessageRequest9+替代。 +以同步或异步方式向对端进程发送MessageParcel消息。如果为选项设置了异步模式,则期约立即兑现,reply报文里没有内容。如果为选项设置了同步模式,则期约将在sendRequest返回时兑现,回复内容在reply报文里。 **系统能力**:SystemCapability.Communication.IPC.Core @@ -5871,8 +5881,8 @@ sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options | 参数名 | 类型 | 必填 | 说明 | | ------- | ------------------------------- | ---- | ---- | | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | - | data | [MessageParcel](#messageparcel) | 是 | 保存待发送数据的 MessageParcel对象。 | - | reply | [MessageParcel](#messageparcel) | 是 | 接收应答数据的MessageParcel对象。 | + | data | [MessageParcel](#messageparceldeprecated) | 是 | 保存待发送数据的 MessageParcel对象。 | + | reply | [MessageParcel](#messageparceldeprecated) | 是 | 接收应答数据的MessageParcel对象。 | | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | **返回值:** @@ -5884,9 +5894,11 @@ sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options ### sendRequest8+(deprecated) +>从API version 9 开始不再维护,建议使用[sendMessageRequest](#sendmessagerequest9)类替代。 + sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<SendRequestResult> -以同步或异步方式向对端进程发送MessageParcel消息。如果为选项设置了异步模式,则期约立即兑现,reply报文里没有内容。如果为选项设置了同步模式,则期约将在sendRequest返回时兑现,回复内容在reply报文里。后续建议使用sendMessageRequest9+替代。 +以同步或异步方式向对端进程发送MessageParcel消息。如果为选项设置了异步模式,则期约立即兑现,reply报文里没有内容。如果为选项设置了同步模式,则期约将在sendRequest返回时兑现,回复内容在reply报文里。 **系统能力**:SystemCapability.Communication.IPC.Core @@ -5895,8 +5907,8 @@ sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options | 参数名 | 类型 | 必填 | 说明 | | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | - | data | [MessageParcel](#messageparcel) | 是 | 保存待发送数据的 MessageParcel对象。 | - | reply | [MessageParcel](#messageparcel) | 是 | 接收应答数据的MessageParcel对象。 | + | data | [MessageParcel](#messageparceldeprecated) | 是 | 保存待发送数据的 MessageParcel对象。 | + | reply | [MessageParcel](#messageparceldeprecated) | 是 | 接收应答数据的MessageParcel对象。 | | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | **返回值:** @@ -5919,8 +5931,8 @@ sendMessageRequest(code : number, data : MessageSequence, reply : MessageSequenc | 参数名 | 类型 | 必填 | 说明 | | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | - | data | MessageSequence | 是 | 保存待发送数据的 MessageSequence对象。 | - | reply | MessageSequence | 是 | 接收应答数据的MessageSequence对象。 | + | data | [MessageSequence](#messagesequence9) | 是 | 保存待发送数据的 MessageSequence对象。 | + | reply | [MessageSequence](#messagesequence9) | 是 | 接收应答数据的MessageSequence对象。 | | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | **返回值:** @@ -5943,17 +5955,19 @@ sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------- | ---- | -------------------------------------------------------------------------------------- | | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | - | data | MessageSequence | 是 | 保存待发送数据的 MessageSequence对象。 | - | reply | MessageSequence | 是 | 接收应答数据的MessageSequence对象。 | + | data | [MessageSequence](#messagesequence9) | 是 | 保存待发送数据的 MessageSequence对象。 | + | reply | [MessageSequence](#messagesequence9) | 是 | 接收应答数据的MessageSequence对象。 | | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | | callback | AsyncCallback<RequestResult> | 是 | 接收发送结果的回调。 | ### sendRequest8+(deprecated) +>从API version 9 开始不再维护,建议使用[sendMessageRequest](#sendmessagerequest9)类替代。 + sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption, callback: AsyncCallback<SendRequestResult>): void -以同步或异步方式向对端进程发送MessageParcel消息。如果为选项设置了异步模式,则立即收到回调,reply报文里没有内容。如果为选项设置了同步模式,则将在sendRequest返回时收到回调,回复内容在reply报文里。后续建议使用sendMessageRequest替代。 +以同步或异步方式向对端进程发送MessageParcel消息。如果为选项设置了异步模式,则立即收到回调,reply报文里没有内容。如果为选项设置了同步模式,则将在sendRequest返回时收到回调,回复内容在reply报文里。 **系统能力**:SystemCapability.Communication.IPC.Core @@ -5962,8 +5976,8 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------------------- | ---- | -------------------------------------------------------------------------------------- | | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | - | data | [MessageParcel](#messageparcel) | 是 | 保存待发送数据的 MessageParcel对象。 | - | reply | [MessageParcel](#messageparcel) | 是 | 接收应答数据的MessageParcel对象。 | + | data | [MessageParcel](#messageparceldeprecated) | 是 | 保存待发送数据的 MessageParcel对象。 | + | reply | [MessageParcel](#messageparceldeprecated) | 是 | 接收应答数据的MessageParcel对象。 | | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | | callback | AsyncCallback<SendRequestResult> | 是 | 接收发送结果的回调。 | @@ -5994,9 +6008,11 @@ registerDeathRecipient(recipient: DeathRecipient, flags: number): void ### addDeathrecipient(deprecated) +>从API version 9 开始不再维护,建议使用[registerDeathRecipient](#registerdeathrecipient9)类替代。 + addDeathRecipient(recipient: DeathRecipient, flags: number): boolean -注册用于接收远程对象死亡通知的回调。如果与RemoteProxy对象匹配的远程对象进程死亡,则调用此方法。建议使用registerDeathRecipient替代。 +注册用于接收远程对象死亡通知的回调。如果与RemoteProxy对象匹配的远程对象进程死亡,则调用此方法。 **系统能力**:SystemCapability.Communication.IPC.Core @@ -6040,9 +6056,11 @@ removeDeathRecipient(recipient: DeathRecipient, flags: number): void ### removeDeathRecipient(deprecated) +>从API version 9 开始不再维护,建议使用[unregisterDeathRecipient](#unregisterdeathrecipient9)类替代。 + removeDeathRecipient(recipient: DeathRecipient, flags: number): boolean -注销用于接收远程对象死亡通知的回调。建议使用unregisterDeathRecipient替代。 +注销用于接收远程对象死亡通知的回调。 **系统能力**:SystemCapability.Communication.IPC.Core @@ -6085,9 +6103,11 @@ getDescriptor(): string ### getInterfaceDescriptor(deprecated) +>从API version 9 开始不再维护,建议使用[getDescriptor](#getdescriptor9)类替代。 + getInterfaceDescriptor(): string -获取对象的接口描述符。接口描述符为字符串。建议使用getDescriptor替代。 +获取对象的接口描述符。接口描述符为字符串。 **系统能力**:SystemCapability.Communication.IPC.Core @@ -6119,7 +6139,7 @@ isObjectDead(): boolean **系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.IPC.Core。 -| 参数: | 值 | 说明 | +| 参数名 | 值 | 说明 | | --------------------- | ----------------------- | --------------------------------- | | PING_TRANSACTION | 1599098439 (0x5f504e47) | 内部指令码,用于测试IPC服务正常。 | | DUMP_TRANSACTION | 1598311760 (0x5f444d50) | 内部指令码,获取Binder内部状态。 | @@ -6130,9 +6150,11 @@ isObjectDead(): boolean ### sendRequest(deprecated) +>从API version 9 开始不再维护,建议使用[sendMessageRequest](#sendmessagerequest9)类替代。 + sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean -以同步或异步方式向对端进程发送MessageParcel消息。如果为选项设置了异步模式,则期约立即兑现,reply报文里没有内容。如果为选项设置了同步模式,则期约将在sendRequest返回时兑现,回复内容在reply报文里。建议使用sendMessageRequest9+替代。 +以同步或异步方式向对端进程发送MessageParcel消息。如果为选项设置了异步模式,则期约立即兑现,reply报文里没有内容。如果为选项设置了同步模式,则期约将在sendRequest返回时兑现,回复内容在reply报文里。 **系统能力**:SystemCapability.Communication.IPC.Core @@ -6141,8 +6163,8 @@ sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options | 参数名 | 类型 | 必填 | 说明 | | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | - | data | [MessageParcel](#messageparcel) | 是 | 保存待发送数据的 MessageParcel对象。 | - | reply | [MessageParcel](#messageparcel) | 是 | 接收应答数据的MessageParcel对象。 | + | data | [MessageParcel](#messageparceldeprecated) | 是 | 保存待发送数据的 MessageParcel对象。 | + | reply | [MessageParcel](#messageparceldeprecated) | 是 | 接收应答数据的MessageParcel对象。 | | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | **返回值:** @@ -6204,8 +6226,8 @@ sendMessageRequest(code : number, data : MessageSequence, reply : MessageSequenc | 参数名 | 类型 | 必填 | 说明 | | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | - | data | MessageSequence | 是 | 保存待发送数据的 MessageSequence对象。 | - | reply | MessageSequence | 是 | 接收应答数据的MessageSequence对象。 | + | data | [MessageSequence](#messagesequence9) | 是 | 保存待发送数据的 MessageSequence对象。 | + | reply | [MessageSequence](#messagesequence9) | 是 | 接收应答数据的MessageSequence对象。 | | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | **返回值:** @@ -6263,9 +6285,11 @@ sendMessageRequest(code : number, data : MessageSequence, reply : MessageSequenc ### sendRequest8+(deprecated) +>从API version 9 开始不再维护,建议使用[sendMessageRequest](#sendmessagerequest9)类替代。 + sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<SendRequestResult> -以同步或异步方式向对端进程发送MessageParcel消息。如果为选项设置了异步模式,则期约立即兑现,reply报文里没有内容。如果为选项设置了同步模式,则期约将在sendRequest返回时兑现,回复内容在reply报文里。建议使用sendMessageRequest9+替代。 +以同步或异步方式向对端进程发送MessageParcel消息。如果为选项设置了异步模式,则期约立即兑现,reply报文里没有内容。如果为选项设置了同步模式,则期约将在sendRequest返回时兑现,回复内容在reply报文里。 **系统能力**:SystemCapability.Communication.IPC.Core @@ -6274,8 +6298,8 @@ sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options | 参数名 | 类型 | 必填 | 说明 | | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | - | data | [MessageParcel](#messageparcel) | 是 | 保存待发送数据的 MessageParcel对象。 | - | reply | [MessageParcel](#messageparcel) | 是 | 接收应答数据的MessageParcel对象。 | + | data | [MessageParcel](#messageparceldeprecated) | 是 | 保存待发送数据的 MessageParcel对象。 | + | reply | [MessageParcel](#messageparceldeprecated) | 是 | 接收应答数据的MessageParcel对象。 | | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | **返回值:** @@ -6343,8 +6367,8 @@ sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------- | ---- | -------------------------------------------------------------------------------------- | | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | - | data | MessageSequence | 是 | 保存待发送数据的 MessageSequence对象。 | - | reply | MessageSequence | 是 | 接收应答数据的MessageSequence对象。 | + | data | [MessageSequence](#messagesequence9) | 是 | 保存待发送数据的 MessageSequence对象。 | + | reply | [MessageSequence](#messagesequence9) | 是 | 接收应答数据的MessageSequence对象。 | | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | | callback | AsyncCallback<RequestResult> | 是 | 接收发送结果的回调。 | @@ -6400,8 +6424,10 @@ sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, ### sendRequest8+(deprecated) +>从API version 9 开始不再维护,建议使用[sendMessageRequest](#sendmessagerequest9)类替代。 + sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption, callback: AsyncCallback<SendRequestResult>): void -以同步或异步方式向对端进程发送MessageParcel消息。如果为选项设置了异步模式,则立即收到回调,reply报文里没有内容。如果为选项设置了同步模式,则将在sendRequest返回时收到回调,回复内容在reply报文里。建议使用sendMessageRequest替代。 +以同步或异步方式向对端进程发送MessageParcel消息。如果为选项设置了异步模式,则立即收到回调,reply报文里没有内容。如果为选项设置了同步模式,则将在sendRequest返回时收到回调,回复内容在reply报文里。 **系统能力**:SystemCapability.Communication.IPC.Core @@ -6410,8 +6436,8 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------------------- | ---- | -------------------------------------------------------------------------------------- | | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | - | data | [MessageParcel](#messageparcel) | 是 | 保存待发送数据的 MessageParcel对象。 | - | reply | [MessageParcel](#messageparcel) | 是 | 接收应答数据的MessageParcel对象。 | + | data | [MessageParcel](#messageparceldeprecated) | 是 | 保存待发送数据的 MessageParcel对象。 | + | reply | [MessageParcel](#messageparceldeprecated) | 是 | 接收应答数据的MessageParcel对象。 | | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | | callback | AsyncCallback<SendRequestResult> | 是 | 接收发送结果的回调。 | @@ -6514,9 +6540,11 @@ getLocalInterface(interface: string): IRemoteBroker ### queryLocalInterface(deprecated) +>从API version 9 开始不再维护,建议使用[getLocalInterface](#getlocalinterface9)类替代。 + queryLocalInterface(interface: string): IRemoteBroker -查询并获取当前接口描述符对应的本地接口对象。建议使用getLocalInterface替代。 +查询并获取当前接口描述符对应的本地接口对象。 **系统能力**:SystemCapability.Communication.IPC.Core @@ -6621,9 +6649,11 @@ registerDeathRecipient(recipient: DeathRecipient, flags: number): void ### addDeathRecippient(deprecated) +>从API version 9 开始不再维护,建议使用[registerDeathRecipient](#registerdeathrecipient9)类替代。 + addDeathRecipient(recipient : DeathRecipient, flags : number): boolean -注册用于接收远程对象死亡通知的回调,增加proxy对象上的死亡通知。建议使用registerDeathRecipient替代。 +注册用于接收远程对象死亡通知的回调,增加proxy对象上的死亡通知。 **系统能力**:SystemCapability.Communication.IPC.Core @@ -6673,7 +6703,7 @@ addDeathRecipient(recipient : DeathRecipient, flags : number): boolean ### unregisterDeathRecipient9+ -removeDeathRecipient(recipient: DeathRecipient, flags: number): void +unregisterDeathRecipient(recipient: DeathRecipient, flags: number): void 注销用于接收远程对象死亡通知的回调。 @@ -6734,9 +6764,11 @@ removeDeathRecipient(recipient: DeathRecipient, flags: number): void ### removeDeathRecipient(deprecated) +>从API version 9 开始不再维护,建议使用[unregisterDeathRecipient](#unregisterdeathrecipient9)类替代。 + removeDeathRecipient(recipient : DeathRecipient, flags : number): boolean -注销用于接收远程对象死亡通知的回调。建议使用unregisterDeathRecipient替代。 +注销用于接收远程对象死亡通知的回调。 **系统能力**:SystemCapability.Communication.IPC.Core @@ -6807,6 +6839,7 @@ getInterfaceDescriptor(): string | 错误码ID | 错误信息 | | -------- | ------- | | 1900008 | proxy or remote object is invalid | + | 1900007 | communication failed | **示例:** @@ -6842,9 +6875,11 @@ getInterfaceDescriptor(): string ### getInterfaceDescriptor(deprecated) +>从API version 9 开始不再维护,建议使用[getDescriptor](#getdescriptor9)类替代。 + getInterfaceDescriptor(): string -查询当前代理对象接口的描述符。建议使用getDescriptor替代。 +查询当前代理对象接口的描述符。 **系统能力**:SystemCapability.Communication.IPC.Core @@ -6928,7 +6963,7 @@ isObjectDead(): boolean **系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.IPC.Core。 - | 参数: | 值 | 说明 | + | 参数名 | 值 | 说明 | | ------------- | ---- | ----------------------------------------------------------- | | TF_SYNC | 0 | 同步调用。 | | TF_ASYNC | 1 | 异步调用。 | @@ -7267,8 +7302,8 @@ static flushCmdBuffer(object : IRemoteObject): void constructor(descriptor) { super(descriptor); } - addDeathRecipient(recipient: MyDeathRecipient, flags: number); - removeDeathRecipient(recipient: MyDeathRecipient, flags: number); + registerDeathRecipient(recipient: MyDeathRecipient, flags: number); + unregisterDeathRecipient(recipient: MyDeathRecipient, flags: number); isObjectDead(): boolean { return false; } @@ -7285,9 +7320,11 @@ static flushCmdBuffer(object : IRemoteObject): void ### flushCommands(deprecated) +>从API version 9 开始不再维护,建议使用[flushCmdBuffer](#flushcmdbuffer9)类替代。 + static flushCommands(object : IRemoteObject): number -将所有挂起的命令从指定的RemoteProxy刷新到相应的RemoteObject。建议在执行任何时间敏感操作之前调用此方法。使用flushCmdBuffer替代。 +将所有挂起的命令从指定的RemoteProxy刷新到相应的RemoteObject。建议在执行任何时间敏感操作之前调用此方法。 **系统能力**:SystemCapability.Communication.IPC.Core @@ -7391,9 +7428,11 @@ static restoreCallingIdentity(identity : string): void ### setCallingIdentity(deprecated) +>从API version 9 开始不再维护,建议使用[restoreCallingIdentity](#restorecallingidentity9)类替代。 + static setCallingIdentity(identity : string): boolean -将UID和PID恢复为远程用户的UID和PID。它通常在使用resetCallingIdentity后调用,需要resetCallingIdentity返回的远程用户的UID和PID。建议使用restoreCallingIdentity替代。 +将UID和PID恢复为远程用户的UID和PID。它通常在使用resetCallingIdentity后调用,需要resetCallingIdentity返回的远程用户的UID和PID。 **系统能力**:SystemCapability.Communication.IPC.Core @@ -7449,6 +7488,8 @@ RemoteObject构造函数。 ### sendRequest(deprecated) +>从API version 9 开始不再维护,建议使用[sendMessageRequest](#sendmessagerequest9)类替代。 + sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean 以同步或异步方式向对端进程发送MessageParcel消息。如果为选项设置了异步模式,则期约立即兑现,reply报文里没有内容。如果为选项设置了同步模式,则期约将在sendRequest返回时兑现,回复内容在reply报文里。 @@ -7460,8 +7501,8 @@ sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options | 参数名 | 类型 | 必填 | 说明 | | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | - | data | [MessageParcel](#messageparcel) | 是 | 保存待发送数据的 MessageParcel对象。 | - | reply | [MessageParcel](#messageparcel) | 是 | 接收应答数据的MessageParcel对象。 | + | data | [MessageParcel](#messageparceldeprecated) | 是 | 保存待发送数据的 MessageParcel对象。 | + | reply | [MessageParcel](#messageparceldeprecated) | 是 | 接收应答数据的MessageParcel对象。 | | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | **返回值:** @@ -7514,9 +7555,11 @@ sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options ### sendRequest8+(deprecated) +>从API version 9 开始不再维护,建议使用[sendMessageRequest](#sendmessagerequest9)类替代。 + sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<SendRequestResult> -以同步或异步方式向对端进程发送MessageParcel消息。如果为选项设置了异步模式,则期约立即兑现,reply报文里没有内容。如果为选项设置了同步模式,则期约将在sendRequest返回时兑现,回复内容在reply报文里。建议使用sendMessageRequest9+替代。 +以同步或异步方式向对端进程发送MessageParcel消息。如果为选项设置了异步模式,则期约立即兑现,reply报文里没有内容。如果为选项设置了同步模式,则期约将在sendRequest返回时兑现,回复内容在reply报文里。 **系统能力**:SystemCapability.Communication.IPC.Core @@ -7525,8 +7568,8 @@ sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options | 参数名 | 类型 | 必填 | 说明 | | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | - | data | [MessageParcel](#messageparcel) | 是 | 保存待发送数据的 MessageParcel对象。 | - | reply | [MessageParcel](#messageparcel) | 是 | 接收应答数据的MessageParcel对象。 | + | data | [MessageParcel](#messageparceldeprecated) | 是 | 保存待发送数据的 MessageParcel对象。 | + | reply | [MessageParcel](#messageparceldeprecated) | 是 | 接收应答数据的MessageParcel对象。 | | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | **返回值:** @@ -7595,8 +7638,8 @@ sendMessageRequest(code : number, data : MessageSequence, reply : MessageSequenc | 参数名 | 类型 | 必填 | 说明 | | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | - | data | MessageSequence | 是 | 保存待发送数据的 MessageSequence对象。 | - | reply | MessageSequence | 是 | 接收应答数据的MessageSequence对象。 | + | data | [MessageSequence](#messagesequence9) | 是 | 保存待发送数据的 MessageSequence对象。 | + | reply | [MessageSequence](#messagesequence9) | 是 | 接收应答数据的MessageSequence对象。 | | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | **返回值:** @@ -7662,8 +7705,8 @@ sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, | 参数名 | 类型 | 必填 | 说明 | | ------------- | ---------------------------------- | ---- | -------------------------------------------------------------------------------------- | | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | - | data | MessageSequence | 是 | 保存待发送数据的 MessageSequence对象。 | - | reply | MessageSequence | 是 | 接收应答数据的MessageSequence对象。 | + | data | [MessageSequence](#messagesequence9) | 是 | 保存待发送数据的 MessageSequence对象。 | + | reply | [MessageSequence](#messagesequence9) | 是 | 接收应答数据的MessageSequence对象。 | | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | | AsyncCallback | AsyncCallback<RequestResult> | 是 | 接收发送结果的回调。 | @@ -7679,10 +7722,8 @@ sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, constructor(descriptor) { super(descriptor); } - addDeathRecipient(recipient: MyDeathRecipient, flags: number); - removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } + registerDeathRecipient(recipient: MyDeathRecipient, flags: number); + unregisterDeathRecipient(recipient: MyDeathRecipient, flags: number); isObjectDead(): boolean { return false; } @@ -7712,9 +7753,11 @@ sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, ### sendRequest8+(deprecated) +>从API version 9 开始不再维护,建议使用[sendMessageRequest](#sendmessagerequest9)类替代。 + sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption, callback: AsyncCallback<SendRequestResult>): void -以同步或异步方式向对端进程发送MessageParcel消息。如果为选项设置了异步模式,则立即收到回调,reply报文里没有内容。如果为选项设置了同步模式,则将在sendRequest返回时收到回调,回复内容在reply报文里。建议使用sendMessageRequest替代。 +以同步或异步方式向对端进程发送MessageParcel消息。如果为选项设置了异步模式,则立即收到回调,reply报文里没有内容。如果为选项设置了同步模式,则将在sendRequest返回时收到回调,回复内容在reply报文里。 **系统能力**:SystemCapability.Communication.IPC.Core @@ -7723,8 +7766,8 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me | 参数名 | 类型 | 必填 | 说明 | | ------------- | -------------------------------------- | ---- | -------------------------------------------------------------------------------------- | | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | - | data | [MessageParcel](#messageparcel) | 是 | 保存待发送数据的 MessageParcel对象。 | - | reply | [MessageParcel](#messageparcel) | 是 | 接收应答数据的MessageParcel对象。 | + | data | [MessageParcel](#messageparceldeprecated) | 是 | 保存待发送数据的 MessageParcel对象。 | + | reply | [MessageParcel](#messageparceldeprecated) | 是 | 接收应答数据的MessageParcel对象。 | | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | | AsyncCallback | AsyncCallback<SendRequestResult> | 是 | 接收发送结果的回调。 | @@ -7775,9 +7818,11 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me ### onRemoteRequest8+(deprecated) +>从API version 9 开始不再维护,建议使用[onRemoteRequestEx](#onremoterequestex9)类替代。 + onRemoteRequest(code : number, data : MessageParcel, reply: MessageParcel, options : MessageOption): boolean -sendMessageRequest请求的响应处理函数,服务端在该函数里处理请求,回复结果。建议使用onRemoteRequestEx9+替代。 +sendMessageRequest请求的响应处理函数,服务端在该函数里处理请求,回复结果。 **系统能力**:SystemCapability.Communication.IPC.Core @@ -7786,8 +7831,8 @@ sendMessageRequest请求的响应处理函数,服务端在该函数里处理 | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------------------------- | ---- | --------------------------------------- | | code | number | 是 | 对端发送的服务请求码。 | - | data | [MessageParcel](#messageparcel) | 是 | 携带客户端调用参数的MessageParcel对象。 | - | reply | [MessageParcel](#messageparcel) | 是 | 写入结果的MessageParcel对象。 | + | data | [MessageParcel](#messageparceldeprecated) | 是 | 携带客户端调用参数的MessageParcel对象。 | + | reply | [MessageParcel](#messageparceldeprecated) | 是 | 写入结果的MessageParcel对象。 | | option | [MessageOption](#messageoption) | 是 | 指示操作是同步还是异步。 | **返回值:** @@ -7847,9 +7892,9 @@ sendMessageRequest请求的响应处理函数,服务端在该函数里同步 | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------------------------- | ---- | ----------------------------------------- | | code | number | 是 | 对端发送的服务请求码。 | - | data | MessageSequence | 是 | 携带客户端调用参数的MessageSequence对象。 | - | reply | MessageSequence | 是 | 写入结果的MessageSequence对象。 | - | option | MessageSequence(#messageoption) | 是 | 指示操作是同步还是异步。 | + | data | [MessageSequence](#messagesequence9) | 是 | 携带客户端调用参数的MessageSequence对象。 | + | reply | [MessageSequence](#messagesequence9) | 是 | 写入结果的MessageSequence对象。 | + | option | [MessageOption](#messageoption) | 是 | 指示操作是同步还是异步。 | **返回值:** @@ -8124,9 +8169,11 @@ getLocalInterface(descriptor: string): IRemoteBroker ### queryLocalInterface(deprecated) +>从API version 9 开始不再维护,建议使用[getLocalInterface](#getlocalinterface9)类替代。 + queryLocalInterface(descriptor: string): IRemoteBroker -查询并获取当前接口描述符对应的远端对象是否已经存在。建议使用getLocalInterface替代。 +查询并获取当前接口描述符对应的远端对象是否已经存在。 **系统能力**:SystemCapability.Communication.IPC.Core @@ -8222,9 +8269,11 @@ getInterfaceDescriptor(): string ### getInterfaceDescriptor(deprecated) +>从API version 9 开始不再维护,建议使用[getDescriptor](#getdescriptor9)类替代。 + getInterfaceDescriptor(): string -查询接口描述符。建议使用getDescriptor替代。 +查询接口描述符。 **系统能力**:SystemCapability.Communication.IPC.Core @@ -8310,9 +8359,11 @@ modifyLocalInterface(localInterface: IRemoteBroker, descriptor: string): void ### attachLocalInterface(deprecated) +>从API version 9 开始不再维护,建议使用[modifyLocalInterface](#modifylocalinterface9)类替代。 + attachLocalInterface(localInterface: IRemoteBroker, descriptor: string): void -此接口用于把接口描述符和IRemoteBroker对象绑定。建议使用modifyLocalInterface替代。 +此接口用于把接口描述符和IRemoteBroker对象绑定。 **系统能力**:SystemCapability.Communication.IPC.Core @@ -8407,9 +8458,11 @@ static create(name: string, size: number): Ashmem ### createAshmem8+(deprecated) +>从API version 9 开始不再维护,建议使用[create](#create9)类替代。 + static createAshmem(name: string, size: number): Ashmem -根据指定的名称和大小创建Ashmem对象。建议使用create替代。 +根据指定的名称和大小创建Ashmem对象。 **系统能力**:SystemCapability.Communication.IPC.Core @@ -8479,9 +8532,11 @@ static create(ashmem: Ashmem): Ashmem ### createAshmemFromExisting8+(deprecated) +>从API version 9 开始不再维护,建议使用[create](#create9)类替代。 + static createAshmemFromExisting(ashmem: Ashmem): Ashmem -通过复制现有Ashmem对象的文件描述符(fd)来创建Ashmem对象。两个Ashmem对象指向同一个共享内存区域。建议使用create替代。 +通过复制现有Ashmem对象的文件描述符(fd)来创建Ashmem对象。两个Ashmem对象指向同一个共享内存区域。 **系统能力**:SystemCapability.Communication.IPC.Core @@ -8599,9 +8654,11 @@ mapTypedAshmem(mapType: number): void ### mapAshmem8+(deprecated) +>从API version 9 开始不再维护,建议使用[mapTypedAshmem](#maptypedashmem9)类替代。 + mapAshmem(mapType: number): boolean -在此进程的虚拟地址空间上创建共享文件映射,映射区域大小由此Ashmem对象指定。建议使用mapTypedAshmem替代。 +在此进程的虚拟地址空间上创建共享文件映射,映射区域大小由此Ashmem对象指定。 **系统能力**:SystemCapability.Communication.IPC.Core @@ -8657,9 +8714,11 @@ mapReadAndWriteAshmem(): void ### mapReadAndWriteAshmem8+(deprecated) +>从API version 9 开始不再维护,建议使用[mapReadWriteAshmem](#mapreadwriteashmem9)类替代。 + mapReadAndWriteAshmem(): boolean -在此进程虚拟地址空间上创建可读写的共享文件映射。建议使用mapReadWriteAshmem替代。 +在此进程虚拟地址空间上创建可读写的共享文件映射。 **系统能力**:SystemCapability.Communication.IPC.Core @@ -8709,9 +8768,11 @@ mapReadonlyAshmem(): void ### mapReadOnlyAshmem8+(deprecated) +>从API version 9 开始不再维护,建议使用[mapReadonlyAshmem](#mapreadonlyashmem9)类替代。 + mapReadOnlyAshmem(): boolean -在此进程虚拟地址空间上创建只读的共享文件映射。建议使用mapReadonlyAshmem替代。 +在此进程虚拟地址空间上创建只读的共享文件映射。 **系统能力**:SystemCapability.Communication.IPC.Core @@ -8767,9 +8828,11 @@ setProtectionType(protectionType: number): void ### setProtection8+(deprecated) +>从API version 9 开始不再维护,建议使用[setProtectionType](#setprotectiontype9)类替代。 + setProtection(protectionType: number): boolean -设置映射内存区域的保护等级。建议使用setProtectionType替代。 +设置映射内存区域的保护等级。 **系统能力**:SystemCapability.Communication.IPC.Core @@ -8835,9 +8898,11 @@ writeAshmem(buf: number[], size: number, offset: number): void ### writeToAshmem8+(deprecated) +>从API version 9 开始不再维护,建议使用[writeAshmem](#writeashmem9)类替代。 + writeToAshmem(buf: number[], size: number, offset: number): boolean -将数据写入此Ashmem对象关联的共享文件。建议使用writeAshmem替代。 +将数据写入此Ashmem对象关联的共享文件。 **系统能力**:SystemCapability.Communication.IPC.Core @@ -8915,9 +8980,11 @@ readAshmem(size: number, offset: number): number[] ### readFromAshmem8+(deprecated) +>从API version 9 开始不再维护,建议使用[readAshmem](#readashmem9)类替代。 + readFromAshmem(size: number, offset: number): number[] -从此Ashmem对象关联的共享文件中读取数据。建议使用readAshmem替代。 +从此Ashmem对象关联的共享文件中读取数据。 **系统能力**:SystemCapability.Communication.IPC.Core diff --git a/zh-cn/application-dev/reference/apis/js-apis-sim.md b/zh-cn/application-dev/reference/apis/js-apis-sim.md index 9a73d5f485e38f088f98530e62ae0a1afb55159d..d523096d88ce741a3aaa2a4dcbbf43658e5020ef 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-sim.md +++ b/zh-cn/application-dev/reference/apis/js-apis-sim.md @@ -1155,6 +1155,8 @@ getLockState(slotId: number, lockType: LockType, callback: AsyncCallback 此接口为系统接口。 +**需要权限**:ohos.permission.GET_TELEPHONY_STATE + **系统能力**:SystemCapability.Telephony.CoreService **参数:** @@ -2238,7 +2242,6 @@ addIccDiallingNumbers(slotId: number, type: ContactType, diallingNumbers: Dialli let diallingNumbersInof = { alphaTag: "alpha", number: "138xxxxxxxx", - recordNumber: 123, pin2: "1234" }; sim.addIccDiallingNumbers(0, sim.ContactType.GENERAL_CONTACT, diallingNumbersInof, (err, data) => { @@ -2278,9 +2281,7 @@ addIccDiallingNumbers(slotId: number, type: ContactType, diallingNumbers: Dialli ```js let diallingNumbersInof = { alphaTag: "alpha", - number: "138xxxxxxxx", - recordNumber: 123, - pin2: "1234" + number: "138xxxxxxxx" }; let promise = sim.addIccDiallingNumbers(0, sim.ContactType.GENERAL_CONTACT, diallingNumbersInof); promise.then(data => { @@ -2357,9 +2358,7 @@ delIccDiallingNumbers(slotId: number, type: ContactType, diallingNumbers: Dialli ```js let diallingNumbersInof = { alphaTag: "alpha", - number: "138xxxxxxxx", - recordNumber: 123, - pin2: "1234" + number: "138xxxxxxxx" }; let promise = sim.delIccDiallingNumbers(0, sim.ContactType.GENERAL_CONTACT, diallingNumbersInof); promise.then(data => { @@ -2437,8 +2436,7 @@ updateIccDiallingNumbers(slotId: number, type: ContactType, diallingNumbers: Dia let diallingNumbersInof = { alphaTag: "alpha", number: "138xxxxxxxx", - recordNumber: 123, - pin2: "1234" + recordNumber: 123 }; let promise = sim.updateIccDiallingNumbers(0, sim.ContactType.GENERAL_CONTACT, diallingNumbersInof); promise.then(data => { diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-router.md b/zh-cn/application-dev/reference/apis/js-apis-system-router.md index ee3167d8c5a5058aa854ef4de817262409acd242..0df6fc6d7cfad73262b82996fbff5f42328eb5e6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-router.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-router.md @@ -342,7 +342,7 @@ export default { | 名称 | 参数类型 | 必填 | 说明 | | ------ | ------ | ---- | ---------------------------------------- | | uri | string | 是 | 目标页面的uri,可以是以下的两种格式:
1. 页面的绝对路径,由config.json文件中的页面列表提供。例如:
- pages/index/index
-pages/detail/detail
2. 特定路径。如果URI为斜杠(/),则显示主页。 | -| params | Object | 否 | 跳转时要同时传递到目标页面的数据,跳转到目标页面后,参数可以在页面中直接使用,如this.data1(data1为跳转时params参数中的key值)。如果目标页面中已有该字段,则其值会被传入的字段值覆盖。 | +| params | Object | 否 | 表示路由跳转时要同时传递到目标页面的数据。跳转到目标页面后,使用router.getParams()获取传递的参数,此外,在类web范式中,参数也可以在页面中直接使用,如this.keyValue(keyValue为跳转时params参数中的key值),如果目标页面中已有该字段,则其值会被传入的字段值覆盖。 | ## BackRouterOptions diff --git a/zh-cn/application-dev/reference/apis/js-apis-webview.md b/zh-cn/application-dev/reference/apis/js-apis-webview.md index fdaaf855c584ebb1d34038f0155893bb32afb27f..383ae8a70980ec02a14e6cc6bcd80c07d357c6ce 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-webview.md +++ b/zh-cn/application-dev/reference/apis/js-apis-webview.md @@ -1380,14 +1380,41 @@ import web_webview from '@ohos.web.webview'; struct WebComponent { controller: web_webview.WebviewController = new web_webview.WebviewController(); ports: web_webview.WebMessagePort[]; + @State sendFromEts: string = 'Send this message from ets to HTML'; + @State receivedFromHtml: string = 'Display received message send from HTML'; build() { Column() { + // 展示接收到的来自HTML的内容 + Text(this.receivedFromHtml) + // 输入框的内容发送到html + TextInput({placeholder: 'Send this message from ets to HTML'}) + .onChange((value: string) => { + this.sendFromEts = value; + }) + Button('postMessage') .onClick(() => { try { + // 1、创建两个消息端口 this.ports = this.controller.createWebMessagePorts(); + // 2、将其中一个消息端口发送到HTML侧,由HTML侧保存并使用。 this.controller.postMessage('__init_port__', [this.ports[0]], '*'); + // 3、另一个消息端口在应用侧注册回调事件。 + this.ports[1].onMessageEvent((result: string) => { + var msg = 'Got msg from HTML: ' + result; + this.receivedFromHtml = msg; + }) + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + + // 4、使用应用侧的端口给另一个已经发送到html的端口发送消息。 + Button('SendDataToHTML') + .onClick(() => { + try { + this.ports[1].postMessageEvent("post message from ets to HTML"); } catch (error) { console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); } @@ -1404,36 +1431,40 @@ struct WebComponent { - WebView Callback Demo + WebView Message Port Demo - -

Message Demo

-
-
-
-
-

My body

- - + +

WebView Message Port Demo

+
+
+
+
+

display received message send from ets

+ + ``` ```js //xxx.js var h5Port; +var output = document.querySelector('.output'); window.addEventListener('message', function (event) { if (event.data == '__init_port__') { if (event.ports[0] != null) { - h5Port = event.ports[0]; + h5Port = event.ports[0]; // 1. 保存从ets侧发送过来的端口 h5Port.onmessage = function (event) { - console.log('receive message from ets, on message:' + event.data); + // 2. 接收ets侧发送过来的消息. + var msg = 'Got message from ets:' + event.data; + output.innerHTML = msg; } } } }) -function PostWebMsg(data) { +// 3. 使用h5Port往ets侧发送消息. +function PostMsgToEts(data) { h5Port.postMessage(data); } ``` 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 1007f7883d67e91b197f5b674c8c54abbb234402..0637099a7052af876589fed83c64dbb251da3854 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-window.md +++ b/zh-cn/application-dev/reference/apis/js-apis-window.md @@ -165,7 +165,7 @@ import window from '@ohos.window'; | --------------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ | | type | [WindowType](#windowtype7) | 是 | 否 | 当前属性改变的系统栏类型,仅支持类型为导航栏、状态栏的系统栏。 | | isEnable | boolean | 是 | 否 | 当前系统栏是否显示。true表示显示;false表示不显示。 | -| region | [Rect](#rect) | 是 | 否 | 当前系统栏的位置及大小。 | +| region | [Rect](#rect7) | 是 | 否 | 当前系统栏的位置及大小。 | | backgroundColor | string | 是 | 否 | 系统栏背景颜色,为十六进制RGB或ARGB颜色,不区分大小写,例如`#00FF00`或`#FF00FF00`。 | | contentColor | string | 是 | 否 | 系统栏文字颜色。 | @@ -204,10 +204,10 @@ import window from '@ohos.window'; | 名称 | 参数类型 | 可读 | 可写 | 说明 | | ---------- | ------------- | ---- | ---- | ------------------ | | visible9+ | boolean | 是 | 是 | 规避区域是否可见。true表示可见;false表示不可见。 | -| leftRect | [Rect](#rect) | 是 | 是 | 屏幕左侧的矩形区。 | -| topRect | [Rect](#rect) | 是 | 是 | 屏幕顶部的矩形区。 | -| rightRect | [Rect](#rect) | 是 | 是 | 屏幕右侧的矩形区。 | -| bottomRect | [Rect](#rect) | 是 | 是 | 屏幕底部的矩形区。 | +| leftRect | [Rect](#rect7) | 是 | 是 | 屏幕左侧的矩形区。 | +| topRect | [Rect](#rect7) | 是 | 是 | 屏幕顶部的矩形区。 | +| rightRect | [Rect](#rect7) | 是 | 是 | 屏幕右侧的矩形区。 | +| bottomRect | [Rect](#rect7) | 是 | 是 | 屏幕底部的矩形区。 | ## Size7+ @@ -228,7 +228,7 @@ import window from '@ohos.window'; | 名称 | 参数类型 | 可读 | 可写 | 说明 | | ------------------------------------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ | -| windowRect7+ | [Rect](#rect) | 是 | 是 | 窗口尺寸。 | +| windowRect7+ | [Rect](#rect7) | 是 | 是 | 窗口尺寸。 | | type7+ | [WindowType](#windowtype7) | 是 | 是 | 窗口类型。 | | isFullScreen | boolean | 是 | 是 | 是否全屏,默认为false。true表示全屏;false表示非全屏。 | | isLayoutFullScreen7+ | boolean | 是 | 是 | 窗口是否为沉浸式,默认为false。true表示沉浸式;false表示非沉浸式。 | 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 f75b98a10733627de2d38e4ab22950deeff3d749..38d46f170edc8f55ec3d41a30a1e009a2338afee 100644 --- a/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md +++ b/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md @@ -159,5 +159,7 @@ - [时间选择弹窗](ts-methods-timepicker-dialog.md) - [文本选择弹窗](ts-methods-textpicker-dialog.md) - [菜单](ts-methods-menu.md) +- [应用级变量的状态管理](ts-state-management.md) +- [像素单位](ts-pixel-units.md) - [枚举说明](ts-appendix-enums.md) - [类型说明](ts-types.md) diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/contextmenu_close.gif b/zh-cn/application-dev/reference/arkui-ts/figures/contextmenu_close.gif new file mode 100644 index 0000000000000000000000000000000000000000..424f418c9d18997a3ed29eb777ffb4817d1b2dc4 Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/contextmenu_close.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/row.png b/zh-cn/application-dev/reference/arkui-ts/figures/row.png index dd97ea25d042abb1bf14ea0ba1012eedc57eb135..d7fced9fe4a9fc618dee88ae95cc2f04a34bb3c3 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/row.png and b/zh-cn/application-dev/reference/arkui-ts/figures/row.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/text_clock.gif b/zh-cn/application-dev/reference/arkui-ts/figures/text_clock.gif index 29a32d79a14fbcf8a27f6e27fc3fa226a2b83446..c0f013242aa3ba0024ed25453078437427187a42 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/text_clock.gif and b/zh-cn/application-dev/reference/arkui-ts/figures/text_clock.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169582302.gif b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001169582302.gif similarity index 100% rename from zh-cn/application-dev/ui/figures/zh-cn_image_0000001169582302.gif rename to zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001169582302.gif diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-rating.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-rating.md index d214fffaf780f0f39efe8cb1f62f61f789a7dbea..605f333d3ad6dc85ee688321bc3f3f23dbaf321a 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-rating.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-rating.md @@ -21,7 +21,7 @@ Rating(options?: { rating: number, indicator?: boolean }) | 参数名 | 参数类型 | 必填 | 参数描述 | | -------- | -------- | -------- | -------- | | rating | number | 是 | 设置并接收评分值。
默认值:0 | -| indicator | boolean | 否 | 仅作为指示器使用,不可操作。
默认值:false | +| indicator | boolean | 否 | 设置评分组件作为指示器使用,不可改变评分。
默认值:false, 可进行评分 | ## 属性 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md index 6b6d25095b5323a0fe4f17bcdcf3eb7b84045368..13855a9815cc2ab0ba23ca1e3b0c5c02c2cc8d62 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md @@ -55,7 +55,7 @@ TimePicker(options?: {selected?: Date}) @Entry @Component struct TimePickerExample { - private selectedTime: Date = new Date('7/22/2022 8:00:00') + private selectedTime: Date = new Date('2022-07-22T08:00:00') build() { Column() { diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md index cfc799864db233086458ac6106bc3670b4d4e12b..df6e8b8f121fc9a3758a7b4fe6b91ca14d3546c2 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md @@ -123,7 +123,7 @@ domStorageAccess(domStorageAccess: boolean) fileAccess(fileAccess: boolean) -设置是否开启应用中文件系统的访问,默认启用。[$rawfile(filepath/filename)](../../ui/ts-resource-access.md)中rawfile路径的文件不受该属性影响而限制访问。 +设置是否开启应用中文件系统的访问,默认启用。[$rawfile(filepath/filename)](../../quick-start/resource-categories-and-access.md)中rawfile路径的文件不受该属性影响而限制访问。 **参数:** @@ -152,7 +152,7 @@ fileAccess(fileAccess: boolean) fileFromUrlAccess(fileFromUrlAccess: boolean) -设置是否允许通过网页中的JavaScript脚本访问应用文件系统中的内容,默认未启用。[$rawfile(filepath/filename)](../../ui/ts-resource-access.md)中rawfile路径的文件不受该属性影响而限制访问。 +设置是否允许通过网页中的JavaScript脚本访问应用文件系统中的内容,默认未启用。[$rawfile(filepath/filename)](../../quick-start/resource-categories-and-access.md)中rawfile路径的文件不受该属性影响而限制访问。 **参数:** @@ -3644,38 +3644,99 @@ postMessage(options: { message: WebMessageEvent, uri: string}): void **示例:** ```ts - // xxx.ets + // index.ets @Entry @Component struct WebComponent { controller: WebController = new WebController(); ports: WebMessagePort[] = null; + @State sendFromEts: string = 'Send this message from ets to HTML'; + @State receivedFromHtml: string = 'Display received message send from HTML'; + build() { Column() { - Button('postMessage') + // 展示接收到的来自HTML的内容 + Text(this.receivedFromHtml) + // 输入框的内容发送到HTML + TextInput({placeholder: 'Send this message from ets to HTML'}) + .onChange((value: string) => { + this.sendFromEts = value; + }) + + // 1、创建两个消息端口 + Button('1.CreateWebMessagePorts') + .onClick(() => { + this.ports = this.controller.createWebMessagePorts(); + console.log("createWebMessagePorts size:" + this.ports.length) + }) + + // 2、将其中一个消息端口发送到HTML侧,由HTML侧保存并使用。 + Button('2.PostMessagePort') .onClick(() => { var sendPortArray = new Array(this.ports[1]); var msgEvent = new WebMessageEvent(); - msgEvent.setData("__init_ports__"); + msgEvent.setData("__init_port__"); msgEvent.setPorts(sendPortArray); this.controller.postMessage({message: msgEvent, uri: "*"}); }) - Web({ src: 'www.example.com', controller: this.controller }) + + // 3、另一个消息端口在应用侧注册回调事件。 + Button('3.RegisterCallback') + .onClick(() => { + this.ports[0].onMessageEvent((result: string) => { + var msg = 'Got msg from HTML: ' + result; + this.receivedFromHtml = msg; + }) + }) + + // 4、使用应用侧的端口给另一个已经发送到HTML的消息端口发送消息。 + Button('4.SendDataToHtml5') + .onClick(() => { + var msg = new WebMessageEvent(); + msg.setData(this.sendFromEts); + this.ports[0].postMessageEvent(msg); + }) + Web({ src: $rawfile("index.html"), controller: this.controller }) + .javaScriptAccess(true) + .fileAccess(true) } } } - // xxx.js + + // index.html + + + +

Web Message Port Demo

+
+
+
+
+

display received message send from ets

+ + + + + // index.js var h5Port; - window.addEventListener('message', function(event){ - if (event.data == '__init_ports__') { + var output = document.querySelector('.output'); + window.addEventListener('message', function(event) { + if (event.data == '__init_port__') { if(event.ports[0] != null) { - h5Port = event.ports[0]; + h5Port = event.ports[0]; // 1. 保存从ets侧发送过来的端口 h5Port.onmessage = function(event) { - console.log('receive message from ets, on message:' + event.data); + // 2. 接收ets侧发送过来的消息. + var msg = 'Got message from ets:' + event.data; + output.innerHTML = msg; } } } }) + + // 3. 使用h5Port往ets侧发送消息. + function PostMsgToEts(data) { + h5Port.postMessage(data) + } ``` ### getUrl9+ @@ -5305,7 +5366,7 @@ close(): void ### postMessageEvent9+ postMessageEvent(message: WebMessageEvent): void -发送消息。 +发送消息。完整示例代码参考[postMessage](#postmessage9) **参数:** @@ -5340,7 +5401,7 @@ postMessageEvent(message: WebMessageEvent): void ### onMessageEvent9+ onMessageEvent(callback: (result: string) => void): void -注册回调函数,接收HTML5侧发送过来的消息。 +注册回调函数,接收HTML5侧发送过来的消息。完整示例代码参考[postMessage](#postmessage9) **参数:** @@ -5412,7 +5473,7 @@ getData(): string ### setData9+ setData(data: string): void -设置当前对象中的消息。 +设置当前对象中的消息。完整示例代码参考[postMessage](#postmessage9) **参数:** @@ -5480,7 +5541,7 @@ getPorts(): Array\ ### setPorts9+ setPorts(ports: Array\): void -设置当前对象中的消息端口。 +设置当前对象中的消息端口。完整示例代码参考[postMessage](#postmessage9) **参数:** diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md b/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md index de1aaccb15c26e4ff9f7c225b22f4af295f3cfc2..40a3f6611fba38b4e552c80c95246e8ec951c5cc 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md @@ -1424,7 +1424,7 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number | rotation | number | 是 | 0 | 椭圆的旋转角度,单位为弧度。 | | startAngle | number | 是 | 0 | 椭圆绘制的起始点角度,以弧度表示。 | | endAngle | number | 是 | 0 | 椭圆绘制的结束点角度,以弧度表示。 | -| counterclockwise | boolean | 否 | false | 是否以逆时针方向绘制椭圆。 | +| counterclockwise | boolean | 否 | false | 是否以逆时针方向绘制椭圆。
true:逆时针方向绘制椭圆。
false:顺时针方向绘制椭圆。 | **示例:** diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-path2d.md b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-path2d.md index b37d56db73e7684aac0cb0c40b206f1d910d3bd6..dbad82b43f93702bc3f7f8a00f5572641a2d8833 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-path2d.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-path2d.md @@ -383,7 +383,7 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void ## ellipse -ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, counterclockwise?: number): void +ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, counterclockwise?: boolean): void 在规定的矩形区域绘制一个椭圆。 @@ -398,7 +398,7 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number | rotation | number | 是 | 0 | 椭圆的旋转角度,单位为弧度。 | | startAngle | number | 是 | 0 | 椭圆绘制的起始点角度,以弧度表示。 | | endAngle | number | 是 | 0 | 椭圆绘制的结束点角度,以弧度表示。 | - | counterclockwise | number | 否 | 0 | 是否以逆时针方向绘制椭圆,0为顺时针,1为逆时针。(可选参数,默认为0) | + | counterclockwise | boolean | 否 | false | 是否以逆时针方向绘制椭圆。
true:逆时针方向绘制椭圆。
false:顺时针方向绘制椭圆。 | **示例:** diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-badge.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-badge.md index 6db7e8dbfb219c2538725ccb8fd908f902ccc5b0..7e03805a45bfb67da494a67a7025450c05ffa42f 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-badge.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-badge.md @@ -46,12 +46,13 @@ | Left | 圆点显示在左侧纵向居中。 | ## BadgeStyle对象说明 -| 名称 | 类型 | 必填 | 默认值 | 描述 | - | -------- | -------- | -------- | -------- | -------- | -| color | [ResourceColor](ts-types.md#resourcecolor) | 否 | Color.White | 文本颜色。 | -| fontSize | number \| string | 否 | 10 | 文本大小。 | -| badgeSize | number \| string | 是 | - | badge的大小。 | -| badgeColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | Color.Red | badge的颜色。 | + +| 名称 | 类型 | 必填 | 默认值 | 描述 | +| ---------- | ------------------------------------------ | ---- | ----------- | ------------------------------------------- | +| color | [ResourceColor](ts-types.md#resourcecolor) | 否 | Color.White | 文本颜色。 | +| fontSize | number \| string | 否 | 10 | 文本大小,单位vp。 | +| badgeSize | number \| string | 否 | 16 | Badge的大小,单位vp。不支持百分比形式设置。 | +| badgeColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | Color.Red | Badge的颜色。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-grid.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-grid.md index e4a0722bda929988aa717c14e98c8bd5b806917f..f8fc0b4ad9a90f363be6e7d26701ea6b697895df 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 @@ -34,7 +34,7 @@ Grid(scroller?: Scroller) | scrollBar | [BarState](ts-appendix-enums.md#barstate) | 设置滚动条状态。
默认值:BarState.Off | | scrollBarColor | string \| number \| Color | 设置滚动条的颜色。 | | scrollBarWidth | string \| number | 设置滚动条的宽度。 | -| cachedCount | number | 设置预加载的GridItem的数量。具体使用可参考[减少应用白块说明](../../ui/ts-performance-improvement-recommendation.md#减少应用滑动白块)。
默认值:1 | +| cachedCount | number | 设置预加载的GridItem的数量。具体使用可参考[减少应用白块说明](../../ui/ui-ts-performance-improvement-recommendation.md#减少应用滑动白块)。
默认值:1 | | 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 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-gridcontainer.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-gridcontainer.md index 4e1b8dca3b18562ecd9e6ff66c2a356d0aa37dbc..5e3f55564ba8cf3147a12a086c726b9abb7019da 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-gridcontainer.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-gridcontainer.md @@ -22,8 +22,8 @@ GridContainer(value?: { columns?: number | 'auto', sizeType?: SizeType, gutter?: | -------- | -------- | -------- | -------- | | columns | number \| 'auto' | 否 | 设置当前布局总列数。
默认值:'auto' | | sizeType | SizeType | 否 | 选用设备宽度类型。
默认值:SizeType.Auto | -| gutter | number \| string | 否 | 栅格布局列间距。 | -| margin | number \| string | 否 | 栅格布局两侧间距。 | +| gutter | number \| string | 否 | 栅格布局列间距,不支持百分比。 | +| margin | number \| string | 否 | 栅格布局两侧间距,不支持百分比。 | ## SizeType枚举说明 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 f4334a9399cbedf07f2048981eeb5a857fc870d9..70faec26cdd7476b88fc73e4c878f0b4cc888e9a 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 @@ -34,7 +34,7 @@ List(value?:{space?: number | string, initialIndex?: number, scroller? | listDirection | [Axis](ts-appendix-enums.md#axis) | 设置List组件排列方向。
默认值:Axis.Vertical | | divider | {
strokeWidth: [Length](ts-types.md#length),
color?:[ResourceColor](ts-types.md),
startMargin?: Length,
endMargin?: Length
} \| null | 设置ListItem分割线样式,默认无分割线。
- strokeWidth: 分割线的线宽。
- color: 分割线的颜色。
- startMargin: 分割线与列表侧边起始端的距离。
- endMargin: 分割线与列表侧边结束端的距离。 | | scrollBar | [BarState](ts-appendix-enums.md#barstate) | 设置滚动条状态。
默认值:BarState.Off | -| cachedCount | number | 设置预加载的ListItem数量。具体使用可参考[减少应用白块说明](../../ui/ts-performance-improvement-recommendation.md#减少应用滑动白块)。
默认值:1 | +| cachedCount | number | 设置预加载的ListItem数量。具体使用可参考[减少应用白块说明](../../ui/ui-ts-performance-improvement-recommendation.md#减少应用滑动白块)。
默认值:1 | | editMode | boolean | 声明当前List组件是否处于可编辑模式。
默认值:false | | edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | 设置组件的滑动效果。
默认值:EdgeEffect.Spring | | chainAnimation | boolean | 设置当前List是否启用链式联动动效,开启后列表滑动以及顶部和底部拖拽时会有链式联动的效果。链式联动效果:List内的list-item间隔一定距离,在基本的滑动交互行为下,主动对象驱动从动对象进行联动,驱动效果遵循弹簧物理动效。
默认值:false
- false:不启用链式联动。
- true:启用链式联动。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-scroll.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-scroll.md index e0a02896e93d84a2134a740731beae086e0f71d3..b6e0e30f1490ec2b2a80d57893ee97f41058d19d 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-scroll.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-scroll.md @@ -25,7 +25,7 @@ Scroll(scroller?: Scroller) | 名称 | 参数类型 | 描述 | | -------------- | ---------------------------------------- | --------- | | scrollable | [ScrollDirection](#scrolldirection枚举说明) | 设置滚动方向。
默认值:ScrollDirection.Vertical | -| scrollBar | [BarState](ts-appendix-enums.md#barstate) | 设置滚动条状态。
默认值:BarState.Off | +| scrollBar | [BarState](ts-appendix-enums.md#barstate) | 设置滚动条状态。
默认值:BarState.Auto | | scrollBarColor | string \| number \| [Color](ts-appendix-enums.md#color) | 设置滚动条的颜色。 | | scrollBarWidth | string \| number | 设置滚动条的宽度。 | | edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | 设置滑动效果,目前支持的滑动效果参见EdgeEffect的枚举说明。
默认值:EdgeEffect.None | 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 e26486a08a88f65055a141fe3aae3b3c36f64cb9..be91208736d0a799ed977aca676d5e1dd5c55c78 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 @@ -40,7 +40,7 @@ Swiper(controller?: SwiperController) | displayMode | SwiperDisplayMode | 主轴方向上元素排列的模式,优先以displayCount设置的个数显示,displayCount未设置时本属性生效。
默认值:SwiperDisplayMode.Stretch | | cachedCount8+ | number | 设置预加载子组件个数。
默认值:1 | | disableSwipe8+ | boolean | 禁用组件滑动切换功能。
默认值:false | -| curve8+ | [Curve](ts-appendix-enums.md#curve) \| string | 设置Swiper的动画曲线,默认为淡入淡出曲线,常用曲线参考[Curve枚举说明](ts-appendix-enums.md#curve),也可以通过插值计算模块提供的接口创建自定义的Curves([插值曲线对象](ts-interpolation-calculation.md))。
默认值:Curve.Ease | +| curve8+ | [Curve](ts-appendix-enums.md#curve) \| string | 设置Swiper的动画曲线,默认为淡入淡出曲线,常用曲线参考[Curve枚举说明](ts-appendix-enums.md#curve),也可以通过[插值计算](../apis/js-apis-curve.md)模块提供的接口创建自定义的插值曲线对象。
默认值:Curve.Ease | | indicatorStyle8+ | {
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: 设置导航点的直径。
\- mask: 设置是否显示导航点蒙层样式。
\- color: 设置导航点的颜色。
\- selectedColor: 设置选中的导航点的颜色。 | | displayCount8+ | number\|string | 设置元素显示个数。
默认值:1 | | effectMode8+ | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | 滑动效果,目前支持的滑动效果参见EdgeEffect的枚举说明。
默认值:EdgeEffect.Spring | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-path.md b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-path.md index ecdc9f2e09cbab6f5e1ac00ad5b47ef61edc28e0..fbf5860c2bc5b6fc98d7bb9a8c113e3c247aacc9 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-path.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-path.md @@ -29,7 +29,7 @@ Path(value?: { width?: number | string; height?: number | string; commands?: str | 参数名称 | 参数类型 | 默认值 | 必填 | 参数描述 | | -------- | ----------------------------------- | ---- | ---- | ---------------------------------------- | -| commands | string | '' | 否 | 路径绘制的命令字符串,单位为px。像素单位转换方法请参考[像素单位转换](../../ui/ts-pixel-units.md)。 | +| commands | string | '' | 否 | 路径绘制的命令字符串,单位为px。像素单位转换方法请参考[像素单位转换](ts-pixel-units.md)。 | | fill | [ResourceColor](ts-types.md) | Color.Black | 否 | 设置填充区域颜色。 | | fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 否 | 设置填充区域透明度。 | | stroke | [ResourceColor](ts-types.md) | - | 否 | 设置线条颜色。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-methods-menu.md b/zh-cn/application-dev/reference/arkui-ts/ts-methods-menu.md index 7a64be6a6bd8d668babfb0738660eb53aba8f0de..df6b4f8b24e75937f0d1109893055cd3b00a03a5 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-methods-menu.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-methods-menu.md @@ -26,25 +26,36 @@ struct Index { @Builder MenuBuilder() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Text('close') - .fontSize(30) - .fontWeight(FontWeight.Bold) - .onClick(() => { - ContextMenu.close(); - }) - }.height(400) - .backgroundColor(Color.Pink) - + Button('Test ContextMenu1') + Divider().strokeWidth(2).margin(5) + Button('Test ContextMenu2') + Divider().strokeWidth(2).margin(5) + Button('Test ContextMenu3') + } + .width(200) + .height(160) } build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.Start }) { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Column() { - Text("Text") - }.bindContextMenu(this.MenuBuilder, ResponseType.LongPress) + Text("Test ContextMenu") + .fontSize(20) + .width('100%') + .height(500) + .backgroundColor(0xAFEEEE) + .textAlign(TextAlign.Center) + } + .bindContextMenu(this.MenuBuilder, ResponseType.LongPress) + .onDragStart(()=>{ + // 拖拽时关闭菜单 + ContextMenu.close(); + }) } .width('100%') .height('100%') } } ``` + +![contextmenu_close.gif](figures/contextmenu_close.gif) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md b/zh-cn/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md index 25576aa891bb8f00d951d26a3cc62c67156458a6..981e3657b58f26359fe17d126a73a4763836f6f4 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md @@ -13,11 +13,11 @@ show(options?: TextPickerDialogOptions) 定义文本滑动选择器弹窗并弹出。 -- TextPickerDialogOptions参数说明 +**TextPickerDialogOptions参数说明:** | 参数名 | 参数类型 | 必填 | 参数描述 | | -------- | -------- | -------- | -------- | - | range | string[] \| [Resource](../../ui/ts-types.md#resource类型) | 是 | 设置文本选择器的选择范围。 | + | range | string[] \| [Resource](ts-types.md#resource) | 是 | 设置文本选择器的选择范围。 | | selected | number | 否 | 设置选中项的索引值。
默认值:0 | | value | string | 否 | 设置选中项的文本内容。当设置了selected参数时,该参数不生效。如果设置的value值不在range范围内,则默认取range第一个元素。| | defaultPickerItemHeight | number \| string | 否 | 设置选择器中选项的高度。 | @@ -25,7 +25,7 @@ show(options?: TextPickerDialogOptions) | onCancel | () => void | 否 | 点击弹窗中的“取消”按钮时触发该回调。 | | onChange | (value: TextPickerResult) => void | 否 | 滑动弹窗中的选择器使当前选中项改变时触发该回调。 | -- TextPickerResult对象说明 +## TextPickerResult对象说明 | 名称 | 类型 | 描述 | | -------- | -------- | -------- | 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 b84eef2a7be0bd0d10328d952c856d1b9dc35774..5928d2c9c52ee3b4d17d4c72b6e86853d92d4a90 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md @@ -1508,7 +1508,7 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number | rotation | number | 是 | 0 | 椭圆的旋转角度,单位为弧度。 | | startAngle | number | 是 | 0 | 椭圆绘制的起始点角度,以弧度表示。 | | endAngle | number | 是 | 0 | 椭圆绘制的结束点角度,以弧度表示。 | -| counterclockwise | boolean | 否 | false | 是否以逆时针方向绘制椭圆。 | +| counterclockwise | boolean | 否 | false | 是否以逆时针方向绘制椭圆。
true:逆时针方向绘制椭圆。
false:顺时针方向绘制椭圆。 | **示例:** diff --git a/zh-cn/application-dev/ui/ts-pixel-units.md b/zh-cn/application-dev/reference/arkui-ts/ts-pixel-units.md similarity index 87% rename from zh-cn/application-dev/ui/ts-pixel-units.md rename to zh-cn/application-dev/reference/arkui-ts/ts-pixel-units.md index 3a4c5c7e6a0ef27361f80529265cff853e5600db..aa077567dec5f971cb4ecc13de55214026107413 100644 --- a/zh-cn/application-dev/ui/ts-pixel-units.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-pixel-units.md @@ -3,12 +3,12 @@ 为开发者提供4种像素单位,框架采用vp为基准数据单位。 -| 名称 | 描述 | -| ---- | ---------------------------------------- | -| px | 屏幕物理像素单位。 | -| vp | 屏幕密度相关像素,根据屏幕像素密度转换为屏幕物理像素,当数值不带单位时,默认单位vp。 | -| fp | 字体像素,与vp类似适用屏幕密度变化,随系统字体大小设置变化。 | -| lpx | 视窗逻辑像素单位,lpx单位为实际屏幕宽度与逻辑宽度(通过[designWidth](../quick-start/package-structure.md)配置)的比值,designWidth默认值为720。当designWidth为720时,在实际宽度为1440物理像素的屏幕上,1lpx为2px大小。 | +| 名称 | 描述 | +| ---- | ------------------------------------------------------------ | +| px | 屏幕物理像素单位。 | +| vp | 屏幕密度相关像素,根据屏幕像素密度转换为屏幕物理像素,当数值不带单位时,默认单位vp。 | +| fp | 字体像素,与vp类似适用屏幕密度变化,随系统字体大小设置变化。 | +| lpx | 视窗逻辑像素单位,lpx单位为实际屏幕宽度与逻辑宽度(通过[designWidth](../../quick-start/package-structure.md)配置)的比值,designWidth默认值为720。当designWidth为720时,在实际宽度为1440物理像素的屏幕上,1lpx为2px大小。 | ## 像素单位转换 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 88cc46ca11a38816f64af5e3f7ae3cf9138597c8..c9f4cb0422c71be641d1ebc404597a5ca5fbcdfe 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 @@ -1,4 +1,4 @@ -# 状态管理 +# 应用级变量的状态管理 状态管理模块提供了应用程序的数据存储能力、持久化数据管理能力、Ability数据存储能力和应用程序需要的环境状态,其中Ability数据存储从API version9开始支持。 @@ -15,7 +15,7 @@ Link(propName: string): any **参数:** | 参数名 | 类型 | 必填 | 参数描述 | -| -------- | ------ | :--- | :--------------------- | +| -------- | ------ | --- | --------------------- | | propName | string | 是 | 要双向绑定的属性名称。 | **返回值:** @@ -25,7 +25,7 @@ Link(propName: string): any | @Link | 在具有给定键的数据,则返回到此属性的双向数据绑定,该双向绑定意味着变量或者组件对数据的更改将同步到AppStorage,通过AppStorage对数据的修改将同步到变量或者组件。 | ```ts -let simple = AppStorage.Link('simpleProp'); +let simple = AppStorage.Link('simpleProp') ``` ### SetAndLink @@ -37,7 +37,7 @@ SetAndLink\(propName: string, defaultValue: T): SubscribedAbstractProperty\(propName: string, defaultValue: T): SubscribedAbstractProperty\(propName: string, defaultValue: S): SubscribedAbstractProperty\(propName: string, defaultValue: S): SubscribedAbstractProperty\(propName: string): T | undefined | boolean或undefined | 返回属性的属性值是否存在。 | ```ts -let simple = AppStorage.Get('simpleProp'); +let simple = AppStorage.Get('simpleProp') ``` ### Set @@ -149,7 +149,7 @@ Set(propName: string, newValue: T): boolean **参数:** | 参数名 | 类型 | 必填 | 参数描述 | -| -------- | ------ | :--- | ----------------- | +| -------- | ------ | --- | ----------------- | | propName | string | 是 | 要设置的key值。 | | newValue | T | 是 | 要设置的value值。 | @@ -172,7 +172,7 @@ SetOrCreate(propName: string, newValue: T): void **参数:** | 参数名 | 类型 | 必填 | 参数描述 | -| -------- | ------ | :--- | ------------------------- | +| -------- | ------ | --- | ------------------------- | | propName | string | 是 | 要更新或者创建的key值。 | | newValue | T | 是 | 要更新或者创建的value值。 | @@ -183,7 +183,7 @@ SetOrCreate(propName: string, newValue: T): void | boolean | 如果已存在与给定键名字相同的属性,更新其值且返回true。如果不存在具有给定名称的属性,在LocalStorage中创建具有给定默认值的新属性,默认值必须是T类型。不允许undefined 或 null 返回true。 | ```ts -let simple = AppStorage.SetOrCreate('simpleProp',121); +let simple = AppStorage.SetOrCreate('simpleProp', 121) ``` ### Delete @@ -195,7 +195,7 @@ Delete(propName: string): boolean **参数:** | 参数名 | 类型 | 必填 | 参数描述 | -| -------- | ------ | :--- | --------------------- | +| -------- | ------ | --- | --------------------- | | propName | string | 是 | 要删除的属性的key值。 | **返回值:** @@ -205,7 +205,7 @@ Delete(propName: string): boolean | boolean | 删除key指定的键值对,如果存在且删除成功返回true,不存在或删除失败返回false。 | ```ts -let simple = AppStorage.Delete('simpleProp'); +let simple = AppStorage.Delete('simpleProp') ``` ### keys @@ -221,7 +221,7 @@ keys(): IterableIterator\ | array\ | 返回包含所有键的字符串数组。 | ```ts -let simple = AppStorage.Keys(); +let simple = AppStorage.Keys() ``` ### staticClear @@ -237,7 +237,7 @@ staticClear(): boolean | boolean | 删除所有的属性,如果当前有状态变量依旧引用此属性,返回false。 | ```ts -let simple = AppStorage.staticClear(); +let simple = AppStorage.staticClear() ``` ### IsMutable @@ -259,7 +259,7 @@ IsMutable(propName: string): boolean | boolean | 返回此属性是否存在并且是否可以改变。 | ```ts -let simple = AppStorage.IsMutable(); +let simple = AppStorage.IsMutable() ``` ### Size @@ -275,7 +275,7 @@ Size(): number | number | 返回键值对的数量。 | ```ts -let simple = AppStorage.Size(); +let simple = AppStorage.Size() ``` ## LocalStorage9+ @@ -293,7 +293,7 @@ constructor(initializingProperties?: Object) | initializingProperties | Object | 否 | object.keys(obj)返回的所有对象属性及其值都将添加到LocalStorage。 | ```ts -this.storage = new LocalStorage(); +this.storage = new LocalStorage() ``` ### GetShared9+ @@ -311,7 +311,7 @@ static GetShared(): LocalStorage | [LocalStorage](#localstorage) | 返回LocalStorage对象。 | ```ts -let storage = LocalStorage.GetShared(); +let storage = LocalStorage.GetShared() ``` ### has9+ @@ -323,7 +323,7 @@ has(propName: string): boolean **参数:** | 参数名 | 类型 | 必填 | 参数描述 | -| -------- | ------ | :--- | -------------- | +| -------- | ------ | --- | -------------- | | propName | string | 是 | 属性的属性值。 | **返回值:** @@ -333,8 +333,8 @@ has(propName: string): boolean | boolean | 返回属性的属性值是否存在。 | ```ts -this.storage = new LocalStorage(); -this.storage.has("storageSimpleProp"); +this.storage = new LocalStorage() +this.storage.has('storageSimpleProp') ``` ### get9+ @@ -346,7 +346,7 @@ get\(propName: string): T **参数:** | 参数名 | 类型 | 必填 | 参数描述 | -| -------- | ------ | :--- | ------------------- | +| -------- | ------ | --- | ------------------- | | propName | string | 是 | 要获取对应的key值。 | **返回值:** @@ -356,8 +356,8 @@ get\(propName: string): T | T \| undefined | 当keyvalue存在时,返回keyvalue值。不存在返回undefined。 | ```ts -this.storage = new LocalStorage(); -let simpleValue = this.storage.get("storageSimpleProp"); +this.storage = new LocalStorage() +let simpleValue = this.storage.get('storageSimpleProp') ``` ### set9+ @@ -369,7 +369,7 @@ set\(propName: string, newValue: T): boolean **参数:** | 参数名 | 类型 | 必填 | 参数描述 | -| -------- | ------ | :--- | ----------------- | +| -------- | ------ | --- | ----------------- | | propName | string | 是 | 要设置的key值。 | | newValue | T | 是 | 要设置的value值。 | @@ -380,8 +380,8 @@ set\(propName: string, newValue: T): boolean | boolean | 如果存在key值,设置value值并返回true,否则返回false。 | ```ts -this.storage = new LocalStorage(); -this.storage.set("storageSimpleProp",121); +this.storage = new LocalStorage() +this.storage.set('storageSimpleProp', 121) ``` ### setOrCreate9+ @@ -404,8 +404,8 @@ setOrCreate\(propName: string, newValue: T): boolean | boolean | 如果已存在与给定键名字相同的属性,更新其值且返回true。如果不存在具有给定名称的属性,在LocalStorage中创建具有给定默认值的新属性,默认值必须是T类型,不允许undefined 或 null 。 | ```ts -this.storage = new LocalStorage(); -this.storage.setOrCreate("storageSimpleProp",121); +this.storage = new LocalStorage() +this.storage.setOrCreate('storageSimpleProp', 121) ``` ### link9+ @@ -417,7 +417,7 @@ link\(propName: string): T **参数:** | 参数名 | 类型 | 必填 | 参数描述 | -| -------- | ------ | :--- | ---------------------- | +| -------- | ------ | --- | ---------------------- | | propName | string | 是 | 要双向绑定的属性名称。 | **返回值:** @@ -427,8 +427,8 @@ link\(propName: string): T | T | 如果存在具有给定键的属性,返回到此属性的双向绑定,该双向绑定意味着变量或者组件对数据的更改将同步到LocalStorage,然后通过LocalStorage实例同步到任何变量或组件。如果不存在给定键的属性,返回undefined。 | ```ts -this.storage = new LocalStorage(); -let localStorage = this.storage.link("storageSimpleProp"); +this.storage = new LocalStorage() +let localStorage = this.storage.link('storageSimpleProp') ``` ### setAndLink9+ @@ -440,7 +440,7 @@ setAndLink\(propName: string, defaultValue: T): T **参数:** | 参数名 | 类型 | 必填 | 参数描述 | -| ------------ | ------ | :--- | -------------------- | +| ------------ | ------ | --- | -------------------- | | propName | string | 是 | 要进行创建的key值。 | | defaultValue | T | 是 | 要进行设置的默认值。 | @@ -451,8 +451,8 @@ setAndLink\(propName: string, defaultValue: T): T | @Link | 与Link接口类似,如果当前的key保存于LocalStorage,返回该key值对应的value值。如果该key值未被创建,则创建一个对应的defaultValue的Link返回。 | ```ts -this.storage = new LocalStorage(); -let localStorage = this.storage.setAndLink("storageSimpleProp",121); +this.storage = new LocalStorage() +let localStorage = this.storage.setAndLink('storageSimpleProp', 121) ``` ### prop9+ @@ -464,7 +464,7 @@ prop\(propName: string): T **参数:** | 参数名 | 类型 | 必填 | 参数描述 | -| -------- | ------ | :--- | ----------------------- | +| -------- | ------ | --- | ----------------------- | | propName | string | 是 | 要单向数据绑定的key值。 | **返回值:** @@ -474,8 +474,8 @@ prop\(propName: string): T | @Prop | 如果存在具有给定键的属性,返回此属性的单向数据绑定。该单向绑定意味着只能通过LocalStorage将属性的更改同步到变量或组件。该方法返回的变量为不可变变量,适用于可变和不可变的状态变量。如果此键的属性不存在则返回undefined。 | ```ts -this.storage = new LocalStorage(); -let localStorage = this.storage.prop("storageSimpleProp"); +this.storage = new LocalStorage() +let localStorage = this.storage.prop('storageSimpleProp') ``` ### setAndProp9+ @@ -487,7 +487,7 @@ setAndProp\(propName: string, defaultValue: T): T **参数:** | 参数名 | 类型 | 必填 | 参数描述 | -| ------------ | ------ | :--- | ------------------------- | +| ------------ | ------ | --- | ------------------------- | | propName | string | 是 | 要保存的键值对中的key值。 | | defaultValue | T | 是 | 创建的默认值。 | @@ -498,8 +498,8 @@ setAndProp\(propName: string, defaultValue: T): T | @Prop | 如果当前的key保存与LocalStorage,返回该key值对应的value值。如果该key值未被创建,则创建一个对应的defaultValue的Prop返回。 | ```ts -this.storage = new LocalStorage(); -let localStorage = this.storage.setAndProp("storageSimpleProp",121); +this.storage = new LocalStorage() +let localStorage = this.storage.setAndProp('storageSimpleProp', 121) ``` ### delete9+ @@ -521,8 +521,8 @@ delete(propName: string): boolean | boolean | 删除key指定的键值对,如果存在且删除成功返回true,不存在或删除失败返回false。 | ```ts -this.storage = new LocalStorage(); -this.storage.delete("storageSimpleProp"); +this.storage = new LocalStorage() +this.storage.delete('storageSimpleProp') ``` ### keys9+ @@ -533,13 +533,13 @@ keys(): IterableIterator\ **返回值:** -| 类型 | 描述 | -| -------------- | ---------------------------- | -| array\ | 返回包含所有键的字符串数组。 | +| 类型 | 描述 | +| -------------- | -------------------------------------- | +| array\ | 返回包含所有键不可序列化的字符串数组。 | ```ts -this.storage = new LocalStorage(); -let simple = this.storage.keys(); +this.storage = new LocalStorage() +let simple = this.storage.keys() ``` ### size9+ @@ -555,8 +555,8 @@ size(): number | number | 返回键值对的数量。 | ```ts -this.storage = new LocalStorage(); -let simple = this.storage.size(); +this.storage = new LocalStorage() +let simple = this.storage.size() ``` ### Clear9+ @@ -572,11 +572,11 @@ clear(): boolean | boolean | 删除所有的属性,如果当前有状态变量依旧引用此属性,返回false。 | ```ts -this.storage = new LocalStorage(); -let simple = this.storage.clear(); +this.storage = new LocalStorage() +let simple = this.storage.clear() ``` -## persistentstorage +## PersistentStorage ### constructor @@ -587,29 +587,29 @@ constructor(appStorage: AppStorage, storage: Storage) **参数:** | 参数名 | 类型 | 必填 | 参数描述 | -| ---------- | ---------- | :--- | -------------------------------- | +| ---------- | ---------- | --- | -------------------------------- | | appStorage | AppStorage | 是 | 保存所有属性及属性值的单例对象。 | | storage | Storage | 是 | Storage实例对象。 | ```ts -this.persistentstorage = new PersistentStorage(AppStorage,Storage); +this.persistentstorage = new PersistentStorage(AppStorage,Storage) ``` ### PersistProp -PersistProp(key:string,defaultValue:T):void +PersistProp(key:string,defaultValue:T): void 关联命名的属性再AppStorage变为持久化数据。 **参数:** | 参数名 | 类型 | 必填 | 参数描述 | -| ------------ | ------ | :--- | ----------------------- | +| ------------ | ------ | --- | ----------------------- | | key | string | 是 | 要关联的属性的key值。 | | defaultValue | T | 是 | 要关联的属性的value值。 | ```ts -PersistentStorage.PersistProp("highScore", "0"); +PersistentStorage.PersistProp('highScore', '0') ``` ### DeleteProp @@ -621,11 +621,11 @@ DeleteProp(key: string): void **参数:** | 参数名 | 类型 | 必填 | 参数描述 | -| ------ | ------ | :--- | --------------------- | +| ------ | ------ | --- | --------------------- | | key | string | 是 | 要取消的属性的key值。 | ```ts -PersistentStorage.DeleteProp("highScore"); +PersistentStorage.DeleteProp('highScore') ``` ### PersistProps @@ -637,11 +637,11 @@ PersistProps(properties: {key: string, defaultValue: any}[]): void; **参数:** | 参数名 | 类型 | 必填 | 参数描述 | -| ------ | ---------------------------------- | :--: | ------------------ | +| ------ | ---------------------------------- | -- | ------------------ | | key | {key: string, defaultValue: any}[] | 是 | 要关联的属性数组。 | ```ts -PersistentStorage.PersistProps([{"highScore", "0"},{"wightScore","1"}]); +PersistentStorage.PersistProps([{'highScore', '0'},{'wightScore','1'}]) ``` ### Keys @@ -657,7 +657,7 @@ Keys(): Array | Array | 返回所有持久化属性的标记。 | ```ts -let simple = PersistentStorage.keys(); +let simple = PersistentStorage.Keys() ``` > **说明:** @@ -673,7 +673,7 @@ let simple = PersistentStorage.keys(); 创建一个environment对象。 ```ts -let simple = new Environment(); +let simple = new Environment() ``` ### EnvProp @@ -685,34 +685,45 @@ EnvProp\(key: string, value: S): boolean **参数:** | 参数名 | 类型 | 必填 | 参数描述 | 参数描述 | -| ------ | ------ | :--- | --------------- | ----------------- | -| key | string | 是 | 要关联的key值 | 要关联的key值。 | +| ------ | ------ | --- | --------------- | ----------------- | +| key | string | 是 | 要关联的key值 | 要关联的key值,支持的范围详见内置环境变量说明。 | | value | S | 是 | 要关联的value值 | 要关联的value值。 | **返回值:** | 类型 | 描述 | | ------- | ---------------------------------- | -| boolean | 返回该属性再AppStorage中是否存在。 | +| boolean | 返回该属性在AppStorage中是否存在。 | + +**内置环境变量说明:** + +| key | 类型 | 说明 | +| ------------ | ------------- | ------------------- | +| accessibilityEnabled | boolean | 无障碍屏幕朗读是否启用。 | +| colorMode | ColorMode | 深浅色模式,可选值为:
- ColorMode.LIGHT:浅色模式;
- ColorMode.DARK:深色模式。 | +| fontScale | number | 字体大小比例。 | +| fontWeightScale | number | 字重比例。 | +| layoutDirection | LayoutDirection | 布局方向类型,可选值为:
- LayoutDirection.LTR:从左到右;
- LayoutDirection.RTL:从右到左。 | +| languageCode | string | 当前系统语言,小写字母,例如zh。 | ```ts -Environment.EnvProp("accessibilityEnabled", "default"); +Environment.EnvProp('accessibilityEnabled', 'default') ``` ### EnvProps -EnvProps(props: {key: string;defaultValue: any}[]): void +EnvProps(props: {key: string, defaultValue: any}[]): void 关联此系统项数组到AppStorage中 **参数:** | 参数名 | 类型 | 必填 | 参数描述 | 参数描述 | -| ------ | ---------------------------------- | :--- | ------------------ | ------------------ | +| ------ | ---------------------------------- | --- | ------------------ | ------------------ | | key | {key: string, defaultValue: any}[] | 是 | 要关联的属性数组。 | 要关联的属性数组。 | ```ts -Environment.EnvProps([{"accessibilityEnabled", "default"},{"accessibilityUnEnabled","undefault"}]); +Environment.EnvProps([{'accessibilityEnabled', 'default'},{'accessibilityUnEnabled','undefault'}]) ``` ### Keys @@ -728,6 +739,6 @@ Keys(): Array | Array | 返回关联的系统项数组。 | ```ts -let simple = Environment.keys(); +let simple = Environment.Keys() ``` 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 ea49954ac5e7a1771a4976597f318d2bcdcc12a4..1726ad14146e9f2c4aeb6919e3e031aa661fdfec 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 @@ -13,7 +13,7 @@ | backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | 设置组件的背景色。 | | backgroundImage | src: [ResourceStr](ts-types.md#resourcestr),
repeat?: [ImageRepeat](ts-appendix-enums.md#imagerepeat) | src:图片地址,支持网络图片资源和本地图片资源地址(不支持svg类型的图片)。
repeat:设置背景图片的重复样式,默认不重复。 | | backgroundImageSize | {
width?: [Length](ts-types.md#length),
height?: [Length](ts-types.md#length)
} \| [ImageSize](ts-appendix-enums.md#imagesize) | 设置背景图像的高度和宽度。当输入为{width: Length, height: Length}对象时,如果只设置一个属性,则第二个属性保持图片原始宽高比进行调整。默认保持原图的比例不变。
默认值:ImageSize.Auto | -| backgroundImagePosition | [Position](ts-types.md#position8) \| [Alignment](ts-appendix-enums.md#alignment) | 设置背景图在组件中显示位置。
默认值:
{
x: 0,
y: 0
}
使用百分比设置x和y值时,偏移量是相对于容器的。 | +| backgroundImagePosition | [Position](ts-types.md#position8) \| [Alignment](ts-appendix-enums.md#alignment) | 设置背景图在组件中显示位置,即相对于组件左上角的坐标。
默认值:
{
x: 0,
y: 0
}
x和y值设置百分比时,偏移量是相对组件自身宽高计算的。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border.md index e4861b5876a42bbd9b0c5367d111661358eb8512..58a64f62891cce602d65efe18cd04ee46c92abb5 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border.md @@ -16,7 +16,7 @@ | border | {
width?: [Length](ts-types.md#length) \| [EdgeWidths](#edgewidths9对象说明)9+,
color?:  [ResourceColor](ts-types.md#resourcecolor) \| [EdgeColors](#edgecolors9对象说明)9+,
radius?:  [Length](ts-types.md#length) \| [BorderRadiuses](#borderradiuses9对象说明)9+,
style?: [BorderStyle](ts-appendix-enums.md#borderstyle) \| [EdgeStyles](#edgestyles9对象说明)9+
} | 统一边框样式设置接口。
- width:设置边框宽度。
- color:设置边框颜色。
- radius:设置边框圆角半径。
- style:设置边框样式。 | | borderStyle | [BorderStyle](ts-appendix-enums.md#borderstyle) \| [EdgeStyles](#edgestyles9对象说明)9+ | 设置元素的边框样式。
默认值:BorderStyle.Solid | | borderWidth | [Length](ts-types.md#length) \| [EdgeWidths](#edgewidths9对象说明)9+ | 设置元素的边框宽度,不支持百分比。 | -| borderColor | [ResourceColor](ts-types.md#resourcecolor) \| [EdgeColors](#edgecolors9对象说明)9+ | 设置元素的边框颜色。 | +| borderColor | [ResourceColor](ts-types.md#resourcecolor) \| [EdgeColors](#edgecolors9对象说明)9+ | 设置元素的边框颜色。
默认值:Color.Black | | borderRadius | [Length](ts-types.md#length) \| [BorderRadiuses](#borderradiuses9对象说明)9+ | 设置元素的边框圆角半径,不支持百分比。 | ## EdgeWidths9+对象说明 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-location.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-location.md index 912a81a63445d0c95963190a7fc4d894346ed19c..8d1704f0692ba3a9a655dad8a1a95a900dbe8364 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-location.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-location.md @@ -12,7 +12,7 @@ | 名称 | 参数类型 | 描述 | | -------- | -------- | -------- | -| align | [Alignment](ts-appendix-enums.md#alignment) | 设置元素内容的对齐方式,当元素的width和height大小大于元素本身内容大小时生效。
默认值:Alignment.Center | +| align | [Alignment](ts-appendix-enums.md#alignment) | 设置元素内容在元素绘制区域内的对齐方式。
默认值:Alignment.Center | | direction | [Direction](ts-appendix-enums.md#direction) | 设置元素水平方向的布局。
默认值:Direction.Auto | | position | [Position](ts-types.md#position8) | 绝对定位,设置元素左上角相对于父容器左上角偏移位置。在布局容器中,设置该属性不影响父容器布局,仅在绘制时进行位置调整。 | | markAnchor | [Position](ts-types.md#position8) | 设置元素在位置定位时的锚点,以元素左上角作为基准点进行偏移。通常配合position和offset属性使用,单独使用时,效果类似offset
默认值:
{
x: 0,
y: 0
} | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md index cb99c14a586d282f17134f82cc7c26ef405ae8dd..c03775fc9dbeb8e98226a3df3aefd65d7b39d3ae 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md @@ -20,7 +20,7 @@ | -------------------------| ------------------------------------------------| -----| ----------------------------------------- | | message | string | 是 | 弹窗信息内容。 | | placementOnTop | boolean | 否 | 是否在组件上方显示,默认值为false。 | -| arrowOffset9+ | [Length](ts-types.md#length) | 否 | popup箭头在弹窗处的偏移。箭头在气泡上下方时,默认居左;箭头在气泡左右侧时,默认居上。 | +| arrowOffset9+ | [Length](ts-types.md#length) | 否 | popup箭头在弹窗处的偏移。箭头在气泡上下方时,数值为0表示箭头居最左侧,偏移量为箭头至最左侧的距离,默认居中。箭头在气泡左右侧时,偏移量为箭头至最上侧的距离,默认居中。 | | showInSubWindow9+ | boolean | 否 | 是否在子窗口显示气泡,默认值为false。 | | primaryButton | {
value: string,
action: () => void
} | 否 | 第一个按钮。
value: 弹窗里主按钮的文本。
action: 点击主按钮的回调函数。 | | secondaryButton | {
value: string,
action: () => void
} | 否 | 第二个按钮。
value: 弹窗里辅助按钮的文本。
action: 点击辅助按钮的回调函数。 | @@ -32,7 +32,7 @@ | -------------------------| ------------------------- | ---- | ---------------------------------------------------- | | builder | [CustomBuilder](ts-types.md#custombuilder8) | 是 | 提示气泡内容的构造器。 | | placement | [Placement](ts-appendix-enums.md#placement8) | 否 | 气泡组件优先显示的位置,当前位置显示不下时,会自动调整位置。
默认值:Placement.Bottom | -| arrowOffset9+ | [Length](ts-types.md#length) | 否 | popup箭头在弹窗处的偏移。箭头在气泡上下方时,默认居左;箭头在气泡左右侧时,默认居上。 | +| arrowOffset9+ | [Length](ts-types.md#length) | 否 | popup箭头在弹窗处的偏移。箭头在气泡上下方时,数值为0表示箭头居最左侧,偏移量为箭头至最左侧的距离,默认居中。箭头在气泡左右侧时,偏移量为箭头至最上侧的距离,默认居中。 | | showInSubWindow9+ | boolean | 否 | 是否在子窗口显示气泡,默认值为false。 | | maskColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | 提示气泡遮障层的颜色。 | | popupColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | 提示气泡的颜色。 | diff --git a/zh-cn/application-dev/reference/errorcodes/errcode-Account.md b/zh-cn/application-dev/reference/errorcodes/errcode-Account.md index e176a23a6f7d23a11f5a3afd3990649183c10d98..26baf2f9e9954af7ae89022507f53445ed5a994b 100644 --- a/zh-cn/application-dev/reference/errorcodes/errcode-Account.md +++ b/zh-cn/application-dev/reference/errorcodes/errcode-Account.md @@ -1,6 +1,6 @@ # Account错误码 -以下错误码包括系统帐号和分布式帐号错误码。 +以下错误码包括系统帐号、分布式帐号和应用帐号错误码。 ## 12300001 系统服务异常 @@ -37,7 +37,7 @@ Invalid parameter. 1. 用户名为空。 2. 系统帐号用户名长度大于1024。 3. 分布式帐号用户名长度大于256。 -4. 系统帐号id小于0、小于100或大于1000。 +4. 系统帐号id小于0、小于100或大于1099。 5. 分布式帐号id长度大于512。 6. 分布式帐号传入不支持的事件类型。 7. 域名为空。 @@ -55,6 +55,9 @@ Invalid parameter. 19. 令牌长度超过1024。 20. 键名长度超过1024。 21. 自定义数据值长度超过1024。 +22. 无效的令牌。 +23. 无效的上下文标识。 +24. 无效的凭据标识。 **处理步骤** @@ -85,82 +88,82 @@ The account does not exist. 请检查帐号是否存在。 -## 12300004 操作受限帐号 +## 12300004 帐号已存在 **错误信息** -The specified account is restricted. +The account already exists. **可能原因** -该错误码表示操作的是受限帐号,可能原因如下: -1. 删除系统保留用户。 -2. 查询系统保留用户的约束源类型。 -3. 创建id为0-100的帐号。 +该错误码表示帐号已存在,可能原因如下: +创建已存在的帐号。 **处理步骤** -指定id为系统保留用户,无法操作。 +请取消创建,或使用其他账户号名重试。 -## 12300005 监听器已注册 +## 12300005 不支持多用户 **错误信息** -The listener has been registered. +Multi-user is not supported. **可能原因** -该错误码表示监听器已注册,可能原因如下: -当前应用向系统注册一个已经注册过的监听器,无法重复注册。 +该错误码表示不支持多用户,可能原因如下: +当前设备不支持多用户,无法创建帐号 **处理步骤** -请取消注册,或使用未注册过的监听器重新注册。 +无法创建其他帐号,请取消创建 -## 12300006 监听器未注册 +## 12300006 不支持的帐号类型 **错误信息** -The Listener is not registered. +The account type is not supported. **可能原因** -该错误码表示监听器未注册,可能原因如下: -解注册一个未注册过的监听器。 +该错误码表示提供了不支持的帐号类型,可能原因如下: +当前设备不支持创建指定类型的帐号 **处理步骤** -请使用注册的监听器执行解注册操作 +请创建其他类型的帐号 -## 12300007 PIN码输入器已注册 +## 12300007 帐号数量已达上限 **错误信息** -The PIN inputer already exists. +The account number has reached the upper limit. **可能原因** -该错误码表示PIN码输入器已注册,可能原因如下: -PIN码输入器已注册,解注册之前无法重复注册。 +该错误码表示帐号数量已达上限,可能原因如下: +创建系统帐号/应用帐号时,已存在1000个帐号。 **处理步骤** -PIN码输入器已存在,请勿重复操作。 +请删除其他帐号后再创建。 -## 12300008 帐号已存在 +## 12300008 受限的帐号 **错误信息** -The account already exists. +The specified account is restricted. **可能原因** -该错误码表示帐号已存在,可能原因如下: -创建已存在的帐号。 +该错误码表示操作的是受限帐号,可能原因如下: +1. 删除系统保留用户。 +2. 查询系统保留用户的约束源类型。 +3. 创建id为0-100的帐号。 **处理步骤** -请取消创建,或使用其他账户号名重试。 +指定id为系统保留用户,无法操作。 ## 12300009 帐号已激活 @@ -177,7 +180,7 @@ The account has been activated. 当前帐号已激活,请勿重复操作。 -## 12300010 帐号服务忙 +## 12300010 帐号服务忙碌 **错误信息** @@ -193,52 +196,101 @@ The account service is busy. 请等待一段时间后重试,并降低调用频率。 -## 12300011 帐号数量已达上限 +## 12300011 事件监听器已注册 **错误信息** -The account number has reached the upper limit. +The event listener has been registered. **可能原因** -该错误码表示帐号数量已达上限,可能原因如下: -创建系统帐号/应用帐号时,已存在1000个帐号。 +该错误码表示监听器已注册,可能原因如下: +当前应用向系统注册一个已经注册过的监听器,无法重复注册。 **处理步骤** -请删除其他帐号后再创建。 +请取消注册,或使用未注册过的监听器重新注册。 -## 12300012 不支持多用户 +## 12300012 事件监听器未注册 **错误信息** -Multi-user is not supported. +The event listener has not been registered. **可能原因** -该错误码表示不支持多用户,可能原因如下: -当前设备不支持多用户,无法创建帐号 +该错误码表示监听器未注册,可能原因如下: +解注册一个未注册过的监听器。 **处理步骤** -无法创建其他帐号,请取消创建 +请使用注册的监听器执行解注册操作 -## 12300013 不支持的帐号类型 +## 12300101 凭据不正确 **错误信息** -The account type is not supported. +The credential is incorrect. **可能原因** -该错误码表示提供了不支持的帐号类型,可能原因如下: -当前设备不支持创建管理员帐号 +该错误码表示凭据不正确,可能原因如下: +1. 密码输入错误; +2. 生物特征不匹配; +2. 令牌失效; + +**处理步骤** + +请输入正确有效的凭据重试。 + +## 12300102 凭据不存在 + +**错误信息** + +The credential does not exist. + +**可能原因** + +该错误码表示凭据不存在,可能原因如下: +1. 认证未录入的凭据类型。 +2. 查询未录入的凭据类型。 +3. 删除未录入的凭据类型。 + +**处理步骤** + +请确认凭据类型是否存在。 + +## 12300103 凭据输入器已注册 + +**错误信息** + +The crdential inputer already exists. + +**可能原因** + +该错误码表示凭据输入器已注册,可能原因如下: +PIN码输入器已注册,解注册之前无法重复注册。 **处理步骤** -请创建非管理员帐号 +凭据输入器已存在,请勿重复操作。 -## 12300014 可信等级不支持 +## 12300104 凭据输入器不存在 + +**错误信息** + +The crdential inputer not found. + +**可能原因** + +该错误码表示凭据输入器不存在,可能原因如下: +认证、添加、修改凭据时,未注册凭据输入器。 + +**处理步骤** + +注册凭据输入器。 + +## 12300105 可信等级不支持 **错误信息** @@ -253,7 +305,7 @@ The trust level is not supported. 请输入正确的可信等级。 -## 12300015 认证类型不支持 +## 12300106 认证类型不支持 **错误信息** @@ -268,81 +320,130 @@ The auth type is not supported. 请提供系统支持的认证类型。 -## 12300016 认证超时 +## 12300007 认证类型不存在 **错误信息** -The auth service is timeout. +The auth type does not exist. +**可能原因** + +该错误码表示认证类型不存在,可能原因如下: +查询/删除令牌时,指定的鉴权类型不存在。 + +**处理步骤** + +请使用存在的认证类型查询/删除。 + +## 12300008 认证会话不存在 + +**错误信息** + +The authentication session does not exist. **可能原因** -该错误码表示认证超时,可能原因如下: -1. 认证录入超过三分钟。 -2. 认证服务因网络原因无法及时响应而超时。 +该错误码表示会话不存在,可能原因如下: + +查询不存在的会话回调。 **处理步骤** -1. 认证录入超时,请重试。 -2. 请确认网络环境无问题后重试。 +请使用已成功打开的会话标识查询会话回调。 -## 12300017 认证服务忙 +## 12300109 认证被取消 **错误信息** -The auth service is busy. +The authentication is canceled. **可能原因** -该错误码表示认证服务忙,可能原因如下: -认证总数超过5个。 +该错误码表示认证被取消,可能原因如下: +认证过程中,用户取消认证操作。 **处理步骤** -当前认证服务忙,请稍后重试。 +重新或结束认证操作。 -## 12300018 认证服务锁定 +## 12300110 认证被锁定 **错误信息** -The auth service is locked. +The authentication is locked. **可能原因** -该错误码表示认证服务锁定,可能原因如下: +该错误码表示认证被锁定,可能原因如下: 认证类型错误次数超过上限。 **处理步骤** 认证错误次数超过上限,请在freezingTime之后重试。 -## 12300019 凭据不存在 +## 12300111 认证超时 **错误信息** -The credential does not exist. +The authentication is timeout. **可能原因** -该错误码表示凭据不存在,可能原因如下: -1. 认证未录入的凭据类型。 -2. 查询未录入的凭据类型。 -3. 删除未录入的凭据类型。 +该错误码表示认证超时,可能原因如下: +1. 对于系统帐号,认证、录入超过三分钟。 +2. 认证服务因网络原因无法及时响应而超时。 **处理步骤** -请确认凭据类型是否存在。 +1. 认证录入超时,请重试。 +2. 请确认网络环境无问题后重试。 + +## 12300112 认证服务忙 + +**错误信息** + +The auth service is busy. + +**可能原因** + +该错误码表示认证服务忙,可能原因如下: +系统帐号认证时,认证总数超过5个。 +应用帐号认证时,三方应用的认证器服务忙碌(根据实际情况决定)。 + +**处理步骤** + +当前认证服务忙,请稍后重试。 -## 12300020 无效的contextId +## 12300113 认证服务不存在 **错误信息** -The contextId is invalid. +The account authenticator service does not exist. +**可能原因** + +该错误码表示认证服务不存在,可能原因如下: +对于应用帐号: +1. 请求鉴权时,帐号所属应用不支持认证器服务。 +2. 隐式添加帐号时,帐号所属应用不支持认证器服务。 +3. 验证指定帐号的凭据时,该帐号所属应用不支持认证器服务。 +4. 设置应用的认证器属性时,指定的应用不支持认证器服务。 +5. 检查帐号标签时,指定的应用不支持认证器服务。 + +**处理步骤** + +请取消操作,或向支持认证服务的应用进行认证。 + +## 12300114 认证服务异常 + +**错误信息** +The account authenticator service works abnormally. **可能原因** -该错误码表示contextId无效,可能原因如下: -传入取消的contexId未发起认证录入或已经完成。 +该错误码表示帐号认证服务异常,可能原因如下: +1. 身份认证服务出现未知错误; +2. 应用认证器不符合规范; **处理步骤** -请输入正确的contextId。 +1. 请重试或重启系统; +2. 按照规范开发应用认证器; diff --git a/zh-cn/application-dev/reference/errorcodes/errcode-DistributedNotificationService.md b/zh-cn/application-dev/reference/errorcodes/errcode-DistributedNotificationService.md new file mode 100644 index 0000000000000000000000000000000000000000..5a11da27ec9beab9169156b370fa5ddbe6e9a000 --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errcode-DistributedNotificationService.md @@ -0,0 +1,229 @@ +# DistributedNotificationService错误码 + +## 1600001 内部错误 + +**错误信息** + +Internal Error. + +**错误描述** + +当内存申请、多线程处理异常等内部处理错误,系统会报此错误码。 + +**可能原因** + +1. 内存申请、多线程处理等内核通用错误。 + +**处理步骤** + +1. 确认系统内存是否足够。 +2. 重启系统。 + +## 1600002 应用与通知子系统数据处理或交互错误 + +**错误信息** + +IPC Error. + +**错误描述** + +当序列化与反序列化错误与通知子系统交互失败时,系统会报此错误码。 + +**可能原因** + +1. 序列化、反序列化错误。 +2. 与通知子系统交互失败。 + +**处理步骤** + +1. 确认参入参数是否超长。 +2. 确认通知子系统是否启动中。 + +## 1600003 连接服务错误 + +**错误信息** + +Failed to connect to service. + +**错误描述** + +当连接服务失败使通知子系统异常时,系统会报此错误码。 + +**可能原因** + +1. 服务繁忙、或通知子系统异常。 + +**处理步骤** + +1. 服务繁忙,请稍后重试。 +2. 确认通知子系统是否启动。 + +## 1600004 通知使能未开启 + +**错误信息** + +Notification is not enabled. + +**错误描述** + +当通知使能未开启或手动被用户关闭时,系统会报此错误码。 + +**可能原因** + +1. 应用的通知使能是初始的未开启状态或者被用户关闭。 + +**处理步骤** + +1. 检查应用通知使能是否已开启。 + +## 1600005 通知渠道未开启 + +**错误信息** + +Notification slot is not enabled. + +**错误描述** + +当通知渠道未开启时,系统会报此错误码。 + +**可能原因** + +1. 通知渠道使能未开启。 + +**处理步骤** + +1. 检查应用通知渠道使能是否已开启。 + +## 1600006 通知不允许删除 + +**错误信息** + +Notification is not allowed to remove. + +**错误描述** + +当通知设置isUnremoveable=true标识时全清,当设置isRemoveAllowed=false时,删除时,系统会报此错误码。 + +**可能原因** + +1. 通知上设置了isUnremoveable=true标识,不允许全清只允许单条删除。 +2. 通知上设置了isRemoveAllowed=false,不允许删除。 + +**处理步骤** + +1. 检查通知是否设置了unremovable=true标识。 +2. 检查通知是否设置了isRemoveAllowed=false标识。 + +## 1600007 通知不存在 + +**错误信息** + +The notification is not exist. + +**错误描述** + +当通知被删除或取消,不存在时,系统会报此错误码。 + +**可能原因** + +1. 通知已被删除。 +2. 通知已被取消。 + +**处理步骤** + +1. 检查当前通知是否存在。 + +## 1600008 用户不存在 + +**错误信息** + +The user is not exist. + +**错误描述** + +用当用户ID错误,或设备用户未激活时,系统会报此错误码。 + +**可能原因** + +1. 用户ID输入错误。 +2. 设备上没有激活的用户。 + +**处理步骤** + +1. 检查指定id的用户是否已经存在。 + +## 1600009 每秒发送通知超过最大限制 + +**错误信息** + +Over max number notifications per second. + +**错误描述** + +当每秒发送通知超过最大限制时,系统会报此错误码。 + +**可能原因** + +1. 每秒发送通知超过数超过10条。 + +**处理步骤** + +1. 降低通知发送频率。 + +## 1600010 分布式处理错误 + +**错误信息** + +Distributed operation failed. + +**错误描述** + +当操作数据库太频繁导致数据库处理异常,系统会报此错误码。 + +**可能原因** + +1. 数据库处理异常、操作太频繁。 + +**处理步骤** + +1. 检查分布式数据运行是否正常。 +2. 降低操作频率。 + +## 1600011 读取模板配置文件错误 + +**错误信息** + +Read template config failed. + +**错误描述** + +当模板配置文件丢失或不支持当前版本模板时,系统会报此错误码。 + +**可能原因** + +1. 模板配置文件丢失。 +2. 当前版本不支持模板。 + +**处理步骤** + +1. 检查系统/system/etc/notification_template/external.json文件是否存在。 +2. 升级版本到3.2及以上。 + +## 17700001 包名不存在 + +**错误信息** + +The specified bundle name was not found. + +**错误描述** + +当应用未安装或包名不正确时,系统会报此错误码。 + +**可能原因** + +1. 包名不正确。 +2. 应用未安装。 + +**处理步骤** + +1. 检查应用是否存在。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-EnterpriseDeviceManager.md b/zh-cn/application-dev/reference/errorcodes/errorcode-EnterpriseDeviceManager.md index b1bbc7a87a1651733e3b4331c9401005732b0241..1d2b695dd3d2266ddb84380f7eaa024ff718375a 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-EnterpriseDeviceManager.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-EnterpriseDeviceManager.md @@ -2,117 +2,145 @@ ## 9200001 应用没有激活成设备管理器 -### 错误信息 +**错误信息** + The application is not a administrator of the device. -### 错误描述 +**错误描述** + 当应用没有激活成设备管理器时,则会产生此错误码。 -### 可能原因 +**可能原因** + 应用没有激活设备管理器。 -### 处理步骤 +**处理步骤** + 请检查调用者是否成功激活过设备管理器,没有激活过的设备管理器的应用无法调用设备管理接口。 ## 9200002 设备管理器权限不够 -### 错误信息 +**错误信息** + The administrator application does not have permission to manage the device. -### 错误描述 +**错误描述** + 当设备管理器调用高权限接口时,则会产生此错误码。 -### 可能原因 +**可能原因** + 激活成了DA管理器,调用了SDA管理器接口。 -### 处理步骤 +**处理步骤** + 请检查调用者是否存在越权调用,即激活的设备管理器类型和调用的API要求的管理器类型是否一致。 ## 9200003 指定的设备管理器元能力组件无效 -### 错误信息 +**错误信息** + The administrator ability component is invalid. -### 错误描述 +**错误描述** + 当应用传入参数中指定的设备管理器元能力组件无效,则会产生此错误码。 -### 可能原因 +**可能原因** + 该错误码表示指定的设备管理器元能力组件无效,可能原因如下。 1. 应用激活设备管理器时指定的设备管理器元能力组件不存在。 2. 设备管理器元能力组件不是合法的企业设备管理元能力组件。 -### 处理步骤 +**处理步骤** + 1. 请检查激活时输入的设备管理器元能力组件name是否存在应用包中。 2. 请检查企业设备管理组件是否继承企业设备管理框架定义的EnterpriseAdminExtensionAbility组件。 ## 9200004 激活设备管理器失败 -### 错误信息 +**错误信息** + Failed to activate the administrator application of the device. -### 错误描述 +**错误描述** + 当应用重复激活不同类型的设备管理器或激活多个管理器时,则会产生此错误码。 -### 可能原因 +**可能原因** + 该错误码表示激活设备管理器失败,可能原因如下。 1. 同时激活多个SDA设备管理器。 2. 重复激活设备管理器,且管理器类型发生变化。 3. 同一个应用多个设备管理器元能力组件激活。 -### 处理步骤 +**处理步骤** + 1. 检查是否激活多个SDA设备管理器,SDA设备管理器只允许激活一个。 2. 检查指定的设备管理器是否已激活了,且重复激活时管理器类型发生变化,此时需要先去激活,再重新激活。 3. 检查待激活的设备管理器应用中是否已有设备管理元能力组件激活过,同一个应用只允许激活一个设备管理器元能力组件 ## 9200005 去激活设备管理器失败 -### 错误信息 +**错误信息** + Failed to deactivate the administrator application of the device. -### 错误描述 +**错误描述** + 当应用没有激活过或者去激活其他设备管理器时,则会产生此错误码。 -### 可能原因 +**可能原因** + 该错误码表示去激活设备管理器失败,可能原因如下。 1. 去激活的设备管理器应用没有激活过。 2. 不能去激活其他设备管理器。 -### 处理步骤 +**处理步骤** + 1. 检查去激活时设备管理应用是否激活过。 2. 检查去激活时设备管理应用中指定设备管理元能力组件是否激活过。 3. 检查调用者是否去激活自身,设备管理器应用不能去激活其他设备管理器应用。 ## 9200006 指定的用户ID非法 -### 错误信息 +**错误信息** + The specified user ID is invalid. -### 错误描述 +**错误描述** + 当应用调用接口设置用户策略,指定的user id不存在、或者DA,SDA管理器跨用户设置时,则会产生此错误码。 -### 可能原因 +**可能原因** + 该错误码表示指定的用户ID非法,可能原因如下。 1. 调用接口设置用户策略时候,指定的user id不存在。 2. 指定的user id和调用者user id不同。DA,SDA管理器不允许跨用户设置。 -### 处理步骤 +**处理步骤** + 1. 检查去调用接口中指定的user id是否是有效的user id。 2. 检查调用者user id和指定设置的user id是否是同一user id,非SDA模式下不允许跨用户设置策略。 ## 9200007 系统服务工作异常 -### 错误信息 +**错误信息** + The system ability work abnormally. -### 错误描述 +**错误描述** + 当企业设备管理服务异常时,则会产生此错误码。 -### 可能原因 +**可能原因** + 该错误码表示系统服务工作异常,可能原因如下。 1. 企业设备管理服务没有正常启动。 2. 企业设备管理的RPC对象无法获取。 3. 企业设备管理依赖的其他服务没有正常启动或者RPC对象无法获取。 4. 企业设备管理运行过程中系统异常。 -### 处理步骤 +**处理步骤** + 系统服务内部工作异常,请稍后重试,或者重启设备尝试。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-animator.md b/zh-cn/application-dev/reference/errorcodes/errorcode-animator.md index 72848e1acab47797cb406ccda9ad01bc65b75099..b07c42ebb8fee6b564c521d6f431a6f337ce2f9e 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-animator.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-animator.md @@ -2,18 +2,18 @@ ## 100001 内部错误 -### 错误信息 +**错误信息** Internal error. -### 错误描述 +**错误描述** 当出现了开发者解决不了的内部异常错误,会报此错误码,并描述具体是哪种内部错误。 -### 可能原因 +**可能原因** 未成功获取渲染引擎,解析参数失败等。 -### 处理步骤 +**处理步骤** NA \ No newline at end of file diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-app-account.md b/zh-cn/application-dev/reference/errorcodes/errorcode-app-account.md index e9d1820c857b5bf10b2424e3aca47f9e96460033..a9751d48fadbb8227537ccff2f65708638c89325 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-app-account.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-app-account.md @@ -16,85 +16,42 @@ The application does not exist. 请取消设置,或使用已安装的应用包名重试。 -## 12400002 帐号认证器服务不存在 +## 12400002 自定义数据不存在 **错误信息** -The account authenticator service does not exist. -**可能原因** - -该错误码表示帐号认证器服务不存在,可能原因如下: -1. 请求鉴权时,帐号所属应用不支持认证器服务。 -2. 隐式添加帐号时,帐号所属应用不支持认证器服务。 -3. 验证指定帐号的凭据时,该帐号所属应用不支持认证器服务。 -4. 设置应用的认证器属性时,指定的应用不支持认证器服务。 - -**处理步骤** - -请取消操作,或使用支持认证器服务的应用的包名重试。 - -## 12400003 帐号认证器服务异常 - -**错误信息** - -The account authenticator service works abnormally. -**可能原因** - -该错误码表示帐号认证器服务异常,可能原因如下: -三方应用的鉴权服务接连失败。 - -**处理步骤** - -请重试或重启系统。 - -## 12400004 鉴权类型不存在 - -**错误信息** +The custom data does not exist. -The auth type does not exist. **可能原因** -该错误码表示鉴权类型不存在,可能原因如下: -查询/删除令牌时,指定的鉴权类型不存在。 +该错误码表示自定义数据不存在,可能原因如下: +查询帐号的自定义数据时,输入的键名不存在。 **处理步骤** -请使用存在的鉴权类型查询/删除。 +请使用存在的自定义数据的键名查询。 -## 12400005 会话不存在 +## 12400003 自定义数据的数量已达上限 **错误信息** -The session does not exist. +The number of custom data reaches upper limit. **可能原因** -该错误码表示会话不存在,可能原因如下: - -查询不存在的会话回调。 +该错误码表示自定义数据的数量已达上限,可能原因如下: +设置自定义数据时,目标帐号的自定义数据数量已达512。 **处理步骤** -请使用已成功打开的会话标识查询会话回调。 - -## 12400006 授权列表已达上限 - -**错误信息** - -The size of authorization list reaches upper limit. -**可能原因** - -该错误码表示授权列表已达上限,可能原因如下: -设置访问/开放授权时,授权列表的大小超过1024。 - -**处理步骤** -1. 请取消设置操作,或者撤销已存在的访问/开放授权后再设置。 +请取消设置操作,或者删除已存在的自定义数据。 -## 12400007 令牌数量已达上限 +## 12400004 令牌数量已达上限 **错误信息** The number of token reaches upper limit. + **可能原因** 该错误码表示令牌数量已达上限,可能原因如下: @@ -104,31 +61,17 @@ The number of token reaches upper limit. 请取消添加操作,或者删除已存在的令牌后再添加。 -## 12400008 自定义数据的数量已达上限 - -**错误信息** - -The number of custom data reaches upper limit. -**可能原因** - -该错误码表示自定义数据的数量已达上限,可能原因如下: -设置自定义数据时,目标帐号的自定义数据数量已达512。 - -**处理步骤** - -请取消设置操作,或者删除已存在的自定义数据。 - -## 12400009 自定义数据不存在 +## 12400005 授权列表已达上限 **错误信息** -The custom data does not exist. +The size of authorization list reaches upper limit. **可能原因** -该错误码表示自定义数据不存在,可能原因如下: -查询帐号的自定义数据时,输入的键名不存在。 +该错误码表示授权列表已达上限,可能原因如下: +设置访问/开放授权时,授权列表的大小超过1024。 **处理步骤** -请使用存在的自定义数据的键名查询。 +1. 请取消设置操作,或者撤销已存在的访问/开放授权后再设置。 diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-buffer.md b/zh-cn/application-dev/reference/errorcodes/errorcode-buffer.md new file mode 100644 index 0000000000000000000000000000000000000000..6f31b7246041e653701be54dc82c13dbe00a6250 --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-buffer.md @@ -0,0 +1,55 @@ +# buffer错误码 + +## 10200001 参数范围越界错误 + +**错误信息** + +The value of ${param} is out of range. + +**错误描述** + +调用接口时某个参数超出了其正常范围的取值。 + +**可能原因** + +某个参数取值超出可用范围。 + +**处理步骤** + +检查所传参数是否在可用取值范围内。 + +## 10200009 Buffer size 错误 + +**错误信息** + +Buffer size must be a multiple of ${size} + +**错误描述** + +Buffer的长度必须是${size}的整数倍,${size}为16-bits,32-bits或者64-bits。 + +**可能原因** + +Buffer的长度不是${size}的整数倍,${size}为16-bits,32-bits或者64-bits。 + +**处理步骤** + +请检查Buffer的长度值。 + +## 10200013 只读属性设置错误 + +**错误信息** + +Cannot set property ${propertyName} of Buffer which has only a getter. + +**错误描述** + +Buffer的属性${propertyName}只读,不能进行设置。 + +**可能原因** + +将${propertyName}放在了等号左边(即对属性值进行设置)。 + +**处理步骤** + +请检查属性${propertyName}是否在等号左边。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-distributed-data_object.md b/zh-cn/application-dev/reference/errorcodes/errorcode-distributed-data_object.md new file mode 100644 index 0000000000000000000000000000000000000000..1a48200bf58c284f7ba46b257d00d98d3e506904 --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-distributed-data_object.md @@ -0,0 +1,19 @@ +# 分布式数据对象错误码 + +## 15400001 创建内存数据库失败 + +**错误信息** + +Create table failed. + +**错误描述** + +创建内存数据库失败。 + +**可能原因** + +已经存在加入相同session的对象。 + +**处理步骤** + +检查是否已经有加入相同session的对象。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-i18n.md b/zh-cn/application-dev/reference/errorcodes/errorcode-i18n.md index 90b123f4797d90c8abdaac1b03a8a4ca23a8785d..3b6ba5548faa1d029b060135bf1990d9e5c02c4b 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-i18n.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-i18n.md @@ -2,28 +2,36 @@ ## 890001 参数类型错误 -### 错误信息 +**错误信息** + Unspported para value. -### 错误描述 +**错误描述** + 当接口传入错误的参数类型时,系统会产生此错误码。 -### 可能原因 +**可能原因** + 该错误码表示参数错误,可能原因是传入参数的类型错误。 -### 处理步骤 +**处理步骤** + 检查参数的类型是否正确。 ## 890002 配置项参数错误 -### 错误信息 +**错误信息** + Unspported option value. -### 错误描述 +**错误描述** + 当接口的option配置参数中包含不合法的配置项时,系统会产生此错误码。 -### 可能原因 +**可能原因** + 该错误码表示配置项参数错误,可能原因是option参数中使用了不支持的配置项。 -### 处理步骤 +**处理步骤** + 检查option参数中是否使用了不合法的配置项。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-promptAction.md b/zh-cn/application-dev/reference/errorcodes/errorcode-promptAction.md index 0bf40f83975af5027b176ab4df75b9739b33a8d7..193f2fad84401f0064e8ae2b817cf3dd270f9381 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-promptAction.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-promptAction.md @@ -2,18 +2,18 @@ ## 100001 内部错误 -### 错误信息 +**错误信息** Internal error. -### 错误描述 +**错误描述** 当出现了开发者解决不了的内部异常错误,会报此错误码,并描述具体是哪种内部错误。 -### 可能原因 +**可能原因** 未成功获取渲染引擎,解析参数失败等。 -### 处理步骤 +**处理步骤** NA \ No newline at end of file diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-resource-manager.md b/zh-cn/application-dev/reference/errorcodes/errorcode-resource-manager.md index e733f2814fb3f7b90ad431d88461abbffe268b72..93fbc1f8423fc26a45262d7055d77657f98bdb46 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-resource-manager.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-resource-manager.md @@ -2,88 +2,112 @@ ## 9001001 无效的资源id -### 错误信息 +**错误信息** + The resId invalid. -### 错误描述 +**错误描述** + 当传入的资源id符合类型校验,但却是一个不存在的资源id时,会报出此错误。 -### 可能原因 +**可能原因** + 传入的是一个不存在的id值。 -### 处理步骤 +**处理步骤** + 检查传入参数的资源id是否已有。 ## 9001002 根据当前资源id,找不到匹配的资源 -### 错误信息 +**错误信息** + The resource not found by resId. -### 错误描述 +**错误描述** + 当传入的资源id符合类型校验,但是根据此资源id匹配不到资源时,会报出此错误。 -### 可能原因 +**可能原因** + 1、传入的是资源id有误。 2、资源解析有误。 -### 处理步骤 +**处理步骤** + 检查传入的资源id是否符合预期。 ## 9001003 无效的资源名称 -### 错误信息 +**错误信息** + The resName invalid. -### 错误描述 +**错误描述** + 当传入的资源名称符合类型校验,但却是一个不存在的资源名称时,会报出此错误。 -### 可能原因 +**可能原因** + 传入的是一个不存在的资源名称。 -### 处理步骤 +**处理步骤** + 检查传入的资源名称是否符合预期。 ## 9001004 根据当前资源名称,找不到匹配的资源 -### 错误信息 +**错误信息** + The resource not found by resName. -### 错误描述 +**错误描述** + 当传入的资源名称符合类型校验,但是根据此资源名称,匹配不到资源。 -### 可能原因 +**可能原因** + 1、传入的是资源名称有误。 2、资源解析有误。 -### 处理步骤 +**处理步骤** + 可先检查传入的资源名称是否符合预期。 ## 9001005 无效的相对路径 -### 错误信息 +**错误信息** + The resource not found by path. -### 错误描述 +**错误描述** + 根据参数相对路径, 找不到对应的资源。 -### 可能原因 +**可能原因** + 传入的相对路径有误。 -### 处理步骤 +**处理步骤** + 可检查传入的相对路径是否符合预期。 ## 9001006 循环引用 -### 错误信息 +**错误信息** + the resource re-ref too much. -### 错误描述 +**错误描述** + 解析引用次数过高。 -### 可能原因 +**可能原因** + 出现资源循环引用的情况。 -### 处理步骤 +**处理步骤** + 查看资源$引用的地方,去除循环引用的情况。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-router.md b/zh-cn/application-dev/reference/errorcodes/errorcode-router.md index 5b459aa69f62fb17f951eba7d8b747f340130057..45d158081c4275c0c9cc43822df901b44ae20899 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-router.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-router.md @@ -2,72 +2,72 @@ ## 100001 内部错误 -### 错误信息 +**错误信息** Internal error. -### 错误描述 +**错误描述** 当出现了开发者解决不了的内部异常错误,系统会产生此错误码,并描述具体是哪种内部错误。 -### 可能原因 +**可能原因** 未成功获取渲染引擎,解析参数失败等。 -### 处理步骤 +**处理步骤** NA ## 100002 路由输入的uri错误 -### 错误信息 +错误信息 Uri error. The uri of router is not exist. -### 错误描述 +**错误描述** 当跳转页面输入的uri错误或者不存在,系统会产生此错误码。 -### 可能原因 +**可能原因** 输入的路由uri错误或者不存在。 -### 处理步骤 +**处理步骤** 请检查输入的路由uri是否正确。 ## 100003 路由压入的page过多 -### 错误信息 +**错误信息** Page stack error. The pages are pushed too much. -### 错误描述 +**错误描述** 当跳转页面压入页面数超过32,系统会产生此错误码。 -### 可能原因 +**可能原因** 压入pages过多。 -### 处理步骤 +**处理步骤** 请清除多余或无效的页面。 ## 200002 路由输入的uri错误 -### 错误信息 +**错误信息** Uri error. The uri of router is not exist. -### 错误描述 +**错误描述** 当替换页面输入的uri错误或不存在,系统会产生此错误码。 -### 可能原因 +**可能原因** 输入的路由uri错误或不存在。 -### 处理步骤 +**处理步骤** 请检查输入的路由uri是否正确。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-sensor.md b/zh-cn/application-dev/reference/errorcodes/errorcode-sensor.md index 9aa5828ffb994d2615485fb9f4de984a629a2e4f..add7b1aa6109a85fab4741bcb205fa4ec2f891fd 100755 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-sensor.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-sensor.md @@ -2,19 +2,19 @@ ## 14500101 传感器服务异常 -### 错误信息 +**错误信息** Service exception. -### 错误描述 +**错误描述** 当调用sensor模块on、once、off接口时,若hdi服务异常,会报此错误码。 -### 可能原因 +**可能原因** 访问hdi服务状态异常。 -### 处理步骤 +**处理步骤** 1. 定时重试操作,如间隔1s或者按照指数增长间隔重试。 2. 连续重试3次不可用则停止尝试,期间可优先尝试获取器件列表方式进一步获取设备可用性。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-vibrator.md b/zh-cn/application-dev/reference/errorcodes/errorcode-vibrator.md index edab04eca48ff0819392fd7563fb22e7694fbfe4..5787a083a24ecde7ceaa44ff579ade5332064f7f 100755 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-vibrator.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-vibrator.md @@ -2,20 +2,20 @@ ## 14600101 操作设备失败 -### 错误信息 +**错误信息** Device operation failed. -### 错误描述 +**错误描述** 当调用vibrator模块startVibration接口时,若hdi服务异常或者设备被占用,会报此错误码。 -### 可能原因 +**可能原因** 1. 访问hdi服务状态异常。 2. 当前设备被占用。 -### 处理步骤 +**处理步骤** 1. 间隔一段时间重试操作,或按指数增长间隔重试;连续重试3次不可用则停止尝试,期间可优先尝试获取器件列表方式进一步获取设备可用性。 2. 设置振动优先级较低,尝试设置更高优先级。 \ No newline at end of file diff --git a/zh-cn/application-dev/ui/Readme-CN.md b/zh-cn/application-dev/ui/Readme-CN.md index 8131710e12f0374526d018ad93b998b7aff41f45..6aff125446fd976063ff9d15776ecf27fe7ad863 100755 --- a/zh-cn/application-dev/ui/Readme-CN.md +++ b/zh-cn/application-dev/ui/Readme-CN.md @@ -3,37 +3,30 @@ - [方舟开发框架(ArkUI)概述](arkui-overview.md) - UI开发(基于ArkTS的声明式开发范式) - [概述](ui-ts-overview.md) - - 框架说明 - - 文件组织 - - [目录结构](ts-framework-directory.md) - - [应用代码文件访问规则](ts-framework-file-access-rules.md) - - 资源管理 - - [资源文件的分类](ui-ts-basic-resource-file-categories.md) - - [资源访问](ts-resource-access.md) - - [像素单位](ts-pixel-units.md) - - - 深入理解组件化 - - [自定义组件初始化](ts-custom-component-initialization.md) - - [自定义组件生命周期回调函数](ts-custom-component-lifecycle-callbacks.md) - - [组件创建和重新初始化示例](ts-component-creation-re-initialization.md) - - 常见组件开发指导 - - [Button开发指导](ui-ts-basic-components-button.md) - - [Web开发指导](ui-ts-components-web.md) - - 常见布局开发指导 - - [弹性布局](ui-ts-layout-flex.md) - - [栅格布局](ui-ts-layout-grid-container.md) - - [媒体查询](ui-ts-layout-mediaquery.md) - - 体验声明式UI - - [创建声明式UI工程](ui-ts-creating-project.md) - - [初识Component](ui-ts-components.md) - - [创建简单视图](ui-ts-creating-simple-page.md) - - 页面布局与连接 + - [声明式UI开发指导](ui-ts-developing-intro.md) + - 声明式UI开发实例 + - [创建简单视图](ui-ts-creating-simple-page.md) + - 构建完整实例 - [构建食物数据模型](ui-ts-building-data-model.md) - [构建食物列表List布局](ui-ts-building-category-list-layout.md) - [构建食物分类Grid布局](ui-ts-building-category-grid-layout.md) - - [页面跳转与数据传递](ui-ts-page-redirection-data-transmission.md) - - [性能提升的推荐方法](ts-performance-improvement-recommendation.md) - + - [页面跳转与数据传递](ui-ts-page-redirection-data-transmission.md) + - 添加闪屏动画 + - [绘制图像](ui-ts-drawing-feature.md) + - [添加动画效果](ui-ts-animation-feature.md) + - 常见布局开发指导 + - 自适应布局 + - [线性布局](ui-ts-layout-linear.md) + - [层叠布局](ui-ts-layout-stack.md) + - [弹性布局](ui-ts-layout-flex.md) + - [网格布局](ui-ts-layout-grid.md) + - 响应式布局 + - [栅格布局(新)](ui-ts-layout-grid-container-new.md) + - [栅格布局](ui-ts-layout-grid-container.md) + - [媒体查询](ui-ts-layout-mediaquery.md) + - [自定义组件的生命周期](ui-ts-custom-component-lifecycle-callbacks.md) + - [Web组件开发指导](ui-ts-components-web.md) + - [性能提升的推荐方法](ui-ts-performance-improvement-recommendation.md) - UI开发(兼容JS的类Web开发范式) - [概述](ui-js-overview.md) - 框架说明 diff --git a/zh-cn/application-dev/ui/figures/LazyForEach1.gif b/zh-cn/application-dev/ui/figures/LazyForEach1.gif new file mode 100644 index 0000000000000000000000000000000000000000..66730a7cdb85529ed96a084b9d9b98aaed18474d Binary files /dev/null and b/zh-cn/application-dev/ui/figures/LazyForEach1.gif differ diff --git a/zh-cn/application-dev/ui/figures/aboutToAppear.gif b/zh-cn/application-dev/ui/figures/aboutToAppear.gif new file mode 100644 index 0000000000000000000000000000000000000000..6bddc173b59f69a746592ae8689b0443b704a8b3 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/aboutToAppear.gif differ diff --git a/zh-cn/application-dev/ui/figures/alignself.png b/zh-cn/application-dev/ui/figures/alignself.png new file mode 100644 index 0000000000000000000000000000000000000000..6ab6ba66e53bf7dc3edd72d44727fe40c7ff0fb9 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/alignself.png differ diff --git a/zh-cn/application-dev/ui/figures/animation-feature.gif b/zh-cn/application-dev/ui/figures/animation-feature.gif new file mode 100644 index 0000000000000000000000000000000000000000..f75ac924799af38dbfe43c2c2e5572fb0e3c09d0 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/animation-feature.gif differ diff --git a/zh-cn/application-dev/ui/figures/animation-feature1.gif b/zh-cn/application-dev/ui/figures/animation-feature1.gif new file mode 100644 index 0000000000000000000000000000000000000000..5dc236ba194e59fd46416ca0a738ed7139a59374 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/animation-feature1.gif differ diff --git a/zh-cn/application-dev/ui/figures/blank.gif b/zh-cn/application-dev/ui/figures/blank.gif new file mode 100644 index 0000000000000000000000000000000000000000..879f53781ff9f9087d3343cd867be8d56deeca1e Binary files /dev/null and b/zh-cn/application-dev/ui/figures/blank.gif differ diff --git a/zh-cn/application-dev/ui/figures/breakpoints.gif b/zh-cn/application-dev/ui/figures/breakpoints.gif new file mode 100644 index 0000000000000000000000000000000000000000..f2e18ecafe8202705a34e6c76b4fdc59d5cca8d6 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/breakpoints.gif differ diff --git a/zh-cn/application-dev/ui/figures/column.png b/zh-cn/application-dev/ui/figures/column.png new file mode 100644 index 0000000000000000000000000000000000000000..27321b5a24798d6d423cbf76eab974f4ebc2d0fb Binary files /dev/null and b/zh-cn/application-dev/ui/figures/column.png differ diff --git a/zh-cn/application-dev/ui/figures/columnGap.png b/zh-cn/application-dev/ui/figures/columnGap.png new file mode 100644 index 0000000000000000000000000000000000000000..1b7017a280158e88baabca3dfd1e77c6068c4655 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/columnGap.png differ diff --git a/zh-cn/application-dev/ui/figures/columnTemplate.png b/zh-cn/application-dev/ui/figures/columnTemplate.png new file mode 100644 index 0000000000000000000000000000000000000000..730abeccaffa22f88e916fb199cbc1e44a982789 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/columnTemplate.png differ diff --git a/zh-cn/application-dev/ui/figures/columnalign.png b/zh-cn/application-dev/ui/figures/columnalign.png new file mode 100644 index 0000000000000000000000000000000000000000..a73a28a23c3719aee5379e0c8b3f9cc3627ca3e2 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/columnalign.png differ diff --git a/zh-cn/application-dev/ui/figures/columnjustify.png b/zh-cn/application-dev/ui/figures/columnjustify.png new file mode 100644 index 0000000000000000000000000000000000000000..34e68343a8b621f4a0567ea9424169f6a7e5ef1b Binary files /dev/null and b/zh-cn/application-dev/ui/figures/columnjustify.png differ diff --git a/zh-cn/application-dev/ui/figures/columns1.png b/zh-cn/application-dev/ui/figures/columns1.png new file mode 100644 index 0000000000000000000000000000000000000000..f7e2c38a9b5f22ebf44eaae8eb9fea461d198018 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/columns1.png differ diff --git a/zh-cn/application-dev/ui/figures/columns2.png b/zh-cn/application-dev/ui/figures/columns2.png new file mode 100644 index 0000000000000000000000000000000000000000..5e549b42338ffe87b944807cec7e57144b5cbe74 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/columns2.png differ diff --git a/zh-cn/application-dev/ui/figures/columns3.gif b/zh-cn/application-dev/ui/figures/columns3.gif new file mode 100644 index 0000000000000000000000000000000000000000..e44df1b36066095ed6e8741e26d9f04a4c9a2b0b Binary files /dev/null and b/zh-cn/application-dev/ui/figures/columns3.gif differ diff --git a/zh-cn/application-dev/ui/figures/columnspace.png b/zh-cn/application-dev/ui/figures/columnspace.png new file mode 100644 index 0000000000000000000000000000000000000000..6af047e34c3e1e2ecd8d3d1d99af17ca01c5b58b Binary files /dev/null and b/zh-cn/application-dev/ui/figures/columnspace.png differ diff --git a/zh-cn/application-dev/ui/figures/component.PNG b/zh-cn/application-dev/ui/figures/component.PNG new file mode 100644 index 0000000000000000000000000000000000000000..bf949004e64004c9ac3f24f6edbd625b135c9717 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/component.PNG differ diff --git a/zh-cn/application-dev/ui/figures/component.gif b/zh-cn/application-dev/ui/figures/component.gif new file mode 100644 index 0000000000000000000000000000000000000000..e50a590ed7049a3c52149d10886e5b38ffdae2a5 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/component.gif differ diff --git a/zh-cn/application-dev/ui/figures/crossCenter.png b/zh-cn/application-dev/ui/figures/crossCenter.png new file mode 100644 index 0000000000000000000000000000000000000000..5efa144a653649d5118edf3790c8e26b370c49df Binary files /dev/null and b/zh-cn/application-dev/ui/figures/crossCenter.png differ diff --git a/zh-cn/application-dev/ui/figures/crossEnd.png b/zh-cn/application-dev/ui/figures/crossEnd.png new file mode 100644 index 0000000000000000000000000000000000000000..2330225d2b046b67c30c040a4a72e2e553e0c824 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/crossEnd.png differ diff --git a/zh-cn/application-dev/ui/figures/crossSpacearound.png b/zh-cn/application-dev/ui/figures/crossSpacearound.png new file mode 100644 index 0000000000000000000000000000000000000000..280987579ef8c11a847d6842e9596168aec97cdb Binary files /dev/null and b/zh-cn/application-dev/ui/figures/crossSpacearound.png differ diff --git a/zh-cn/application-dev/ui/figures/crossSpacebetween.png b/zh-cn/application-dev/ui/figures/crossSpacebetween.png new file mode 100644 index 0000000000000000000000000000000000000000..65e408eb2fde074f1a9e65dfff01de8e569ccf66 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/crossSpacebetween.png differ diff --git a/zh-cn/application-dev/ui/figures/crossSpaceevenly.png b/zh-cn/application-dev/ui/figures/crossSpaceevenly.png new file mode 100644 index 0000000000000000000000000000000000000000..83f3a801a8f79d06794680db0309a9fa5fee1387 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/crossSpaceevenly.png differ diff --git a/zh-cn/application-dev/ui/figures/crossStart.png b/zh-cn/application-dev/ui/figures/crossStart.png new file mode 100644 index 0000000000000000000000000000000000000000..1f323600a999f2ca313a5a5273088620f72578c3 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/crossStart.png differ diff --git a/zh-cn/application-dev/ui/figures/direction.png b/zh-cn/application-dev/ui/figures/direction.png new file mode 100644 index 0000000000000000000000000000000000000000..702c9b07fa00b8685415bb83879ead774001ee56 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/direction.png differ diff --git a/zh-cn/application-dev/ui/figures/direction1.png b/zh-cn/application-dev/ui/figures/direction1.png new file mode 100644 index 0000000000000000000000000000000000000000..1153aade7a6764fe871d63783abdcd09366fba13 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/direction1.png differ diff --git a/zh-cn/application-dev/ui/figures/direction2.png b/zh-cn/application-dev/ui/figures/direction2.png new file mode 100644 index 0000000000000000000000000000000000000000..e0a74253389934179d0cbcbaf4a43c01df18f7e5 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/direction2.png differ diff --git a/zh-cn/application-dev/ui/figures/drawing-feature.png b/zh-cn/application-dev/ui/figures/drawing-feature.png new file mode 100644 index 0000000000000000000000000000000000000000..c1468667bdf74b80629c1eaa32cbef935ea5048c Binary files /dev/null and b/zh-cn/application-dev/ui/figures/drawing-feature.png differ diff --git a/zh-cn/application-dev/ui/figures/drawing-feature1.png b/zh-cn/application-dev/ui/figures/drawing-feature1.png new file mode 100644 index 0000000000000000000000000000000000000000..6b3ca4fa90e25b5906bdadcdcbf134bd00b7b34b Binary files /dev/null and b/zh-cn/application-dev/ui/figures/drawing-feature1.png differ diff --git a/zh-cn/application-dev/ui/figures/drawing-feature2.png b/zh-cn/application-dev/ui/figures/drawing-feature2.png new file mode 100644 index 0000000000000000000000000000000000000000..42fc7cdf9436680a30413c5bb07e02fd3230ec0c Binary files /dev/null and b/zh-cn/application-dev/ui/figures/drawing-feature2.png differ diff --git a/zh-cn/application-dev/ui/figures/drawing-feature3.png b/zh-cn/application-dev/ui/figures/drawing-feature3.png new file mode 100644 index 0000000000000000000000000000000000000000..c090ff948d7333f3dea17dd7ec54488638788c0c Binary files /dev/null and b/zh-cn/application-dev/ui/figures/drawing-feature3.png differ diff --git a/zh-cn/application-dev/ui/figures/drawing-feature4.png b/zh-cn/application-dev/ui/figures/drawing-feature4.png new file mode 100644 index 0000000000000000000000000000000000000000..bcfee4728b4d5fc9bfc57e6bb743e708ad0b2379 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/drawing-feature4.png differ diff --git a/zh-cn/application-dev/ui/figures/drawing-feature5.png b/zh-cn/application-dev/ui/figures/drawing-feature5.png new file mode 100644 index 0000000000000000000000000000000000000000..e70c63ed2f601cf4cd30f319dc6ebd74f216c909 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/drawing-feature5.png differ diff --git a/zh-cn/application-dev/ui/figures/drawing-feature6.png b/zh-cn/application-dev/ui/figures/drawing-feature6.png new file mode 100644 index 0000000000000000000000000000000000000000..772bd122cd1ecb252625f59af5ea3e5ff61689fc Binary files /dev/null and b/zh-cn/application-dev/ui/figures/drawing-feature6.png differ diff --git a/zh-cn/application-dev/ui/figures/drawing-feature7.png b/zh-cn/application-dev/ui/figures/drawing-feature7.png new file mode 100644 index 0000000000000000000000000000000000000000..c77366f46008f173bc117f95bed6bc7827af11cd Binary files /dev/null and b/zh-cn/application-dev/ui/figures/drawing-feature7.png differ diff --git a/zh-cn/application-dev/ui/figures/drawing-feature8.png b/zh-cn/application-dev/ui/figures/drawing-feature8.png new file mode 100644 index 0000000000000000000000000000000000000000..17cdf2ba3b6e3eeabbe93ed3115c34801634ba8e Binary files /dev/null and b/zh-cn/application-dev/ui/figures/drawing-feature8.png differ diff --git a/zh-cn/application-dev/ui/figures/flex.png b/zh-cn/application-dev/ui/figures/flex.png new file mode 100644 index 0000000000000000000000000000000000000000..848ceef3873ed6f83466d9ab42f6aa68cb341fe9 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/flex.png differ diff --git a/zh-cn/application-dev/ui/figures/flex1.PNG b/zh-cn/application-dev/ui/figures/flex1.PNG new file mode 100644 index 0000000000000000000000000000000000000000..cb125f009c7473782b463689466708d49ae474e0 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/flex1.PNG differ diff --git a/zh-cn/application-dev/ui/figures/flexExample.png b/zh-cn/application-dev/ui/figures/flexExample.png new file mode 100644 index 0000000000000000000000000000000000000000..73d4e3407dad6422e640dc8a27a4347c2c73dd9d Binary files /dev/null and b/zh-cn/application-dev/ui/figures/flexExample.png differ diff --git a/zh-cn/application-dev/ui/figures/flexbasis.png b/zh-cn/application-dev/ui/figures/flexbasis.png new file mode 100644 index 0000000000000000000000000000000000000000..df26a3272410052e3df94b2c4207015d5d23b613 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/flexbasis.png differ diff --git a/zh-cn/application-dev/ui/figures/flexgrow.png b/zh-cn/application-dev/ui/figures/flexgrow.png new file mode 100644 index 0000000000000000000000000000000000000000..9c2b84e0e070e67613504dcb52ea02acb6ed72b9 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/flexgrow.png differ diff --git a/zh-cn/application-dev/ui/figures/flexshrink.png b/zh-cn/application-dev/ui/figures/flexshrink.png new file mode 100644 index 0000000000000000000000000000000000000000..20ddfe6941c5313b1054f1d479da8b24014c3928 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/flexshrink.png differ diff --git a/zh-cn/application-dev/ui/figures/gridExp1.png b/zh-cn/application-dev/ui/figures/gridExp1.png new file mode 100644 index 0000000000000000000000000000000000000000..6767d92cee335418b9c82aa842359dfce1d887c9 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/gridExp1.png differ diff --git a/zh-cn/application-dev/ui/figures/gridExp2.png b/zh-cn/application-dev/ui/figures/gridExp2.png new file mode 100644 index 0000000000000000000000000000000000000000..c484c27c079f3490b32d7e6c2c8e3f0b84a0151a Binary files /dev/null and b/zh-cn/application-dev/ui/figures/gridExp2.png differ diff --git a/zh-cn/application-dev/ui/figures/griditem.png b/zh-cn/application-dev/ui/figures/griditem.png new file mode 100644 index 0000000000000000000000000000000000000000..9560e2291add8a9117be6a5ccb90033b960190d5 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/griditem.png differ diff --git a/zh-cn/application-dev/ui/figures/gridlayout.png b/zh-cn/application-dev/ui/figures/gridlayout.png new file mode 100644 index 0000000000000000000000000000000000000000..cc0db8ce530d60191adf8ffaefdbf11b97305067 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/gridlayout.png differ diff --git a/zh-cn/application-dev/ui/figures/gutter1.png b/zh-cn/application-dev/ui/figures/gutter1.png new file mode 100644 index 0000000000000000000000000000000000000000..3b246c32f1079b06c18c1a14cbcb286c241a8623 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/gutter1.png differ diff --git a/zh-cn/application-dev/ui/figures/gutter2.png b/zh-cn/application-dev/ui/figures/gutter2.png new file mode 100644 index 0000000000000000000000000000000000000000..534c169420509639cf21b30b41d65ccb34758b66 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/gutter2.png differ diff --git a/zh-cn/application-dev/ui/figures/isVisible.gif b/zh-cn/application-dev/ui/figures/isVisible.gif new file mode 100644 index 0000000000000000000000000000000000000000..bdb7b5ae5fe49adfaf4eb48c1533e4fe599be612 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/isVisible.gif differ diff --git a/zh-cn/application-dev/ui/figures/justifyContent.png b/zh-cn/application-dev/ui/figures/justifyContent.png new file mode 100644 index 0000000000000000000000000000000000000000..2e997f9cba6ce5c2ad93c1f2e33728b7db17bdd3 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/justifyContent.png differ diff --git a/zh-cn/application-dev/ui/figures/layoutWeight.gif b/zh-cn/application-dev/ui/figures/layoutWeight.gif new file mode 100644 index 0000000000000000000000000000000000000000..b7d0cdeeb268f96427c67daeb1673c5ec1b55ed0 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/layoutWeight.gif differ diff --git a/zh-cn/application-dev/ui/figures/lifecycle.PNG b/zh-cn/application-dev/ui/figures/lifecycle.PNG new file mode 100644 index 0000000000000000000000000000000000000000..a9b5769ad867f880dbe2b746b15de80cadbf799e Binary files /dev/null and b/zh-cn/application-dev/ui/figures/lifecycle.PNG differ diff --git a/zh-cn/application-dev/ui/figures/list1.gif b/zh-cn/application-dev/ui/figures/list1.gif new file mode 100644 index 0000000000000000000000000000000000000000..f421df651539da975e30d2294598e587e44d665e Binary files /dev/null and b/zh-cn/application-dev/ui/figures/list1.gif differ diff --git a/zh-cn/application-dev/ui/figures/list2.gif b/zh-cn/application-dev/ui/figures/list2.gif new file mode 100644 index 0000000000000000000000000000000000000000..97d8e42b844537f19ec1fab10aca7af58a45c0a4 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/list2.gif differ diff --git a/zh-cn/application-dev/ui/figures/listcolumn.gif b/zh-cn/application-dev/ui/figures/listcolumn.gif new file mode 100644 index 0000000000000000000000000000000000000000..4c0d4453b6e8d1207452e65d47c4867d77206115 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/listcolumn.gif differ diff --git a/zh-cn/application-dev/ui/figures/listrow.gif b/zh-cn/application-dev/ui/figures/listrow.gif new file mode 100644 index 0000000000000000000000000000000000000000..16b77e79d3288a84b47feb7b99beac0392a2e4f5 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/listrow.gif differ diff --git a/zh-cn/application-dev/ui/figures/mainCenter.png b/zh-cn/application-dev/ui/figures/mainCenter.png new file mode 100644 index 0000000000000000000000000000000000000000..30aa156d5ab296c25e30958cbd3f83ac35de88d1 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/mainCenter.png differ diff --git a/zh-cn/application-dev/ui/figures/mainEnd.png b/zh-cn/application-dev/ui/figures/mainEnd.png new file mode 100644 index 0000000000000000000000000000000000000000..fea2431892d09a06f067b438ae9462a09ad97ed0 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/mainEnd.png differ diff --git a/zh-cn/application-dev/ui/figures/mainSpacearound.png b/zh-cn/application-dev/ui/figures/mainSpacearound.png new file mode 100644 index 0000000000000000000000000000000000000000..0398af5f8f1a4dece7057ec3b1a852e1518933ef Binary files /dev/null and b/zh-cn/application-dev/ui/figures/mainSpacearound.png differ diff --git a/zh-cn/application-dev/ui/figures/mainSpacebetween.png b/zh-cn/application-dev/ui/figures/mainSpacebetween.png new file mode 100644 index 0000000000000000000000000000000000000000..d230aa1e735c0964581d1cf17d18af5152a5b466 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/mainSpacebetween.png differ diff --git a/zh-cn/application-dev/ui/figures/mainSpaceevenly.png b/zh-cn/application-dev/ui/figures/mainSpaceevenly.png new file mode 100644 index 0000000000000000000000000000000000000000..d22917514351643139709069af9f78419be7c748 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/mainSpaceevenly.png differ diff --git a/zh-cn/application-dev/ui/figures/mainStart.png b/zh-cn/application-dev/ui/figures/mainStart.png new file mode 100644 index 0000000000000000000000000000000000000000..207577b642507badc1b8064ab2f75c51130e58dd Binary files /dev/null and b/zh-cn/application-dev/ui/figures/mainStart.png differ diff --git a/zh-cn/application-dev/ui/figures/offset.gif b/zh-cn/application-dev/ui/figures/offset.gif new file mode 100644 index 0000000000000000000000000000000000000000..13d5614f4cfa0ede034e44f9fc333b1d55e891ff Binary files /dev/null and b/zh-cn/application-dev/ui/figures/offset.gif differ diff --git a/zh-cn/application-dev/ui/figures/offset1.png b/zh-cn/application-dev/ui/figures/offset1.png new file mode 100644 index 0000000000000000000000000000000000000000..e760daef7809d60e1c7b9323bffc267f592c8fc5 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/offset1.png differ diff --git a/zh-cn/application-dev/ui/figures/offset2.gif b/zh-cn/application-dev/ui/figures/offset2.gif new file mode 100644 index 0000000000000000000000000000000000000000..b517e892ed6ff4ad337e57d044aa518ff78a8792 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/offset2.gif differ diff --git a/zh-cn/application-dev/ui/figures/order1.png b/zh-cn/application-dev/ui/figures/order1.png new file mode 100644 index 0000000000000000000000000000000000000000..297dea381d85074e91edfb664bac5b8e3151f7bb Binary files /dev/null and b/zh-cn/application-dev/ui/figures/order1.png differ diff --git a/zh-cn/application-dev/ui/figures/order2.gif b/zh-cn/application-dev/ui/figures/order2.gif new file mode 100644 index 0000000000000000000000000000000000000000..315c82e417d240d0624a8206c9adf47c4c0a3ec3 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/order2.gif differ diff --git a/zh-cn/application-dev/ui/figures/position.gif b/zh-cn/application-dev/ui/figures/position.gif new file mode 100644 index 0000000000000000000000000000000000000000..67811987caa4b35beaea64da68e7d3786db52a58 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/position.gif differ diff --git a/zh-cn/application-dev/ui/figures/row.png b/zh-cn/application-dev/ui/figures/row.png new file mode 100644 index 0000000000000000000000000000000000000000..d7fced9fe4a9fc618dee88ae95cc2f04a34bb3c3 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/row.png differ diff --git a/zh-cn/application-dev/ui/figures/rowalign.png b/zh-cn/application-dev/ui/figures/rowalign.png new file mode 100644 index 0000000000000000000000000000000000000000..1f87579bb75ea031951dc073f0cd0a3a65698ee6 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/rowalign.png differ diff --git a/zh-cn/application-dev/ui/figures/rowjustify.png b/zh-cn/application-dev/ui/figures/rowjustify.png new file mode 100644 index 0000000000000000000000000000000000000000..7ed6dfc34d5c3dee1202925b373d5c7b7928c248 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/rowjustify.png differ diff --git a/zh-cn/application-dev/ui/figures/rowspace.png b/zh-cn/application-dev/ui/figures/rowspace.png new file mode 100644 index 0000000000000000000000000000000000000000..9bf2d2da0b1634d8051214908b83bc5e41f1702d Binary files /dev/null and b/zh-cn/application-dev/ui/figures/rowspace.png differ diff --git a/zh-cn/application-dev/ui/figures/scrollcolumn.gif b/zh-cn/application-dev/ui/figures/scrollcolumn.gif new file mode 100644 index 0000000000000000000000000000000000000000..80ee68958c80502be31ddcecc22f198c14a4c335 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/scrollcolumn.gif differ diff --git a/zh-cn/application-dev/ui/figures/scrollrow.gif b/zh-cn/application-dev/ui/figures/scrollrow.gif new file mode 100644 index 0000000000000000000000000000000000000000..14f3d25cbf137366ce3c2bb93f683d75a9297597 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/scrollrow.gif differ diff --git a/zh-cn/application-dev/ui/figures/span1.png b/zh-cn/application-dev/ui/figures/span1.png new file mode 100644 index 0000000000000000000000000000000000000000..fe59d441c386189694b3185e23279f14c6dd4a97 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/span1.png differ diff --git a/zh-cn/application-dev/ui/figures/span2.gif b/zh-cn/application-dev/ui/figures/span2.gif new file mode 100644 index 0000000000000000000000000000000000000000..eba3ab4a41c44642c47f1864858094771043dcc7 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/span2.gif differ diff --git a/zh-cn/application-dev/ui/figures/stack1.png b/zh-cn/application-dev/ui/figures/stack1.png new file mode 100644 index 0000000000000000000000000000000000000000..87574a9c72652fdda57f54405b675b622f804479 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stack1.png differ diff --git a/zh-cn/application-dev/ui/figures/stack2.png b/zh-cn/application-dev/ui/figures/stack2.png new file mode 100644 index 0000000000000000000000000000000000000000..6a518ad4ac87cc91ef44894d15774cb3d60568d1 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stack2.png differ diff --git a/zh-cn/application-dev/ui/figures/stackbottom.png b/zh-cn/application-dev/ui/figures/stackbottom.png new file mode 100644 index 0000000000000000000000000000000000000000..d4a1d76611bb608becded581f24b69b48185d96d Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stackbottom.png differ diff --git a/zh-cn/application-dev/ui/figures/stackbottomend.png b/zh-cn/application-dev/ui/figures/stackbottomend.png new file mode 100644 index 0000000000000000000000000000000000000000..6f34877f2ed88390eca31bab2370c187d012fd73 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stackbottomend.png differ diff --git a/zh-cn/application-dev/ui/figures/stackbottomstart.png b/zh-cn/application-dev/ui/figures/stackbottomstart.png new file mode 100644 index 0000000000000000000000000000000000000000..d6539785544de70d20ce382465974cfb24d955c7 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stackbottomstart.png differ diff --git a/zh-cn/application-dev/ui/figures/stackcenter.png b/zh-cn/application-dev/ui/figures/stackcenter.png new file mode 100644 index 0000000000000000000000000000000000000000..0ba76abeba693ae3d1654b6b3fbde91661669237 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stackcenter.png differ diff --git a/zh-cn/application-dev/ui/figures/stackend.png b/zh-cn/application-dev/ui/figures/stackend.png new file mode 100644 index 0000000000000000000000000000000000000000..2bf91c717a94ce47a2f3c9ca766eb89fae513a71 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stackend.png differ diff --git a/zh-cn/application-dev/ui/figures/stackstart.png b/zh-cn/application-dev/ui/figures/stackstart.png new file mode 100644 index 0000000000000000000000000000000000000000..3936627a8d4134acd3e02833cb2c3c593f52c66e Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stackstart.png differ diff --git a/zh-cn/application-dev/ui/figures/stacktop.png b/zh-cn/application-dev/ui/figures/stacktop.png new file mode 100644 index 0000000000000000000000000000000000000000..01a649049c24df96510727918689455ad9898559 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stacktop.png differ diff --git a/zh-cn/application-dev/ui/figures/stacktopend.png b/zh-cn/application-dev/ui/figures/stacktopend.png new file mode 100644 index 0000000000000000000000000000000000000000..95e8fef4f2c2a6905ed0efc00e9cacd14852c5de Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stacktopend.png differ diff --git a/zh-cn/application-dev/ui/figures/stacktopstart.png b/zh-cn/application-dev/ui/figures/stacktopstart.png new file mode 100644 index 0000000000000000000000000000000000000000..7b742984076e7066cca56a5647bfa3c096b317f2 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stacktopstart.png differ diff --git a/zh-cn/application-dev/ui/figures/width.gif b/zh-cn/application-dev/ui/figures/width.gif new file mode 100644 index 0000000000000000000000000000000000000000..34007100b438eb6fc47dd5f48eda6033bc759412 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/width.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image1_0000001169918548.gif b/zh-cn/application-dev/ui/figures/zh-cn_image1_0000001169918548.gif new file mode 100644 index 0000000000000000000000000000000000000000..aac78d2abe528a9781e7e07ed2e46a4bf56d7891 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/zh-cn_image1_0000001169918548.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image1_0000001170008198.gif b/zh-cn/application-dev/ui/figures/zh-cn_image1_0000001170008198.gif new file mode 100644 index 0000000000000000000000000000000000000000..a7d9b572abb833cc7cd52e63d25c4c261a10af65 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/zh-cn_image1_0000001170008198.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image1_0000001204776353.png b/zh-cn/application-dev/ui/figures/zh-cn_image1_0000001204776353.png new file mode 100644 index 0000000000000000000000000000000000000000..25330d63162d9999d2c57d3c33bcc20731df7851 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/zh-cn_image1_0000001204776353.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001168410342.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001168410342.png index 5accde8bbb1146e3bade9d6cc4d35127dd58b86f..67b8d1571853fe13079a13ed32aff66bc2fc4452 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001168410342.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001168410342.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001168728872.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001168728872.png index b6045521e10cf66733222c0b85b1b65dd20cb66f..ddf24cd804055371cbd8a753089263f6bcc32b79 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001168728872.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001168728872.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169678922.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169678922.png index 546fb29b1f18573353d11d5515f444bf720fcf52..9c89860f26331dc11cf8104711be1ad3be918111 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169678922.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169678922.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169759552.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169759552.png index a6d0026ba316551ff0819493b84ae8c9cb063289..f910230ebfab9c5315eb1c2bc99f0ca35b3cbe23 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169759552.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169759552.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169918548.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169918548.gif index 0173419db3fd06cc5d328dd6931a2c76664f4596..b59ae3d79b2bc926634a50c1f3f6aecce247763c 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169918548.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169918548.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170008198.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170008198.gif index 26152ef9f22387729561bdddb9fa7d50019e08cb..c88150c77afccf736d42fe7253df27f2b1d27cd5 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170008198.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170008198.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170167520.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170167520.png new file mode 100644 index 0000000000000000000000000000000000000000..2441a46f00b3083dfaa8ec2dcdb1760aa7e2aeb7 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170167520.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170411978.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170411978.gif index b07f4a9f456b5bccab8fe2a2dc997818efad5ddb..a7d9b572abb833cc7cd52e63d25c4c261a10af65 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170411978.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170411978.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204537865.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204537865.png index f6b70b8f1ef886bf8ed6f26e148bddee0b163fd5..60160d18d66fef9a5b65a4c5675fe91873e95582 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204537865.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204537865.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204538065.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204538065.png index a84303ae2d68affe3f5702317d9f2bf951c90698..b775a2bf408dd710861afa0dfa9f756d5181e811 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204538065.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204538065.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204776353.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204776353.png index d0e9cf658b9b396873f24666945bb796384c2041..b27a7f5358c954fe7e1bd912358d29d456870c2a 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204776353.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204776353.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001213968747.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001213968747.png index 767315d2f69278028746341e79f88ad179930338..b60416b59cb77e096d615ba1b25d2b14056abe00 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001213968747.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001213968747.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214128687.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214128687.png index 653da4be405165f59cbbe570e9d4d64747fa7495..3f2f15792563ec89015abce1fcf30248b3c0288e 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214128687.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214128687.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214210217.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214210217.png index aaa0cbf699a302616ce142f43ea3b96df99d75ac..18abb7b725fcf0172f189c0f1cf70e9c5ae31642 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214210217.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214210217.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214998349.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214998349.png index fb85274edcd9b0a66eaa9e3da3b77e543c048cc8..6a845d64a542809c05f008eef5d1e1ed9d1c22a5 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214998349.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214998349.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215079443.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215079443.png index 49182b6d8f1c96dcbaac493179fdab3d4b9a7bd4..0a53a5742ac5fda3501a93f576b945e21bd2addf 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215079443.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215079443.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215199399.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215199399.png index 2923d13dcf52b856158b440de03df929abc4955b..c508bb8764c28f228e2c0a33dd6ee97e48dfe682 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215199399.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215199399.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215318403.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215318403.gif index 8e9c75334361806ac822c8c0f2c377c1679c6ca3..aac78d2abe528a9781e7e07ed2e46a4bf56d7891 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215318403.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215318403.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001224173302.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001224173302.png new file mode 100644 index 0000000000000000000000000000000000000000..68b537c0afc28896fc8d14d36a5d7190fcfa256c Binary files /dev/null and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001224173302.png differ diff --git a/zh-cn/application-dev/ui/ts-component-creation-re-initialization.md b/zh-cn/application-dev/ui/ts-component-creation-re-initialization.md deleted file mode 100644 index 86db59447ccb15bad9579553a1eef2e03e143d23..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/ui/ts-component-creation-re-initialization.md +++ /dev/null @@ -1,97 +0,0 @@ -# 组件创建和重新初始化 - -## 初始创建和渲染 - -1. 创建父组件ParentComp; - -2. 本地初始化ParentComp的状态变量isCountDown; - -3. 执行ParentComp的build函数; - -4. 创建Column内置组件; - 1. 创建Text内置组件,设置其文本展示内容,并将Text组件实例添加到Column中; - 2. 判断if条件,创建true分支上的组件; - 1. 创建Image内置组件,并设置其图片源地址; - 2. 使用给定的构造函数创建TimerComponent; - 1. 创建TimerComponent对象; - 2. 本地初始化成员变量初始值; - 3. 使用TimerComponent构造函数提供的参数更新成员变量的值; - 4. 执行TimerComponent的aboutToAppear函数; - 5. 执行TimerComponent的build函数,创建相应的UI描述结构; - 3. 创建Button内置组件,设置相应的内容。 - - -## 状态更新 - -用户单击按钮时: - -1. ParentComp的isCountDown状态变量的值更改为false; - -2. 执行ParentComp的build函数; - -3. Column内置组件会被框架重用并执行重新初始化; - -4. Column的子组件会重用内存中的对象,但会进行重新初始化; - 1. Text内置组件会被重用,但使用新的文本内容进行重新初始化; - 2. 判断if条件,使用false分支上的组件; - 1. 原来true分支上的组件不在使用,这些组件会进行销毁; - 1. 创建的Image内置组件实例进行销毁; - 2. TimerComponent组件实例进行销毁,aboutToDisappear函数被调用; - 2. 创建false分支上的组件; - 1. 创建Image内置组件,并设置其图片源地址; - 2. 使用给定的构造函数重新创建TimerComponent; - 3. 新创建的TimerComponent进行初始化,并调用aboutToAppear函数和build函数。 - 3. Button内置组件会被重用,但使用新的图片源地址。 - - -## 示例 - -```ts -// xxx.ets -@Entry -@Component -struct ParentComp { - @State isCountDown: boolean = true - build() { - Column() { - Text(this.isCountDown ? 'Count Down' : 'Stopwatch') - if (this.isCountDown) { - Image($r("app.media.countdown")).width(200).height(200) - TimerComponent({counter: 10, changePerSec: -1, showInColor: Color.Red}) - } else { - Image($r("app.media.stopwatch")).width(200).height(200) - TimerComponent({counter: 0, changePerSec: +1, showInColor: Color.Black }) - } - Button(this.isCountDown ? 'Switch to Stopwatch' : 'Switch to Count Down') - .onClick(() => {this.isCountDown = !this.isCountDown}) - } - } -} - -// Manage and display a count down / stop watch timer -@Component -struct TimerComponent { - @State counter: number = 0 - private changePerSec: number = -1 - private showInColor: Color = Color.Black - private timerId : number = -1 - - build() { - Text(`${this.counter}sec`) - .fontColor(this.showInColor) - } - - aboutToAppear() { - this.timerId = setInterval(() => {this.counter += this.changePerSec}, 1000) - } - - aboutToDisappear() { - if (this.timerId > 0) { - clearTimeout(this.timerId) - this.timerId = -1 - } - } -} -``` - -![](figures/zh-cn_image_0000001118642023.gif) \ No newline at end of file diff --git a/zh-cn/application-dev/ui/ts-custom-component-initialization.md b/zh-cn/application-dev/ui/ts-custom-component-initialization.md deleted file mode 100644 index 1433542af3203e3a54f6d883ef099b8f5438f52f..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/ui/ts-custom-component-initialization.md +++ /dev/null @@ -1,125 +0,0 @@ -# 自定义组件成员变量初始化 - -组件的成员变量可以通过两种方式初始化: - - -- 本地初始化,例如: - ```ts - @State counter: Counter = new Counter() - ``` - -- 在构造组件时通过构造参数初始化,例如: - ```ts - MyComponent({counter: $myCounter}) - ``` - - -具体允许哪种方式取决于状态变量的装饰器: - - -| 装饰器类型 | 本地初始化 | 通过构造函数参数初始化 | -| ------------ | ----- | ----------- | -| @State | 必须 | 可选 | -| @Prop | 禁止 | 必须 | -| @Link | 禁止 | 必须 | -| @StorageLink | 必须 | 禁止 | -| @StorageProp | 必须 | 禁止 | -| @Provide | 必须 | 可选 | -| @Consume | 禁止 | 禁止 | -| @ObjectLink | 禁止 | 必须 | -| 常规成员变量 | 推荐 | 可选 | - - -从上表中可以看出: - - -- @State变量需要本地初始化,初始化的值可以被构造参数覆盖; - -- @Prop和@Link变量必须且仅通过构造函数参数进行初始化。 - - -通过构造函数方法初始化成员变量,需要遵循如下规则: - - -| 从父组件中的变量(下)到子组件中的变量(右) | @State | @Link | @Prop | 常规变量 | -| ---------------------- | ------ | ----- | ----- | ---- | -| @State | 不允许 | 允许 | 允许 | 允许 | -| @Link | 不允许 | 允许 | 不推荐 | 允许 | -| @Prop | 不允许 | 不允许 | 允许 | 允许 | -| @StorageLink | 不允许 | 允许 | 不允许 | 允许 | -| @StorageProp | 不允许 | 不允许 | 不允许 | 允许 | -| 常规变量 | 允许 | 不允许 | 不允许 | 允许 | - - -从上表中可以看出: - - -- 父组件的常规变量可以用于初始化子组件的@State变量,但不能用于初始化@Link或@Prop变量。 - -- 父组件的@State变量可以初始化子组件的@Prop、@Link(通过$)或常规变量,但不能初始化子组件的@State变量。 - -- 父组件的@Link变量可以初始化子组件的@Link或常规变量。但是初始化子组件的@State成员是语法错误,此外不建议初始化@prop。 - -- 父组件的@Prop变量可以初始化子组件的常规变量或@Prop变量,但不能初始化子组件的@State或@Link变量。 - -- @StorageLink和@StorageProp不允许由父组件中传递到子组件。 - -- 除了上述规则外,还需要遵循TS的强类型规则。 - - -## 示例 - -```ts -// xxx.ets -class ClassA { - public a:number - constructor(a: number) { - this.a = a - } -} -@Entry -@Component -struct Parent { - @State parentState: ClassA = new ClassA(1) - - build() { - Column() { - Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { - CompA({ aState: new ClassA(2), aLink: $parentState }) - } - Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { - CompA({ aLink: $parentState }) - } - Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { - CompA({ aState: new ClassA(3), aLink: $parentState }) - } - } - } -} - -@Component -struct CompA { - @State aState: any = false - @Link aLink: ClassA - - build() { - Column() { - CompB({ bLink: $aLink, bProp: this.aState }) - CompB({ bLink: $aState, bProp: false }) - } - } -} - -@Component -struct CompB { - @Link bLink: ClassA - @Prop bProp: boolean - - build() { - Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { - Text(JSON.stringify(this.bLink.a)).fontSize(30) - Text(JSON.stringify(this.bProp)).fontSize(30).fontColor(Color.Red) - }.margin(10) - } -} -``` diff --git a/zh-cn/application-dev/ui/ts-custom-component-lifecycle-callbacks.md b/zh-cn/application-dev/ui/ts-custom-component-lifecycle-callbacks.md deleted file mode 100644 index 5a0126b00ae83f1e41792a2d60aa5032e5131525..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/ui/ts-custom-component-lifecycle-callbacks.md +++ /dev/null @@ -1,57 +0,0 @@ -# 自定义组件生命周期回调函数 - -自定义组件的生命周期回调函数用于通知用户该自定义组件的生命周期,这些回调函数是私有的,在运行时由开发框架在特定的时间进行调用,不能从应用程序中手动调用这些回调函数。 - - -## 生命周期回调函数定义 - -| 函数名 | 描述 | -| ---------------- | ------------------------------------------------------------ | -| aboutToAppear | 函数在创建自定义组件的新实例后,在执行其build函数之前执行。允许在aboutToAppear函数中改变状态变量,更改将在后续执行build函数中生效。 | -| aboutToDisappear | 函数在自定义组件析构销毁之前执行。不允许在aboutToDisappear函数中改变状态变量,特别是@Link变量的修改可能会导致应用程序行为不稳定。 | -| onPageShow | 页面每次显示时触发一次,包括路由过程、应用进入前后台等场景,仅@Entry修饰的自定义组件生效。 | -| onPageHide | 页面每次隐藏时触发一次,包括路由过程、应用进入前后台等场景,仅@Entry修饰的自定义组件生效。 | -| onBackPress | 当用户点击返回按钮时触发,仅\@Entry修饰的自定义组件生效。
- 返回true表示页面自己处理返回逻辑, 不进行页面路由。
- 返回false表示使用默认的返回逻辑。
- 不返回值会作为false处理。 | -| onMeasure9+ | 框架会在自定义组件确定尺寸时,将该自定义组件的子节点信息和自身的尺寸范围通过onMeasure传递给该自定义组件。不允许在onMeasure函数中改变状态变量 | -| onLayout9+ | 框架会在自定义组件布局时,将该自定义组件的子节点信息和自身的尺寸范围通过onLayout传递给该自定义组件。不允许在onLayout函数中改变状态变量 | - - -## 示例 - -```ts -// xxx.ets -@Entry -@Component -struct CountDownTimerComponent { - @State countDownFrom: number = 10 - private timerId: number = -1 - - aboutToAppear(): void { - this.timerId = setInterval(() => { - if (this.countDownFrom <= 1) { - clearTimeout(this.timerId) - } - this.countDownFrom -= 1 - }, 1000) // decr counter by 1 every second - } - - aboutToDisappear(): void { - if (this.timerId > 0) { - clearTimeout(this.timerId) - this.timerId = -1 - } - } - - build() { - Text(`${this.countDownFrom} sec left`) - } -} -``` - -上述示例表明,生命周期函数对于允许CountDownTimerComponent管理其计时器资源至关重要,类似的函数也包括异步从网络请求加载资源。 - - -> **说明:** -> - 允许在生命周期函数中使用Promise和异步回调函数,比如网络资源获取,定时器设置等; -> -> - 不允许在生命周期函数中使用async await。 diff --git a/zh-cn/application-dev/ui/ts-framework-directory.md b/zh-cn/application-dev/ui/ts-framework-directory.md deleted file mode 100644 index b20e3023475a0ced28afa89fb94ad2f02a75e077..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/ui/ts-framework-directory.md +++ /dev/null @@ -1,38 +0,0 @@ -# 目录结构 - - -FA应用的ArkTS模块(entry/src/main)的典型开发目录结构如下: - - -![zh-cn_image_0000001182200571](figures/zh-cn_image_0000001182200571.png) - - -**目录结构中文件分类如下:** - - -.ets结尾的ArkTS文件,用于描述UI布局、样式、事件交互和页面逻辑。 - -**各个文件夹和文件的作用:** - -- **app.ets**文件用于全局应用逻辑和应用生命周期管理。 - -- **pages**目录用于存放所有页面。 - -- **common**目录用于存放公共代码文件,比如:自定义组件和公共方法。 - - -> **说明:** -> -> - 资源目录resources文件夹位于src/main下,此目录下资源文件的详细规范以及子目录结构规范参看[资源文件的分类](ui-ts-basic-resource-file-categories.md)。 ->- 页面支持导入TypeScript和JavaScript文件。 - -**js标签配置:** - - 开发框架需要在配置文件中标识相关的js标签,其中的每个元素代表一个JS模块的信息,包含了实例名称、页面路由、视图窗口等。 - - -> **说明:** -> -> FA模型请参考 [表22 js对象的内部结构说明](../quick-start/package-structure.md#module对象的内部结构)。 -> -> Stage模型请参考 [表3 module对象内部结构说明](../quick-start/stage-structure.md#module对象内部结构)。 diff --git a/zh-cn/application-dev/ui/ts-resource-access.md b/zh-cn/application-dev/ui/ts-resource-access.md deleted file mode 100644 index a2ea1141108398203160e8fa752d1cc4727c5889..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/ui/ts-resource-access.md +++ /dev/null @@ -1,154 +0,0 @@ -# 资源访问 - - -## 访问应用资源 - -在工程中,通过```"$r('app.type.name')"```的形式引用应用资源。app代表是应用内resources目录中定义的资源;type代表资源类型(或资源的存放位置),可以取“color”、“float”、“string”、“plural”、“media”,name代表资源命名,由开发者定义资源时确定。 - -引用rawfile下资源时使用```"$rawfile('filename')"```的形式,filename需要表示为rawfile目录下的文件相对路径,文件名需要包含后缀,路径开头不可以以"/"开头。 - -> **说明:** -> -> 资源描述符不能拼接使用,仅支持普通字符串如`'app.type.name'`。 -> -> `$r`返回值为Resource对象,可通过[getString](../reference/apis/js-apis-resource-manager.md#getstring) 方法获取对应的字符串。 - -在xxx.ets文件中,可以使用在resources目录中定义的资源。 - -```ts -Text($r('app.string.string_hello')) - .fontColor($r('app.color.color_hello')) - .fontSize($r('app.float.font_hello')) -} - -Text($r('app.string.string_world')) - .fontColor($r('app.color.color_world')) - .fontSize($r('app.float.font_world')) -} - -Text($r('app.string.message_arrive', "five of the clock")) // 引用string资源,$r的第二个参数用于替换%s - .fontColor($r('app.color.color_hello')) - .fontSize($r('app.float.font_hello')) -} - -Text($r('app.plural.eat_apple', 5, 5)) // plural$r引用,第一个指定plural资源,第二个参数指定单复数的数量,此处第三个数字为对%d的替换 - .fontColor($r('app.color.color_world')) - .fontSize($r('app.float.font_world')) -} - -Image($r('app.media.my_background_image')) // media资源的$r引用 - -Image($rawfile('test.png')) // rawfile$r引用rawfile目录下图片 - -Image($rawfile('newDir/newTest.png')) // rawfile$r引用rawfile目录下图片 -``` -## 访问系统资源 - -系统资源包含色彩、圆角、字体、间距、字符串及图片等。通过使用系统资源,不同的开发者可以开发出具有相同视觉风格的应用。 - - -开发者可以通过```“$r('sys.type.resource_id')”```的形式引用系统资源。sys代表是系统资源;type代表资源类型,可以取“color”、“float”、“string”、“media”;resource_id代表资源id。 - -```ts -Text('Hello') - .fontColor($r('sys.color.ohos_id_color_emphasize')) - .fontSize($r('sys.float.ohos_id_text_size_headline1')) - .fontFamily($r('sys.string.ohos_id_text_font_family_medium')) - .backgroundColor($r('sys.color.ohos_id_color_palette_aux1')) -Image($r('sys.media.ohos_app_icon')) - .border({color: $r('sys.color.ohos_id_color_palette_aux1'), radius: $r('sys.float.ohos_id_corner_radius_button'), width: 2}) - .margin({top: $r('sys.float.ohos_id_elements_margin_horizontal_m'), bottom: $r('sys.float.ohos_id_elements_margin_horizontal_l')}) - .height(200) - .width(300) -``` -## 资源文件示例 - -color.json文件的内容如下: - - -```json -{ - "color": [ - { - "name": "color_hello", - "value": "#ffff0000" - }, - { - "name": "color_world", - "value": "#ff0000ff" - } - ] -} -``` - -float.json文件的内容如下: - - -```json -{ - "float":[ - { - "name":"font_hello", - "value":"28.0fp" - }, - { - "name":"font_world", - "value":"20.0fp" - } - ] -} -``` - -string.json文件的内容如下: - - -```json -{ - "string":[ - { - "name":"string_hello", - "value":"Hello" - }, - { - "name":"string_world", - "value":"World" - }, - { - "name":"message_arrive", - "value":"We will arrive at %s." - } - ] -} -``` - -plural.json文件的内容如下: - - -```json -{ - "plural":[ - { - "name":"eat_apple", - "value":[ - { - "quantity":"one", - "value":"%d apple" - }, - { - "quantity":"other", - "value":"%d apples" - } - ] - } - ] -} -``` - - - - -## 相关实例 - -针对访问应用资源,有以下相关实例可供参考: - -- [`ResourceManager`:资源管理器(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/ResourceManager) diff --git a/zh-cn/application-dev/ui/ui-ts-animation-feature.md b/zh-cn/application-dev/ui/ui-ts-animation-feature.md new file mode 100644 index 0000000000000000000000000000000000000000..16869cea7b746874566257d31d4e9448d0a3967f --- /dev/null +++ b/zh-cn/application-dev/ui/ui-ts-animation-feature.md @@ -0,0 +1,343 @@ +# 添加动画效果 + +动画主要包含了组件动画和页面间动画,并提供了[插值计算](../reference/apis/js-apis-curve.md)和[矩阵变换](../reference/apis/js-apis-matrix4.md)的动画能力接口,让开发者极大程度的自主设计动画效果。 + +在本节主要完成两个动画效果: + +1. 启动页的闪屏动画,即Logo图标的渐出和放大效果; +2. 食物列表页和食物详情页的共享元素转场动画效果。 + +## animateTo实现闪屏动画 + +组件动画包括属性动画和animateTo显式动画: + +1. 属性动画:设置组件通用属性变化的动画效果。 +2. 显式动画:设置组件从状态A到状态B的变化动画效果,包括样式、位置信息和节点的增加删除等,开发者无需关注变化过程,只需指定起点和终点的状态。animateTo还提供播放状态的回调接口,是对属性动画的增强与封装。 + +闪屏页面的动画效果是Logo图标的渐出和放大,动画结束后跳转到食物分类列表页面。接下来,我们就使用animateTo来实现启动页动画的闪屏效果。 + +1. 动画效果自动播放。闪屏动画的预期效果是,进入Logo页面后,animateTo动画效果自动开始播放,可以借助于组件显隐事件的回调接口来实现。调用Shape的onAppear方法,设置其显式动画。 + + ```ts + Shape() { + ... + } + .onAppear(() => { + animateTo() + }) + ``` + +2. 创建opacity和scale数值的成员变量,用装饰器@State修饰。表示其为有状态的数据,即改变会触发页面的刷新。 + + ```ts + @Entry + @Component + struct Logo { + @State private opacityValue: number = 0 + @State private scaleValue: number = 0 + build() { + Shape() { + ... + } + .scale({ x: this.scaleValue, y: this.scaleValue }) + .opacity(this.opacityValue) + .onAppear(() => { + animateTo() + }) + } + } + ``` + +3. 设置animateTo的动画曲线curve。Logo的加速曲线为先慢后快,使用贝塞尔曲线cubicBezier,cubicBezier(0.4, 0, 1, 1)。 + + 需要使用动画能力接口中的插值计算,首先要导入curves模块。 + + ```ts + import Curves from '@ohos.curves' + ``` + + @ohos.curves模块提供了线性Curve. Linear、阶梯step、三阶贝塞尔(cubicBezier)和弹簧(spring)插值曲线的初始化函数,可以根据入参创建一个插值曲线对象。 + + ```ts + @Entry + @Component + struct Logo { + @State private opacityValue: number = 0 + @State private scaleValue: number = 0 + private curve1 = Curves.cubicBezier(0.4, 0, 1, 1) + + build() { + Shape() { + ... + } + .scale({ x: this.scaleValue, y: this.scaleValue }) + .opacity(this.opacityValue) + .onAppear(() => { + animateTo({ + curve: this.curve1 + }) + }) + } + } + ``` + +4. 设置动画时长为1s,延时0.1s开始播放,设置显示动效event的闭包函数,即起点状态到终点状态为透明度opacityValue和大小scaleValue从0到1,实现Logo的渐出和放大效果。 + + ```ts + @Entry + @Component + struct Logo { + @State private opacityValue: number = 0 + @State private scaleValue: number = 0 + private curve1 = Curves.cubicBezier(0.4, 0, 1, 1) + + build() { + Shape() { + ... + } + .scale({ x: this.scaleValue, y: this.scaleValue }) + .opacity(this.opacityValue) + .onAppear(() => { + animateTo({ + duration: 2000, + curve: this.curve1, + delay: 100, + }, () => { + this.opacityValue = 1 + this.scaleValue = 1 + }) + }) + } + } + ``` + +5. 闪屏动画播放结束后定格1s,进入FoodCategoryList页面。设置animateTo的onFinish回调接口,调用定时器Timer的setTimeout接口延时1s后,调用router.replace,显示FoodCategoryList页面。 + + ```ts + import router from '@ohos.router' + + @Entry + @Component + struct Logo { + @State private opacityValue: number = 0 + @State private scaleValue: number = 0 + private curve1 = Curves.cubicBezier(0.4, 0, 1, 1) + + build() { + Shape() { + ... + } + .scale({ x: this.scaleValue, y: this.scaleValue }) + .opacity(this.opacityValue) + .onAppear(() => { + + animateTo({ + duration: 2000, + curve: this.curve1, + delay: 100, + onFinish: () => { + setTimeout(() => { + router.replace({ url: "pages/FoodCategoryList" }) + }, 1000); + } + }, () => { + this.opacityValue = 1 + this.scaleValue = 1 + }) + }) + } + } + ``` + + 整体代码如下。 + + ```ts + import Curves from '@ohos.curves' + import router from '@ohos.router' + + @Entry + @Component + struct Logo { + @State private opacityValue: number = 0 + @State private scaleValue: number = 0 + private curve1 = Curves.cubicBezier(0.4, 0, 1, 1) + private pathCommands1: string = 'M319.5 128.1 c103.5 0 187.5 84 187.5 187.5 v15 a172.5 172.5 0 0 3 -172.5 172.5 H198 a36 36 0 0 3 -13.8 -1 207 207 0 0 0 87 -372 h48.3 z' + private pathCommands2: string = 'M270.6 128.1 h48.6 c51.6 0 98.4 21 132.3 54.6 a411 411 0 0 3 -45.6 123 c-25.2 45.6 -56.4 84 -87.6 110.4 a206.1 206.1 0 0 0 -47.7 -288 z' + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Shape() { + Path() + .commands('M162 128.7 a222 222 0 0 1 100.8 374.4 H198 a36 36 0 0 3 -36 -36') + .fill(Color.White) + Path() + .commands(this.pathCommands1) + .fill('none') + .linearGradient( + { + angle: 30, + colors: [["#C4FFA0", 0], ["#ffffff", 1]] + }) + .clip(new Path().commands(this.pathCommands1)) + + Path() + .commands(this.pathCommands2) + .fill('none') + .linearGradient( + { + angle: 50, + colors: [['#8CC36A', 0.1], ["#B3EB90", 0.4], ["#ffffff", 0.7]] + }) + .clip(new Path().commands(this.pathCommands2)) + } + .height('630px') + .width('630px') + .scale({ x: this.scaleValue, y: this.scaleValue }) + .opacity(this.opacityValue) + .onAppear(() => { + animateTo({ + duration: 2000, + curve: this.curve1, + delay: 100, + onFinish: () => { + setTimeout(() => { + router.replace({ url: "pages/FoodCategoryList" }) + }, 1000); + } + }, () => { + this.opacityValue = 1 + this.scaleValue = 1 + }) + }) + + Text('Healthy Diet') + .fontSize(26) + .fontColor(Color.White) + .margin({ top: 300 }) + + Text('Healthy life comes from a balanced diet') + .fontSize(17) + .fontColor(Color.White) + .margin({ top: 4 }) + } + .width('100%') + .height('100%') + .linearGradient( + { + angle: 180, + colors: [['#BDE895', 0.1], ["#95DE7F", 0.6], ["#7AB967", 1]] + }) + } + } + ``` + + ![animation-feature](figures/animation-feature.gif) + +## 页面转场动画 + +食物分类列表页和食物详情页之间的共享元素转场,即点击FoodListItem/FoodGridItem后,食物缩略图会放大,随着页面跳转,到食物详情页的大图。 + +1. 设置FoodListItem和FoodGridItem的Image组件的共享元素转场方法(sharedTransition)。转场id为foodItem.id,转场动画时长为1s,延时0.1s播放,变化曲线为贝塞尔曲线Curves.cubicBezier(0.2, 0.2, 0.1, 1.0) ,需引入curves模块。 + + 共享转场时会携带当前元素的被设置的属性,所以创建Row组件,使其作为Image的父组件,设置背景颜色在Row上。 + + 在FoodListItem的Image组件上设置autoResize为false,因为image组件默认会根据最终展示的区域,去调整图源的大小,以优化图片渲染性能。在转场动画中,图片在放大的过程中会被重新加载,所以为了转场动画的流畅,autoResize设置为false。 + + ```ts + // FoodList.ets + import Curves from '@ohos.curves' + + @Component + struct FoodListItem { + private foodItem: FoodData + build() { + Navigator({ target: 'pages/FoodDetail' }) { + Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { + Row() { + Image(this.foodItem.image) + .objectFit(ImageFit.Contain) + .autoResize(false) + .height(40) + .width(40) + .sharedTransition(this.foodItem.id, { duration: 1000, curve: Curves.cubicBezier(0.2, 0.2, 0.1, 1.0), delay: 100 }) + } + + .margin({ right: 16 }) + Text(this.foodItem.name) + .fontSize(14) + .flexGrow(1) + Text(this.foodItem.calories + ' kcal') + .fontSize(14) + } + .height(64) + } + .params({ foodData: this.foodItem }) + .margin({ right: 24, left:32 }) + } + } + + @Component + struct FoodGridItem { + private foodItem: FoodData + build() { + Column() { + Row() { + Image(this.foodItem.image) + .objectFit(ImageFit.Contain) + .autoResize(false) + .height(152) + .width('100%') + .sharedTransition(this.foodItem.id, { duration: 1000, curve: Curves.cubicBezier(0.2, 0.2, 0.1, 1.0), delay: 100 }) + } + Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { + Text(this.foodItem.name) + .fontSize(14) + .flexGrow(1) + .padding({ left: 8 }) + Text(this.foodItem.calories + 'kcal') + .fontSize(14) + .margin({ right: 6 }) + } + .height(32) + .width('100%') + .backgroundColor('#FFe5e5e5') + } + .height(184) + .width('100%') + .onClick(() => { + router.push({ url: 'pages/FoodDetail', params: { foodId: this.foodItem } }) + }) + } + } + + + ``` + +2. 设置FoodDetail页面的FoodImageDisplay的Image组件的共享元素转场方法(sharedTransition)。设置方法同上。 + + ```ts + import Curves from '@ohos.curves' + + @Component + struct FoodImageDisplay { + private foodItem: FoodData + build() { + Stack({ alignContent: Alignment.BottomStart }) { + Image(this.foodItem.image) + .objectFit(ImageFit.Contain) + .sharedTransition(this.foodItem.id, { duration: 1000, curve: Curves.cubicBezier(0.2, 0.2, 0.1, 1.0), delay: 100 }) + Text(this.foodItem.name) + .fontSize(26) + .fontWeight(500) + .margin({ left: 26, bottom: 17.4 }) + } + .height(357) + } + } + ``` + + ![animation-feature1](figures/animation-feature1.gif) + + 通过对绘制组件和动画的学习,我们已完成了启动Logo的绘制、启动页动画和页面间的转场动画,声明式UI框架提供了丰富的动效接口,合理地应用和组合可以让应用更具有设计感。 + + diff --git a/zh-cn/application-dev/ui/ui-ts-basic-components-button.md b/zh-cn/application-dev/ui/ui-ts-basic-components-button.md deleted file mode 100644 index 06ff221c14b45531dc919dca123e6d1ac28f5b43..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/ui/ui-ts-basic-components-button.md +++ /dev/null @@ -1,193 +0,0 @@ -# Button - - -Button是按钮组件,通常用于响应用户的点击操作,如提交表单,其类型包括胶囊按钮、圆形按钮、普通按钮。具体用法请参考[Button](../reference/arkui-ts/ts-basic-components-button.md)。 - - -## 创建按钮 - -Button通过调用接口来创建,接口调用有以下两种形式: - -- 创建包含子组件的按钮 - - `Button(options?: {type?: ButtonType, stateEffect?: boolean})`,该接口用于创建包含子组件的按钮,其中type用于设置Button类型,stateEffect属性设置Button是否开启点击效果。 - - ``` - Button({ type: ButtonType.Normal, stateEffect: true }) { - Row() { - Image($r('app.media.loading')).width(20).height(20).margin({ left: 12 }) - Text('loading').fontSize(12).fontColor(0xffffff).margin({ left: 5, right: 12 }) - }.alignItems(VerticalAlign.Center) - }.borderRadius(8).backgroundColor(0x317aff).width(90) - ``` - - - ![zh-cn_image_0000001260555857](figures/zh-cn_image_0000001260555857.png) - -- 创建不包含子组件的按钮 - - `Button(label?: string, options?: { type?: ButtonType, stateEffect?: boolean })`,该接口用于创建不包含子组件的按钮,其中label确定所创建的Button是否包含子组件。 - - ``` - Button('Ok', { type: ButtonType.Normal, stateEffect: true }) - .borderRadius(8) - .backgroundColor(0x317aff) - .width(90) - ``` - - - ![zh-cn_image_0000001215796030](figures/zh-cn_image_0000001215796030.png) - - -## 设置按钮类型 - -Button有三种可选类型,分别为Capsule(胶囊类型)、Circle(圆形按钮)和Normal(普通按钮),通过type进行设置。 - -- 胶囊按钮(默认类型) - - ```ts - Button('Disable', { type: ButtonType.Capsule, stateEffect: false }) - .backgroundColor(0x317aff) - .width(90) - ``` - - ![zh-cn_image_0000001215645452](figures/zh-cn_image_0000001215645452.png) - -- 圆形按钮 - - ```ts - Button('Circle', { type: ButtonType.Circle, stateEffect: false }) - .backgroundColor(0x317aff) - .width(90) - .height(90) - ``` - - ![zh-cn_image_0000001215965420](figures/zh-cn_image_0000001215965420.png) - - -## 自定义样式 - -- 设置边框弧度 - 一般使用通用属性来自定义按钮样式。例如通过borderRadius属性设置按钮的边框弧度。 - - - ```ts - Button('circle border', { type: ButtonType.Normal }) - .borderRadius(20) - ``` - - ![zh-cn_image_0000001190463780](figures/zh-cn_image_0000001190463780.png) - -- 设置文本样式 - 通过添加文本样式设置按钮文本的展示样式。 - - - ```ts - Button('font style', { type: ButtonType.Normal }) - .fontSize(20) - .fontColor(Color.Red) - .fontWeight(800) - ``` - - ![zh-cn_image_0000001189744672](figures/zh-cn_image_0000001189744672.png) - -- 设置背景颜色 - 添加backgroundColor属性设置按钮的背景颜色。 - - - ```ts - Button('background color').backgroundColor(0xF55A42) - ``` - - ![zh-cn_image_0000001235146483](figures/zh-cn_image_0000001235146483.png) - -- 用作功能型按钮 - 为删除操作创建一个按钮。 - - - ```ts - Button({ type: ButtonType.Circle, stateEffect: true }) { - Image($r('app.media.ic_public_delete_filled')).width(30).height(30) - }.width(55).height(55).margin({ left: 20 }).backgroundColor(0xF55A42) - ``` - - ![zh-cn_image_0000001260373911](figures/zh-cn_image_0000001260373911.png) - - -## 添加事件 - -Button组件通常用于触发某些操作,可以在绑定onClick事件来响应点击操作后的自定义行为。 - - -```ts -Button('Ok', { type: ButtonType.Normal, stateEffect: true }) - .onClick(()=>{ - console.info('Button onClick') - }) -``` - - -## 场景示例 - -- 用于启动操作 - - 可以将按钮用于启动操作的任何用户界面元素。按钮会根据用户的操作触发相应的事件。如,在List容器里边通过点击按钮进行页面跳转: - - ```ts - // xxx.ets - import router from '@ohos.router' - - @Entry - @Component - struct ButtonCase1 { - build() { - List({ space: 4 }) { - ListItem() { - Button("First").onClick(() => { - router.push({ url: 'xxx' }) - }) - } - - ListItem() { - Button("Second").onClick(() => { - router.push({ url: 'yyy' }) - }) - } - - ListItem() { - Button("Third").onClick(() => { - router.push({ url: 'zzz' }) - }) - } - } - .listDirection(Axis.Vertical) - .backgroundColor(0xDCDCDC).padding(20) - } - } - ``` - - -​ ![zh-cn_image_0000001235626467](figures/zh-cn_image_0000001235626467.png) - - -- 用于表单的提交 - - 在用户登录/注册页面,用户的登录或注册的提交操作会用按钮。 - - ```ts - // xxx.ets - @Entry - @Component - struct ButtonCase2 { - build() { - Column() { - TextInput({ placeholder: 'input your username' }).margin({ top: 20 }) - TextInput({ placeholder: 'input your password' }).type(InputType.Password).margin({ top: 20 }) - Button('Register').width(300).margin({ top: 20 }) - }.padding(20) - } - } - ``` - - - ![zh-cn_image_0000001190466492](figures/zh-cn_image_0000001190466492.png) diff --git a/zh-cn/application-dev/ui/ui-ts-building-category-grid-layout.md b/zh-cn/application-dev/ui/ui-ts-building-category-grid-layout.md index 1f8e88029e8a192fbed74060f3c72d1e21d2357b..8df2f7bd9c6d81a5fe9778a3cfeca9185e19f19c 100644 --- a/zh-cn/application-dev/ui/ui-ts-building-category-grid-layout.md +++ b/zh-cn/application-dev/ui/ui-ts-building-category-grid-layout.md @@ -1,16 +1,16 @@ # 构建食物分类Grid布局 - - 健康饮食应用在主页提供给用户两种食物显示方式:列表显示和网格显示。开发者将实现通过页签切换不同食物分类的网格布局。 1. 将Category枚举类型引入FoodCategoryList页面。 + ```ts import { Category, FoodData } from '../model/FoodData' ``` 2. 创建FoodCategoryList和FoodCategory组件,其中FoodCategoryList作为新的页面入口组件,在入口组件调用initializeOnStartup方法。 + ```ts @Component struct FoodList { @@ -19,7 +19,7 @@ ...... } } - + @Component struct FoodCategory { private foodItems: FoodData[] @@ -27,7 +27,7 @@ ...... } } - + @Entry @Component struct FoodCategoryList { @@ -39,13 +39,14 @@ ``` 3. 在FoodCategoryList组件内创建showList成员变量,用于控制List布局和Grid布局的渲染切换。需要用到条件渲染语句if...else...。 + ```ts @Entry @Component struct FoodCategoryList { private foodItems: FoodData[] = initializeOnStartup() private showList: boolean = false - + build() { Stack() { if (this.showList) { @@ -59,13 +60,14 @@ ``` 4. 在页面右上角创建切换List/Grid布局的图标。设置Stack对齐方式为顶部尾部对齐TopEnd,创建Image组件,设置其点击事件,即showList取反。 + ```ts @Entry @Component struct FoodCategoryList { private foodItems: FoodData[] = initializeOnStartup() private showList: boolean = false - + build() { Stack({ alignContent: Alignment.TopEnd }) { if (this.showList) { @@ -85,14 +87,15 @@ } ``` -5. 添加\@State装饰器。点击右上角的switch标签后,页面没有任何变化,这是因为showList不是有状态数据,它的改变不会触发页面的刷新。需要为其添加\@State装饰器,使其成为状态数据,它的改变会引起其所在组件的重新渲染。 +5. 添加@State装饰器。点击右上角的switch标签后,页面没有任何变化,这是因为showList不是有状态数据,它的改变不会触发页面的刷新。需要为其添加\@State装饰器,使其成为状态数据,它的改变会引起其所在组件的重新渲染。 + ```ts @Entry @Component struct FoodCategoryList { private foodItems: FoodData[] = initializeOnStartup() @State private showList: boolean = false - + build() { Stack({ alignContent: Alignment.TopEnd }) { if (this.showList) { @@ -110,7 +113,7 @@ }.height('100%') } } - + ``` 点击切换图标,FoodList组件出现,再次点击,FoodList组件消失。 @@ -118,6 +121,7 @@ ![zh-cn_image_0000001170411978](figures/zh-cn_image_0000001170411978.gif) 6. 创建显示所有食物的页签(All)。在FoodCategory组件内创建Tabs组件和其子组件TabContent,设置tabBar为All。设置TabBars的宽度为280,布局模式为Scrollable,即超过总长度后可以滑动。Tabs是一种可以通过页签进行内容视图切换的容器组件,每个页签对应一个内容视图TabContent。 + ```ts @Component struct FoodCategory { @@ -137,13 +141,14 @@ ![zh-cn_image_0000001204538065](figures/zh-cn_image_0000001204538065.png) 7. 创建FoodGrid组件,作为TabContent的子组件。 + ```ts @Component struct FoodGrid { private foodItems: FoodData[] build() {} } - + @Component struct FoodCategory { private foodItems: FoodData[] @@ -162,6 +167,7 @@ ``` 8. 实现2 \* 6的网格布局(一共12个食物数据资源)。创建Grid组件,设置列数columnsTemplate('1fr 1fr'),行数rowsTemplate('1fr 1fr 1fr 1fr 1fr 1fr'),行间距和列间距rowsGap和columnsGap为8。创建Scroll组件,使其可以滑动。 + ```ts @Component struct FoodGrid { @@ -185,6 +191,7 @@ ``` 9. 创建FoodGridItem组件,展示食物图片、名称和卡路里,实现其UI布局,为GridItem的子组件。每个FoodGridItem高度为184,行间距为8,设置Grid总高度为(184 + 8) \* 6 - 8 = 1144。 + ```ts @Component struct FoodGridItem { @@ -196,7 +203,7 @@ .objectFit(ImageFit.Contain) .height(152) .width('100%') - }.backgroundColor('#FFf1f3f5') + } Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { Text(this.foodItem.name) .fontSize(14) @@ -214,7 +221,7 @@ .width('100%') } } - + @Component struct FoodGrid { private foodItems: FoodData[] @@ -239,123 +246,126 @@ } ``` - ![zh-cn_image_0000001170167520](figures/zh-cn_image_0000001170167520.gif) + ![zh-cn_image_0000001170167520](figures/zh-cn_image_0000001170167520.png) 10. 创建展示蔬菜(Category.Vegetable)、水果(Category.Fruit)、坚果(Category.Nut)、海鲜(Category.SeaFood)和甜品(Category.Dessert)分类的页签。 - ```ts - @Component - struct FoodCategory { - private foodItems: FoodData[] - build() { - Stack() { - Tabs() { - TabContent() { - FoodGrid({ foodItems: this.foodItems }) - }.tabBar('All') - - TabContent() { - FoodGrid({ foodItems: this.foodItems.filter(item => (item.category === Category.Vegetable)) }) - }.tabBar('Vegetable') - - TabContent() { - FoodGrid({ foodItems: this.foodItems.filter(item => (item.category === Category.Fruit)) }) - }.tabBar('Fruit') - - TabContent() { - FoodGrid({ foodItems: this.foodItems.filter(item => (item.category === Category.Nut)) }) - }.tabBar('Nut') - - TabContent() { - FoodGrid({ foodItems: this.foodItems.filter(item => (item.category === Category.Seafood)) }) - }.tabBar('Seafood') - - TabContent() { - FoodGrid({ foodItems: this.foodItems.filter(item => (item.category === Category.Dessert)) }) - }.tabBar('Dessert') + + ```ts + @Component + struct FoodCategory { + private foodItems: FoodData[] + + build() { + Stack() { + Tabs() { + TabContent() { + FoodGrid({ foodItems: this.foodItems }) + }.tabBar('All') + + TabContent() { + FoodGrid({ foodItems: this.foodItems.filter(item => (item.category === Category.Vegetable)) }) + }.tabBar('Vegetable') + + TabContent() { + FoodGrid({ foodItems: this.foodItems.filter(item => (item.category === Category.Fruit)) }) + }.tabBar('Fruit') + + TabContent() { + FoodGrid({ foodItems: this.foodItems.filter(item => (item.category === Category.Nut)) }) + }.tabBar('Nut') + + TabContent() { + FoodGrid({ foodItems: this.foodItems.filter(item => (item.category === Category.Seafood)) }) + }.tabBar('Seafood') + + TabContent() { + FoodGrid({ foodItems: this.foodItems.filter(item => (item.category === Category.Dessert)) }) + }.tabBar('Dessert') + } + .barWidth(280) + .barMode(BarMode.Scrollable) } - .barWidth(280) - .barMode(BarMode.Scrollable) } } - } - ``` + ``` 11. 设置不同食物分类的Grid的行数和高度。因为不同分类的食物数量不同,所以不能用'1fr 1fr 1fr 1fr 1fr 1fr '常量来统一设置成6行。 创建gridRowTemplate和HeightValue成员变量,通过成员变量设置Grid行数和高度。 - ```ts - @Component - struct FoodGrid { - private foodItems: FoodData[] - private gridRowTemplate : string = '' - private heightValue: number - build() { - Scroll() { - Grid() { - ForEach(this.foodItems, (item: FoodData) => { - GridItem() { - FoodGridItem({foodItem: item}) - } - }, (item: FoodData) => item.id.toString()) - } - .rowsTemplate(this.gridRowTemplate) - .columnsTemplate('1fr 1fr') - .columnsGap(8) - .rowsGap(8) - .height(this.heightValue) - } - .scrollBar(BarState.Off) - .padding({left: 16, right: 16}) - } - } - ``` - - 调用aboutToAppear接口计算行数(gridRowTemplate )和高度(heightValue)。 - - ```ts - aboutToAppear() { - var rows = Math.round(this.foodItems.length / 2); - this.gridRowTemplate = '1fr '.repeat(rows); - this.heightValue = rows * 192 - 8; - } - ``` - - 自定义组件提供了两个生命周期的回调接口aboutToAppear和aboutToDisappear。aboutToAppear的执行时机在创建自定义组件后,执行自定义组件build方法之前。aboutToDisappear在自定义组件销毁之前的时机执行。 + ```ts + @Component + struct FoodGrid { + private foodItems: FoodData[] + private gridRowTemplate: string = '' + private heightValue: number + + build() { + Scroll() { + Grid() { + ForEach(this.foodItems, (item: FoodData) => { + GridItem() { + FoodGridItem({ foodItem: item }) + } + }, (item: FoodData) => item.id.toString()) + } + .rowsTemplate(this.gridRowTemplate) + .columnsTemplate('1fr 1fr') + .columnsGap(8) + .rowsGap(8) + .height(this.heightValue) + } + .scrollBar(BarState.Off) + .padding({ left: 16, right: 16 }) + } + } + ``` - ![zh-cn_image_0000001215113569](figures/zh-cn_image_0000001215113569.png) + 调用aboutToAppear接口计算行数(gridRowTemplate )和高度(heightValue)。 - ```ts - @Component - struct FoodGrid { - private foodItems: FoodData[] - private gridRowTemplate : string = '' - private heightValue: number - - aboutToAppear() { - var rows = Math.round(this.foodItems.length / 2); - this.gridRowTemplate = '1fr '.repeat(rows); - this.heightValue = rows * 192 - 8; - } - - build() { - Scroll() { - Grid() { - ForEach(this.foodItems, (item: FoodData) => { - GridItem() { - FoodGridItem({foodItem: item}) - } - }, (item: FoodData) => item.id.toString()) - } - .rowsTemplate(this.gridRowTemplate) - .columnsTemplate('1fr 1fr') - .columnsGap(8) - .rowsGap(8) - .height(this.heightValue) - } - .scrollBar(BarState.Off) - .padding({left: 16, right: 16}) - } - } - ``` + ```ts + aboutToAppear() { + var rows = Math.round(this.foodItems.length / 2); + this.gridRowTemplate = '1fr '.repeat(rows); + this.heightValue = rows * 192 - 8; + } + ``` + + 自定义组件提供了两个生命周期的回调接口aboutToAppear和aboutToDisappear。aboutToAppear的执行时机在创建自定义组件后,执行自定义组件build方法之前。aboutToDisappear在自定义组件销毁之前的时机执行。 + + ![zh-cn_image_0000001215113569](figures/zh-cn_image_0000001215113569.png) + + ```ts + @Component + struct FoodGrid { + private foodItems: FoodData[] + private gridRowTemplate: string = '' + private heightValue: number + + aboutToAppear() { + var rows = Math.round(this.foodItems.length / 2); + this.gridRowTemplate = '1fr '.repeat(rows); + this.heightValue = rows * 192 - 8; + } + + build() { + Scroll() { + Grid() { + ForEach(this.foodItems, (item: FoodData) => { + GridItem() { + FoodGridItem({ foodItem: item }) + } + }, (item: FoodData) => item.id.toString()) + } + .rowsTemplate(this.gridRowTemplate) + .columnsTemplate('1fr 1fr') + .columnsGap(8) + .rowsGap(8) + .height(this.heightValue) + } + .scrollBar(BarState.Off) + .padding({ left: 16, right: 16 }) + } + } + ``` - ![zh-cn_image_0000001170008198](figures/zh-cn_image_0000001170008198.gif) + ![zh-cn_image_0000001170008198](figures/zh-cn_image_0000001170008198.gif) \ No newline at end of file diff --git a/zh-cn/application-dev/ui/ui-ts-building-category-list-layout.md b/zh-cn/application-dev/ui/ui-ts-building-category-list-layout.md index bb5ab8da2f5078e85109101f3f0a07257e609f40..5201e0e720b83083b0ceaeaac73ca95d15ed9290 100644 --- a/zh-cn/application-dev/ui/ui-ts-building-category-list-layout.md +++ b/zh-cn/application-dev/ui/ui-ts-building-category-list-layout.md @@ -1,23 +1,12 @@ # 构建食物列表List布局 - - 使用List组件和ForEach循环渲染,构建食物列表布局。 -1. 在pages目录新建页面FoodCategoryList.ets,将index.ets改名为FoodDetail.ets,并将其添加到config.json文件下的pages标签,位于第一序位的页面为首页。 - ```json - "js": [ - { - "pages": [ - "pages/FoodCategoryList", - "pages/FoodDetail" - ], - ] - ``` - +1. 在pages目录新建页面FoodCategoryList.ets,将index.ets改名为FoodDetail.ets。 + 2. 新建FoodList组件作为页面入口组件,FoodListItem为其子组件。List组件是列表组件,适用于重复同类数据的展示,其子组件为ListItem,适用于展示列表中的单元。 - ``` + ```ts @Component struct FoodListItem { build() {} @@ -43,7 +32,7 @@ ``` 4. FoodList和FoodListItem组件数值传递。在FoodList组件内创建类型为FoodData[]成员变量foodItems,调用initializeOnStartup方法为其赋值。在FoodListItem组件内创建类型为FoodData的成员变量foodItem。将父组件foodItems数组的第一个元素的foodItems[0]作为参数传递给FoodListItem。 - ``` + ```ts import { FoodData } from '../model/FoodData' import { initializeOnStartup } from '../model/FoodDataModels' @@ -68,20 +57,64 @@ ``` 5. 声明子组件FoodListItem 的UI布局。创建Flex组件,包含食物图片缩略图,食物名称,和食物对应的卡路里。 - ``` + ```ts import { FoodData } from '../model/FoodData' import { initializeOnStartup } from '../model/FoodDataModels' + @Component + struct FoodListItem { + private foodItem: FoodData + build() { + Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { + Image(this.foodItem.image) + .objectFit(ImageFit.Contain) + .height(40) + .width(40) + .margin({ right: 16 }) + Text(this.foodItem.name) + .fontSize(14) + .flexGrow(1) + Text(this.foodItem.calories + ' kcal') + .fontSize(14) + } + .height(64) + .margin({ right: 24, left:32 }) + } + } + + @Entry + @Component + struct FoodList { + private foodItems: FoodData[] = initializeOnStartup() + build() { + List() { + ListItem() { + FoodListItem({ foodItem: this.foodItems[0] }) + } + } + } + } + ``` + + + ![zh-cn_image_0000001204776353](figures/zh-cn_image_0000001204776353.png) + +6. 创建两个FoodListItem。在List组件创建两个FoodListItem,分别给FoodListItem传递foodItems数组的第一个元素this.foodItems[0]和第二个元素foodItem: this.foodItems[1]。 + + ```ts + import { FoodData } from '../model/FoodData' + import { initializeOnStartup } from '../model/FoodDataModels' + @Component struct FoodListItem { private foodItem: FoodData + build() { Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { Image(this.foodItem.image) .objectFit(ImageFit.Contain) .height(40) .width(40) - .backgroundColor('#FFf1f3f5') .margin({ right: 16 }) Text(this.foodItem.name) .fontSize(14) @@ -90,62 +123,21 @@ .fontSize(14) } .height(64) - .margin({ right: 24, left:32 }) + .margin({ right: 24, left: 32 }) } } - - @Entry - @Component - struct FoodList { - private foodItems: FoodData[] = initializeOnStartup() - build() { - List() { - ListItem() { - FoodListItem({ foodItem: this.foodItems[0] }) - } - } - } - } - ``` - - ![zh-cn_image_0000001204776353](figures/zh-cn_image_0000001204776353.png) - -6. 创建两个FoodListItem。在List组件创建两个FoodListItem,分别给FoodListItem传递foodItems数组的第一个元素this.foodItems[0]和第二个元素foodItem: this.foodItems[1]。 - ``` - import { FoodData } from '../model/FoodData' - import { initializeOnStartup } from '../model/FoodDataModels' - - @Component - struct FoodListItem { - private foodItem: FoodData - build() { - Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { - Image(this.foodItem.image) - .objectFit(ImageFit.Contain) - .height(40) - .width(40) - .backgroundColor('#FFf1f3f5') - .margin({ right: 16 }) - Text(this.foodItem.name) - .fontSize(14) - .flexGrow(1) - Text(this.foodItem.calories + ' kcal') - .fontSize(14) - } - .height(64) - .margin({ right: 24, left:32 }) - } - } - + @Entry @Component struct FoodList { private foodItems: FoodData[] = initializeOnStartup() + build() { List() { ListItem() { FoodListItem({ foodItem: this.foodItems[0] }) } + ListItem() { FoodListItem({ foodItem: this.foodItems[1] }) } @@ -153,36 +145,16 @@ } } ``` + + + ![zh-cn_image1_0000001204776353](figures/zh-cn_image1_0000001204776353.png) + +7. 单独创建每一个FoodListItem肯定是不合理的,这就需要引入[ForEach循环渲染](../quick-start/arkts-rendering-control.md#循环渲染)。 - ![zh-cn_image_0000001204537865](figures/zh-cn_image_0000001204537865.png) - -7. 单独创建每一个FoodListItem肯定是不合理的。这就需要引入ForEach循环渲染,ForEach语法如下。 - ``` - ForEach( - arr: any[], // Array to be iterated - itemGenerator: (item: any) => void, // child component generator - keyGenerator?: (item: any) => string // (optional) Unique key generator, which is recommended. - ) - ``` - - ForEach组有三个参数,第一个参数是需要被遍历的数组,第二个参数为生成子组件的lambda函数,第三个参数是键值生成器。出于性能原因,即使第三个参数是可选的,强烈建议开发者提供。keyGenerator使开发框架能够更好地识别数组更改,而不必因为item的更改重建全部节点。 - - 遍历foodItems数组循环创建ListItem组件,foodItems中每一个item都作为参数传递给FoodListItem组件。 - - ``` - ForEach(this.foodItems, item => { - ListItem() { - FoodListItem({ foodItem: item }) - } - }, item => item.id.toString()) - ``` - - 整体的代码如下。 - - ``` + ```ts import { FoodData } from '../model/FoodData' import { initializeOnStartup } from '../model/FoodDataModels' - + @Component struct FoodListItem { private foodItem: FoodData @@ -191,8 +163,7 @@ Image(this.foodItem.image) .objectFit(ImageFit.Contain) .height(40) - .width(40) - .backgroundColor('#FFf1f3f5') + .width(40) .margin({ right: 16 }) Text(this.foodItem.name) .fontSize(14) @@ -204,7 +175,7 @@ .margin({ right: 24, left:32 }) } } - + @Entry @Component struct FoodList { @@ -220,22 +191,25 @@ } } ``` - + 8. 添加FoodList标题。 + ``` @Entry @Component struct FoodList { private foodItems: FoodData[] = initializeOnStartup() + build() { Column() { - Flex({justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center}) { + Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { Text('Food List') .fontSize(20) - .margin({ left:20 }) + .margin({ left: 20 }) } .height('7%') .backgroundColor('#FFf1f3f5') + List() { ForEach(this.foodItems, item => { ListItem() { @@ -249,4 +223,4 @@ } ``` - ![zh-cn_image_0000001169678922](figures/zh-cn_image_0000001169678922.png) + ![zh-cn_image_0000001169678922](figures/zh-cn_image_0000001169678922.png) \ No newline at end of file diff --git a/zh-cn/application-dev/ui/ui-ts-building-data-model.md b/zh-cn/application-dev/ui/ui-ts-building-data-model.md index b0627fe491d6207825bf775dcc9a95d1c50c9d12..4d516a2b3fa81a482ebaf5337efd7c080871bd07 100644 --- a/zh-cn/application-dev/ui/ui-ts-building-data-model.md +++ b/zh-cn/application-dev/ui/ui-ts-building-data-model.md @@ -13,7 +13,7 @@ 2. 定义食物数据的存储模型FoodData和枚举变量Category,FoodData类包含食物id、名称(name)、分类(category)、图片(image)、热量(calories)、蛋白质(protein)、脂肪(fat)、碳水(carbohydrates)和维生素C(vitaminC)属性。 ArkTS语言是在ts语言的基础上的扩展,同样支持ts语法。 - ``` + ```ts enum Category { Fruit, Vegetable, @@ -52,7 +52,7 @@ 4. 创建食物资源数据。在model文件夹下创建FoodDataModels.ets,在该页面中声明食物成分数组FoodComposition。以下示例创建了两个食物数据。 - ``` + ```ts const FoodComposition: any[] = [ { 'name': 'Tomato', 'image': $r('app.media.Tomato'), 'category': Category.Vegetable, 'calories': 17, 'protein': 0.9, 'fat': 0.2, 'carbohydrates': 3.9, 'vitaminC': 17.8 }, { 'name': 'Walnut', 'image': $r('app.media.Walnut'), 'category': Category.Nut, 'calories': 654 , 'protein': 15, 'fat': 65, 'carbohydrates': 14, 'vitaminC': 1.3 } @@ -62,7 +62,7 @@ 实际开发中,开发者可以自定义更多的数据资源,当食物资源很多时,建议使用数据懒加载LazyForEach。 5. 创建initializeOnStartUp方法来初始化FoodData的数组。在FoodDataModels.ets中使用了定义在FoodData.ets的FoodData和Category,所以要将FoodData.ets的FoodData类export,在FoodDataModels.ets内import FoodData和Category。 - ``` + ```ts // FoodData.ets export enum Category { ...... diff --git a/zh-cn/application-dev/ui/ui-ts-components.md b/zh-cn/application-dev/ui/ui-ts-components.md deleted file mode 100644 index 775cb434d336028df04109f4a1eda38a1d007923..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/ui/ui-ts-components.md +++ /dev/null @@ -1,78 +0,0 @@ -# 初识Component - -在自定义组件之前,需要先了解什么是[组件和装饰器](#组件和装饰器),并进行初始化组件。然后通过[修改组件属性和构造参数](#修改组件属性和构造参数),实现一个自定义组件。 - - -## 组件和装饰器 - -在声明式UI中,所有的页面都是由组件构成。组件的数据结构为struct,装饰器@Component是组件化的标志。用@Component修饰的struct表示这个结构体有了组件化的能力。 - -自定义组件的声明方式为: - -```ts -@Component -struct MyComponent {} -``` - -在IDE创建工程模板中,MyComponent就是一个可以居中显示文字的自定义组件。开发者可以在Component的build方法里描述自己的UI结构,但需要遵循Builder的接口约束。 - -```ts -interface Builder { - build: () => void -} -``` - -@Entry修饰的Component表示该Component是页面的总入口,也可以理解为页面的根节点。值得注意的是,一个页面有且仅能有一个@Entry,只有被@Entry修饰的组件或者其子组件,才会在页面上显示。 - -@Component和@Entry都是基础且十分重要的装饰器。简单地理解,装饰器就是某一种修饰,给被装饰的对象赋予某一种能力,比如@Entry就是页面入口的能力,@Component就是组件化能力。 - -在了解了组件和装饰器这两个重要概念后,接下来可以开始开发健康饮食应用。 - - -## 修改组件属性和构造参数 - -开发者创建系统组件时,会显示其默认样式。开发者可以通过更改组件的属性样式来改变组件的视图显示。 - -1. 修改Text组件的fontSize属性来更改组件的字体大小,将字体大小设置为26,通过fontWeight属性更改字体粗细,将其设置为500。fontWeight属性支持三种设置方式: - 1. number类型的取值范围为100到900,取值间隔为100,默认为400,取值越大,字体越粗。 - 2. FontWeight为内置枚举类型,取值支持FontWeight.Lighter、FontWeight.Normal、FontWeight.Regular、FontWeight.Medium、FontWeight.Bold、FontWeight.Bolder。FontWeight.Normal即为400数值的字体粗细。 - 3. string类型仅支持number类型取值的字符串形式,例如"400",以及"bold"、"bolder"、"lighter"、"regular"、"medium",分别对应FontWeight中相应的枚举值。设置其他字符串则为无效,保持默认字体粗细显示。 - - 属性方法要紧随组件,通过“.”运算符连接,也可以通过链式调用的方式配置组件的多个属性。 - - ``` - @Entry - @Component - struct MyComponent { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Text('Hello World') - .fontSize(26) - .fontWeight(500) - } - .width('100%') - .height('100%') - } - } - ``` - - ![zh-cn_image_0000001168728272](figures/zh-cn_image_0000001168728272.png) - -2. 修改Text组件的显示内容“Hello World”为“Tomato”,通过修改Text组件的构造参数来实现。 - ``` - @Entry - @Component - struct MyComponent { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Text('Tomato') - .fontSize(26) - .fontWeight(500) - } - .width('100%') - .height('100%') - } - } - ``` - - ![zh-cn_image_0000001168888224](figures/zh-cn_image_0000001168888224.png) diff --git a/zh-cn/application-dev/ui/ui-ts-creating-project.md b/zh-cn/application-dev/ui/ui-ts-creating-project.md deleted file mode 100644 index e35ca9fa9b76d6dd69cbdc26864d649971265693..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/ui/ui-ts-creating-project.md +++ /dev/null @@ -1,65 +0,0 @@ -# 创建声明式UI工程 - - - -创建工程之前,首先需要安装DevEco Studio。 - - -1. 打开DevEco Studio,点击Create Project。如果已有一个工程,则点击File > New > New project。 - - ![zh-cn_image_0000001168956332](figures/zh-cn_image_0000001168956332.png) - -2. - 进入选择Ability Template界面,选择Empty Ability。 - - ![zh-cn_image_0000001168059158](figures/zh-cn_image_0000001168059158.png) - -3. 进入配置工程界面,将工程名字改为HealthyDiet,Project Type选择Application,Compile API选择8,UI Syntax选择eTS。DevEco Studio会默认将工程保存在C盘,如果要更改工程保存位置,点击Save Location的文件夹图标,自行指定工程创建位置。配置完成后点击Finish。 - - - ![zh-cn_image_0000001167746622](figures/zh-cn_image_0000001167746622.png) - -4. 工程创建完成后,打开app.ets。 - app.ets提供了应用生命周期的接口:onCreate和onDestroy,分别在应用创建之初和应用被销毁时调用。在app.ets里可以声明全局变量,并且声明的数据和方法是整个应用共享的。 - - ``` - export default { - onCreate() { - console.info('Application onCreate') - }, - onDestroy() { - console.info('Application onDestroy') - }, - } - ``` - -5. 在工程导航栏里,打开index.ets。该页面展示了当前的UI描述,声明式UI框架会自动生成一个组件化的struct,这个struct遵循Builder接口声明,在build方法里面声明当前的布局和组件。 - ``` - @Entry - @Component - struct MyComponent { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Text('Hello World') - .fontSize(50) - .fontWeight(FontWeight.Bold) - } - .width('100%') - .height('100%') - } - } - ``` - -6. 点击右侧的Previewer按钮,打开预览窗口。可以看到预览窗口中“Hello World”居中加粗显示。 - 如果没有Previewer按钮,点击settings > SDK Manager > OpenHarmony SDK> Tools 查看是否安装了Previewer。 - - ![zh-cn_image_0000001214595111](figures/zh-cn_image_0000001214595111.png) - -7. 应用安装到设备上运行应用。 - - 将设备连接电脑,等IDE识别到物理设备后,点击Run 'entry'按钮。 - ![zh-cn_image_0000001148858818](figures/zh-cn_image_0000001148858818.png) - - 在安装之前,需要配置应用签名。安装成功后,点击屏幕上的Run图标打开应用,可以看到居中加粗显示的“Hello World”。 - - ![zh-cn_image_0000001158896538](figures/zh-cn_image_0000001158896538.png) diff --git a/zh-cn/application-dev/ui/ui-ts-creating-simple-page.md b/zh-cn/application-dev/ui/ui-ts-creating-simple-page.md index 18152fe84e1c3ff337bd9db0b41ce9c3359adcfa..ca4fe0bd1e5f2f04a8e2aba9d881f0a37f3ac969 100644 --- a/zh-cn/application-dev/ui/ui-ts-creating-simple-page.md +++ b/zh-cn/application-dev/ui/ui-ts-creating-simple-page.md @@ -2,12 +2,16 @@ 在这一小节中,我们将开始食物详情页的开发,学习如何通过容器组件Stack、Flex和基础组件Image、Text,构建用户自定义组件,完成图文并茂的食物介绍。 +在创建页面前,请先创建eTS工程,FA模型请参考[创建FA模型的eTS工程](../quick-start/start-with-ets-stage.md#创建ets工程),Stage模型请参考[创建Stage模型的eTS工程](..//quick-start/start-with-ets-fa.md#创建ets工程)。 + ## 构建Stack布局 1. 创建食物名称。 - 删掉工程模板的build方法的代码,创建Stack组件,将Text组件放进Stack组件的花括号中,使其成为Stack组件的子组件。Stack组件为堆叠组件,可以包含一个或多个子组件,其特点是后一个子组件覆盖前一个子组件。 - ``` + + 在index.ets文件中,创建Stack组件,将Text组件放进Stack组件的花括号中,使其成为Stack组件的子组件。Stack组件为堆叠组件,可以包含一个或多个子组件,其特点是后一个子组件覆盖前一个子组件。 + + ```ts @Entry @Component struct MyComponent { @@ -22,11 +26,11 @@ ``` ![zh-cn_image_0000001214128687](figures/zh-cn_image_0000001214128687.png) - + 2. 食物图片展示。 创建Image组件,指定Image组件的url,Image组件是必选构造参数组件。为了让Text组件在Image组件上方显示,所以要先声明Image组件。图片资源放在resources下的rawfile文件夹内,引用rawfile下资源时使用`$rawfile('filename')`的形式,filename为rawfile目录下的文件相对路径。当前`$rawfile`仅支持Image控件引用图片资源。 - - ``` + + ```ts @Entry @Component struct MyComponent { @@ -42,30 +46,29 @@ ``` -![zh-cn_image_0000001168410342](figures/zh-cn_image_0000001168410342.png) + ![zh-cn_image_0000001168410342](figures/zh-cn_image_0000001168410342.png) 3. 通过资源访问图片。 除指定图片路径外,也可以使用引用媒体资源符$r引用资源,需要遵循resources文件夹的资源限定词的规则。右键resources文件夹,点击New>Resource Directory,选择Resource Type为Media(图片资源)。 将Tomato.png放入media文件夹内。就可以通过`$r('app.type.name')`的形式引用应用资源,即`$r('app.media.Tomato')`。 -``` -@Entry + ```ts + @Entry @Component struct MyComponent { build() { Stack() { - Image($r('app.media.Tomato')) - .objectFit(ImageFit.Contain) - .height(357) - Text('Tomato') - .fontSize(26) - .fontWeight(500) + Image($r('app.media.Tomato')) + .objectFit(ImageFit.Contain) + .height(357) + Text('Tomato') + .fontSize(26) + .fontWeight(500) } } } -``` - + ``` 4. 设置Image宽高,并且将image的objectFit属性设置为ImageFit.Contain,即保持图片长宽比的情况下,使得图片完整地显示在边界内。 如果Image填满了整个屏幕,原因如下: @@ -73,83 +76,53 @@ 2. Image的objectFit默认属性是ImageFit.Cover,即在保持长宽比的情况下放大或缩小,使其填满整个显示边界。 -``` -@Entry + ```ts + @Entry @Component struct MyComponent { build() { Stack() { - Image($r('app.media.Tomato')) - .objectFit(ImageFit.Contain) - .height(357) - Text('Tomato') - .fontSize(26) - .fontWeight(500) + Image($r('app.media.Tomato')) + .objectFit(ImageFit.Contain) + .height(357) + Text('Tomato') + .fontSize(26) + .fontWeight(500) } } } -``` - + ``` - ![zh-cn_image_0000001214210217](figures/zh-cn_image_0000001214210217.png) + ![zh-cn_image_0000001214210217](figures/zh-cn_image_0000001214210217.png) 5. 设置食物图片和名称布局。设置Stack的对齐方式为底部起始端对齐,Stack默认为居中对齐。设置Stack构造参数alignContent为Alignment.BottomStart。其中Alignment和FontWeight一样,都是框架提供的内置枚举类型。 -``` -@Entry + ```ts + @Entry @Component struct MyComponent { build() { Stack({ alignContent: Alignment.BottomStart }) { - Image($r('app.media.Tomato')) - .objectFit(ImageFit.Contain) - .height(357) - Text('Tomato') - .fontSize(26) - .fontWeight(500) + Image($r('app.media.Tomato')) + .objectFit(ImageFit.Contain) + .height(357) + Text('Tomato') + .fontSize(26) + .fontWeight(500) } } } -``` - - - ![zh-cn_image_0000001168728872](figures/zh-cn_image_0000001168728872.png) - -6. 通过设置Stack的背景颜色来改变食物图片的背景颜色,设置颜色有四种方式: - 1. 通过框架提供的Color内置枚举值来设置,比如backgroundColor(Color.Red),即设置背景颜色为红色。 - 2. string类型参数,支持的颜色格式有:rgb、rgba和HEX颜色码。比如backgroundColor('\#0000FF'),即设置背景颜色为蓝色,backgroundColor('rgb(255, 255, 255)'),即设置背景颜色为白色。 - 3. number类型参数,支持十六进制颜色值。比如backgroundColor(0xFF0000),即设置背景颜色为红色。 - - 4. Resource类型参数请参考[资源访问](ts-resource-access.md) 。 - - -``` -@Entry - @Component - struct MyComponent { - build() { - Stack({ alignContent: Alignment.BottomStart }) { - Image($r('app.media.Tomato')) - .objectFit(ImageFit.Contain) - .height(357) - Text('Tomato') - .fontSize(26) - .fontWeight(500) - } - .backgroundColor('#FFedf2f5') - } -} -``` + ``` + ![zh-cn_image_0000001168728872](figures/zh-cn_image_0000001168728872.png) - ![zh-cn_image_0000001168888822](figures/zh-cn_image_0000001168888822.png) +6. 调整Text组件的外边距margin,使其距离左侧和底部有一定的距离。margin是简写属性,可以统一指定四个边的外边距,也可以分别指定。具体设置方式如下: -7. 调整Text组件的外边距margin,使其距离左侧和底部有一定的距离。margin是简写属性,可以统一指定四个边的外边距,也可以分别指定。具体设置方式如下: 1. 参数为Length时,即统一指定四个边的外边距,比如margin(20),即上、右、下、左四个边的外边距都是20。 2. 参数为{top?: Length, right?: Length, bottom?: Length, left?:Length},即分别指定四个边的边距,比如margin({ left: 26, bottom: 17.4 }),即左边距为26,下边距为17.4。 -``` -@Entry + ```ts + @Entry @Component struct MyComponent { build() { @@ -161,20 +134,19 @@ .fontSize(26) .fontWeight(500) .margin({left: 26, bottom: 17.4}) - } - .backgroundColor('#FFedf2f5') + } } } -``` + ``` + ![zh-cn_image_0000001213968747](figures/zh-cn_image_0000001213968747.png) - ![zh-cn_image_0000001213968747](figures/zh-cn_image_0000001213968747.png) +7. 调整组件间的结构,语义化组件名称。创建页面入口组件为FoodDetail,在FoodDetail中创建Column,设置水平方向上居中对齐 alignItems(HorizontalAlign.Center)。MyComponent组件名改为FoodImageDisplay,为FoodDetail的子组件。 -8. 调整组件间的结构,语义化组件名称。创建页面入口组件为FoodDetail,在FoodDetail中创建Column,设置水平方向上居中对齐 alignItems(HorizontalAlign.Center)。MyComponent组件名改为FoodImageDisplay,为FoodDetail的子组件。 Column是子组件竖直排列的容器组件,本质为线性布局,所以只能设置交叉轴方向的对齐。 -``` -@Component + ```ts + @Component struct FoodImageDisplay { build() { Stack({ alignContent: Alignment.BottomStart }) { @@ -185,11 +157,10 @@ .fontWeight(500) .margin({ left: 26, bottom: 17.4 }) } - .height(357) - .backgroundColor('#FFedf2f5') + .height(357) } } - + @Entry @Component struct FoodDetail { @@ -200,9 +171,7 @@ .alignItems(HorizontalAlign.Center) } } -``` - - + ``` ## 构建Flex布局 @@ -210,8 +179,8 @@ 1. 创建ContentTable组件,使其成为页面入口组件FoodDetail的子组件。 -``` -@Component + ```ts + @Component struct FoodImageDisplay { build() { Stack({ alignContent: Alignment.BottomStart }) { @@ -223,15 +192,15 @@ .fontWeight(500) .margin({ left: 26, bottom: 17.4 }) } - .backgroundColor('#FFedf2f5') } } - + @Component struct ContentTable { - build() {} + build() { + } } - + @Entry @Component struct FoodDetail { @@ -243,8 +212,7 @@ .alignItems(HorizontalAlign.Center) } } -``` - + ``` 2. 创建Flex组件展示Tomato两类成分。 一类是热量Calories,包含卡路里(Calories);一类是营养成分Nutrition,包含蛋白质(Protein)、脂肪(Fat)、碳水化合物(Carbohydrates)和维生素C(VitaminC)。 @@ -253,8 +221,8 @@ 已省略FoodImageDisplay代码,只针对ContentTable进行扩展。 -``` -@Component + ```ts + @Component struct ContentTable { build() { Flex() { @@ -270,7 +238,7 @@ .padding({ top: 30, right: 30, left: 30 }) } } - + @Entry @Component struct FoodDetail { @@ -282,15 +250,15 @@ .alignItems(HorizontalAlign.Center) } } -``` - - - ![zh-cn_image_0000001169759552](figures/zh-cn_image_0000001169759552.png) - + ``` + + + ![zh-cn_image_0000001169759552](figures/zh-cn_image_0000001169759552.png) + 3. 调整布局,设置各部分占比。分类名占比(layoutWeight)为1,成分名和成分含量一共占比(layoutWeight)2。成分名和成分含量位于同一个Flex中,成分名占据所有剩余空间flexGrow(1)。 -``` -@Component + ```ts + @Component struct FoodImageDisplay { build() { Stack({ alignContent: Alignment.BottomStart }) { @@ -301,11 +269,10 @@ .fontSize(26) .fontWeight(500) .margin({ left: 26, bottom: 17.4 }) - } - .backgroundColor('#FFedf2f5') + } } } - + @Component struct ContentTable { build() { @@ -327,7 +294,7 @@ .padding({ top: 30, right: 30, left: 30 }) } } - + @Entry @Component struct FoodDetail { @@ -339,16 +306,15 @@ .alignItems(HorizontalAlign.Center) } } -``` - - - ![zh-cn_image_0000001215079443](figures/zh-cn_image_0000001215079443.png) - + ``` + + ![zh-cn_image_0000001215079443](figures/zh-cn_image_0000001215079443.png) + 4. 仿照热量分类创建营养成分分类。营养成分部分(Nutrition)包含:蛋白质(Protein)、脂肪(Fat)、碳水化合物(Carbohydrates)和维生素C(VitaminC)四个成分,后三个成分在表格中省略分类名,用空格代替。 设置外层Flex为竖直排列FlexDirection.Column, 在主轴方向(竖直方向)上等距排列FlexAlign.SpaceBetween,在交叉轴方向(水平轴方向)上首部对齐排列ItemAlign.Start。 -``` -@Component + ```ts + @Component struct ContentTable { build() { Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Start }) { @@ -427,7 +393,7 @@ .padding({ top: 30, right: 30, left: 30 }) } } - + @Entry @Component struct FoodDetail { @@ -439,8 +405,7 @@ .alignItems(HorizontalAlign.Center) } } -``` - + ``` 5. 使用自定义构造函数\@Builder简化代码。可以发现,每个成分表中的成分单元其实都是一样的UI结构。 ![zh-cn_image_0000001169599582](figures/zh-cn_image_0000001169599582.png) @@ -449,8 +414,8 @@ 在ContentTable内声明\@Builder修饰的IngredientItem方法,用于声明分类名、成分名称和成分含量UI描述。 -``` - @Component + ```ts + @Component struct ContentTable { @Builder IngredientItem(title:string, name: string, value: string) { Flex() { @@ -469,13 +434,12 @@ } } } -``` - + ``` - 在ContentTable的build方法内调用IngredientItem接口,需要用this去调用该Component作用域内的方法,以此来区分全局的方法调用。 + 在ContentTable的build方法内调用IngredientItem接口,需要用this去调用该Component作用域内的方法,以此来区分全局的方法调用。 -``` -@Component + ```ts + @Component struct ContentTable { ...... build() { @@ -490,13 +454,12 @@ .padding({ top: 30, right: 30, left: 30 }) } } -``` - + ``` - ContentTable组件整体代码如下。 + ContentTable组件整体代码如下。 -``` -@Component + ```ts + @Component struct ContentTable { @Builder IngredientItem(title:string, name: string, value: string) { Flex() { @@ -514,21 +477,20 @@ .layoutWeight(2) } } - - build() { - Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Start }) { - this.IngredientItem('Calories', 'Calories', '17kcal') - this.IngredientItem('Nutrition', 'Protein', '0.9g') - this.IngredientItem('', 'Fat', '0.2g') - this.IngredientItem('', 'Carbohydrates', '3.9g') - this.IngredientItem('', 'VitaminC', '17.8mg') - } - .height(280) - .padding({ top: 30, right: 30, left: 30 }) - } - + + build() { + Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Start }) { + this.IngredientItem('Calories', 'Calories', '17kcal') + this.IngredientItem('Nutrition', 'Protein', '0.9g') + this.IngredientItem('', 'Fat', '0.2g') + this.IngredientItem('', 'Carbohydrates', '3.9g') + this.IngredientItem('', 'VitaminC', '17.8mg') + } + .height(280) + .padding({ top: 30, right: 30, left: 30 }) + } } - + @Entry @Component struct FoodDetail { @@ -540,10 +502,9 @@ .alignItems(HorizontalAlign.Center) } } -``` - + ``` - ![zh-cn_image_0000001215199399](figures/zh-cn_image_0000001215199399.png) + ![zh-cn_image_0000001215199399](figures/zh-cn_image_0000001215199399.png) 通过学习Stack布局和Flex布局已完成食物的图文展示和营养成分表,构建出第一个普通视图的食物详情页。在下一个章节中,将开发食物分类列表页,并完成食物分类列表页面和食物详情页面的跳转和数据传递,现在我们就进入下一个章节的学习吧。 diff --git a/zh-cn/application-dev/ui/ui-ts-custom-component-lifecycle-callbacks.md b/zh-cn/application-dev/ui/ui-ts-custom-component-lifecycle-callbacks.md new file mode 100644 index 0000000000000000000000000000000000000000..970076fbc3bdb74596a565cf1090f9765d01d4bf --- /dev/null +++ b/zh-cn/application-dev/ui/ui-ts-custom-component-lifecycle-callbacks.md @@ -0,0 +1,139 @@ +# 自定义组件的生命周期 + +自定义组件的生命周期回调函数用于通知用户该自定义组件的生命周期,这些回调函数是私有的,在运行时由开发框架在特定的时间进行调用,不能从应用程序中手动调用这些回调函数。 + +> **说明:** +> +> - 允许在生命周期函数中使用Promise和异步回调函数,比如网络资源获取,定时器设置等; +> +> - 不允许在生命周期函数中使用async await。 + + +## aboutToAppear + +aboutToAppear?(): void + +aboutToAppear函数在创建自定义组件的新实例后,在执行其build函数之前执行。允许在aboutToAppear函数中改变状态变量,更改将在后续执行build函数中生效。 + +## aboutToDisappear + +aboutToDisappear?(): void + +aboutToDisappear函数在自定义组件析构销毁之前执行。不允许在aboutToDisappear函数中改变状态变量,特别是@Link变量的修改可能会导致应用程序行为不稳定。 + +**示例1:** + +```ts +// xxx.ets +@Entry +@Component +struct CountDownTimerComponent { + @State countDownFrom: number = 10 + private timerId: number = -1 + + aboutToAppear(): void { + this.timerId = setInterval(() => { + if (this.countDownFrom <= 1) { + clearTimeout(this.timerId) // countDownFrom小于等于1时清除计时器 + } + this.countDownFrom -= 1 + }, 1000) // countDownFrom每1s减1 + } + + aboutToDisappear(): void { + if (this.timerId > 0) { + clearTimeout(this.timerId) + this.timerId = -1 + } + } + + build() { + Column() { + Text(`${this.countDownFrom} sec left`) + .fontSize(30) + .margin(30) + }.width('100%') + } +} +``` + +![aboutToAppear](figures/aboutToAppear.gif) + +上述示例表明,生命周期函数对于允许CountDownTimerComponent管理其计时器资源至关重要,类似的函数也包括异步从网络请求加载资源。 + +## onPageShow + +onPageShow?(): void + +页面每次显示时触发一次,包括路由过程、应用进入前后台等场景,仅@Entry修饰的自定义组件生效。 + +## onPageHide + +onPageHide?(): void + +页面每次隐藏时触发一次,包括路由过程、应用进入前后台等场景,仅@Entry修饰的自定义组件生效。 + +## onBackPress + +onBackPress?(): void + +当用户点击返回按钮时触发,仅@Entry修饰的自定义组件生效。返回true表示页面自己处理返回逻辑,不进行页面路由,返回false表示使用默认的路由返回逻辑。不设置返回值按照false处理。 + +**示例2:** + +```ts +// xxx.ets +@Entry +@Component +struct IndexComponent { + @State textColor: Color = Color.Black + + onPageShow() { + this.textColor = Color.Blue + console.info('IndexComponent onPageShow') + } + + onPageHide() { + this.textColor = Color.Transparent + console.info('IndexComponent onPageHide') + } + + onBackPress() { + this.textColor = Color.Red + console.info('IndexComponent onBackPress') + } + + build() { + Column() { + Text('Hello World') + .fontColor(this.textColor) + .fontSize(30) + .margin(30) + }.width('100%') + } +} +``` + +![lifecycle](figures/lifecycle.PNG) + +## onLayout + +onLayout?(children: Array, constraint: [ConstraintSizeOptions](../reference/arkui-ts/ts-types.md#constraintsizeoptions)): void + +框架会在自定义组件布局时,将该自定义组件的子节点信息和自身的尺寸范围通过onLayout传递给该自定义组件。不允许在onLayout函数中改变状态变量。 + +## onMeasure + +onMeasure?(children: Array, constraint: [ConstraintSizeOptions](../reference/arkui-ts/ts-types.md#constraintsizeoptions)): void + +框架会在自定义组件确定尺寸时,将该自定义组件的子节点信息和自身的尺寸范围通过onMeasure传递给该自定义组件。不允许在onMeasure函数中改变状态变量。 + +## LayoutChild类型说明 + +| 参数 | 参数类型 | 描述 | +| ----- | ----------- | ----------- | +| name | string | 子组件名称 | +| id | string | 子组件id | +| constraint | [ConstraintSizeOptions](../reference/arkui-ts/ts-types.md#constraintsizeoptions) | 子组件约束尺寸 | +| borderInfo | { borderWidth: number, margin: [Margin](../reference/arkui-ts/ts-types.md#margin), padding: [Padding](../reference/arkui-ts/ts-types.md#padding) } | 子组件边框样式 | +| position | { x: number, y: number } | 子组件位置坐标 | diff --git a/zh-cn/application-dev/ui/ui-ts-developing-intro.md b/zh-cn/application-dev/ui/ui-ts-developing-intro.md new file mode 100644 index 0000000000000000000000000000000000000000..d5bfbf46859bb2fe260f18d63eedf15aa7fb768f --- /dev/null +++ b/zh-cn/application-dev/ui/ui-ts-developing-intro.md @@ -0,0 +1,227 @@ +# 声明式UI开发指导 + +## 开发说明 + +声明式UI的工程结构还请参考[OpenHarmony APP工程结构介绍](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-project-overview-0000001218440650#section133380945818)。其中,.ets结尾的ArkTS文件用于描述UI布局、样式、事件交互和页面逻辑,支持导入TypeScript和JavaScript文件。资源目录resources文件夹位于src/main下,此目录下资源文件的详细规范以及子目录结构规范参看[资源分类与访问](../quick-start/resource-categories-and-access.md)。 + +在开发页面之前,请先[学习ArkTS语言](../quick-start/arkts-get-started.md)了解声明式UI的基本语法。 + +在开发页面时,可先根据使用场景,在[常见布局](ui-ts-layout-linear.md)中选择合适的布局。再根据页面需要实现的内容,为页面添加系统内置组件,更新组件状态。页面开发过程中请参考[自定义组件的生命周期](ui-ts-custom-component-lifecycle-callbacks.md)了解如何添加需要的生命周期回调方法。 + +也可在页面中添加[绘图](../reference/arkui-ts/ts-drawing-components-circle.md)和[动画](../reference/arkui-ts/ts-animatorproperty.md),丰富页面的展现形态。还可以使用[路由](../reference/apis/js-apis-router.md)实现多个页面之间的跳转和数据传递。 + +另外请参考[性能提升的推荐方法](ui-ts-performance-improvement-recommendation.md),避免低性能代码对应用的性能造成负面影响。 + +## 创建页面 + +请先根据页面预期效果选择布局结构创建页面,并在页面中添加基础的系统内置组件。下述示例采用了[弹性布局(Flex)](ui-ts-layout-flex.md),对页面中的Text组件进行横纵向居中布局显示。 + + ```ts + // xxx.ets + @Entry + @Component + struct MyComponent { + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text('Hello') + } + .width('100%') + .height('100%') + } + } + ``` + +## 修改组件样式 + +创建系统内置组件时,若不设置属性方法,则会显示其默认样式。通过更改组件的属性样式或者组件支持的[通用属性](../reference/arkui-ts/ts-universal-attributes-size.md)样式,设置可以改变组件的UI显示。 + +1. 通过修改Text组件的构造参数,将Text组件的显示内容修改为“Tomato”。 + +2. 修改Text组件的fontSize属性更改组件的字体大小,将字体大小设置为26,通过fontWeight属性更改字体粗细,将其设置为500。fontWeight属性支持三种设置方式: + + a. number类型的取值范围为100到900,取值间隔为100,默认为400,取值越大,字体越粗。 + + b. FontWeight为内置枚举类型,取值支持FontWeight.Lighter、FontWeight.Normal、FontWeight.Regular、FontWeight.Medium、FontWeight.Bold、FontWeight.Bolder。FontWeight.Normal即为400数值的字体粗细。 + + c. string类型仅支持number类型取值的字符串形式,例如"400",以及"bold"、"bolder"、"lighter"、"regular"、"medium",分别对应FontWeight中相应的枚举值。设置其他字符串则为无效,保持默认字体粗细显示。 + + 属性方法要紧随组件,通过“.”操作符连接,也可以通过链式调用的方式配置组件的多个属性。 + + ```ts + // xxx.ets + @Entry + @Component + struct MyComponent { + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text('Tomato') + .fontSize(26) + .fontWeight(500) + } + .width('100%') + .height('100%') + } + } + ``` + + ![zh-cn_image_0000001168888224](figures/zh-cn_image_0000001168888224.png) + +## 组件成员变量初始化 + +自定义组件的成员变量可以通过[本地初始化](../quick-start/arkts-restrictions-and-extensions.md#自定义组件成员变量初始化的方式与约束)和[在构造组件时通过构造参数初始化](../quick-start/arkts-restrictions-and-extensions.md#自定义组件成员变量初始化的方式与约束)两种方式实现,具体允许哪种方式取决于该变量所使用的装饰器: + + +**示例:** + +```ts +// xxx.ets +class ClassA { + public str: string + + constructor(str: string) { + this.str = str + } +} + +@Entry +@Component +struct Parent { + // Parent的变量parentState进行本地初始化 + @State parentState: ClassA = new ClassA('hello') + + build() { + Column() { + Row() { + CompA({ aState: new ClassA('Tomato'), aLink: $parentState }) + } + // aState在CompA中已进行初始化,因此可以缺省 + Row() { + CompA({ aLink: $parentState }) + } + }.width('100%') + } +} + +@Component +struct CompA { + // CompA中的变量aState进行本地初始化,aLink在Parent中使用时通过构造参数初始化 + @State aState: any = new ClassA('CompA') + @Link aLink: ClassA + + build() { + Row() { + Text(JSON.stringify(this.aState)).fontSize(20).margin(30) + Text(JSON.stringify(this.aLink)).fontSize(20).margin(30) + } + } +} +``` + +![component](figures/component.PNG) + +## 组件的状态更新 + +组件的状态可以通过动态修改组件成员变量的值来更新,下面以示例来进行说明。 + +**示例:** + +```ts +// xxx.ets +@Entry +@Component +struct ParentComp { + @State isCountDown: boolean = true + + build() { + Column() { + Text(this.isCountDown ? 'Count Down' : 'Stopwatch').fontSize(20).margin(20) + if (this.isCountDown) { + // 图片资源放在media目录下 + Image($r("app.media.countdown")).width(120).height(120) + TimerComponent({ counter: 10, changePerSec: -1, showInColor: Color.Red }) + } else { + // 图片资源放在media目录下 + Image($r("app.media.stopwatch")).width(120).height(120) + TimerComponent({ counter: 0, changePerSec: +1, showInColor: Color.Black }) + } + Button(this.isCountDown ? 'Switch to Stopwatch' : 'Switch to Count Down') + .onClick(() => { + this.isCountDown = !this.isCountDown + }) + }.width('100%') + } +} + +// 自定义计时器/倒计时组件 +@Component +struct TimerComponent { + @State counter: number = 0 + private changePerSec: number = -1 + private showInColor: Color = Color.Black + private timerId: number = -1 + + build() { + Text(`${this.counter}sec`) + .fontColor(this.showInColor) + .fontSize(20) + .margin(20) + } + + aboutToAppear() { + this.timerId = setInterval(() => { + this.counter += this.changePerSec + }, 1000) + } + + aboutToDisappear() { + if (this.timerId > 0) { + clearTimeout(this.timerId) + this.timerId = -1 + } + } +} +``` + +![component](figures/component.gif) + +**初始创建和渲染:** + +1. 创建父组件ParentComp; + +2. 本地初始化ParentComp的状态变量isCountDown; + +3. 执行ParentComp的build函数; + +4. 创建Column组件; + 1. 创建Text组件,设置其文本展示内容,并将Text组件实例添加到Column中; + 2. 判断if条件,创建true条件下的元素; + 1. 创建Image组件,并设置其图片源地址; + 2. 使用给定的构造函数创建TimerComponent; + 1. 创建TimerComponent对象; + 2. 本地初始化成员变量初始值; + 3. 使用TimerComponent构造函数提供的参数更新成员变量的值; + 4. 执行TimerComponent的aboutToAppear函数; + 5. 执行TimerComponent的build函数,创建相应的UI描述结构; + 3. 创建Button内置组件,设置相应的内容。 + +**状态更新:** + +用户单击按钮时: + +1. ParentComp的isCountDown状态变量的值更改为false; + +2. 执行ParentComp的build函数; + +3. Column组件被重用并执行重新初始化; + +4. Column的子组件会重用内存中的对象,但会进行重新初始化; + 1. Text组件会被重用,但使用新的文本内容进行重新初始化; + 2. 判断if条件,使用false条件下的元素; + 1. 原来true条件的组件不再使用,将这些组件销毁; + 1. 销毁Image组件实例; + 2. 销毁TimerComponent组件实例,aboutToDisappear函数被调用; + 2. 创建false条件下的组件; + 1. 创建Image组件,并设置其图片源地址; + 2. 使用给定的构造函数重新创建TimerComponent; + 3. 初始化TimerComponent,并调用aboutToAppear函数和build函数。 + 3. 重用Button组件,使用新的图片源地址。 diff --git a/zh-cn/application-dev/ui/ui-ts-drawing-feature.md b/zh-cn/application-dev/ui/ui-ts-drawing-feature.md new file mode 100644 index 0000000000000000000000000000000000000000..915748a8acec87ff5a2ef16820467d3999e4d432 --- /dev/null +++ b/zh-cn/application-dev/ui/ui-ts-drawing-feature.md @@ -0,0 +1,404 @@ +# 绘制图形 + +绘制能力主要是通过框架提供的绘制组件来支撑,支持svg标准绘制命令。 + +本节主要学习如何使用绘制组件,绘制详情页食物成分标签(基本几何图形)和应用Logo(自定义图形)。 + +## 绘制基本几何图形 + +绘制组件封装了一些常见的基本几何图形,比如矩形Rect、圆形Circle、椭圆形Ellipse等,为开发者省去了路线计算的过程。 + +FoodDetail页面的食物成分表里,给每一项成分名称前都加上一个圆形的图标作为成分标签。 + +1. 创建Circle组件,在每一项含量成分前增加一个圆形图标作为标签。设置Circle的直径为 6vp。修改FoodDetail页面的ContentTable组件里的IngredientItem方法,在成分名称前添加Circle。 + + ```ts + // FoodDetail.ets + @Component + struct ContentTable { + private foodItem: FoodData + + @Builder IngredientItem(title:string, colorValue: string, name: string, value: string) { + Flex() { + Text(title) + .fontSize(17.4) + .fontWeight(FontWeight.Bold) + .layoutWeight(1) + Flex({ alignItems: ItemAlign.Center }) { + Circle({width: 6, height: 6}) + .margin({right: 12}) + .fill(colorValue) + Text(name) + .fontSize(17.4) + .flexGrow(1) + Text(value) + .fontSize(17.4) + } + .layoutWeight(2) + } + } + + build() { + ...... + } + } + ``` + +2. 每个成分的标签颜色不一样,所以我们在build方法中,调用IngredientItem,给每个Circle填充不一样的颜色。 + + ```ts + // FoodDetail.ets + @Component + struct ContentTable { + private foodItem: FoodData + + @Builder IngredientItem(title:string, colorValue: string, name: string, value: string) { + Flex() { + Text(title) + .fontSize(17.4) + .fontWeight(FontWeight.Bold) + .layoutWeight(1) + Flex({ alignItems: ItemAlign.Center }) { + Circle({width: 6, height: 6}) + .margin({right: 12}) + .fill(colorValue) + Text(name) + .fontSize(17.4) + .flexGrow(1) + Text(value) + .fontSize(17.4) + } + .layoutWeight(2) + } + } + + build() { + Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Start }) { + this.IngredientItem('Calories', '#FFf54040', 'Calories', this.foodItem.calories + 'kcal') + this.IngredientItem('Nutrition', '#FFcccccc', 'Protein', this.foodItem.protein + 'g') + this.IngredientItem(' ', '#FFf5d640', 'Fat', this.foodItem.fat + 'g') + this.IngredientItem(' ', '#FF9e9eff', 'Carbohydrates', this.foodItem.carbohydrates + 'g') + this.IngredientItem(' ', '#FF53f540', 'VitaminC', this.foodItem.vitaminC + 'mg') + } + .height(280) + .padding({ top: 30, right: 30, left: 30 }) + } + } + ``` + + ![drawing-feature](figures/drawing-feature.png) + +## 绘制自定义几何图形 + +除绘制基础几何图形,开发者还可以使用Path组件来绘制自定义的路线,下面进行绘制应用的Logo图案。 + +1. 在pages文件夹下创建新的eTS页面Logo.ets。 + + ![drawing-feature1](figures/drawing-feature1.png) + +2. Logo.ets中删掉模板代码,创建Logo Component。 + + ```ts + @Entry + @Component + struct Logo { + build() { + } + } + ``` + +3. 创建Flex组件为根节点,宽高设置为100%,设置其在主轴方向和交叉轴方向的对齐方式都为Center,创建Shape组件为Flex子组件。 + + Shape组件是所有绘制组件的父组件。如果需要组合多个绘制组件成为一个整体,需要创建Shape作为其父组件。 + + 我们要绘制的Logo的大小630px * 630px。声明式UI范式支持多种长度单位的设置,在前面的章节中,我们直接使用number作为参数,即采用了默认长度单位vp,虚拟像素单位。vp和设备分辨率以及屏幕密度有关。比如设备分辨率为1176 * 2400,屏幕基准密度(resolution)为3,vp = px / resolution,则该设备屏幕宽度是392vp。 + + 但是绘制组件采用svg标准,默认采取px为单位的,为方便统一,在这绘制Logo这一部分,统一采取px为单位。声明式UI框架同样也支持px单位,入参类型为string,设置宽度为630px,即210vp,设置方式为width('630px')或者width(210)。 + + ```ts + @Entry + @Component + struct Logo { + build() { + Flex({ alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Shape() { + + } + .height('630px') + .width('630px') + } + .width('100%') + .height('100%') + } + } + ``` + +4. 给页面填充渐变色。设置为线性渐变,偏移角度为180deg,三段渐变 #BDE895 -->95DE7F --> #7AB967,其区间分别为[0, 0.1], (0.1, 0.6], (0.6, 1]。 + + ```ts + .linearGradient( + { + angle: 180, + colors: [['#BDE895', 0.1], ["#95DE7F", 0.6], ["#7AB967", 1]] + }) + ``` + + ![drawing-feature2](figures/drawing-feature2.png) + + ```ts + @Entry + @Component + struct Logo { + build() { + Flex({ alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Shape() { + + } + .height('630px') + .width('630px') + } + .width('100%') + .height('100%') + .linearGradient( + { + angle: 180, + colors: [['#BDE895', 0.1], ["#95DE7F", 0.6], ["#7AB967", 1]] + }) + } + } + ``` + + ![drawing-feature3](figures/drawing-feature3.png) + +5. 绘制第一条路线Path,设置其绘制命令。 + + ```ts + Path() + .commands('M162 128.7 a222 222 0 0 1 100.8 374.4 H198 a36 36 0 0 3 -36 -36') + ``` + + Path的绘制命令采用svg标准,上述命令可分解为: + + ```ts + M162 128.7 + ``` + + 将笔触移动到(Moveto)坐标点(162, 128.7)。 + + ```ts + a222 222 0 0 1 100.8 374.4 + ``` + + 画圆弧线(elliptical arc)半径rx,ry为222,x轴旋转角度x-axis-rotation为0,角度大小large-arc-flag为0,即小弧度角,弧线方向(sweep-flag)为1,即逆时针画弧线,小写a为相对位置,即终点坐标为(162 + 100.8 = 262.8, 128.7 + 374.4 = 503.1)。 + + ```ts + H198 + ``` + + 画水平线(horizontal lineto)到198,即画(262.8, 503.1)到(198, 503.1)的水平线。 + + ```ts + a36 36 0 0 3 -36 -36 + ``` + + 画圆弧线(elliptical arc),含义同上,结束点为(198 - 36 = 162, 503.1 - 36 = 467.1)。 + + ```ts + V128.7 + ``` + + 画垂直线(vertical lineto)到128.7,即画(162, 467.1)到(162, 128.7)的垂直线。 + + ```ts + z + ``` + + 关闭路径(closepath)。 + + ![drawing-feature4](figures/drawing-feature4.png) + + 填充颜色为白色。 + + ```ts + .fill(Color.White) + ``` + + ```ts + @Entry + @Component + struct Logo { + build() { + Flex({ alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Shape() { + Path() + .commands('M162 128.7 a222 222 0 0 1 100.8 374.4 H198 a36 36 0 0 3 -36 -36') + .fill(Color.White) + } + .height('630px') + .width('630px') + } + .width('100%') + .height('100%') + .linearGradient( + { + angle: 180, + colors: [['#BDE895', 0.1], ["#95DE7F", 0.6], ["#7AB967", 1]] + }) + } + } + ``` + + ![drawing-feature5](figures/drawing-feature5.png) + +6. 在Shape组件内绘制第二个Path。第二条Path的背景色为渐变色,但是渐变色的填充是其整体的box,所以需要clip将其裁剪,入参为Shape,即按照Shape的形状进行裁剪。 + + ```ts + Path() + .commands('M319.5 128.1 c103.5 0 187.5 84 187.5 187.5 v15 a172.5 172.5 0 0 3 -172.5 172.5 H198 a36 36 0 0 3 -13.8 -1 207 207 0 0 0 87 -372 h48.3 z') + .fill('none') + .linearGradient( + { + angle: 30, + colors: [["#C4FFA0", 0], ["#ffffff", 1]] + }) + .clip(new Path().commands('M319.5 128.1 c103.5 0 187.5 84 187.5 187.5 v15 a172.5 172.5 0 0 3 -172.5 172.5 H198 a36 36 0 0 3 -13.8 -1 207 207 0 0 0 87 -372 h48.3 z')) + ``` + + Path的绘制命令比较长,可以将其作为组件的成员变量,通过this调用。 + + ```ts + @Entry + @Component + struct Logo { + private pathCommands1:string = 'M319.5 128.1 c103.5 0 187.5 84 187.5 187.5 v15 a172.5 172.5 0 0 3 -172.5 172.5 H198 a36 36 0 0 3 -13.8 -1 207 207 0 0 0 87 -372 h48.3 z' + build() { + ...... + Path() + .commands(this.pathCommands1) + .fill('none') + .linearGradient( + { + angle: 30, + colors: [["#C4FFA0", 0], ["#ffffff", 1]] + }) + .clip(new Path().commands(this.pathCommands1)) + ...... + } + } + ``` + + ![drawing-feature6](figures/drawing-feature6.png) + +7. 在Shape组件内绘制第二个Path。 + + ```ts + @Entry + @Component + struct Logo { + private pathCommands1:string = 'M319.5 128.1 c103.5 0 187.5 84 187.5 187.5 v15 a172.5 172.5 0 0 3 -172.5 172.5 H198 a36 36 0 0 3 -13.8 -1 207 207 0 0 0 87 -372 h48.3 z' + private pathCommands2:string = 'M270.6 128.1 h48.6 c51.6 0 98.4 21 132.3 54.6 a411 411 0 0 3 -45.6 123 c-25.2 45.6 -56.4 84 -87.6 110.4 a206.1 206.1 0 0 0 -47.7 -288 z' + build() { + Flex({ alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Shape() { + Path() + .commands('M162 128.7 a222 222 0 0 1 100.8 374.4 H198 a36 36 0 0 3 -36 -36') + .fill(Color.White) + + Path() + .commands(this.pathCommands1) + .fill('none') + .linearGradient( + { + angle: 30, + colors: [["#C4FFA0", 0], ["#ffffff", 1]] + }) + .clip(new Path().commands(this.pathCommands1)) + + Path() + .commands(this.pathCommands2) + .fill('none') + .linearGradient( + { + angle: 50, + colors: [['#8CC36A', 0.1], ["#B3EB90", 0.4], ["#ffffff", 0.7]] + }) + .clip(new Path().commands(this.pathCommands2)) + } + .height('630px') + .width('630px') + } + .width('100%') + .height('100%') + .linearGradient( + { + angle: 180, + colors: [['#BDE895', 0.1], ["#95DE7F", 0.6], ["#7AB967", 1]] + }) + } + } + ``` + + ![drawing-feature7](figures/drawing-feature7.png) + + 完成应用Logo的绘制。Shape组合了三个Path组件,通过svg命令绘制出一个艺术的叶子,寓意绿色健康饮食方式。 + +8. 添加应用的标题和slogan。 + + ```ts + @Entry + @Component + struct Logo { + private pathCommands1:string = 'M319.5 128.1 c103.5 0 187.5 84 187.5 187.5 v15 a172.5 172.5 0 0 3 -172.5 172.5 H198 a36 36 0 0 3 -13.8 -1 207 207 0 0 0 87 -372 h48.3 z' + private pathCommands2:string = 'M270.6 128.1 h48.6 c51.6 0 98.4 21 132.3 54.6 a411 411 0 0 3 -45.6 123 c-25.2 45.6 -56.4 84 -87.6 110.4 a206.1 206.1 0 0 0 -47.7 -288 z' + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Shape() { + Path() + .commands('M162 128.7 a222 222 0 0 1 100.8 374.4 H198 a36 36 0 0 3 -36 -36') + .fill(Color.White) + + Path() + .commands(this.pathCommands1) + .fill('none') + .linearGradient( + { + angle: 30, + colors: [["#C4FFA0", 0], ["#ffffff", 1]] + }) + .clip(new Path().commands(this.pathCommands1)) + + Path() + .commands(this.pathCommands2) + .fill('none') + .linearGradient( + { + angle: 50, + colors: [['#8CC36A', 0.1], ["#B3EB90", 0.4], ["#ffffff", 0.7]] + }) + .clip(new Path().commands(this.pathCommands2)) + } + .height('630px') + .width('630px') + + Text('Healthy Diet') + .fontSize(26) + .fontColor(Color.White) + .margin({ top:300 }) + + Text('Healthy life comes from a balanced diet') + .fontSize(17) + .fontColor(Color.White) + .margin({ top:4 }) + } + .width('100%') + .height('100%') + .linearGradient( + { + angle: 180, + colors: [['#BDE895', 0.1], ["#95DE7F", 0.6], ["#7AB967", 1]] + }) + } + } + ``` + + ![drawing-feature8](figures/drawing-feature8.png) \ No newline at end of file diff --git a/zh-cn/application-dev/ui/ui-ts-layout-flex.md b/zh-cn/application-dev/ui/ui-ts-layout-flex.md index 16479a4c171c4459bebb61ca67e9ca9058a80c19..3d33681082d1dc1014a17a4a9dae262a7a9e359f 100644 --- a/zh-cn/application-dev/ui/ui-ts-layout-flex.md +++ b/zh-cn/application-dev/ui/ui-ts-layout-flex.md @@ -1,351 +1,560 @@ # 弹性布局 +弹性布局(Flex布局)是自适应布局中使用最为灵活的布局。弹性布局提供一种更加有效的方式来对容器中的子组件进行排列、对齐和分配空白空间。弹性布局 -Flex组件用于创建弹性布局,开发者可以通过Flex的接口创建容器组件,进而对容器内的其他元素进行弹性布局,例如:使三个元素在容器内水平居中,垂直等间隔分散。 +- 容器: [Flex组件](../reference/arkui-ts/ts-container-flex.md)作为Flex布局的容器,用于设置布局相关属性。 +- 子组件: Flex组件内的子组件自动成为布局的子组件。 +- 主轴: 水平方向的轴线,子组件默认沿着主轴排列。主轴开始的位置称为主轴起始端,结束位置称为主轴终点端。 +- 交叉轴: 垂直方向的轴线。交叉始的位置称为主轴首部,结束位置称为交叉轴尾部。 -## 创建弹性布局 + ![](figures/flex.png) -接口的调用形式如下: +## 容器组件属性 -`Flex(options?: { direction?: FlexDirection, wrap?: FlexWrap, justifyContent?: FlexAlign, alignItems?: ItemAlign, alignContent?: FlexAlign })` -通过参数direction定义弹性布局的布局方向,justifyContent定义弹性布局方向上的子组件对齐方式, alignContent定义与布局方向垂直的方向上的子组件对齐方式,wrap定义内容超过一行时是否换行。 - -## 弹性布局方向 +通过Flex组件提供的Flex接口创建弹性布局。如下: -弹性布局有两个方向,子组件放置的方向是主轴,与主轴垂直的方向是交叉轴。通过direction参数设置容器主轴的方向,可选值有: +`Flex(options?: { direction?: FlexDirection, wrap?: FlexWrap, justifyContent?: FlexAlign, alignItems?: ItemAlign, alignContent?: FlexAlign })` -- FlexDirection.Row(默认值):主轴为水平方向,子组件从起始端沿着水平方向开始排布。 - ```ts - Flex({ direction: FlexDirection.Row }) { - Text('1').width('33%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(50).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .height(70) - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - ![zh-cn_image_0000001218579606](figures/zh-cn_image_0000001218579606.png) +### 弹性布局方向 +参数direction决定主轴的方向,即子组件的排列方向。可选值有: -- FlexDirection.RowReverse:主轴为水平方向,子组件从终点端沿着FlexDirection.Row相反的方向开始排布。 +![](figures/direction.png) - ```ts - Flex({ direction: FlexDirection.RowReverse }) { - Text('1').width('33%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(50).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .height(70) - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` +- FlexDirection.Row(默认值):主轴为水平方向,子组件从起始端沿着水平方向开始排布。 - ![zh-cn_image_0000001218739566](figures/zh-cn_image_0000001218739566.png) + ```ts + Flex({ direction: FlexDirection.Row }) { + Text('1').width('33%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(50).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .height(70) + .width('90%') + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + ![zh-cn_image_0000001218579606](figures/zh-cn_image_0000001218579606.png) + +- FlexDirection.RowReverse:主轴为水平方向,子组件从终点端沿着FlexDirection. Row相反的方向开始排布。 + + ```ts + Flex({ direction: FlexDirection.RowReverse }) { + Text('1').width('33%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(50).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .height(70) + .width('90%') + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001218739566](figures/zh-cn_image_0000001218739566.png) - FlexDirection.Column:主轴为垂直方向,子组件从起始端沿着垂直方向开始排布。 - ```ts - Flex({ direction: FlexDirection.Column }) { - Text('1').width('100%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('100%').height(50).backgroundColor(0xD2B48C) - Text('3').width('100%').height(50).backgroundColor(0xF5DEB3) - } - .height(70) - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001263019457](figures/zh-cn_image_0000001263019457.png) - -- FlexDirection.ColumnReverse:主轴为垂直方向,子组件从终点端沿着FlexDirection.Column相反的方向开始排布。 - - ```ts - Flex({ direction: FlexDirection.ColumnReverse }) { - Text('1').width('100%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('100%').height(50).backgroundColor(0xD2B48C) - Text('3').width('100%').height(50).backgroundColor(0xF5DEB3) - } - .height(70) - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001263339459](figures/zh-cn_image_0000001263339459.png) - - -## 弹性布局换行 - -默认情况下,子组件在Flex容器中都排在一条线(又称"轴线")上。通过wrap参数设置其他换行方式,可选值有: - -- FlexWrap.NoWrap : 不换行。如果子元素的宽度总和大于父元素的宽度,则子元素会被压缩宽度。 - - ```ts - Flex({ wrap: FlexWrap.NoWrap }) { - Text('1').width('50%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('50%').height(50).backgroundColor(0xD2B48C) - Text('3').width('50%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001263139409](figures/zh-cn_image_0000001263139409.png) - -- FlexWrap.Wrap:换行。 - - ```ts - Flex({ wrap: FlexWrap.Wrap }) { - Text('1').width('50%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('50%').height(50).backgroundColor(0xD2B48C) - Text('3').width('50%').height(50).backgroundColor(0xD2B48C) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001218419614](figures/zh-cn_image_0000001218419614.png) - -- FlexWrap.WrapReverse:换行,且与行排列方向相反。 - - ```ts - Flex({ wrap: FlexWrap.WrapReverse}) { - Text('1').width('50%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('50%').height(50).backgroundColor(0xD2B48C) - Text('3').width('50%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001263259399](figures/zh-cn_image_0000001263259399.png) - - -## 弹性布局对齐方式 - - -### 主轴对齐 - -可以通过justifyContent参数设置在主轴的对齐方式,可选值有: - -- FlexAlign.Start: 元素在主轴方向首端对齐, 第一个元素与行首对齐,同时后续的元素与前一个对齐。 - - ```ts - Flex({ justifyContent: FlexAlign.Start }) { - Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('20%').height(50).backgroundColor(0xD2B48C) - Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001218259634](figures/zh-cn_image_0000001218259634.png) - -- FlexAlign.Center: 元素在主轴方向中心对齐,第一个元素与行首的距离与最后一个元素与行尾距离相同。 - - ```ts - Flex({ justifyContent: FlexAlign.Center }) { - Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('20%').height(50).backgroundColor(0xD2B48C) - Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001218579608](figures/zh-cn_image_0000001218579608.png) - -- FlexAlign.End: 元素在主轴方向尾部对齐, 最后一个元素与行尾对齐,其他元素与后一个对齐。 - - ```ts - Flex({ justifyContent: FlexAlign.End }) { - Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('20%').height(50).backgroundColor(0xD2B48C) - Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001218739568](figures/zh-cn_image_0000001218739568.png) - -- FlexAlign.SpaceBetween: Flex主轴方向均匀分配弹性元素,相邻元素之间距离相同。 第一个元素与行首对齐,最后一个元素与行尾对齐。 - - ```ts - Flex({ justifyContent: FlexAlign.SpaceBetween }) { - Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('20%').height(50).backgroundColor(0xD2B48C) - Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001263019461](figures/zh-cn_image_0000001263019461.png) - -- FlexAlign.SpaceAround: Flex主轴方向均匀分配弹性元素,相邻元素之间距离相同。 第一个元素到行首的距离和最后一个元素到行尾的距离是相邻元素之间距离的一半。 - - ```ts - Flex({ justifyContent: FlexAlign.SpaceAround }) { - Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('20%').height(50).backgroundColor(0xD2B48C) - Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001263339461](figures/zh-cn_image_0000001263339461.png) - -- FlexAlign.SpaceEvenly: Flex主轴方向元素等间距布局, 相邻元素之间的间距、第一个元素与行首的间距、最后一个元素到行尾的间距都完全一样。 - - ```ts - Flex({ justifyContent: FlexAlign.SpaceEvenly }) { - Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('20%').height(50).backgroundColor(0xD2B48C) - Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001263139411](figures/zh-cn_image_0000001263139411.png) - - -### 交叉轴对齐 - -可以通过alignItems参数设置在交叉轴的对齐方式,可选值有: + ```ts + Flex({ direction: FlexDirection.Column }) { + Text('1').width('100%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('100%').height(50).backgroundColor(0xD2B48C) + Text('3').width('100%').height(50).backgroundColor(0xF5DEB3) + } + .height(70) + .width('90%') + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001263019457](figures/zh-cn_image_0000001263019457.png) + +- FlexDirection.ColumnReverse:主轴为垂直方向,子组件从终点端沿着FlexDirection. Column相反的方向开始排布。 + + ```ts + Flex({ direction: FlexDirection.ColumnReverse }) { + Text('1').width('100%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('100%').height(50).backgroundColor(0xD2B48C) + Text('3').width('100%').height(50).backgroundColor(0xF5DEB3) + } + .height(70) + .width('90%') + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001263339459](figures/zh-cn_image_0000001263339459.png) + +### 弹性布局换行 + +默认情况下,子组件在Flex容器中都排在一条线(又称"轴线")上。通过wrap参数设置子组件换行方式。可选值有: + +- FlexWrap. NoWrap(默认值): 不换行。如果子组件的宽度总和大于父元素的宽度,则子组件会被压缩宽度。 + + ```ts + Flex({ wrap: FlexWrap.NoWrap }) { + Text('1').width('50%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('50%').height(50).backgroundColor(0xD2B48C) + Text('3').width('50%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001263139409](figures/zh-cn_image_0000001263139409.png) + +- FlexWrap. Wrap:换行,每一行子组件按照主轴方向排列。 + + ```ts + Flex({ wrap: FlexWrap.Wrap }) { + Text('1').width('50%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('50%').height(50).backgroundColor(0xD2B48C) + Text('3').width('50%').height(50).backgroundColor(0xD2B48C) + } + .width('90%') + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001218419614](figures/zh-cn_image_0000001218419614.png) + +- FlexWrap. WrapReverse:换行,每一行子组件按照主轴反方向排列。 + + ```ts + Flex({ wrap: FlexWrap.WrapReverse}) { + Text('1').width('50%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('50%').height(50).backgroundColor(0xD2B48C) + Text('3').width('50%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001263259399](figures/zh-cn_image_0000001263259399.png) + +### 弹性布局对齐方式 + +#### 主轴对齐 + +通过justifyContent参数设置在主轴方向的对齐方式,存在下面六种情况: + +![](figures/justifyContent.png) + +- FlexAlign.Start(默认值): 子组件在主轴方向起始端对齐, 第一个子组件与父元素边沿对齐,其他元素与前一个元素对齐。 + + ```ts + Flex({ justifyContent: FlexAlign.Start }) { + Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('20%').height(50).backgroundColor(0xD2B48C) + Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding({ top: 10, bottom: 10 }) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001218259634](figures/mainStart.png) + +- FlexAlign.Center: 子组件在主轴方向居中对齐。 + + ```ts + Flex({ justifyContent: FlexAlign.Center }) { + Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('20%').height(50).backgroundColor(0xD2B48C) + Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding({ top: 10, bottom: 10 }) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001218579608](figures/mainCenter.png) + +- FlexAlign.End: 子组件在主轴方向终点端对齐, 最后一个子组件与父元素边沿对齐,其他元素与后一个元素对齐。 + + ```ts + Flex({ justifyContent: FlexAlign.End }) { + Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('20%').height(50).backgroundColor(0xD2B48C) + Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding({ top: 10, bottom: 10 }) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001218739568](figures/mainEnd.png) + +- FlexAlign.SpaceBetween: Flex主轴方向均匀分配弹性元素,相邻子组件之间距离相同。第一个子组件和最后一个子组件与父元素边沿对齐。 + + ```ts + Flex({ justifyContent: FlexAlign.SpaceBetween }) { + Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('20%').height(50).backgroundColor(0xD2B48C) + Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding({ top: 10, bottom: 10 }) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001263019461](figures/mainSpacebetween.png) + +- FlexAlign.SpaceAround: Flex主轴方向均匀分配弹性元素,相邻子组件之间距离相同。第一个子组件到主轴起始端的距离和最后一个子组件到主轴终点端的距离是相邻元素之间距离的一半。 + + ```ts + Flex({ justifyContent: FlexAlign.SpaceAround }) { + Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('20%').height(50).backgroundColor(0xD2B48C) + Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding({ top: 10, bottom: 10 }) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001263339461](figures/mainSpacearound.png) + +- FlexAlign.SpaceEvenly: Flex主轴方向元素等间距布局,相邻子组件之间的间距、第一个子组件与主轴起始端的间距、最后一个子组件到主轴终点端的间距均相等。 + + ```ts + Flex({ justifyContent: FlexAlign.SpaceEvenly }) { + Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('20%').height(50).backgroundColor(0xD2B48C) + Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding({ top: 10, bottom: 10 }) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001263139411](figures/mainSpaceevenly.png) + +#### 交叉轴对齐 + +容器和子组件都可以设置交叉轴对齐方式,且子组件设置的对齐方式优先级较高。 + +##### 容器组件设置交叉轴对齐 +可以通过Flex组件的alignItems参数设置子组件在交叉轴的对齐方式,可选值有: - ItemAlign.Auto: 使用Flex容器中默认配置。 - ```ts - Flex({ alignItems: ItemAlign.Auto }) { - Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(40).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .size({width: '90%', height: 80}) - .padding(10) - .backgroundColor(0xAFEEEE) - ``` + ```ts + Flex({ alignItems: ItemAlign.Auto }) { + Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(40).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .size({width: '90%', height: 80}) + .padding(10) + .backgroundColor(0xAFEEEE) + ``` - ![zh-cn_image_0000001218419616](figures/zh-cn_image_0000001218419616.png) + ![zh-cn_image_0000001218419616](figures/zh-cn_image_0000001218419616.png) - ItemAlign.Start: 交叉轴方向首部对齐。 - ```ts - Flex({ alignItems: ItemAlign.Start }) { - Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(40).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .size({width: '90%', height: 80}) - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001263259401](figures/zh-cn_image_0000001263259401.png) + ```ts + Flex({ alignItems: ItemAlign.Start }) { + Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(40).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .size({width: '90%', height: 80}) + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001263259401](figures/zh-cn_image_0000001263259401.png) - ItemAlign.Center: 交叉轴方向居中对齐。 - ```ts - Flex({ alignItems: ItemAlign.Center }) { - Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(40).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .size({width: '90%', height: 80}) - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001218259636](figures/zh-cn_image_0000001218259636.png) + ```ts + Flex({ alignItems: ItemAlign.Center }) { + Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(40).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .size({width: '90%', height: 80}) + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001218259636](figures/zh-cn_image_0000001218259636.png) - ItemAlign.End:交叉轴方向底部对齐。 - ```ts - Flex({ alignItems: ItemAlign.End }) { - Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(40).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .size({width: '90%', height: 80}) - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001218579610](figures/zh-cn_image_0000001218579610.png) + ```ts + Flex({ alignItems: ItemAlign.End }) { + Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(40).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .size({width: '90%', height: 80}) + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001218579610](figures/zh-cn_image_0000001218579610.png) - ItemAlign.Stretch:交叉轴方向拉伸填充,在未设置尺寸时,拉伸到容器尺寸。 - ```ts - Flex({ alignItems: ItemAlign.Stretch }) { - Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(40).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .size({width: '90%', height: 80}) - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001218739570](figures/zh-cn_image_0000001218739570.png) + ```ts + Flex({ alignItems: ItemAlign.Stretch }) { + Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(40).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .size({width: '90%', height: 80}) + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001218739570](figures/zh-cn_image_0000001218739570.png) + +- ItemAlign. Baseline:交叉轴方向文本基线对齐。 + + ```ts + Flex({ alignItems: ItemAlign.Baseline }) { + Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(40).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .size({width: '90%', height: 80}) + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001263019463](figures/zh-cn_image_0000001263019463.png) + +##### 子组件设置交叉轴对齐 +子组件的alignSelf属性也可以设置子组件在父容器交叉轴的对齐格式,且会覆盖Flex布局容器中alignItems默认配置。如下例所示: -- ItemAlign.Baseline:交叉轴方向文本基线对齐。 +```ts +Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center }) { //容器组件设置子组件居中 + Text('alignSelf Start').width('25%').height(80) + .alignSelf(ItemAlign.Start) + .backgroundColor(0xF5DEB3) + Text('alignSelf Baseline') + .alignSelf(ItemAlign.Baseline) + .width('25%') + .height(80) + .backgroundColor(0xD2B48C) + Text('alignSelf Baseline').width('25%').height(100) + .backgroundColor(0xF5DEB3) + .alignSelf(ItemAlign.Baseline) + Text('no alignSelf').width('25%').height(100) + .backgroundColor(0xD2B48C) + Text('no alignSelf').width('25%').height(100) + .backgroundColor(0xF5DEB3) + +}.width('90%').height(220).backgroundColor(0xAFEEEE) +``` +![](figures/alignself.png) + +上例中,Flex容器中alignItems设置交叉轴子组件的对齐方式为居中,子组件自身设置了alignSelf属性的情况,覆盖父组件的alignItem值,表现为alignSelf的定义。 + +#### 内容对齐 + +可以通过alignContent参数设置子组件各行在交叉轴剩余空间内的对齐方式,只在多行的flex布局中生效,可选值有: + +- FlexAlign.Start: 子组件各行与交叉轴起点对齐。 + + ```ts + Flex({ justifyContent: FlexAlign.SpaceBetween, wrap: FlexWrap.Wrap, alignContent: FlexAlign.Start }) { + Text('1').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('2').width('60%').height(20).backgroundColor(0xD2B48C) + Text('3').width('40%').height(20).backgroundColor(0xD2B48C) + Text('4').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('5').width('20%').height(20).backgroundColor(0xD2B48C) + } + .width('90%') + .height(100) + .backgroundColor(0xAFEEEE) + ``` + + ![crossStart.png](figures/crossStart.png) + +- FlexAlign.Center: 子组件各行在交叉轴方向居中对齐。 + + ```ts + Flex({ justifyContent: FlexAlign.SpaceBetween, wrap: FlexWrap.Wrap, alignContent: FlexAlign.Center }) { + Text('1').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('2').width('60%').height(20).backgroundColor(0xD2B48C) + Text('3').width('40%').height(20).backgroundColor(0xD2B48C) + Text('4').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('5').width('20%').height(20).backgroundColor(0xD2B48C) + } + .width('90%') + .height(100) + .backgroundColor(0xAFEEEE) + ``` + + ![crossCenter.png](figures/crossCenter.png) + +- FlexAlign.End: 子组件各行与交叉轴终点对齐。 + + ```ts + Flex({ justifyContent: FlexAlign.SpaceBetween, wrap: FlexWrap.Wrap, alignContent: FlexAlign.End }) { + Text('1').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('2').width('60%').height(20).backgroundColor(0xD2B48C) + Text('3').width('40%').height(20).backgroundColor(0xD2B48C) + Text('4').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('5').width('20%').height(20).backgroundColor(0xD2B48C) + } + .width('90%') + .height(100) + .backgroundColor(0xAFEEEE) + ``` + + ![crossEnd.png](figures/crossEnd.png) + +- FlexAlign.SpaceBetween: 子组件各行与交叉轴两端对齐,各行间垂直间距平均分布。 + + ```ts + Flex({ justifyContent: FlexAlign.SpaceBetween, wrap: FlexWrap.Wrap, alignContent: FlexAlign.SpaceBetween }) { + Text('1').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('2').width('60%').height(20).backgroundColor(0xD2B48C) + Text('3').width('40%').height(20).backgroundColor(0xD2B48C) + Text('4').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('5').width('20%').height(20).backgroundColor(0xD2B48C) + } + .width('90%') + .height(100) + .backgroundColor(0xAFEEEE) + ``` + + ![crossSpacebetween.png](figures/crossSpacebetween.png) + +- FlexAlign.SpaceAround: 子组件各行间距相等,是元素首尾行与交叉轴两端距离的两倍。 + + ```ts + Flex({ justifyContent: FlexAlign.SpaceBetween, wrap: FlexWrap.Wrap, alignContent: FlexAlign.SpaceAround }) { + Text('1').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('2').width('60%').height(20).backgroundColor(0xD2B48C) + Text('3').width('40%').height(20).backgroundColor(0xD2B48C) + Text('4').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('5').width('20%').height(20).backgroundColor(0xD2B48C) + } + .width('90%') + .height(100) + .backgroundColor(0xAFEEEE) + ``` + + ![crossSpacearound.png](figures/crossSpacearound.png) + +- FlexAlign.SpaceEvenly: 子组件各行间距,子组件首尾行与交叉轴两端距离都相等。 + + ```ts + Flex({ justifyContent: FlexAlign.SpaceBetween, wrap: FlexWrap.Wrap, alignContent: FlexAlign.SpaceAround }) { + Text('1').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('2').width('60%').height(20).backgroundColor(0xD2B48C) + Text('3').width('40%').height(20).backgroundColor(0xD2B48C) + Text('4').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('5').width('20%').height(20).backgroundColor(0xD2B48C) + } + .width('90%') + .height(100) + .backgroundColor(0xAFEEEE) + ``` + + ![crossSpaceevenly.png](figures/crossSpaceevenly.png) + +### 弹性布局的自适应拉伸 + +在弹性布局父组件尺寸不够大的时候,通过子组件的下面几个属性设置其再父容器的占比,达到自适应布局能力。 +- flexBasis: 设置子组件在父容器主轴方向上的基准尺寸。如果设置了该值,则子项占用的空间为设置的值;如果没设置或者为auto,那子项的空间为width/height的值。 + ```ts - Flex({ alignItems: ItemAlign.Baseline }) { - Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(40).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .size({width: '90%', height: 80}) - .padding(10) - .backgroundColor(0xAFEEEE) + Flex() { + Text('flexBasis("auto")') + .flexBasis('auto') // 未设置width以及flexBasis值为auto,内容自身宽松 + .height(100) + .backgroundColor(0xF5DEB3) + Text('flexBasis("auto")'+' width("40%")') + .width('40%') + .flexBasis('auto') //设置width以及flexBasis值auto,使用width的值 + .height(100) + .backgroundColor(0xD2B48C) + + Text('flexBasis(100)') // 未设置width以及flexBasis值为100,宽度为100vp + .flexBasis(100) + .height(100) + .backgroundColor(0xF5DEB3) + + Text('flexBasis(100)') + .flexBasis(100) + .width(200) // flexBasis值为100,覆盖width的设置值,宽度为100vp + .height(100) + .backgroundColor(0xD2B48C) + }.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE) ``` + + ![](figures/flexbasis.png) - ![zh-cn_image_0000001263019463](figures/zh-cn_image_0000001263019463.png) - +- flexGrow: 设置父容器的剩余空间分配给此属性所在组件的比例。用于"瓜分"父组件的剩余空间。 -### 内容对齐 - -可以通过alignContent参数设置在换行组件的行在交叉轴剩余空间内的对齐方式,可选值有: - -- FlexAlign.Start: 左对齐。 - -- FlexAlign.Center: 居中对齐。 - -- FlexAlign.End: 右对齐。 - -- FlexAlign.SpaceBetween: flex items之间的距离相等,与main start、main end两端对齐。 + ```ts + Flex() { + Text('flexGrow(1)') + .flexGrow(2) + .width(100) + .height(100) + .backgroundColor(0xF5DEB3) + + Text('flexGrow(3)') + .flexGrow(2) + .width(100) + .height(100) + .backgroundColor(0xD2B48C) + + Text('no flexGrow') + .width(100) + .height(100) + .backgroundColor(0xF5DEB3) + }.width(400).height(120).padding(10).backgroundColor(0xAFEEEE) + ``` + + ![](figures/flexgrow.png) -- FlexAlign.SpaceAround: flex items之间的距离相等,flex items与main start、main end之间的距离等于flex items之间距离的一半。 +上图中,父容器宽度400vp, 三个子组件原始宽度为100vp,综合300vp,剩余空间100vp根据flexGrow值的占比分配给子组件,未设置flexGrow的子组件不参与“瓜分”。 +第一个元素以及第二个元素以2:3分配剩下的100vp。第一个元素为100vp+100vp*2/5=140vp,第二个元素为100vp+100vp*3/5=160vp。 -- FlexAlign.SpaceEvenly: flex items之间的距离相等,flex items与main start、main end之间的距离等于flex items之间的距离。 +- flexShrink: 当父容器空间不足时,子组件的压缩比例。 + ```ts + Flex({ direction: FlexDirection.Row }) { + Text('flexShrink(3)') + .flexShrink(3) + .width(200) + .height(100) + .backgroundColor(0xF5DEB3) + + Text('no flexShrink') + .width(200) + .height(100) + .backgroundColor(0xD2B48C) + + Text('flexShrink(2)') + .flexShrink(2) + .width(200) + .height(100) + .backgroundColor(0xF5DEB3) + }.width(400).height(120).padding(10).backgroundColor(0xAFEEEE) + ``` + + ![](figures/flexshrink.png) ## 场景示例 - 可使用弹性布局做出子元素排列方式为水平方向排列,且子元素的总宽度超出父元素的宽度不换行,子元素在水平方向两端对齐,中间间距由除首尾外的子元素平分,竖直方向上子元素居中的效果。 +使用弹性布局,可以实现子组件沿水平方向排列,两端对齐,子组件间距平分,竖直方向上子组件居中的效果。示例如下: ```ts -@Entry +@Entry @Component struct FlexExample { build() { @@ -358,7 +567,6 @@ struct FlexExample { } .height(70) .width('90%') - .padding(10) .backgroundColor(0xAFEEEE) }.width('100%').margin({ top: 5 }) }.width('100%') @@ -366,9 +574,7 @@ struct FlexExample { } ``` - -![zh-cn_image_0000001261605867](figures/zh-cn_image_0000001261605867.png) - +![zh-cn_image_0000001261605867](figures/flexExample.png) ## 相关实例 diff --git a/zh-cn/application-dev/ui/ui-ts-layout-grid-container-new.md b/zh-cn/application-dev/ui/ui-ts-layout-grid-container-new.md new file mode 100644 index 0000000000000000000000000000000000000000..c7346b6212432a1fec21def1f4bd81e719248568 --- /dev/null +++ b/zh-cn/application-dev/ui/ui-ts-layout-grid-container-new.md @@ -0,0 +1,391 @@ +# 栅格布局 + +栅格组件[GridRow](../reference/arkui-ts/ts-container-gridrow.md)和[GridCol](../reference/arkui-ts/ts-container-gridcol.md) +相对于[GridContainer](../reference/arkui-ts/ts-container-gridcontainer.md)提供了更灵活、更全面的栅格系统实现方案。GridRow为栅格容器组件,只与栅格子组件GridCol在栅格布局场景中使用。 + + +## 栅格容器GridRow + + +栅格容器有columns、gutter、direction、breakpoints四个属性。 +- columns: 栅格布局的主要定位工具,设置栅格布局的总列数。 +- gutter: 设置元素之间的距离,决定内容间的紧密程度。 +- direction: 设置栅格子组件在栅格容器中的排列方向。 +- breakpoints:以设备宽度为基准,将应用宽度分成了几个不同的区间,即不同的断点。开发者可根据需要在不同的区间下实现不同的页面布局效果。 + + +首先通过设置断点,得到一系列断点区间;然后,借助栅格组件能力监听应用窗口大小的变化,判断应用当前处于哪个断点区间,最后调整应用的布局。 + +### 栅格系统断点 + +断点以设备宽度为基准,将应用宽度分成了几个不同的区间,即不同的断点。开发者根据需求在不同的区间实现不同的页面布局效果。 +[栅格系统默认断点](ui-ts-layout-grid-container.md#系统栅格断点)将设备宽度分为xs、sm、md、lg四类,尺寸范围如下: + +| 断点名称 | 取值范围(vp)| +| --------| ------ | +| xs | [0, 320) | +| sm | [320, 520) | +| md | [520, 840) | +| lg | [840, +∞) | + +在GridRow新栅格组件中,允许开发者使用breakpoints自定义修改断点的取值范围,最多支持6个断点,除了默认的四个断点外, +还可以启用xl,xxl两个断点,支持六种不同尺寸(xs, sm, md, lg, xl, xxl)设备的布局设置。 + +| 断点名称 | 设备描述 | +| ----- | ---------------------------------------- | +| xs | 最小宽度类型设备。 | +| sm | 小宽度类型设备。 | +| md | 中等宽度类型设备。 | +| lg | 大宽度类型设备。 | +| xl | 特大宽度类型设备。 | +| xxl | 超大宽度类型设备。 | + +- 针对断点位置,开发者根据实际使用场景,通过一个单调递增数组设置。由于breakpoints最多支持六个断点,单调递增数组长度最大为5。 + + ```ts + breakpoints: {value: ["100vp", "200vp"]} + ``` + + 表示启用xs、sm、md共3个断点,小于100vp为xs,100vp-200vp为sm,大于200vp为md。 + + ```ts + breakpoints: {value: ["320vp", "520vp", "840vp", "1080vp"]} + ``` + + 表示启用xs、sm、md、lg、xl共5个断点,小于320vp为xs,320vp-520vp为sm,520vp-840vp为md,840vp-1080vp为lg,大于1080vp为xl。 + + +- 栅格系统通过监听窗口或容器的尺寸变化进行断点,通过reference设置断点切换参考物。 考虑到应用可能以非全屏窗口的形式显示,以应用窗口宽度为参照物更为通用。 + +下例中,使用栅格的默认列数12列,通过断点设置将应用宽度分成六个区间,在各区间中,每个栅格子元素占用的列数均不同。效果如图: + ```ts +GridRow({ + breakpoints: { + value: ['200vp', '300vp', '400vp', '500vp', '600vp'], + reference: BreakpointsReference.WindowSize + } +}) { + ForEach(this.bgColors, (color, index) => { + GridCol({ + span: { + xs: 2, + sm: 3, + md: 4, + lg: 6, + xl: 8, + xxl: 12 + } + }) { + Row() { + Text(${index}) + }.width("100%").height("50vp") + }.backgroundColor(color) + }) +} +``` + +![](figures/breakpoints.gif) + + + +### 栅格布局的总列数 + +GridRow中通过columns设置栅格布局的总列数。 + +- columns默认值为12,当未设置columns时,在任何断点下,栅格布局被分成12列。 + ```ts + GridRow() { + ForEach(this.bgColors, (item, index) => { + GridCol() { + Row() { + Text(`${index + 1}`) + }.width("100%").height("50") + }.backgroundColor(item) + }) + } + ``` + + ![](figures/columns1.png) + +- 当columns类型为number时,栅格布局在任何尺寸设备下都被分为columns列。下面分别设置栅格布局列数为4和8,子元素默认占一列,效果如下: + + ```ts + Row() { + GridRow({ columns: 4 }) { + ForEach(this.bgColors, (item, index) => { + GridCol() { + Row() { + Text(`${index + 1}`) + }.width("100%").height("50") + }.backgroundColor(item) + }) + } + .width("100%").height("100%") + .onBreakpointChange((breakpoint) => { + this.currentBp = breakpoint + }) + } + .height(160) + .border({ color: Color.Blue, width: 2 }) + .width('90%') + + Row() { + GridRow({ columns: 8 }) { + ForEach(this.bgColors, (item, index) => { + GridCol() { + Row() { + Text(`${index + 1}`) + }.width("100%").height("50") + }.backgroundColor(item) + }) + } + .width("100%").height("100%") + .onBreakpointChange((breakpoint) => { + this.currentBp = breakpoint + }) + } + .height(160) + .border({ color: Color.Blue, width: 2 }) + .width('90%') + ``` + + ![](figures/columns2.png) + + +- 当columns类型为GridRowColumnOption时,支持下面六种不同尺寸(xs, sm, md, lg, xl, xxl)设备的总列数设置,各个尺寸下数值可不同。 + + ```ts + GridRow({ columns: { sm: 4, md: 8 }, breakpoints: { value: ['200vp', '300vp', '400vp', '500vp', '600vp'] } }) { + ForEach(this.bgColors, (item, index) => { + GridCol() { + Row() { + Text(`${index + 1}`) + }.width("100%").height("50") + }.backgroundColor(item) + }) + } + ``` + ![](figures/columns3.gif) + + 如上,若只设置sm, md的栅格总列数,则较小的尺寸使用默认columns值12,较大的尺寸使用前一个尺寸的columns。这里只设置sm:8, md:10,则较小尺寸的xs:12,较大尺寸的参照md的设置,lg:10, xl:10, xxl:10。 + +### 栅格子组件间距 + +GridRow中通过gutter设置子元素在水平和垂直方向的间距。 + +- 当gutter类型为number时,同时设置栅格子组件间水平和垂直方向边距且相等。下例中,设置子组件水平与垂直方向距离相邻元素的间距为10。 + + ```ts + GridRow({ gutter: 10 }){} + ``` + + ![](figures/gutter1.png) + + + +- 当gutter类型为GutterOption时,单独设置栅格子组件水平垂直边距,x属性为水平方向间距,y为垂直方向间距。 + + ```ts + GridRow({ gutter: { x: 20, y: 50 } }){} + ``` + + ![](figures/gutter2.png) + + + +### 排列方向 + +通过GridRow的direction属性设置栅格子组件在栅格容器中的排列方向。 + +- 子组件默认从左往右排列。 + + ```ts + GridRow({ direction: GridRowDirection.Row }){} + ``` + ![](figures/direction1.png) + +- 子组件从右往左排列。 + + ```ts + GridRow({ direction: GridRowDirection.RowReverse }){} + ``` + + ![](figures/direction2.png) + + + +## 栅格子组件GridCol + +GridCol组件作为GridRow组件的子组件,通过给GridCol传参或者设置属性两种方式,设置span,offset,order的值。 + +- span的设置 + + ```ts + GridCol({ span: 2 }){} + GridCol({ span: { xs: 1, sm: 2, md: 3, lg: 4 } }){} + GridCol(){}.span(2) + GridCol(){}.span({ xs: 1, sm: 2, md: 3, lg: 4 }) + ``` + +- offset的设置 + + ```ts + GridCol({ offset: 2 }){} + GridCol({ offset: { xs: 2, sm: 2, md: 2, lg: 2 } }){} + GridCol(){}.offset(2) + GridCol(){}.offset({ xs: 1, sm: 2, md: 3, lg: 4 }) + ``` + +- order的设置 + + ```ts + GridCol({ order: 2 }){} + GridCol({ order: { xs: 1, sm: 2, md: 3, lg: 4 } }){} + GridCol(){}.order(2) + GridCol(){}.order({ xs: 1, sm: 2, md: 3, lg: 4 }) + ``` + + 下面使用传参的方式演示各属性的使用。 + +### span + +子组件占栅格布局的列数,决定了子组件的宽度,默认为1。 + +- 当类型为number时,子组件在所有尺寸设备下占用的列数相同。 + + ```ts + GridRow({ columns: 8 }) { + ForEach(this.bgColors, (color, index) => { + GridCol({ span: 2 }) { + Row() { + Text(${index}) + }.width("100%").height("50vp") + } + .backgroundColor(color) + }) + } + ``` + + ![](figures/span1.png) + +- 当类型为GridColColumnOption时,支持六种不同尺寸(xs, sm, md, lg, xl, xxl)设备中子组件所占列数设置,各个尺寸下数值可不同。 + + ```ts + GridRow({ columns: 8 }) { + ForEach(this.bgColors, (color, index) => { + GridCol({ span: { xs: 1, sm: 2, md: 3, lg: 4 } }) { + Row() { + Text(${index}) + }.width("100%").height("50vp") + } + .backgroundColor(color) + }) + } + ``` + + ![](figures/span2.gif) + +### offset + +栅格子组件相对于前一个子组件的偏移列数,默认为0。 +- 当类型为number时,子组件偏移相同列数。 + + ```ts + GridRow() { + ForEach(this.bgColors, (color, index) => { + GridCol({ offset: 2 }) { + Row() { + Text("" + index) + }.width("100%").height("50vp") + } + .backgroundColor(color) + }) + } + ``` + + ![](figures/offset1.png) + + 栅格默认分成12列,每一个子组件默认占1列,偏移2列,每个子组件及间距共占3列,一行放四个子组件。 + + +- 当类型为GridColColumnOption时,支持六种不同尺寸(xs, sm, md, lg, xl, xxl)设备中子组件所占列数设置,各个尺寸下数值可不同。 + + ```ts + GridRow() { + ForEach(this.bgColors, (color, index) => { + GridCol({ offset: { xs: 1, sm: 2, md: 3, lg: 4 } }) { + Row() { + Text("" + index) + }.width("100%").height("50vp") + } + .backgroundColor(color) + }) + } + ``` + + ![](figures/offset2.gif) + +### order + + 栅格子组件的序号,决定子组件排列次序。当子组件不设置order或者设置相同的order, 子组件按照代码顺序展示。当子组件设置不同的order时,order较大的组件在前,较小的在后。 + 当子组件部分设置order,部分不设置order时,未设置order的子组件依次排序靠前,设置了order的子组件按照数值从大到小排列。 + + +- 当类型为number时,子组件在任何尺寸下排序次序一致。 + + ```ts + GridRow() { + GridCol({ order: 5 }) { + Row() { + Text("1") + }.width("100%").height("50vp") + }.backgroundColor(Color.Red) + GridCol({ order: 4 }) { + Row() { + Text("2") + }.width("100%").height("50vp") + }.backgroundColor(Color.Orange) + GridCol({ order: 3 }) { + Row() { + Text("3") + }.width("100%").height("50vp") + }.backgroundColor(Color.Yellow) + GridCol({ order: 2 }) { + Row() { + Text("4") + }.width("100%").height("50vp") + }.backgroundColor(Color.Green) + } + ``` + + ![](figures/order1.png) +- 当类型为GridColColumnOption时,支持六种不同尺寸(xs, sm, md, lg, xl, xxl)设备中子组件排序次序设置。 + + ```ts + GridRow() { + GridCol({ order: { xs:1, sm:5, md:3, lg:7}}) { + Row() { + Text("1") + }.width("100%").height("50vp") + }.backgroundColor(Color.Red) + GridCol({ order: { xs:2, sm:2, md:6, lg:1} }) { + Row() { + Text("2") + }.width("100%").height("50vp") + }.backgroundColor(Color.Orange) + GridCol({ order: { xs:3, sm:3, md:1, lg:6} }) { + Row() { + Text("3") + }.width("100%").height("50vp") + }.backgroundColor(Color.Yellow) + GridCol({ order: { xs:4, sm:4, md:2, lg:5} }) { + Row() { + Text("4") + }.width("100%").height("50vp") + }.backgroundColor(Color.Green) + } + ``` + + ![](figures/order2.gif) + + diff --git a/zh-cn/application-dev/ui/ui-ts-layout-grid-container.md b/zh-cn/application-dev/ui/ui-ts-layout-grid-container.md index dc0945724c0725d20d1be7da73790dd602fe71ca..420e594c188eead7944041bd6bffdde13e79c506 100644 --- a/zh-cn/application-dev/ui/ui-ts-layout-grid-container.md +++ b/zh-cn/application-dev/ui/ui-ts-layout-grid-container.md @@ -1,70 +1,76 @@ # 栅格布局 - 栅格系统作为一种辅助布局的定位工具,在平面设计和网站设计都起到了很好的作用,对移动设备的界面设计有较好的借鉴作用。总结栅格系统对于移动设备的优势主要有: - 1. 给布局提供一种可循的规律,解决多尺寸多设备的动态布局问题。 2. 给系统提供一种统一的定位标注,保证各模块各设备的布局一致性。 3. 给应用提供一种灵活的间距调整方法,满足特殊场景布局调整的可能性。 -为实现栅格布局效果,声明式范式提供了[GridContainer](../reference/arkui-ts/ts-container-gridcontainer.md)栅格容器组件,配合其子组件的通用属性useSizeType来实现栅格布局。 +为实现栅格布局效果,声明式范式提供了[GridContainer](../reference/arkui-ts/ts-container-gridcontainer.md)栅格容器组件,配合其子组件的通用属性[useSizeType](../reference/arkui-ts/ts-container-grid.md)来实现栅格布局。 ## 栅格系统 栅格系统有Column、Margin、Gutter三个概念。 - -![zh-cn_image_0000001217236574](figures/zh-cn_image_0000001217236574.png) - +![zh-cn_image_0000001224173302](figures/zh-cn_image_0000001224173302.png) 1. Gutter: - 用来控制元素与元素之间距离关系。可以根据设备的不同尺寸,定义不同的gutter值,作为栅格布局的统一规范。为了保证较好的视觉效果,通常gutter的取值不会大于margin的取值。 + 元素之间的距离,决定了内容间的紧密程度。作为栅格布局的统一规范。为了保证较好的视觉效果,通常gutter的取值不会大于margin的取值。 2. Margin: - 离栅格容器边缘的距离。可以根据设备的不同尺寸,定义不同的margin值,作为栅格布局的统一规范。 + 内容距栅格容器边缘的距离,决定了内容可展示的总宽度。作为栅格布局的统一规范。 3. Column: 栅格布局的主要定位工具。根据设备的不同尺寸,把栅格容器分割成不同的列数,在保证margin和gutter符合规范的情况下,根据总Column的个数计算每个Column列的宽度。 - ### 系统栅格断点 -系统根据不同水平宽度设备对应Column的数量关系,形成了一套断点规则定义。 - -系统以设备的水平宽度的屏幕密度像素值作为断点依据,根据当前设备水平宽度所在的断点范围,定义了设备的宽度类型。系统的栅格断点范围、设备宽度类型及其描述,以及对应的默认总列数(column),边距(margin),间隔(gutter)定义如下: +栅格系统以设备的水平宽度(屏幕密度像素值,vp)作为断点依据,定义设备的宽度类型,设置栅格总列数,间隔,边距,形成了一套断点规则。 +不同设备水平宽度下,栅格系统默认总列数(columns),边距(margin),间隔(gutter)定义如下: | 设备水平宽度断点范围 | 设备宽度类型 | 描述 | columns | gutter | margin | | ----------------------- | ------ | --------- | ------- | ------ | ------ | -| 0<水平宽度<320vp | XS | 最小宽度类型设备。 | 2 | 12vp | 12vp | -| 320vp<=水平宽度<600vp | SM | 小宽度类型设备。 | 4 | 24vp | 24vp | -| 600vp<=水平宽度<840vp | MD | 中等宽度类型设备。 | 8 | 24vp | 32vp | -| 840<=水平分辨率 | LG | 大宽度类型设备。 | 12 | 24vp | 48vp | +| 0< 水平宽度< 320vp | XS | 最小宽度类型设备。 | 2 | 12vp | 12vp | +| 320vp< =水平宽度< 600vp | SM | 小宽度类型设备。 | 4 | 24vp | 24vp | +| 600vp< =水平宽度< 840vp | MD | 中等宽度类型设备。 | 8 | 24vp | 32vp | +| 840< =水平分辨率 | LG | 大宽度类型设备。 | 12 | 24vp | 48vp | -## 如何使用 +> **说明:** +> +> ArkUI在API9对栅格组件做了重构,推出新的栅格组件[GridRow](../reference/arkui-ts/ts-container-gridrow.md)和[GridCol](../reference/arkui-ts/ts-container-gridcol.md),API9推荐使用新的栅格组件,参考[新栅格组件用法](ui-ts-layout-grid-container-new.md) +> -首先创建栅格容器组件,定义栅格布局,然后给栅格容器内的组件设置不同设备宽度类型下的占用列数。 +## GridContainer栅格组件使用 -### 创建栅格容器 +首先使用栅格容器组件创建栅格布局。 -通过接口`GridContainer(options?: { columns?: number | 'auto', sizeType?: SizeType, gutter?: Length, margin?: Length})`创建栅格容器,栅格容器内的所有子组件可以使用栅格布局。 +### 栅格容器创建与设置 -- 可以通过参数定义栅格布局的总列数(columns),间隔(gutter),两侧边距(margin)。例如栅格容器总共分为6列,列与列间隔为10vp, 两侧边距为20vp: +通过接口 `GridContainer(options?: { columns?: number | 'auto', sizeType?: SizeType, gutter?: Length, margin?: Length})` 创建栅格容器,栅格容器内的所有子组件可以使用栅格布局。 - ```ts - GridContainer({ columns: 6, gutter: 10, margin: 20 }) {} - ``` +通过参数定义栅格布局的总列数(columns),间隔(gutter),两侧边距(margin)。例如栅格容器总共分为6列,列与列间隔为10vp, 两侧边距为20vp: - 栅格容器不设置参数,或者sizeType设置为SizeType.Auto时使用默认的栅格系统定义,如: - ```ts - GridContainer() {} - ``` +```ts +GridContainer({ columns: 6, gutter: 10, margin: 20 }) {} +``` - 上述例子中,默认在小宽度类型设备(SizeType.SM)上,栅格容器被分为4列,列与列的间隔为24vp, 两侧边距是24vp。在中等宽度类型设备(SizeType.MD)上,栅格容器被分为8列,列与列的间隔为24vp,两侧边距是32vp。 +栅格容器不设置参数,或者sizeType设置为SizeType. Auto时使用默认的栅格系统定义,如: -- 也可以通过参数sizeType指定此栅格容器内的组件使用此设备宽度类型的栅格设置,如: +```ts +GridContainer() {} +``` - ```ts +```ts +GridContainer({ sizeType: SizeType.Auto }) +``` + +上述例子中,默认在小宽度类型设备(SizeType. SM)上,栅格容器被分为4列,列与列的间隔为24vp, 两侧边距是24vp。在中等宽度类型设备(SizeType. MD)上,栅格容器被分为8列,列与列的间隔为24vp,两侧边距是32vp。 + +也可以通过参数sizeType指定此栅格容器内的组件使用此设备宽度类型的栅格设置,如: + + + +```ts GridContainer({ sizeType: SizeType.SM }) { Row() { Text('1') @@ -78,9 +84,9 @@ } ``` - 上述例子中,不管在任何宽度类型的设备上, Text组件都使用SizeType.SM类型的栅格设置即占用3列,放置在第1列。 + 上述例子中,不管在任何宽度类型的设备上, Text组件都使用SizeType. SM类型的栅格设置, 即占用3列,放置在第1列。 -### 栅格容器内子组件的栅格设置 +### 子组件的栅格设置 栅格容器中的组件使用通用属性useSizeType设置不同的设备宽度类型的占用列数和列偏移。其中span表示栅格容器组件占据columns的数量;offset表示列偏移量,指将组件放置在哪一个columns上。 如: @@ -97,13 +103,14 @@ GridContainer() { } } ``` -其中`sm: { span: 2, offset: 0 } `指在设备宽度类型为SM的设备上,Text组件占用2列,且放在栅格容器的第1列上。 + +其中 `sm: { span: 2, offset: 0 } ` 指在设备宽度类型为SM的设备上,Text组件占用2列,且放在栅格容器的第1列上。 ![zh-cn_image_0000001218108718](figures/zh-cn_image_0000001218108719.png) ## 场景示例 -使用栅格布局可以灵活地在不同的设备宽度类型下呈现合适的效果,而不必书写大量的代码兼容不同宽度类型的设备。 +使用栅格布局可以灵活地在不同的设备宽度类型下呈现合适的效果,不必写大量的代码兼容不同宽度类型的设备。 ```ts @Entry @@ -144,11 +151,10 @@ struct GridContainerExample { } ``` - - -小宽度类型设备(SizeType.SM)运行效果: +小宽度类型设备(SizeType. SM)运行效果: ![zh-cn_image_0000001218108718](figures/zh-cn_image_0000001218108718.png) -中等宽度类型设备(SizeType.MD)运行效果: +中等宽度类型设备(SizeType. MD)运行效果: + ![zh-cn_image_0000001262748569](figures/zh-cn_image_0000001262748569.png) diff --git a/zh-cn/application-dev/ui/ui-ts-layout-grid.md b/zh-cn/application-dev/ui/ui-ts-layout-grid.md new file mode 100644 index 0000000000000000000000000000000000000000..69a9fde64de8d9cb79c0cb40c9f6d6eaba8ba757 --- /dev/null +++ b/zh-cn/application-dev/ui/ui-ts-layout-grid.md @@ -0,0 +1,273 @@ +# 网格布局 + +网格布局(GridLayout)是自适应布局中一种重要的布局,具备较强的页面均分能力,子组件占比控制能力。 +通过[Grid](../reference/arkui-ts/ts-container-grid.md)容器组件和子组件[GridItem](../reference/arkui-ts/ts-container-griditem.md)实现, +Grid用于设置网格布局相关参数,GridItem定义子组件相关特征。优势如下: + +1. 容器组件尺寸发生变化时,所有子组件以及间距等比例调整,实现布局的自适应能力。 +2. 支持自定义网格布局行数和列数,以及每行每列尺寸占比。 +3. 支持设置网格布局中子组件的行列间距。 +4. 支持设置子组件横跨几行或者几列。 + + + +## 容器组件Grid设置 + +### 行列数量占比 +通过Grid的组件的columnsTemplate和rowTemplate属性设置网格布局行列数量与尺寸占比。 + +下面以columnsTemplate为例,介绍该属性的设置,该属性值是一个由多个空格和'数字+fr'间隔拼接的字符串,fr的个数即网格布局的列数,fr前面的数值大小,用于计算该列在网格布局宽度上的占比,最终决定该列的宽度。 + +```ts +struct GridExample { + @State Number: Array = ['1', '2', '3', '4'] + + build() { + Column({ space: 5 }) { + Grid() { + ForEach(this.Number, (num: string) => { + GridItem() { + Text(`列${num}`) + .fontSize(16) + .textAlign(TextAlign.Center) + .backgroundColor(0xd0d0d0) + .width('100%') + .height('100%') + .borderRadius(5) + } + }) + } + .columnsTemplate('1fr 1fr 1fr 1fr') + .rowsTemplate('1fr') + .columnsGap(10) + .rowsGap(20) + .width('90%') + .backgroundColor(0xF0F0F0) + .height(100) + }.width('100%') + } +} +``` + +定义了四个等分的列,每列宽度相等。 + +```ts +struct GridExample { + @State Number: Array = ['1', '2', '3', '4'] + + build() { + Column({ space: 5 }) { + Grid() { + ForEach(this.Number, (num: string) => { + GridItem() { + Text(`列${num}`) + .fontSize(16) + .textAlign(TextAlign.Center) + .backgroundColor(0xd0d0d0) + .width('100%') + .height('100%') + .borderRadius(5) + } + }) + } + .columnsTemplate('1fr 2fr 3fr 4fr') + .rowsTemplate('1fr') + .columnsGap(10) + .rowsGap(20) + .width('90%') + .backgroundColor(0xF0F0F0) + .height(100) + }.width('100%') + } +} +``` + +定义了四列,每列宽度比值为1:2:3:4。 + +```ts +struct GridExample { + @State Number: Array = ['1', '2', '3'] + + build() { + Column({ space: 5 }) { + Grid() { + ForEach(this.Number, (num: string) => { + GridItem() { + Text(`列${num}`) + .fontSize(16) + .textAlign(TextAlign.Center) + .backgroundColor(0xd0d0d0) + .width('100%') + .height('100%') + .borderRadius(5) + } + }) + } + .columnsTemplate('4fr 2fr 3fr') + .rowsTemplate('1fr') + .columnsGap(10) + .rowsGap(20) + .width('90%') + .backgroundColor(0xF0F0F0) + .height(100) + }.width('100%') + } +} +``` + +定义了三列,每列宽度比值为4:2:3。 + +效果如下: + +![](figures/columnTemplate.png) + +### 排列方式 + +通过layoutDirection可以设置网格布局的主轴方向,决定子组件的排列方式。 +可选值包括Row,RowReverse, Column, ColumnReverse四种情况。 +效果如下: + +![](figures/gridlayout.png) + +### 行列间距 + +columnsGap用于设置网格子组件GridItem垂直方向的间距,rowsGap用于设置GridItem水平方向的间距。 + +```ts +Grid() +.columnsTemplate('1fr 1fr 1fr 1fr') +.columnsGap(10) +.rowsGap(20) +``` + +![](figures/columnGap.png) + +上图中,设置网格布局子组件间的垂直间距为20,水平间距为10。 + +## 网格子组件GridItem设置 + +### 设置子组件占的行列数 + +网格布局的行列标号从1开始,依次编号。 + +子组件横跨多行时,通过rowStart设置子组件起始行编号,rowEnd设置终点行编号。当rowStart值与rowEnd值相同时,子组件只占一个网格。示例如下: + +```ts +Grid() { + GridItem() { + Text('5') + .fontSize(16) + .textAlign(TextAlign.Center) + .textStyle() + }.rowStart(2).rowEnd(3) // 5子组件从第二列到第三列 + + GridItem() { + Text('4') + .fontSize(16) + .textAlign(TextAlign.Center) + .textStyle() + }.columnStart(4).columnEnd(5) // 4从第四列到第五列 + + GridItem() { + Text('6') + .fontSize(16) + .textAlign(TextAlign.Center) + .textStyle() + }.columnStart(2).columnEnd(4) // 6从第二列到第四列 + + GridItem() { + Text('9') + .fontSize(16) + .textAlign(TextAlign.Center) + .textStyle() + }.columnStart(3).columnEnd(4) // 从第三列到第四列 +} +.columnsTemplate('1fr 1fr 1fr 1fr 1fr') +.rowsTemplate('1fr 1fr 1fr') +.columnsGap(10) +.rowsGap(20) +.width('90%') +.backgroundColor(0xF0F0F0) +.height('200vp') +.layoutDirection(GridDirection.Column) +``` + +![](figures/griditem.png) + +## 场景示例 + +使用grid布局实现一个计算器的排布效果,代码如下: + +```ts +@Entry +@Component +struct GridExample { + @State Number: Array = ['1', '2', '3', '+', '4', '5', '6', '-', '7', '8', '9', '*', '0', '.', '/'] + + @Styles textStyle(){ + .backgroundColor(0xd0d0d0) + .width('100%') + .height('100%') + .borderRadius(5) + } + + build() { + Column({ space: 5 }) { + Grid() { + GridItem() { + Text('0') + .fontSize(30) + .textStyle() + }.columnStart(1).columnEnd(4) + + GridItem() { + Text('清空') + .fontSize(16) + .textAlign(TextAlign.Center) + .textStyle() + }.columnStart(1).columnEnd(2) + + GridItem() { + Text('回退') + .fontSize(16) + .textAlign(TextAlign.Center) + .textStyle() + }.columnStart(3).columnEnd(4) + + ForEach(this.Number, (day: string) => { + if (day === '0') { + GridItem() { + Text(day) + .fontSize(16) + .textAlign(TextAlign.Center) + .textStyle() + }.columnStart(1).columnEnd(2) + } else { + GridItem() { + Text(day) + .fontSize(16) + .textAlign(TextAlign.Center) + .textStyle() + } + } + }) + } + .columnsTemplate('1fr 1fr 1fr 1fr') + .rowsTemplate('2fr 1fr 1fr 1fr 1fr 1fr') + .columnsGap(10) + .rowsGap(15) + .width('90%') + .backgroundColor(0xF0F0F0) + .height('70%') + }.width('100%').margin({ top: 5 }) + } +} +``` + +在大屏设备上展示效果如下: + +![](figures/gridExp1.png) + +在小屏设备下展示效果如下: + +![](figures/gridExp2.png) diff --git a/zh-cn/application-dev/ui/ui-ts-layout-linear.md b/zh-cn/application-dev/ui/ui-ts-layout-linear.md new file mode 100644 index 0000000000000000000000000000000000000000..0e89b56ad71bb008cae24b6b3151ea7464cd7862 --- /dev/null +++ b/zh-cn/application-dev/ui/ui-ts-layout-linear.md @@ -0,0 +1,370 @@ +# 线性布局 + +线性布局(LinearLayout)是开发中最常用的布局。线性布局的子组件在线性方向上(水平方向和垂直方向)依次排列。 + +通过线性容器[Row](../reference/arkui-ts/ts-container-row.md)和[Column](../reference/arkui-ts/ts-container-column.md)实现线性布局。Column容器内子组件按照垂直方向排列,Row组件中,子组件按照水平方向排列。 + +## 线性布局的排列 + +线性布局的排列方向由所选容器组件决定。根据不同的排列方向,选择使用Row或Column容器创建线性布局,通过调整space,alignItems,justifyContent属性调整子组件的间距,水平垂直方向的对齐方式。 +1. 通过space参数设置主轴(排列方向)上子组件的间距。达到各子组件在排列方向上的等间距效果。 +2. 通过alignItems属性设置子组件在交叉轴(排列方向的垂直方向)的对齐方式。且在各类尺寸屏幕中,表现一致。其中,交叉轴为垂直方向时,取值为[VerticalAlign类型](../reference/arkui-ts/ts-appendix-enums.md#verticalalign),水平方向取值为[HorizontalAlign类型](../reference/arkui-ts/ts-appendix-enums.md#horizontalalign)。 +3. 通过justifyContent属性设置子组件在主轴(排列方向)上的对齐方式。实现布局的自适应均分能力。取值为[FlexAlign类型](../reference/arkui-ts/ts-appendix-enums.md#flexalign)。 + +具体使用以及效果如下表所示: + +|属性名|描述|Row效果图|Column效果图| +|------|---------------------------|----------------------------|---------------------------| +|space |- 横向布局中各子组件的在水平方向的间距
- 纵向布局中个子组件垂直方向间距| ![](figures/rowspace.png) | ![](figures/columnspace.png) | +|alignItems |容器排列方向的垂直方向上,子组件在父容器中的对齐方式|![](figures/rowalign.png) |![](figures/columnalign.png)| +|justifyContent |容器排列方向上,子组件在父容器中的对齐方式 |![](figures/rowjustify.png) |![](figures/columnjustify.png)| + +## 自适应拉伸 + +在线性布局下,常用空白填充组件[Blank](../reference/arkui-ts/ts-basic-components-blank.md),在容器主轴方向自动填充空白空间,达到自适应拉伸效果。 + +```ts +@Entry +@Component +struct BlankExample { + build() { + Column() { + Row() { + Text('Bluetooth').fontSize(18) + Blank() + Toggle({ type: ToggleType.Switch, isOn: true }) + }.backgroundColor(0xFFFFFF).borderRadius(15).padding({ left: 12 }).width('100%') + }.backgroundColor(0xEFEFEF).padding(20).width('100%') + } +} +``` + +![](figures/blank.gif) + +## 自适应缩放 + +自适应缩放是指在各种不同大小设备中,子组件按照预设的比例,尺寸随容器尺寸的变化而变化。在线性布局中有下列方法实现: + +1. 父容器尺寸确定时,设置了layoutWeight属性的子组件与兄弟元素占主轴尺寸按照权重进行分配,忽略元素本身尺寸设置,在任意尺寸设备下,自适应占满剩余空间。 + + ```ts + @Entry + @Component + struct layoutWeightExample { + build() { + Column() { + Text('1:2:3').width('100%') + Row() { + Column() { + Text('layoutWeight(1)') + .textAlign(TextAlign.Center) + }.layoutWeight(2).backgroundColor(0xffd306).height('100%') + + Column() { + Text('layoutWeight(2)') + .textAlign(TextAlign.Center) + }.layoutWeight(4).backgroundColor(0xffed97).height('100%') + + Column() { + Text('layoutWeight(6)') + .textAlign(TextAlign.Center) + }.layoutWeight(6).backgroundColor(0xffd306).height('100%') + + }.backgroundColor(0xffd306).height('30%') + + Text('2:5:3').width('100%') + Row() { + Column() { + Text('layoutWeight(2)') + .textAlign(TextAlign.Center) + }.layoutWeight(2).backgroundColor(0xffd306).height('100%') + + Column() { + Text('layoutWeight(5)') + .textAlign(TextAlign.Center) + }.layoutWeight(5).backgroundColor(0xffed97).height('100%') + + Column() { + Text('layoutWeight(3)') + .textAlign(TextAlign.Center) + }.layoutWeight(3).backgroundColor(0xffd306).height('100%') + }.backgroundColor(0xffd306).height('30%') + } + } + } + ``` + + ![](figures/layoutWeight.gif) + + +3. 父容器尺寸确定时,使用百分比设置子组件以及兄弟组件的width宽度,可以保证各自元素在任意尺寸下的自适应占比。 + + ```ts + @Entry + @Component + struct WidthExample { + build() { + Column() { + Row() { + Column() { + Text('left width 20%') + .textAlign(TextAlign.Center) + }.width('20%').backgroundColor(0xffd306).height('100%') + + Column() { + Text('center width 50%') + .textAlign(TextAlign.Center) + }.width('50%').backgroundColor(0xffed97).height('100%') + + Column() { + Text('right width 30%') + .textAlign(TextAlign.Center) + }.width('30%').backgroundColor(0xffd306).height('100%') + }.backgroundColor(0xffd306).height('30%') + } + } + } + ``` + + ![](figures/width.gif) + + 上例中,在任意大小的设备中,子组件的宽度占比固定。 + +## 定位能力 +- 相对定位 + + 使用组件的[offset属性](../reference/arkui-ts/ts-universal-attributes-location.md)可以实现相对定位,设置元素相对于自身的偏移量。设置该属性,不影响父容器布局,仅在绘制时进行位置调整。使用线性布局和offset可以实现大部分布局的开发。 + + ```ts + @Entry + @Component + struct OffsetExample { + @Styles eleStyle() { + .size({ width: 120, height: '50' }) + .backgroundColor(0xbbb2cb) + .border({ width: 1 }) + } + + build() { + Column({ space: 20 }) { + Row() { + Text('1').size({ width: '15%', height: '50' }).backgroundColor(0xdeb887).border({ width: 1 }).fontSize(16) + Text('2 offset(15, 30)') + .eleStyle() + .fontSize(16) + .align(Alignment.Start) + .offset({ x: 15, y: 30 }) + Text('3').size({ width: '15%', height: '50' }).backgroundColor(0xdeb887).border({ width: 1 }).fontSize(16) + Text('4 offset(-10%, 20%)') + .eleStyle() + .fontSize(16) + .offset({ x: '-5%', y: '20%' }) + }.width('90%').height(150).border({ width: 1, style: BorderStyle.Dashed }) + } + .width('100%') + .margin({ top: 25 }) + } + } + ``` + + ![](figures/offset.gif) + + +- 绝对定位 + + 线性布局中可以使用组件的[positon属性](../reference/arkui-ts/ts-universal-attributes-location.md)实现绝对布局(AbsoluteLayout),设置元素左上角相对于父容器左上角偏移位置。对于不同尺寸的设备,使用绝对定位的适应性会比较差,在屏幕的适配上有缺陷。 + + ```ts + @Entry + @Component + struct PositionExample { + @Styles eleStyle(){ + .backgroundColor(0xbbb2cb) + .border({ width: 1 }) + .size({ width: 120, height: 50 }) + } + + build() { + Column({ space: 20 }) { + // 设置子组件左上角相对于父组件左上角的偏移位置 + Row() { + Text('position(30, 10)') + .eleStyle() + .fontSize(16) + .position({ x: 10, y: 10 }) + + Text('position(50%, 70%)') + .eleStyle() + .fontSize(16) + .position({ x: '50%', y: '70%' }) + + Text('position(10%, 90%)') + .eleStyle() + .fontSize(16) + .position({ x: '10%', y: '80%' }) + }.width('90%').height('100%').border({ width: 1, style: BorderStyle.Dashed }) + } + .width('90%').margin(25) + } + } + ``` + + ![](figures/position.gif) + + +## 自适应延伸 + +自适应延伸是在不同尺寸设备下,当页面显示内容个数不一并延伸到屏幕外时,可通过滚动条拖动展示。适用于线性布局中内容无法一屏展示的场景。常见以下两类实现方法。 + + +- List组件 + + List子项过多一屏放不下时,未展示的子项通过滚动条拖动显示。通过scrollBar属性设置滚动条的常驻状态,edgeEffect属性设置拖动到极限的回弹效果。 + + + 纵向List: + ```ts + @Entry + @Component + struct ListExample1 { + @State arr: string[] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"] + @State alignListItem: ListItemAlign = ListItemAlign.Start + + build() { + Column() { + List({ space: 20, initialIndex: 0 }) { + ForEach(this.arr, (item) => { + ListItem() { + Text('' + item) + .width('100%') + .height(100) + .fontSize(16) + .textAlign(TextAlign.Center) + .borderRadius(10) + .backgroundColor(0xFFFFFF) + } + .border({ width: 2, color: Color.Green }) + }, item => item) + } + .border({ width: 2, color: Color.Red, style: BorderStyle.Dashed }) + .scrollBar(BarState.On) // 滚动条常驻 + .edgeEffect(EdgeEffect.Spring) // 滚动到边缘再拖动回弹效果 + + }.width('100%').height('100%').backgroundColor(0xDCDCDC).padding(20) + } + } + ``` + + ![](figures/listcolumn.gif) + + + 横向List: + + ```ts + @Entry + @Component + struct ListExample2 { + @State arr: string[] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"] + @State alignListItem: ListItemAlign = ListItemAlign.Start + + build() { + Column() { + List({ space: 20, initialIndex: 0 }) { + ForEach(this.arr, (item) => { + ListItem() { + Text('' + item) + .height('100%') + .width(100) + .fontSize(16) + .textAlign(TextAlign.Center) + .borderRadius(10) + .backgroundColor(0xFFFFFF) + } + .border({ width: 2, color: Color.Green }) + }, item => item) + } + .border({ width: 2, color: Color.Red, style: BorderStyle.Dashed }) + .scrollBar(BarState.On) // 滚动条常驻 + .edgeEffect(EdgeEffect.Spring) // 滚动到边缘再拖动回弹效果 + .listDirection(Axis.Horizontal) // 列表水平排列 + }.width('100%').height('100%').backgroundColor(0xDCDCDC).padding(20) + } + } + ``` + + ![](figures/listrow.gif) + +- Scroll组件 + + 线性布局中,当子组件的布局尺寸超过父组件的尺寸时,内容可以滚动。在Column或者Row外层包裹一个可滚动的容器组件Scroll实现。 + + 纵向Scroll: + + ```ts + @Entry + @Component + struct ScrollExample { + scroller: Scroller = new Scroller(); + private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; + + build() { + Scroll(this.scroller) { + Column() { + ForEach(this.arr, (item) => { + Text(item.toString()) + .width('90%') + .height(150) + .backgroundColor(0xFFFFFF) + .borderRadius(15) + .fontSize(16) + .textAlign(TextAlign.Center) + .margin({ top: 10 }) + }, item => item) + }.width('100%') + } + .backgroundColor(0xDCDCDC) + .scrollable(ScrollDirection.Vertical) // 滚动方向纵向 + .scrollBar(BarState.On) // 滚动条常驻显示 + .scrollBarColor(Color.Gray) // 滚动条颜色 + .scrollBarWidth(30) // 滚动条宽度 + .edgeEffect(EdgeEffect.Spring) // 滚动到边沿后回弹 + } + } + ``` + + ![](figures/scrollcolumn.gif) + + 横向Scroll: + + ```ts + @Entry + @Component + struct ScrollExample { + scroller: Scroller = new Scroller(); + private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; + + build() { + Scroll(this.scroller) { + Row() { + ForEach(this.arr, (item) => { + Text(item.toString()) + .height('90%') + .width(150) + .backgroundColor(0xFFFFFF) + .borderRadius(15) + .fontSize(16) + .textAlign(TextAlign.Center) + .margin({ left: 10 }) + }, item => item) + }.height('100%') + } + .backgroundColor(0xDCDCDC) + .scrollable(ScrollDirection.Horizontal) // 滚动方向横向 + .scrollBar(BarState.On) // 滚动条常驻显示 + .scrollBarColor(Color.Gray) // 滚动条颜色 + .scrollBarWidth(30) // 滚动条宽度 + .edgeEffect(EdgeEffect.Spring) // 滚动到边沿后回弹 + } + } + ``` + ![](figures/scrollrow.gif) diff --git a/zh-cn/application-dev/ui/ui-ts-layout-mediaquery.md b/zh-cn/application-dev/ui/ui-ts-layout-mediaquery.md index 27147d07fe719c98db76dd1a6ff57e3569a4faa6..100c4896116baa774b4f608a2764c356b5feef0c 100644 --- a/zh-cn/application-dev/ui/ui-ts-layout-mediaquery.md +++ b/zh-cn/application-dev/ui/ui-ts-layout-mediaquery.md @@ -1,27 +1,31 @@ # 媒体查询 +[媒体查询(Media Query)](../reference/apis/js-apis-mediaquery.md)作为响应式设计的核心,在移动设备上应用十分广泛。它根据不同设备类型或同设备不同状态修改应用的样式。媒体查询的优势有: -媒体查询(Media Query)在移动设备上应用十分广泛,开发者经常需要根据设备的大致类型或者特定的特征和设备参数(例如屏幕分辨率)来修改应用的样式。为此媒体查询提供了如下功能: +1. 提供丰富的媒体特征监听能力,针对设备和应用的属性信息(比如显示区域、深浅色、分辨率),设计出相匹配的布局。 +2. 当屏幕发生动态改变时(比如分屏、横竖屏切换),同步更新应用的页面布局。 -1. 针对设备和应用的属性信息,可以设计出相匹配的布局样式。 + -2. 当屏幕发生动态改变时(比如分屏、横竖屏切换),应用页面布局同步更新。 +## 媒体查询引入与使用流程 +媒体查询通过媒体查询接口,设置查询条件并绑定回调函数,在对应的条件的回调函数里更改页面布局或者实现业务逻辑,实现页面的响应式设计。具体步骤如下: -## 如何使用 +首先导入媒体查询模块。 -通过调用媒体查询接口,设置媒体查询条件和查询结果的回调函数,在对应的条件的回调函数里更改页面布局或者实现业务逻辑。 - -首先导入媒体查询模块,例如: -``` +```ts import mediaquery from '@ohos.mediaquery' ``` -然后通过matchMediaSync接口设置媒体查询条件,并保存返回的条件监听句柄,例如: + +通过matchMediaSync接口设置媒体查询条件,保存返回的条件监听句柄listener。 + ```ts listener = mediaquery.matchMediaSync('(orientation: landscape)') ``` -最后通过上面保存的条件监听句柄listener去注册回调函数,在回调函数里更改页面布局或者实现业务逻辑,当匹配到媒体查询条件时会触发此回调函数,例如: + +给条件监听句柄listener绑定回调函数onPortrait,当listener检测设备状态变化时执行回调函数。在回调函数内,根据不同设备状态更改页面布局或者实现业务逻辑。 + ```ts onPortrait(mediaQueryResult) { if (mediaQueryResult.matches) { @@ -33,19 +37,25 @@ onPortrait(mediaQueryResult) { listener.on('change', onPortrait) ``` -## 媒体查询条件语法规则 +## 媒体查询条件 + +媒体查询条件由媒体类型,逻辑操作符,媒体特征组成,其中媒体类型可省略,逻辑操作符用于连接不同媒体类型与媒体特征,其中,媒体特征要使用()包裹且可以有多个。具体规则如下: + +### 语法规则 + ``` [media-type] [and|not|only] [(media-feature)] ``` + 例如: -`screen and (round-screen: true)` :当设备屏幕是圆形时条件成立 +`screen and (round-screen: true)` :当设备屏幕是圆形时条件成立。 -`(max-height: 800)` :当高度小于800时条件成立 +`(max-height: 800)` :当高度小于等于800时条件成立。 -`(height <= 800) ` :当高度小于等于800时条件成立 +`(height <= 800) ` :当高度小于等于800时条件成立。 -`screen and (device-type: tv) or (resolution < 2)` :包含多个媒体特征的多条件复杂语句查询 +`screen and (device-type: tv) or (resolution < 2)` :包含多个媒体特征的多条件复杂语句查询,当设备类型为tv或设备分辨率小于2时条件成立。 ### 媒体类型(media-type) @@ -53,32 +63,30 @@ listener.on('change', onPortrait) | ------ | -------------- | | screen | 按屏幕相关参数进行媒体查询。 | +### 媒体逻辑操作(and|or|not|only) -### 媒体逻辑操作(and|not|only) - -媒体逻辑操作符:and、or、not、only用于构成复杂媒体查询,也可以通过comma(,)将其组合起来,详细解释说明如下表。 +媒体逻辑操作符:and、or、not、only用于构成复杂媒体查询,也可以通过comma(, )将其组合起来,详细解释说明如下表。 **表1** 媒体逻辑操作符 | 类型 | 说明 | | -------- | ---------------------------------------- | -| and | 将多个媒体特征(Media Feature)以“与”的方式连接成一个媒体查询,只有当所有媒体特征都为true,查询条件成立。另外,它还可以将媒体类型和媒体功能结合起来。
例如:screen and (device-type: wearable) and (max-height: 600) 表示当设备类型是智能穿戴同时应用的最大高度小于等于600个像素单位时成立。 | -| not | 取反媒体查询结果,媒体查询结果不成立时返回true,否则返回false。在媒体查询列表中应用not,则not仅取反应用它的媒体查询。
例如:not screen and (min-height: 50) and (max-height: 600) 表示当应用高度小于50个像素单位或者大于600个像素单位时成立。
使用not运算符时必须指定媒体类型。 | -| only | 当整个表达式都匹配时,才会应用选择的样式,可以应用在防止某些较早的版本的浏览器上产生歧义的场景。一些较早版本的浏览器对于同时包含了媒体类型和媒体特征的语句会产生歧义,比如:
screen and (min-height: 50)
老版本浏览器会将这句话理解成screen,从而导致仅仅匹配到媒体类型(screen),就应用了指定样式,使用only可以很好地规避这种情况。
使用only时必须指定媒体类型。 | -| ,(comma) | 将多个媒体特征以“或”的方式连接成一个媒体查询,如果存在结果为true的媒体特征,则查询条件成立。其效果等同于or运算符。
例如:screen and (min-height: 1000),  (round-screen:true) 表示当应用高度大于等于1000个像素单位或者设备屏幕是圆形时,条件成立。 | -| or | 将多个媒体特征以“或”的方式连接成一个媒体查询,如果存在结果为true的媒体特征,则查询条件成立。
例如:screen and (max-height: 1000) or  (round-screen:true)表示当应用高度小于等于1000个像素单位或者设备屏幕是圆形时,条件成立。 | +| and | 将多个媒体特征(Media  Feature)以“与”的方式连接成一个媒体查询,只有当所有媒体特征都为true,查询条件成立。另外,它还可以将媒体类型和媒体功能结合起来。
例如:screen  and  (device-type:  wearable)  and  (max-height:  600)  表示当设备类型是智能穿戴且应用的最大高度小于等于600个像素单位时成立。 | +| or | 将多个媒体特征以“或”的方式连接成一个媒体查询,如果存在结果为true的媒体特征,则查询条件成立。
例如:screen  and  (max-height:  1000)  or  (round-screen:true)表示当应用高度小于等于1000个像素单位或者设备屏幕是圆形时,条件成立。 | +| not | 取反媒体查询结果,媒体查询结果不成立时返回true,否则返回false。
例如:not  screen  and  (min-height:  50)  and  (max-height:  600)  表示当应用高度小于50个像素单位或者大于600个像素单位时成立。
使用not运算符时必须指定媒体类型。 | +| only | 当整个表达式都匹配时,才会应用选择的样式,可以应用在防止某些较早的版本的浏览器上产生歧义的场景。一些较早版本的浏览器对于同时包含了媒体类型和媒体特征的语句会产生歧义,比如:
screen  and  (min-height:  50)
老版本浏览器会将这句话理解成screen,从而导致仅仅匹配到媒体类型(screen),就应用了指定样式,使用only可以很好地规避这种情况。
使用only时必须指定媒体类型。 | +| , (comma) | 将多个媒体特征以“或”的方式连接成一个媒体查询,如果存在结果为true的媒体特征,则查询条件成立。其效果等同于or运算符。
例如:screen  and  (min-height:  1000),     (round-screen:true)  表示当应用高度大于等于1000个像素单位或者设备屏幕是圆形时,条件成立。 | -在MediaQuery Level 4中引入了范围查询,使其能够使用max-,min-的同时,也支持了<=,>=,<,>操作符。 +在MediaQuery Level 4中引入了范围查询,使其能够使用max-,min-的同时,也支持了< =,> =,< ,> 操作符。 **表2** 媒体逻辑范围操作符 | 类型 | 说明 | | ----- | ---------------------------------------- | -| <= | 小于等于,例如:screen and (50 <= height)。 | -| >= | 大于等于,例如:screen and (600 >= height)。 | -| < | 小于,例如:screen and (50 < height)。 | -| > | 大于,例如:screen and (600 > height)。 | - +| < = | 小于等于,例如:screen  and  (height  < =  50)。 | +| > = | 大于等于,例如:screen  and  (height  > =  600)。 | +| < | 小于,例如:screen  and  (height  <   50)。 | +| > | 大于,例如:screen  and  (height  >   600)。 | ### 媒体特征(media-feature) @@ -90,58 +98,59 @@ listener.on('change', onPortrait) | width | 应用页面显示区域的宽度。 | | min-width | 应用页面显示区域的最小宽度。 | | max-width | 应用页面显示区域的最大宽度。 | -| resolution | 设备的分辨率,支持dpi,dppx和dpcm单位。其中:
- dpi表示每英寸中物理像素个数,1dpi≈0.39dpcm;
- dpcm表示每厘米上的物理像素个数,1dpcm ≈ 2.54dpi;
- dppx表示每个px中的物理像素数(此单位按96px=1英寸为基准,与页面中的px单位计算方式不同),1dppx = 96dpi。 | +| resolution | 设备的分辨率,支持dpi,dppx和dpcm单位。其中:
-  dpi表示每英寸中物理像素个数,1dpi≈0.39dpcm;
-  dpcm表示每厘米上的物理像素个数,1dpcm  ≈  2.54dpi;
-  dppx表示每个px中的物理像素数(此单位按96px=1英寸为基准,与页面中的px单位计算方式不同),1dppx  =  96dpi。 | | min-resolution | 设备的最小分辨率。 | | max-resolution | 设备的最大分辨率。 | -| orientation | 屏幕的方向。
可选值:
- orientation: portrait(设备竖屏)
- orientation: landscape(设备横屏) | +| orientation | 屏幕的方向。
可选值:
-  orientation:  portrait(设备竖屏)
-  orientation:  landscape(设备横屏) | | device-height | 设备的高度。 | | min-device-height | 设备的最小高度。 | | max-device-height | 设备的最大高度。 | | device-width | 设备的宽度。 | | min-device-width | 设备的最小宽度。 | | max-device-width | 设备的最大宽度。 | -| round-screen | 屏幕类型,圆形屏幕为true, 非圆形屏幕为 false。 | +| round-screen | 屏幕类型,圆形屏幕为true,  非圆形屏幕为  false。 | | dark-mode | 系统为深色模式时为true,否则为false。 | ## 场景示例 -通过使用媒体查询实现当屏幕发生横竖屏切换,给页面文本应用不同的内容和样式。 - - ``` - import mediaquery from '@ohos.mediaquery' - let portraitFunc = null - - @Entry - @Component - struct MediaQueryExample { - @State color: string = '#DB7093' - @State text: string = 'Portrait' - @State fontSize: number = 24 - listener = mediaquery.matchMediaSync('(orientation: landscape)') - - onPortrait(mediaQueryResult) { - if (mediaQueryResult.matches) { - this.color = '#FFD700' - this.text = 'Landscape' - } else { - this.color = '#DB7093' - this.text = 'Portrait' - } - } - - aboutToAppear() { - portraitFunc = this.onPortrait.bind(this) //绑定当前应用实例 - this.listener.on('change', portraitFunc) +下例中使用媒体查询,实现屏幕横竖屏切换时给页面文本应用不同的内容和样式的效果。 + +```ts +import mediaquery from '@ohos.mediaquery' + +let portraitFunc = null + +@Entry +@Component +struct MediaQueryExample { + @State color: string = '#DB7093' + @State text: string = 'Portrait' + listener = mediaquery.matchMediaSync('(orientation: landscape)') // 当设备横屏时条件成立 + + onPortrait(mediaQueryResult) { + if (mediaQueryResult.matches) { + this.color = '#FFD700' + this.text = 'Landscape' + } else { + this.color = '#DB7093' + this.text = 'Portrait' } - - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Text(this.text).fontSize(50).fontColor(this.color) - } - .width('100%').height('100%') + } + + aboutToAppear() { + portraitFunc = this.onPortrait.bind(this) // 绑定当前应用实例 + this.listener.on('change', portraitFunc) + } + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text(this.text).fontSize(50).fontColor(this.color) } + .width('100%').height('100%') } - ``` +} +``` + 横屏下文本内容为Landscape,颜色为#FFD700。 ![zh-cn_image_0000001262954829](figures/zh-cn_image_0000001262954829.png) @@ -152,7 +161,7 @@ listener.on('change', onPortrait) ## 相关实例 -针对媒体查询开发,有以下相关实例可供参考: +使用媒体查询的自适应布局开发,有以下相关实例可供参考: - [`MediaQuery`:媒体查询(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/MediaQuery) diff --git a/zh-cn/application-dev/ui/ui-ts-layout-stack.md b/zh-cn/application-dev/ui/ui-ts-layout-stack.md new file mode 100644 index 0000000000000000000000000000000000000000..63904bd277cea803b4c9147ebf618be26e561d02 --- /dev/null +++ b/zh-cn/application-dev/ui/ui-ts-layout-stack.md @@ -0,0 +1,61 @@ +# 层叠布局 + +层叠布局(StackLayout)用于在屏幕上预留一块区域来显示组件中的元素,提供元素可以重叠的布局。 +通过层叠容器[Stack](../reference/arkui-ts/ts-container-stack.md)实现,容器中的子元素依次入栈,后一个子元素覆盖前一个子元素显示。 + +## 对齐方式 + +设置子元素在容器内的对齐方式。支持左上,上中,右上,左,中,右,右下,中下,右下九种对齐方式,如下表所示: + +|名称| 描述| 图示 | +|---| ---|---| +|TopStart| 顶部起始端 |![](figures/stacktopstart.png)| +Top |顶部横向居中 |![](figures/stacktop.png)| +TopEnd| 顶部尾端 |![](figures/stacktopend.png)| +Start| 起始端纵向居中 |![](figures/stackstart.png)| +Center| 横向和纵向居中 |![](figures/stackcenter.png)| +End| 尾端纵向居中 |![](figures/stackend.png)| +BottomStart |底部起始端 |![](figures/stackbottomstart.png)| +Bottom| 底部横向居中 |![](figures/stackbottom.png)| +BottomEnd| 底部尾端 |![](figures/stackbottomend.png)| + +## Z序控制 + +Stack容器中兄弟组件显示层级关系可以通过[zIndex](../reference/arkui-ts/ts-universal-attributes-z-order.md) +属性改变。zIndex值越大,显示层级越高,即zIndex值大的组件会覆盖在zIndex值小的组件上方。 + +- 在层叠布局中,如果后面子元素尺寸大于前面子元素尺寸,则前面子元素完全隐藏。 + + ```ts + Stack({ alignContent: Alignment.BottomStart }) { + Column() { + Text('Stack子元素1').textAlign(TextAlign.End).fontSize(20) + }.width(100).height(100).backgroundColor(0xffd306) + Column() { + Text('Stack子元素2').fontSize(20) + }.width(150).height(150).backgroundColor(Color.Pink) + Column() { + Text('Stack子元素3').fontSize(20) + }.width(200).height(200).backgroundColor(Color.Grey) + }.margin({ top: 100 }).width(350).height(350).backgroundColor(0xe0e0e0) + ``` + + ![](figures/stack2.png) + + 上图中,最后的子元素3的尺寸大于前面的所有子元素,所以,前面两个元素完全隐藏。改变子元素1,子元素2的zIndex属性后,可以将元素展示出来。 + + ```ts + Stack({ alignContent: Alignment.BottomStart }) { + Column() { + Text('Stack子元素1').textAlign(TextAlign.End).fontSize(20) + }.width(100).height(100).backgroundColor(0xffd306).zIndex(2) + Column() { + Text('Stack子元素2').fontSize(20) + }.width(150).height(150).backgroundColor(Color.Pink).zIndex(1) + Column() { + Text('Stack子元素3').fontSize(20) + }.width(200).height(200).backgroundColor(Color.Grey) + }.margin({ top: 100 }).width(350).height(350).backgroundColor(0xe0e0e0) + ``` + + ![](figures/stack1.png) diff --git a/zh-cn/application-dev/ui/ui-ts-overview.md b/zh-cn/application-dev/ui/ui-ts-overview.md index 348ce1cde17b33f3a6bb7fe393e74427f6852a63..7c6d9bf7771d91be396b6f5b94ad6eb881024a1a 100644 --- a/zh-cn/application-dev/ui/ui-ts-overview.md +++ b/zh-cn/application-dev/ui/ui-ts-overview.md @@ -1,30 +1,25 @@ # 概述 -基于ArkTS的声明式开发范式的方舟开发框架是一套开发极简、高性能、跨设备应用的UI开发框架,支持开发者高效的构建跨设备应用UI界面。 +基于ArkTS的声明式开发范式的方舟开发框架是一套开发极简、高性能、支持跨设备的UI开发框架,支持开发者高效地构建OpenHarmony应用UI界面。 ## 基础能力 -使用基于ArkTS的声明式开发范式的方舟开发框架,采用更接近自然语义的编程方式,让开发者可以直观地描述UI界面,不必关心框架如何实现UI绘制和渲染,实现极简高效开发。开发框架不仅从组件、动效和状态管理三个维度来提供UI能力,还提供了系统能力接口,实现系统能力的极简调用。 - -请参考[基于ArkTS的声明式开发范式API](../reference/arkui-ts/ts-universal-events-click.md)文档,全面地了解组件,更好地开发应用。 - +使用基于ArkTS的声明式开发范式的方舟开发框架,采用更接近自然语义的编程方式,让开发者可以直观地描述UI界面,不必关心框架如何实现UI绘制和渲染,实现极简高效开发。开发框架不仅从组件、动画和状态管理三个维度来提供UI能力,还提供了系统能力接口以实现系统能力的极简调用。 +ArkTS语言的基础知识请参考[学习ArkTS语言](../quick-start/arkts-get-started.md)文档;此外,请参考[基于ArkTS的声明式开发范式API](../reference/arkui-ts/ts-universal-events-click.md)文档,全面地了解内置组件,更好地开发应用。 - **开箱即用的组件** - 框架提供丰富的系统预置组件,可以通过链式调用的方式设置系统组件的渲染效果。开发者可以组合系统组件为自定义组件,通过这种方式将页面组件化为一个个独立的UI单元,实现页面不同单元的独立创建、开发和复用,使页面具有更强的工程性。 - + 框架提供丰富的系统内置组件,可以通过链式调用的方式设置系统组件的渲染效果。开发者可以组合系统组件为自定义组件,通过这种方式将页面组件化为一个个独立的UI单元,实现页面不同单元的独立创建、开发和复用,使页面具有更强的工程性。 - **丰富的动效接口** 提供svg标准的绘制图形能力,同时开放了丰富的动效接口,开发者可以通过封装的物理模型或者调用动画能力接口来实现自定义动画轨迹。 - - **状态与数据管理** 状态数据管理作为基于ArkTS的声明式开发范式的特色,通过功能不同的装饰器给开发者提供了清晰的页面更新渲染流程和管道。状态管理包括UI组件状态和应用程序状态,两者协作可以使开发者完整地构建整个应用的数据更新和UI渲染。 - - **系统能力接口** 使用基于ArkTS的声明式开发范式的方舟开发框架,还封装了丰富的系统能力接口,开发者可以通过简单的接口调用,实现从UI设计到系统能力调用的极简开发。 @@ -32,8 +27,6 @@ ## 整体架构 - - ![zh-cn_image_0000001169532276](figures/zh-cn_image_0000001169532276.png) - **声明式UI前端** @@ -50,7 +43,7 @@ - **渲染引擎** - 提供了高效的绘制能力,将渲染管线收集的渲染指令,绘制到屏幕能力。 + 提供了高效的绘制能力,将渲染管线收集的渲染指令,绘制到屏幕的能力。 - **平台适配层** diff --git a/zh-cn/application-dev/ui/ts-performance-improvement-recommendation.md b/zh-cn/application-dev/ui/ui-ts-performance-improvement-recommendation.md similarity index 94% rename from zh-cn/application-dev/ui/ts-performance-improvement-recommendation.md rename to zh-cn/application-dev/ui/ui-ts-performance-improvement-recommendation.md index e37724ed2f5d44cf9557e36bcc072f7430a81658..8a0b469305af0bb990edc42c04ef09c7cf65f189 100644 --- a/zh-cn/application-dev/ui/ts-performance-improvement-recommendation.md +++ b/zh-cn/application-dev/ui/ui-ts-performance-improvement-recommendation.md @@ -127,6 +127,8 @@ struct MyComponent { } ``` +![LazyForEach1](figures/LazyForEach1.gif) + 上述代码在页面加载时仅初始化加载三个列表元素,之后每点击一次列表元素,将增加一个列表元素。 ## 使用条件渲染替代显隐控制 @@ -179,6 +181,8 @@ struct MyComponent { } ``` +![isVisible](figures/isVisible.gif) + ## 使用Column/Row替代Flex 由于Flex容器组件默认情况下存在shrink导致二次布局,这会在一定程度上造成页面渲染上的性能劣化。 @@ -213,6 +217,8 @@ struct MyComponent { } ``` +![flex1](figures/flex1.PNG) + ## 设置List组件的宽高 开发者在使用Scroll容器组件嵌套List子组件时,若不指定List的宽高尺寸,则默认全部加载,如下所示: @@ -259,7 +265,10 @@ struct MyComponent { } ``` +![list1](figures/list1.gif) + ## 减少应用滑动白块 + 应用通过增大List/Grid控件的cachedCount参数,调整UI的加载范围。cachedCount表示屏幕外List/Grid预加载item的个数。 如果需要请求网络图片,可以在item滑动到屏幕显示之前,提前下载好内容,从而减少滑动白块。 如下是使用cachedCount参数的例子: @@ -269,33 +278,41 @@ struct MyComponent { @Component struct MyComponent { private source: MyDataSource = new MyDataSource(); + build() { List() { - LazyForEach (this.source, item => { + LazyForEach(this.source, item => { ListItem() { Text("Hello" + item) - .fontSize(100) - .onAppear(()=>{ + .fontSize(50) + .onAppear(() => { console.log("appear:" + item) }) } }) - }.cachedCount(3) // 扩大数值appear日志范围会变大 + }.cachedCount(3) // 扩大数值appear日志范围会变大 } } + class MyDataSource implements IDataSource { - data: number[] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]; + data: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; + public totalCount(): number { return this.data.length } + public getData(index: number): any { return this.data[index] } + registerDataChangeListener(listener: DataChangeListener): void { } + unregisterDataChangeListener(listener: DataChangeListener): void { } } ``` +![list2](figures/list2.gif) + **使用说明:** cachedCount的增加会增大UI的cpu、内存开销。使用时需要根据实际情况,综合性能和用户体验进行调整。 \ No newline at end of file diff --git "a/zh-cn/contribute/\350\264\241\347\214\256\344\273\243\347\240\201.md" "b/zh-cn/contribute/\350\264\241\347\214\256\344\273\243\347\240\201.md" index 4006d5a1d8b7f384eb1169e6867b5f97d35b02ad..ae8a73e9c771c7a42ce662c325c43d4990f82182 100755 --- "a/zh-cn/contribute/\350\264\241\347\214\256\344\273\243\347\240\201.md" +++ "b/zh-cn/contribute/\350\264\241\347\214\256\344\273\243\347\240\201.md" @@ -10,7 +10,7 @@ [OpenHarmony安全设计规范](OpenHarmony-security-design-guide.md) -[OpenHarmony编译规范](https://gitee.com/openharmony/community/blob/master/sig/sig-QA/%E7%BC%96%E8%AF%91%E8%A7%84%E8%8C%83.md) +[OpenHarmony编译规范](https://gitee.com/openharmony/community/blob/master/sig/sig-buildsystem/%E7%BC%96%E8%AF%91%E8%A7%84%E8%8C%83.md) ### 代码风格 diff --git a/zh-cn/device-dev/device-test/figures/FAQ-1.PNG b/zh-cn/device-dev/device-test/figures/FAQ-1.PNG new file mode 100644 index 0000000000000000000000000000000000000000..bebb315141c4cc3c004b502bb288705c8af9ebd8 Binary files /dev/null and b/zh-cn/device-dev/device-test/figures/FAQ-1.PNG differ diff --git a/zh-cn/device-dev/device-test/figures/L0-1.PNG b/zh-cn/device-dev/device-test/figures/L0-1.PNG new file mode 100644 index 0000000000000000000000000000000000000000..35fb66bafc980f97f755d09f26ed682737d371a0 Binary files /dev/null and b/zh-cn/device-dev/device-test/figures/L0-1.PNG differ diff --git a/zh-cn/device-dev/device-test/figures/NFS-1.PNG b/zh-cn/device-dev/device-test/figures/NFS-1.PNG new file mode 100644 index 0000000000000000000000000000000000000000..5fd5fb4f9063c00f1041eea1bb87b1b2519852cc Binary files /dev/null and b/zh-cn/device-dev/device-test/figures/NFS-1.PNG differ diff --git a/zh-cn/device-dev/device-test/figures/NFS-2.PNG b/zh-cn/device-dev/device-test/figures/NFS-2.PNG new file mode 100644 index 0000000000000000000000000000000000000000..0cd6f271936b2ee4fa97b256263bf85ba76c833b Binary files /dev/null and b/zh-cn/device-dev/device-test/figures/NFS-2.PNG differ diff --git a/zh-cn/device-dev/device-test/figures/NFS-3.PNG b/zh-cn/device-dev/device-test/figures/NFS-3.PNG new file mode 100644 index 0000000000000000000000000000000000000000..5a76e272ff763f3e31421d7c50c80f70febf1ce9 Binary files /dev/null and b/zh-cn/device-dev/device-test/figures/NFS-3.PNG differ diff --git a/zh-cn/device-dev/device-test/figures/result-1.PNG b/zh-cn/device-dev/device-test/figures/result-1.PNG new file mode 100644 index 0000000000000000000000000000000000000000..64c730feade073029102459e92c01f8ff885f51d Binary files /dev/null and b/zh-cn/device-dev/device-test/figures/result-1.PNG differ diff --git a/zh-cn/device-dev/device-test/xdevice.md b/zh-cn/device-dev/device-test/xdevice.md new file mode 100644 index 0000000000000000000000000000000000000000..54662ecf75e2248d40b287edba9ead3fc3f9e491 --- /dev/null +++ b/zh-cn/device-dev/device-test/xdevice.md @@ -0,0 +1,706 @@ +# xDevice测试调度执行框架使用指南 + + +## 概述 + +OpenHarmony开源操作系统有众多芯片场景基于其之上进行开发版本等相关产品的开发,为了保障OpenHarmony生态的兼容性,OpenHarmony提供了[兼容性测试测评服务](https://www.openharmony.cn/certification/document/guid),其中针对产品需要进行接口相关的测试执行验证,但是大量自动化用例的执行需要一套调度执行框架,并且支持生成可视化的测试报告等能力,故我们设计并开发了xdevice测试调度框架来支持该场景。 + +### 简介 + +xDevice测试调度框架是OpenHarmony中测试基础设施的核心组件,提供调度自动化用例执行所依赖的相关服务,支持大量自动化用例的调度执行能力,并可自带生成可视化测试报告。而xDevice二进制包会跟踪随OpenHarmony的XTS套件编译,开发者可以从XTS套件归档路径中获取xDevice工具, + +根据设备类型的不同,xDevice主要测试的任务场景有以下三个: + +- 对轻量系统设备进行XTS测试(如:Hi3861开发板) +- 对小型系统设备进行XTS测试(如:Hi3516开发板) +- 对标准系统设备进行XTS测试(如:RK3568开发板) + +### 实现原理 + +xDevice包括以下功能模块: + +- command:用户与测试平台命令行交互模块,提供用户输入命令解析,命令处理。 +- config:测试框架配置模块,提供测试平台串口连接方式和USB连接方式的不同配置选项。 +- driver:测试用例执行器,提供测试用例分发,执行,结果收集等主要测试步骤定义。 +- report:测试报告模块,提供测试结果解析和测试报告生成。 +- scheduler:测试框架调度模块,提供不同类型的测试执行器调度的调度功能。 +- environment:测试框架的环境配置模块,提供设备发现,设备管理的功能。 +- testkit:测试框架工具模块,提供json解析,网络文件挂载等操作。 +- log:测试框架日志模块,提供记录任务日志以及设备日志的功能。 + +除了上述功能模块之外,测试调度框架还依赖了用户自定义配置文件,配置文件主要分为两类。 + +**测试任务配置文件** + +user_config.xml是框架提供的测试任务配置文件,用户可以根据自身环境信息配置相关内容,主要包括以下配置内容。 + +environment环境相关配置,详解介绍如下。 + +```xml + + + + + + + + + + + + + + cmd + 115200 + 8 + 1 + 20 + + + + deploy + 115200 + + + + + + + + cmd + 115200 + 8 + 1 + 1 + + + + + + + + + +``` + +测试用例目录设置。 + +```xml + + + + + + + + + + + + + + + +``` + +资源目录设置。 + +```xml + + + + +``` + +日志打印级别设置。 + +```xml + +INFO +``` + +**测试套配置文件** + +设备执行的测试支撑套件是由测试配置文件所指定。 + +每个测试套都都有一个测试配置文件,主要配置了需要使用的测试支撑套件(kits)等信息,并支持配置执行预制和清理操作。 + +以下为配置文件样例。 + +```json +{ + // 测试支撑套件描述 + "description": "Configuration for aceceshi Tests", + + // 指定执行当前测试支撑套的设备 + "environment": { + "type": "device", + "label": "wifiiot" + }, + + // 指定设备执行的驱动 + "driver": { + "type": "OHJSUnitTest", + "test-timeout": "700000", + "bundle-name": "com.open.harmony.acetestfive", + "package-name": "com.open.harmony.acetestfive", + "shell-timeout": "700000" + }, + // kit的作用主要是为了支撑测试执行活动,在测试前执行预制操作(Setup),在测试后执行清理操作(Teardown) + "kits": [ + { + "type": "ShellKit", + "run-command": [ + "remount", + "mkdir /data/data/resource", + "chmod -R 777 /data/data/resource", + "settings put secure adb_install_need_confirm 0" + ], + "teardown-command": [ + "remount", + "rm -rf /data/data/resource" + ] + }, + ] +} +``` + +### 测试命令 + +测试命令可以分为三组:help、list、run。在指令序列中,以run为最常用的执行指令。 + +------ + +输入help指令可以查询框架指令帮助信息。 + +```text +help: + use help to get information. +usage: + run: Display a list of supported run command. + list: Display a list of supported device and task record. +Examples: + help run + help list +``` + +**说明:** + +help run:展示run指令相关说明 。 + +help list:展示 list指令相关说明。 + +------ + +list指令用来展示设备和相关的任务信息。 + +```text +list: + This command is used to display device list and task record. +usage: + list + list history + list +Introduction: + list: display device list + list history: display history record of a serial of tasks + list : display history record about task what contains specific id +Examples: + list + list history + list 6e****90 +``` + + **说明:** + + list: 展示设备信息。 + + list history: 展示任务历史信息 。 + + list : 展示特定id的任务其历史信息。 + +------ + +run指令主要用于执行测试任务。 + +```text +run: + This command is used to execute the selected testcases. + It includes a series of processes such as use case compilation, execution, and result collection. +usage: run [-l TESTLIST [TESTLIST ...] | -tf TESTFILE + [TESTFILE ...]] [-tc TESTCASE] [-c CONFIG] [-sn DEVICE_SN] + [-rp REPORT_PATH [REPORT_PATH ...]] + [-respath RESOURCE_PATH [RESOURCE_PATH ...]] + [-tcpath TESTCASES_PATH [TESTCASES_PATH ...]] + [-ta TESTARGS [TESTARGS ...]] [-pt] + [-env TEST_ENVIRONMENT [TEST_ENVIRONMENT ...]] + [-e EXECTYPE] [-t [TESTTYPE [TESTTYPE ...]]] + [-td TESTDRIVER] [-tl TESTLEVEL] [-bv BUILD_VARIANT] + [-cov COVERAGE] [--retry RETRY] [--session SESSION] + [--dryrun] [--reboot-per-module] [--check-device] + [--repeat REPEAT] + action task +Specify tests to run. + positional arguments: + action Specify action + task Specify task name,such as "ssts", "acts", "hits" +``` + +run指令基本使用方法如下。 + +| xDevice命令 | 功能 | 示例 | +| :----------: | :----------------------------------------------------------: | :----------------------------------------------------------: | +| run xts | 运行所有指定类型的XTS模块,如acts,hits,ssys等 | run acts | +| run -l xxx | 运行指定的模块测试套,模块间用分号隔离 | run -l ActsWifiServiceTest;ActsLwipTest | +| run -sn | 指定运行设备的SN号,多个SN号用分号隔离 | run acts -sn 10.117.183.37:17001
run acts -sn 88Y02******57723;VEG02******16642 | +| run -rp | 指定报告生成的路径,默认会在工作目录的reports下用时间戳或任务ID建立子目录 | run acts -rp /suites/hits/xdevice_reports/2020.09.28-14.21.26 | +| run -respath | 指定测试资源路径,默认为resource目录 | run acts -respath /cloud/zidane/xts/release/suites/resource | +| run -ta | 指定模块运行参数,可以指定运行模块用例中指定的用例,多个用例用逗号隔离,目前支持JS驱动测试套 | run acts -ta class:ohos.hardware.soundtrigger.SoundTriggerTest#testKeyphraseParcelUnparcel_noUsers | +| run --retry | 重新运行上一次任务的失败用例,生成新的测试报告 | run –retryrun --retry --session 2020-10-30-17-15-11(任务目录名) | + +### 测试报告 + +框架执行run指令,控制台会输出对应的log打印,还会生成对应的执行结果报告。如果使用了-rp参数指定报告路径,那么报告就会生成在指定的路径下。否则报告会存放在默认目录。 + +```text +当前报告目录(默认目录/指定目录) + ├── result(模块执行结果存放目录) + │ ├── <模块名>.xml + │ ├── ... ... + │ + ├── log (设备和任务运行log存放目录) + │ ├── <设备1>.log + │ ├── ... ... + │ ├── <任务>.log + ├── summary_report.xml(任务汇总数据报告) + ├── summary_report.html(任务汇总可视化报告) + ├── details_report.html(用例执性可视化报告) + ├── failures_report.html(失败用例可视化报告,无失败用例时不生成) + ├── summary.ini(记录测试类型,使用的设备,开始和结束时间等信息) + ├── task_info.record(记录执行命令,失败用例清单等信息) + ├── xxxx.zip(对上述文件进行压缩得到的压缩文件) + ├── summary_report.hash(对压缩文件进行sha256加密得到的文件) + └── ... ... +``` + + +## 环境准备 + + +### 环境要求 + +- python版本>=3.7 +- pyserial>=3.3 +- paramiko>=2.7.1 +- rsa>=4.0 + + +### 安装xDevice + +- 安装基础框架xDevice。 + + 1. 进入xDevice根目录。 + + ```bash + cd testfwk_xdevice + ``` + + 2. 打开控制台,执行如下命令。 + + ```bash + python setup.py install + ``` + +- 安装OpenHarmony驱动插件ohos。 + + 1. 进行plugin/ohos目录。 + + ```bash + cd testfwk_xdevice/plugin/ohos + ``` + + 2. 打开控制台,当前用户下执行如下命令。 + + ```bash + python setup.py install + ``` + +### 检验环境是否搭建成功 + +检验xDevice是否安装成功。 + +1. 进入xDevice根目录。 + + ```bash + cd testfwk_xdevice + ``` + +2. 打开控制台,执行如下命令。 + + ```bash + python -m pip list + ``` + +3. 查看是否已经成功安装**xdevice**以及**xdevice-ohos**两个库。 + + ```text + xdevice 0.0.0 + xdevice-ohos 0.0.0 + ``` + +查看xDevice工具是否能够正常运行。 + +1. 进入xDevice根目录。 + + ```bash + cd testfwk_xdevice + ``` + +2. 打开控制台,执行如下命令。 + + ```bash + python -m xdevice + ``` + +3. 查看控制台是否正常输出如下信息。 + + ```text + [2022-10-13 15:43:31,284] [30076] [Main] [INFO] [*************** xDevice Test Framework 2.11.0.1091 Starting ***************] + [2022-10-13 15:43:31,286] [30076] [ManagerLite] [WARNING] [wifiiot local com cannot be empty, please check] + [2022-10-13 15:43:31,286] [30076] [ManagerLite] [WARNING] [ipcamera local com cannot be empty, please check] + [2022-10-13 15:43:31,287] [30076] [ManagerLite] [WARNING] [device com or ip cannot be empty, please check] + >>> + ``` + + +## 轻量系统设备XTS测试指导(wifiiot) + +1. 识别串口用途,修改根目录中的user_config.xml文件。 + + type为cmd的com口对应板子上的AT命令串口,用于对设备发送指令,示例中配置为ChA(COM20)串口号。 + + type为deploy的com口对应板子上的日志输出串口,用于镜像烧录和日志打印,示例中配置为ChB(COM18)串口号。 + + 若AT命令串口和日志输出串口共用,可以配置为相同,即user_config中的type为cmd的com口与type为deploy的com口可配置为一样的端口,如COM18。 + + ![L0-1](figures/L0-1.PNG) + + user_config.xml的修改示例如下。 + + ```xml + + + + + com20 + cmd + 115200 + 8 + 1 + 20 + + + com18 + deploy + 115200 + + + + + + + + + + + + + + + + + + DEBUG + + ``` + +2. 在xDevice根目录下新建testcase文件夹用于存放测试套文件,具体XTS测试套从系统构建的每日构建中获取。 + + 每日构建:http://ci.openharmony.cn/dailys/dailybuilds + + 测试套测试配置文件json,示例如下。 + + ```json + { + "description": "Config for ActsAllTest test cases", + "environment": [ + { + "type": "device", + "label": "wifiiot" + } + ], + "kits": [ + { + "type": "DeployKit", + "timeout": "20000", + "burn_file": "acts/Hi3861_wifiiot_app_allinone.bin" + } + ], + "driver": { + "type": "CTestLite" + } + } + ``` + +3. 执行用例 + + 进入xDevice根目录;打开控制台进入xDevice控制台,执行如下命令。 + + ```bash + python -m xdevice + ``` + + 执行测试套命令。 + + ```text + run -l ActsAllTest + ``` + + 执行结果如下。 + + ![result-1](figures/result-1.PNG) + +## 小型系统设备XTS测试指导(ipcamera) + +1. 识别串口用途。 + + type为cmd的com口对应板子上的AT命令串口,用于对设备发送指令,示例中配置为ChA(COM20)串口号。 + + L0-1 + + ipcamera设备有两种连接方式,一种是本地串口连接,一种是通过局域网ip连接。 + +2. 配置NFS服务器 + + NFS挂载方式有两种,一种是远程PC挂载方式,一种是本地局域网挂载方式。 + + 本地局域网NFS服务的配置方法如下。 + + 1. 下载安装NFS服务器。下载地址:https://www.hanewin.net/nfs-e.htm + + 2. 配置输出->编辑输出表文件。 + + + + 3. 添加路径NFS共享路径(如:D:\HS\NFS_Share_File -public –alldirs),这里要注意ftp的IP地址192.168.1.10为开发板的IP。 + + + + 4. 停止NFS服务器->重启运行NFS服务器使刚才添加的共享路径生效。 + + 5. 找到ipcamera设备在PC上面映射的网口:控制面板->网络和Internet->网络共享中心->以太网状态->以太网属性->手动设置IP地址为:192.168.1.11。 + + + +3. 修改根目录中的user_config.xml文件,示例如下。 + + ```xml + + + + + com20 + cmd + 115200 + 8 + 1 + 1 + + + + 10.176.49.47 + 10003 + + + + + + 10.176.48.202 + 1022 + /data/data/local/ + root + xxx + true + + + 192.168.1.11 + 2049 + D:\test + false + + + + + + DEBUG + + ``` + +4. 在xDevice根目录下新建testcase文件夹用于存放测试套文件,具体XTS测试套从系统构建的每日构建。 + + 每日构建:http://ci.openharmony.cn/dailys/dailybuilds + + 测试套测试配置文件json,示例如下。 + + ```json + { + "description": "Config for kernel test cases", + "environment": [ + { + "type": "device", + "label": "ipcamera" + } + ], + "kits": [ + { + "type": "MountKit", + "server": "NfsServer", + "mount": [ + { + "source": "testcases/kernel", + "target": "/test_root/kernel" + } + ] + } + ], + "driver": { + "type": "CppTestLite", + "excute": "/test_root/kernel/ActsKernelIPCTest.bin" + } + } + ``` + +5. 执行用例。 + + 进入xDevice根目录,打开控制台进入xDevice控制台,执行如下命令。 + + ```bash + python -m xdevice + ``` + + 执行测试套命令。 + + ```text + run -l kernel + ``` + + 执行结果如下。 + + ![result-1](figures/result-1.PNG) + +## 标准系统设备XTS测试指导(RK3568) + +1. 配置hdc工具,从每日构建上下载ohos_sdk最新版本即可。 + + 每日构建地址:http://ci.openharmony.cn/dailys/dailybuilds + + 下载工具后,把hdc配置到环境变量中,配置方法:右键单击我的电脑->属性->高级系统设置->环境变量->Path。 + +2. 执行如下命令查看设备是否正常连接。 + + ```bash + hdc_std list targets + ``` + +3. 修改user_config.xml文件,示例如下。 + + ```xml + + + + + + xxx;xxx + + + + + + + + + DEBUG + + ``` + +4. 在xDevice根目录下新建testcase文件夹用于存放测试套文件,具体XTS测试套从系统构建的每日构建中获取。 + + 每日构建:http://ci.openharmony.cn/dailys/dailybuilds + + 测试套测试配置文件json,示例如下。 + + ```json + { + "description": "Configuration for hjunit demo Tests", + "driver": { + "type": "OHJSUnitTest", + "test-timeout": "180000", + "bundle-name": "ohos.acts.bundle.stage.test", + "module-name": "phone", + "shell-timeout": "600000", + "testcase-timeout": 70000 + }, + "kits": [ + { + "test-file-name": [ + "ActBmsStageEtsTest.hap" + ], + "type": "AppInstallKit", + "cleanup-apps": true + }, + { + "type": "ShellKit", + "teardown-command":[ + "bm uninstall -n ohos.acts.bundle.stage.test" + ] + } + ] + } + ``` + +5. 执行用例。 + + 进入xDevice根目录,打开控制台进入xDevice控制台,执行如下命令。 + + ```bash + python -m xdevice + ``` + + 执行测试套命令。 + + ```text + run -l ActBmsStageEtsTest + ``` + + 执行结果如下。 + + ![result-1](figures/result-1.PNG) + +## 常见问题 + +### hdc list targets能查找到设备,但xDevice识别不到设备。 + +**问题描述** + +出现如下错误。 + +![FAQ-1](figures/FAQ-1.PNG) + +**可能原因** + +环境变量中曾设置过HDC_SERVER_PORT变量修改过hdc的端口,由于xDevice默认需要使用8710端口,若曾修改过该端口会导致xDevice框架无法识别设备。 + +**解决方法** + +检查是否有设置HDC_SERVER_PROT变量,若有设置,请把该端口的值修改为8710,然后重启xDevice即可。 + diff --git a/zh-cn/device-dev/kernel/Readme-CN.md b/zh-cn/device-dev/kernel/Readme-CN.md index d243354b9c95f462dcddd8fcb6ef7acd396b62d9..d2f636772b96b25854cf596fcb122bc9c08a561b 100755 --- a/zh-cn/device-dev/kernel/Readme-CN.md +++ b/zh-cn/device-dev/kernel/Readme-CN.md @@ -13,8 +13,9 @@ - [互斥锁](kernel-mini-basic-ipc-mutex.md) - [消息队列](kernel-mini-basic-ipc-queue.md) - [信号量](kernel-mini-basic-ipc-sem.md) - - [时间管理](kernel-basic-mini-time.md) + - [时间管理](kernel-mini-basic-time.md) - [软件定时器](kernel-mini-basic-soft.md) + - [双向链表](kernel-mini-basic-list.md) - 扩展组件 - [C++支持](kernel-mini-extend-support.md) - [CPU占用率](kernel-mini-extend-cpup.md) @@ -27,7 +28,6 @@ - [LMS调测](kernel-mini-memory-lms.md) - 附录 - [内核编码规范](kernel-mini-appx-code.md) - - [双向链表](kernel-mini-appx-data-list.md) - [标准库支持](kernel-mini-appx-lib.md) - 小型系统内核(LiteOS-A) - [小型系统内核概述](kernel-small-overview.md) diff --git a/zh-cn/device-dev/kernel/kernel-mini-basic-interrupt.md b/zh-cn/device-dev/kernel/kernel-mini-basic-interrupt.md index 9c8e2e42ded8903ddaa5a864aea95bef8990e043..eaa1f10f6dc98b1ac1b6d6ddbda1d47af85fbf04 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-basic-interrupt.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-interrupt.md @@ -9,25 +9,25 @@ 下面介绍下中断的相关概念: -- 中断号 +- 中断号: 中断请求信号特定的标志,计算机能够根据中断号判断是哪个设备提出的中断请求。 -- 中断请求 +- 中断请求: “紧急事件”向CPU提出申请(发一个电脉冲信号),请求中断,需要CPU暂停当前执行的任务处理该“紧急事件”,这一过程称为中断请求。 -- 中断优先级 +- 中断优先级: 为使系统能够及时响应并处理所有中断,系统根据中断事件的重要性和紧迫程度,将中断源分为若干个级别,称作中断优先级。 -- 中断处理程序 +- 中断处理程序: 当外设发出中断请求后,CPU暂停当前的任务,转而响应中断请求,即执行中断处理程序。产生中断的每个设备都有相应的中断处理程序。 -- 中断触发 +- 中断触发: 中断源向中断控制器发送中断信号,中断控制器对中断进行仲裁,确定优先级,将中断信号发送给CPU。中断源产生中断信号的时候,会将中断触发器置“1”,表明该中断源产生了中断,要求CPU去响应该中断。 -- 中断向量 +- 中断向量: 中断服务程序的入口地址。 -- 中断向量表 +- 中断向量表: 存储中断向量的存储区,中断向量与中断号对应,中断向量在中断向量表中按照中断号顺序存储。 @@ -37,37 +37,46 @@ OpenHarmony LiteOS-M内核的中断模块提供下面几种功能,接口详细 **表1** 创建、删除中断 -| 接口名 | 描述 | +| 接口名 | 描述 | | -------- | -------- | -| HalHwiCreate | 中断创建,注册中断号、中断触发模式、中断优先级、中断处理程序。中断被触发时,会调用该中断处理程序。 | -| HalHwiDelete | 根据指定的中断号,删除中断。 | +| LOS_HwiCreate | 中断创建,注册中断号、中断触发模式、中断优先级、中断处理程序。中断被触发时,会调用该中断处理程序。 | +| LOS_HwiDelete | 根据指定的中断号,删除中断。 | **表2** 打开、关闭中断 -| 接口名 | 描述 | +| 接口名 | 描述 | | -------- | -------- | -| LOS_IntUnLock | 开中断,使能当前处理器所有中断响应。 | -| LOS_IntLock | 关中断,关闭当前处理器所有中断响应。 | -| LOS_IntRestore | 恢复到使用LOS_IntLock、LOS_IntUnLock操作之前的中断状态。 | +| LOS_IntUnLock | 开中断,使能当前处理器所有中断响应。 | +| LOS_IntLock | 关中断,关闭当前处理器所有中断响应。 | +| LOS_IntRestore | 恢复到使用LOS_IntLock、LOS_IntUnLock操作之前的中断状态。 | + + **表3** 其他中断操作 + +| 接口名 | 描述 | +| :----------------- | ---------------- | +| LOS_HwiTrigger | 中断触发。 | +| LOS_HwiEnable | 中断使能。 | +| LOS_HwiDisable | 中断禁用。 | +| LOS_HwiClear | 中断手动清除。 | +| LOS_HwiSetPriority | 设置中断优先级。 | +| LOS_HwiCurIrqNum | 获取当前中断号。 | ## 开发流程 -1. 调用中断创建接口HalHwiCreate创建中断。 +1. 调用中断创建接口LOS_HwiCreate创建中断。 -2. 调用TestHwiTrigger接口触发指定中断(该接口在测试套中定义,通过写中断控制器的相关寄存器模拟外部中断,一般的外设设备,不需要执行这一步)。 +2. 调用LOS_HwiTrigger接口触发指定中断(写中断控制器的相关寄存器模拟外部中断),或通过外设触发中断。 -3. 调用HalHwiDelete接口删除指定中断,此接口根据实际情况使用,判断是否需要删除中断。 +3. 调用LOS_HwiDelete接口删除指定中断,此接口根据实际情况使用,开发者判断是否需要删除中断。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > - 根据具体硬件,配置支持的最大中断数及可设置的中断优先级个数。 -> -> - 中断处理程序耗时不能过长,否则会影响CPU对中断的及时响应。 -> +> - 关中断时间或中断处理程序耗时不能过长,否则会影响CPU对中断的及时响应。 > - 中断响应过程中不能直接、间接执行引起调度的LOS_Schedule等函数。 -> -> - 中断恢复LOS_IntRestore()的入参必须是与之对应的LOS_IntLock()的返回值(即关中断之前的CPSR值)。Cortex-M系列处理器中0-15中断为内部使用,因此不建议用户去申请和创建。 +> - 中断恢复LOS_IntRestore()的入参必须是与之对应的LOS_IntLock()的返回值(即关中断之前的CPSR值)。 +> - Cortex-M系列处理器中0-15中断为内部使用,因此不建议用户去申请和创建。 ## 编程实例 @@ -80,29 +89,39 @@ OpenHarmony LiteOS-M内核的中断模块提供下面几种功能,接口详细 3. 删除中断。 -代码实现如下,演示如何创建中断和删除中断,当指定的中断号HWI_NUM_TEST产生中断时,会调用中断处理函数: +代码实现如下,演示如何创建中断、触发指定的中断号进而调用中断处理函数、删除中断。 + +本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleInterrupt。 + - ``` #include "los_interrupt.h" +#include "los_compiler.h" -/*创建中断*/ +/* 验证的中断号 */ #define HWI_NUM_TEST 7 -STATIC VOID HwiUsrIrq(VOID) +/* 中断处理程序 */ +STATIC VOID UsrIrqEntry(VOID) { - printf("in the func HwiUsrIrq \n"); + printf("in the func UsrIrqEntry\n"); } -static UINT32 Example_Interrupt(VOID) +/* 注册的线程回调函数,用于触发中断 */ +STATIC VOID InterruptTest(VOID) +{ + LOS_HwiTrigger(HWI_NUM_TEST); +} + +UINT32 ExampleInterrupt(VOID) { UINT32 ret; - HWI_PRIOR_T hwiPrio = 3; + HWI_PRIOR_T hwiPrio = 3; // 3,中断优先级 HWI_MODE_T mode = 0; HWI_ARG_T arg = 0; - - /*创建中断*/ - ret = HalHwiCreate(HWI_NUM_TEST, hwiPrio, mode, (HWI_PROC_FUNC)HwiUsrIrq, arg); + + /* 创建中断 */ + ret = LOS_HwiCreate(HWI_NUM_TEST, hwiPrio, mode, (HWI_PROC_FUNC)UsrIrqEntry, arg); if(ret == LOS_OK){ printf("Hwi create success!\n"); } else { @@ -110,17 +129,32 @@ static UINT32 Example_Interrupt(VOID) return LOS_NOK; } - /* 延时50个Ticks, 当有硬件中断发生时,会调用函数HwiUsrIrq*/ + TSK_INIT_PARAM_S taskParam = { 0 }; + UINT32 testTaskID; + + /* 创建一个优先级低优先级的线程,用于验证触发中断 */ + taskParam.pfnTaskEntry = (TSK_ENTRY_FUNC)InterruptTest; + taskParam.uwStackSize = OS_TSK_TEST_STACK_SIZE; + taskParam.pcName = "InterruptTest"; + taskParam.usTaskPrio = TASK_PRIO_TEST - 1; + taskParam.uwResved = LOS_TASK_ATTR_JOINABLE; + ret = LOS_TaskCreate(&testTaskID, &taskParam); + if (LOS_OK != ret) { + PRINTF("InterruptTest task error\n"); + } + + /* 延时50 tick,让出当前线程的调度 */ LOS_TaskDelay(50); - /*删除中断*/ - ret = HalHwiDelete(HWI_NUM_TEST); + /* 删除注册的中断 */ + ret = LOS_HwiDelete(HWI_NUM_TEST, NULL); if(ret == LOS_OK){ printf("Hwi delete success!\n"); } else { printf("Hwi delete failed!\n"); return LOS_NOK; } + return LOS_OK; } ``` @@ -131,8 +165,9 @@ static UINT32 Example_Interrupt(VOID) 编译运行得到的结果为: - + ``` Hwi create success! +in the func UsrIrqEntry Hwi delete success! ``` diff --git a/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-event.md b/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-event.md index 3f22c8ca8805c838933f2a66cead333a6ae34e04..ef398c91849fcae751bcb1c848424acaa609772d 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-event.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-event.md @@ -16,14 +16,12 @@ ## 运行机制 - ### 事件控制块 +由事件初始化函数配置的一个结构体,在事件读写等操作时作为参数传入,用于标识不同的事件,控制块数据结构如下: + ``` -/** - * 事件控制块数据结构 - */ typedef struct tagEvent { UINT32 uwEventID; /* 事件集合,表示已经处理(写入和清零)的事件集合 */ LOS_DL_LIST stEventList; /* 等待特定事件的任务链表 */ @@ -33,7 +31,7 @@ typedef struct tagEvent { ### 事件运作原理 -**事件初始化**:会创建一个事件控制块,该控制块维护一个已处理的事件集合,以及等待特定事件的任务链表。 +**事件初始化**:创建一个事件控制块,该控制块维护一个已处理的事件集合,以及等待特定事件的任务链表。 **写事件**:会向事件控制块写入指定的事件,事件控制块更新事件集合,并遍历任务链表,根据任务等待具体条件满足情况决定是否唤醒相关任务。 @@ -96,31 +94,29 @@ typedef struct tagEvent { ### 实例描述 -示例中,任务Example_TaskEntry创建一个任务Example_Event,Example_Event读事件阻塞,Example_TaskEntry向该任务写事件。可以通过示例日志中打印的先后顺序理解事件操作时伴随的任务切换。 +示例中,任务ExampleEvent创建一个任务EventReadTask,EventReadTask读事件阻塞,ExampleEvent向该任务写事件。可以通过示例日志中打印的先后顺序理解事件操作时伴随的任务切换。 -1. 在任务Example_TaskEntry创建任务Example_Event,其中任务Example_Event优先级高于Example_TaskEntry。 +1. 在任务ExampleEvent创建任务EventReadTask,其中任务EventReadTask优先级高于ExampleEvent。 -2. 在任务Example_Event中读事件0x00000001,阻塞,发生任务切换,执行任务Example_TaskEntry。 +2. 在任务EventReadTask中读事件0x00000001,阻塞,发生任务切换,执行任务ExampleEvent。 -3. 在任务Example_TaskEntry向任务Example_Event写事件0x00000001,发生任务切换,执行任务Example_Event。 +3. 在任务ExampleEvent写事件0x00000001,发生任务切换,执行任务EventReadTask。 -4. Example_Event得以执行,直到任务结束。 +4. EventReadTask得以执行,直到任务结束。 -5. Example_TaskEntry得以执行,直到任务结束。 +5. ExampleEvent得以执行,直到任务结束。 ### 示例代码 示例代码如下: +本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleEvent。 + ``` #include "los_event.h" #include "los_task.h" -#include "securec.h" - -/* 任务ID */ -UINT32 g_testTaskId; /* 事件控制结构体 */ EVENT_CB_S g_exampleEvent; @@ -128,8 +124,11 @@ EVENT_CB_S g_exampleEvent; /* 等待的事件类型 */ #define EVENT_WAIT 0x00000001 +/* 等待超时时间 */ +#define EVENT_TIMEOUT 100 + /* 用例任务入口函数 */ -VOID Example_Event(VOID) +VOID EventReadTask(VOID) { UINT32 ret; UINT32 event; @@ -137,39 +136,39 @@ VOID Example_Event(VOID) /* 超时等待方式读事件,超时时间为100 ticks, 若100 ticks后未读取到指定事件,读事件超时,任务直接唤醒 */ printf("Example_Event wait event 0x%x \n", EVENT_WAIT); - event = LOS_EventRead(&g_exampleEvent, EVENT_WAIT, LOS_WAITMODE_AND, 100); + event = LOS_EventRead(&g_exampleEvent, EVENT_WAIT, LOS_WAITMODE_AND, EVENT_TIMEOUT); if (event == EVENT_WAIT) { - printf("Example_Event,read event :0x%x\n", event); + printf("Example_Event, read event :0x%x\n", event); } else { - printf("Example_Event,read event timeout\n"); + printf("Example_Event, read event timeout\n"); } } -UINT32 Example_TaskEntry(VOID) +UINT32 ExampleEvent(VOID) { UINT32 ret; - TSK_INIT_PARAM_S task1; + UINT32 taskId; + TSK_INIT_PARAM_S taskParam = { 0 }; /* 事件初始化 */ ret = LOS_EventInit(&g_exampleEvent); if (ret != LOS_OK) { printf("init event failed .\n"); - return -1; + return LOS_NOK; } /* 创建任务 */ - (VOID)memset_s(&task1, sizeof(TSK_INIT_PARAM_S), 0, sizeof(TSK_INIT_PARAM_S)); - task1.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_Event; - task1.pcName = "EventTsk1"; - task1.uwStackSize = OS_TSK_DEFAULT_STACK_SIZE; - task1.usTaskPrio = 5; - ret = LOS_TaskCreate(&g_testTaskId, &task1); + taskParam.pfnTaskEntry = (TSK_ENTRY_FUNC)EventReadTask; + taskParam.pcName = "EventReadTask"; + taskParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; + taskParam.usTaskPrio = 3; + ret = LOS_TaskCreate(&taskId, &taskParam); if (ret != LOS_OK) { printf("task create failed.\n"); return LOS_NOK; } - /* 写g_testTaskId 等待事件 */ + /* 写事件 */ printf("Example_TaskEntry write event.\n"); ret = LOS_EventWrite(&g_exampleEvent, EVENT_WAIT); @@ -183,10 +182,10 @@ UINT32 Example_TaskEntry(VOID) LOS_EventClear(&g_exampleEvent, ~g_exampleEvent.uwEventID); printf("EventMask:%d\n", g_exampleEvent.uwEventID); - /* 删除任务 */ - ret = LOS_TaskDelete(g_testTaskId); + /* 删除事件 */ + ret = LOS_EventDestroy(&g_exampleEvent); if (ret != LOS_OK) { - printf("task delete failed.\n"); + printf("destory event failed .\n"); return LOS_NOK; } @@ -202,9 +201,9 @@ UINT32 Example_TaskEntry(VOID) ``` -Example_Event wait event 0x1 +Example_Event wait event 0x1 Example_TaskEntry write event. -Example_Event,read event :0x1 +Example_Event, read event :0x1 EventMask:1 EventMask:0 ``` diff --git a/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-mutex.md b/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-mutex.md index 77b90fb2079a1ea453acde1d4a85ec13270de23e..79fcfd6af0e111bb78184246260a3777afc95d9e 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-mutex.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-mutex.md @@ -5,7 +5,7 @@ 互斥锁又称互斥型信号量,是一种特殊的二值性信号量,用于实现对共享资源的独占式处理。 -任意时刻互斥锁的状态只有两种,开锁或闭锁。当有任务持有时,互斥锁处于闭锁状态,这个任务获得该互斥锁的所有权。当该任务释放它时,该互斥锁被开锁,任务失去该互斥锁的所有权。当一个任务持有互斥锁时,其他任务将不能再对该互斥锁进行开锁或持有。 +任意时刻互斥锁的状态只有两种,开锁或闭锁。当任务持有互斥锁时,该互斥锁处于闭锁状态,这个任务获得该互斥锁的所有权。当该任务释放互斥锁时,该互斥锁被开锁,任务失去该互斥锁的所有权。当一个任务持有互斥锁时,其他任务将不能再对该互斥锁进行开锁或持有。 多任务环境下往往存在多个任务竞争同一共享资源的应用场景,互斥锁可被用于对共享资源的保护从而实现独占式访问。另外互斥锁可以解决信号量存在的优先级翻转问题。 @@ -24,10 +24,10 @@ **表1** 互斥锁模块接口 -| 功能分类 | 接口描述 | +| 功能分类 | 接口描述 | | -------- | -------- | -| 互斥锁的创建和删除 | LOS_MuxCreate:创建互斥锁
LOS_MuxDelete:删除指定的互斥锁 | -| 互斥锁的申请和释放 | LOS_MuxPend:申请指定的互斥锁
LOS_MuxPost:释放指定的互斥锁 | +| 互斥锁的创建和删除 | LOS_MuxCreate:创建互斥锁。
LOS_MuxDelete:删除指定的互斥锁。 | +| 互斥锁的申请和释放 | LOS_MuxPend:申请指定的互斥锁。
LOS_MuxPost:释放指定的互斥锁。 | ## 开发流程 @@ -39,7 +39,7 @@ 2. 申请互斥锁LOS_MuxPend。 申请模式有三种:无阻塞模式、永久阻塞模式、定时阻塞模式。 - - 无阻塞模式:任务需要申请互斥锁,若该互斥锁当前没有任务持有,或者持有该互斥锁的任务和申请该互斥锁的任务为同一个任务,则申请成功。 + - 无阻塞模式:任务需要申请互斥锁,若该互斥锁当前没有任务持有,或者持有该互斥锁的任务和申请该互斥锁的任务为同一个任务,则申请成功。否则直接返回并继续运行当前任务,不会产生阻塞。 - 永久阻塞模式:任务需要申请互斥锁,若该互斥锁当前没有被占用,则申请成功。否则,该任务进入阻塞态,系统切换到就绪任务中优先级高者继续执行。任务进入阻塞态后,直到有其他任务释放该互斥锁,阻塞任务才会重新得以执行。 - 定时阻塞模式:任务需要申请互斥锁,若该互斥锁当前没有被占用,则申请成功。否则该任务进入阻塞态,系统切换到就绪任务中优先级高者继续执行。任务进入阻塞态后,指定时间超时前有其他任务释放该互斥锁,或者用户指定时间超时后,阻塞任务才会重新得以执行。 @@ -50,7 +50,7 @@ 4. 删除互斥锁LOS_MuxDelete。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** -> - 两个任务不能对同一把互斥锁加锁。如果某任务对已被持有的互斥锁加锁,则该任务会被挂起,直到持有该锁的任务对互斥锁解锁,才能执行对这把互斥锁的加锁操作。 +> - 互斥锁支持嵌套,即申请该互斥锁的任务与已经持有该互斥锁的任务为同一个任务时会认为申请成功,按申请次数对应的去释放该锁即可。 > > - 互斥锁不能在中断服务程序中使用。 > @@ -66,67 +66,66 @@ 本实例实现如下流程。 -1. 任务Example_TaskEntry创建一个互斥锁,锁任务调度,创建两个任务Example_MutexTask1、Example_MutexTask2。Example_MutexTask2优先级高于Example_MutexTask1,解锁任务调度。 +1. 任务ExampleMutex创建一个互斥锁,锁任务调度,创建两个任务ExampleMutexTask1、ExampleMutexTask2。ExampleMutexTask2优先级高于ExampleMutexTask1,解锁任务调度。 -2. Example_MutexTask2被调度,以永久阻塞模式申请互斥锁,并成功获取到该互斥锁,然后任务休眠100Tick,Example_MutexTask2挂起,Example_MutexTask1被唤醒。 +2. ExampleMutexTask2被调度,以永久阻塞模式申请互斥锁,并成功获取到该互斥锁,然后任务休眠100Tick,ExampleMutexTask2挂起,ExampleMutexTask1被唤醒。 -3. Example_MutexTask1以定时阻塞模式申请互斥锁,等待时间为10Tick,因互斥锁仍被Example_MutexTask2持有,Example_MutexTask1挂起。10Tick超时时间到达后,Example_MutexTask1被唤醒,以永久阻塞模式申请互斥锁,因互斥锁仍被Example_MutexTask2持有,Example_MutexTask1挂起。 +3. ExampleMutexTask1以定时阻塞模式申请互斥锁,等待时间为10Tick,因互斥锁仍被ExampleMutexTask2持有,ExampleMutexTask1挂起。10Tick超时时间到达后,ExampleMutexTask1被唤醒,以永久阻塞模式申请互斥锁,因互斥锁仍被ExampleMutexTask2持有,ExampleMutexTask1挂起。 -4. 100Tick休眠时间到达后,Example_MutexTask2被唤醒, 释放互斥锁,唤醒Example_MutexTask1。Example_MutexTask1成功获取到互斥锁后,释放,删除互斥锁。 +4. 100Tick休眠时间到达后,ExampleMutexTask2被唤醒, 释放互斥锁,唤醒ExampleMutexTask1。ExampleMutexTask1成功获取到互斥锁后,释放并删除互斥锁。 ### 示例代码 示例代码如下: - +本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleMutex。 + + ``` -#include #include "los_mux.h" -/* 互斥锁句柄id */ +/* 互斥锁句柄 */ UINT32 g_testMux; -/* 任务ID */ -UINT32 g_testTaskId01; -UINT32 g_testTaskId02; -VOID Example_MutexTask1(VOID) +VOID ExampleMutexTask1(VOID) { UINT32 ret; printf("task1 try to get mutex, wait 10 ticks.\n"); /* 申请互斥锁 */ ret = LOS_MuxPend(g_testMux, 10); - if (ret == LOS_OK) { printf("task1 get mutex g_testMux.\n"); - /* 释放互斥锁 */ + /* 释放互斥锁,这个分支正常不应该进来 */ LOS_MuxPost(g_testMux); + LOS_MuxDelete(g_testMux); return; - } + } + if (ret == LOS_ERRNO_MUX_TIMEOUT ) { - printf("task1 timeout and try to get mutex, wait forever.\n"); - /* 申请互斥锁 */ - ret = LOS_MuxPend(g_testMux, LOS_WAIT_FOREVER); - if (ret == LOS_OK) { - printf("task1 wait forever, get mutex g_testMux.\n"); - /* 释放互斥锁 */ - LOS_MuxPost(g_testMux); - /* 删除互斥锁 */ - LOS_MuxDelete(g_testMux); - printf("task1 post and delete mutex g_testMux.\n"); - return; - } + printf("task1 timeout and try to get mutex, wait forever.\n"); + /* 申请互斥锁 */ + ret = LOS_MuxPend(g_testMux, LOS_WAIT_FOREVER); + if (ret == LOS_OK) { + printf("task1 wait forever, get mutex g_testMux.\n"); + /* 释放互斥锁 */ + LOS_MuxPost(g_testMux); + /* 删除互斥锁 */ + LOS_MuxDelete(g_testMux); + printf("task1 post and delete mutex g_testMux.\n"); + return; + } } + return; } -VOID Example_MutexTask2(VOID) +VOID ExampleMutexTask2(VOID) { printf("task2 try to get mutex, wait forever.\n"); /* 申请互斥锁 */ (VOID)LOS_MuxPend(g_testMux, LOS_WAIT_FOREVER); - printf("task2 get mutex g_testMux and suspend 100 ticks.\n"); /* 任务休眠100Ticks */ @@ -138,11 +137,13 @@ VOID Example_MutexTask2(VOID) return; } -UINT32 Example_TaskEntry(VOID) +UINT32 ExampleMutex(VOID) { UINT32 ret; - TSK_INIT_PARAM_S task1; - TSK_INIT_PARAM_S task2; + TSK_INIT_PARAM_S task1 = { 0 }; + TSK_INIT_PARAM_S task2 = { 0 }; + UINT32 taskId01; + UINT32 taskId02; /* 创建互斥锁 */ LOS_MuxCreate(&g_testMux); @@ -151,24 +152,22 @@ UINT32 Example_TaskEntry(VOID) LOS_TaskLock(); /* 创建任务1 */ - memset(&task1, 0, sizeof(TSK_INIT_PARAM_S)); - task1.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_MutexTask1; + task1.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleMutexTask1; task1.pcName = "MutexTsk1"; task1.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; task1.usTaskPrio = 5; - ret = LOS_TaskCreate(&g_testTaskId01, &task1); + ret = LOS_TaskCreate(&taskId01, &task1); if (ret != LOS_OK) { printf("task1 create failed.\n"); return LOS_NOK; } /* 创建任务2 */ - memset(&task2, 0, sizeof(TSK_INIT_PARAM_S)); - task2.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_MutexTask2; + task2.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleMutexTask2; task2.pcName = "MutexTsk2"; task2.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; task2.usTaskPrio = 4; - ret = LOS_TaskCreate(&g_testTaskId02, &task2); + ret = LOS_TaskCreate(&taskId02, &task2); if (ret != LOS_OK) { printf("task2 create failed.\n"); return LOS_NOK; @@ -185,7 +184,7 @@ UINT32 Example_TaskEntry(VOID) ### 结果验证 编译运行得到的结果为: - + ``` task2 try to get mutex, wait forever. task2 get mutex g_testMux and suspend 100 ticks. diff --git a/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-queue.md b/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-queue.md index 16178ecadabea0217f49780744c8d272bc39d590..f2e60ebd8b30ea049f5238dbd1ae52bc17e40ec9 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-queue.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-queue.md @@ -3,7 +3,7 @@ ## 基本概念 -队列又称消息队列,是一种常用于任务间通信的数据结构。队列接收来自任务或中断的不固定长度消息,并根据不同的接口确定传递的消息是否存放在队列空间中。 +消息队列又称队列,是一种任务间通信的机制。消息队列接收来自任务或中断的不固定长度消息,并根据不同的接口确定传递的消息是否存放在队列空间中。 任务能够从队列里面读取消息,当队列中的消息为空时,挂起读取任务;当队列中有新消息时,挂起的读取任务被唤醒并处理新消息。任务也能够往队列里写入消息,当队列已经写满消息时,挂起写入任务;当队列中有空闲消息节点时,挂起的写入任务被唤醒并写入消息。 @@ -12,44 +12,40 @@ 消息队列提供了异步处理机制,允许将一个消息放入队列,但不立即处理。同时队列还有缓冲消息的作用,可以使用队列实现任务异步通信,队列具有如下特性: - 消息以先进先出的方式排队,支持异步读写。 - - 读队列和写队列都支持超时机制。 - - 每读取一条消息,就会将该消息节点设置为空闲。 - - 发送消息类型由通信双方约定,可以允许不同长度(不超过队列的消息节点大小)的消息。 - - 一个任务能够从任意一个消息队列接收和发送消息。 - - 多个任务能够从同一个消息队列接收和发送消息。 - -- 创建队列时所需的队列空间,接口内系统自行动态申请内存。 +- 创建普通队列时所需的队列空间,由系统自行动态申请内存。 +- 创建静态队列时所需的队列空间,由用户传入。这块空间在队列删除之后也由用户去释放。 ## 运行机制 - ### 队列控制块 - +队列会在初始化时给分配一个属于自己的控制块,控制块包含了队列的名称、状态等信息。删除队列时会释放该控制块。 + +队列控制块数据结构如下: + + ``` -/** - * 队列控制块数据结构 - */ typedef struct { - UINT8 *queue; /* 队列消息内存空间的指针 */ - UINT16 queueState; /* 队列状态 */ - UINT16 queueLen; /* 队列中消息节点个数,即队列长度 */ - UINT16 queueSize; /* 消息节点大小 */ - UINT16 queueID; /* 队列ID */ - UINT16 queueHead; /* 消息头节点位置(数组下标)*/ - UINT16 queueTail; /* 消息尾节点位置(数组下标)*/ - UINT16 readWriteableCnt[OS_READWRITE_LEN]; /* 数组下标0的元素表示队列中可读消息数, - 数组下标1的元素表示队列中可写消息数 */ - LOS_DL_LIST readWriteList[OS_READWRITE_LEN]; /* 读取或写入消息的任务等待链表, - 下标0:读取链表,下标1:写入链表 */ - LOS_DL_LIST memList; /* 内存块链表 */ + UINT8 *queue; /* 队列消息内存空间的指针 */ + UINT8 *queueName /* 队列名称 */ + UINT16 queueState; /* 队列状态 */ + UINT16 queueLen; /* 队列中消息节点个数,即队列长度 */ + UINT16 queueSize; /* 消息节点大小 */ + UINT16 queueID; /* 队列ID */ + UINT16 queueHead; /* 消息头节点位置(数组下标)*/ + UINT16 queueTail; /* 消息尾节点位置(数组下标)*/ + UINT16 readWriteableCnt[OS_READWRITE_LEN]; /* 数组下标0的元素表示队列中可读消息数, + 数组下标1的元素表示队列中可写消息数 */ + LOS_DL_LIST readWriteList[OS_READWRITE_LEN]; /* 读取或写入消息的任务等待链表, + 下标0:读取链表,下标1:写入链表 */ + LOS_DL_LIST memList; /* 内存块链表 */ } LosQueueCB; ``` @@ -81,12 +77,12 @@ typedef struct ## 接口说明 - | 功能分类 | 接口描述 | +| 功能分类 | 接口描述 | | -------- | -------- | -| 创建/删除消息队列 | - LOS_QueueCreate:创建一个消息队列,由系统动态申请队列空间。
- LOS_QueueDelete:根据队列ID删除一个指定队列。 | -| 读/写队列(不带拷贝) | - LOS_QueueRead:读取指定队列头节点中的数据(队列节点中的数据实际上是一个地址)。
- LOS_QueueWrite:向指定队列尾节点中写入入参bufferAddr的值(即buffer的地址)。
- LOS_QueueWriteHead:向指定队列头节点中写入入参bufferAddr的值(即buffer的地址)。 | -| 读/写队列(带拷贝) | - LOS_QueueReadCopy:读取指定队列头节点中的数据。
- LOS_QueueWriteCopy:向指定队列尾节点中写入入参bufferAddr中保存的数据。
- LOS_QueueWriteHeadCopy:向指定队列头节点中写入入参bufferAddr中保存的数据。 | -| 获取队列信息 | LOS_QueueInfoGet:获取指定队列的信息,包括队列ID、队列长度、消息节点大小、头节点、尾节点、可读节点数量、可写节点数量、等待读操作的任务、等待写操作的任务。 | +| 创建/删除消息队列 |  LOS_QueueCreate:创建一个消息队列,由系统动态申请队列空间。
LOS_QueueCreateStatic:创建一个消息队列,由用户传入队列空间。
 LOS_QueueDelete:根据队列ID删除一个指定队列,静态消息队列删除后,队列空间需要用例自行处理。 | +| 读/写队列(不带拷贝) |  LOS_QueueRead:读取指定队列头节点中的数据(队列节点中的数据实际上是一个地址)。
 LOS_QueueWrite:向指定队列尾节点中写入入参bufferAddr的值(即buffer的地址)。
 LOS_QueueWriteHead:向指定队列头节点中写入入参bufferAddr的值(即buffer的地址)。 | +| 读/写队列(带拷贝) |  LOS_QueueReadCopy:读取指定队列头节点中的数据。
 LOS_QueueWriteCopy:向指定队列尾节点中写入入参bufferAddr中保存的数据。
 LOS_QueueWriteHeadCopy:向指定队列头节点中写入入参bufferAddr中保存的数据。 | +| 获取队列信息 | LOS_QueueInfoGet:获取指定队列的信息,包括队列ID、队列长度、消息节点大小、头节点、尾节点、可读节点数量、可写节点数量、等待读操作的任务、等待写操作的任务。 | ## 开发流程 @@ -140,11 +136,14 @@ typedef struct 示例代码如下: - +本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleQueue。 + + ``` #include "los_task.h" #include "los_queue.h" -static UINT32 g_queue; + +STATIC UINT32 g_queue; #define BUFFER_LEN 50 VOID SendEntry(VOID) @@ -154,7 +153,7 @@ VOID SendEntry(VOID) UINT32 len = sizeof(abuf); ret = LOS_QueueWriteCopy(g_queue, abuf, len, 0); - if(ret != LOS_OK) { + if (ret != LOS_OK) { printf("send message failure, error: %x\n", ret); } } @@ -165,17 +164,17 @@ VOID RecvEntry(VOID) CHAR readBuf[BUFFER_LEN] = {0}; UINT32 readLen = BUFFER_LEN; - //休眠1s + /* 休眠1s */ usleep(1000000); ret = LOS_QueueReadCopy(g_queue, readBuf, &readLen, 0); - if(ret != LOS_OK) { + if (ret != LOS_OK) { printf("recv message failure, error: %x\n", ret); } - printf("recv message: %s\n", readBuf); + printf("recv message: %s.\n", readBuf); ret = LOS_QueueDelete(g_queue); - if(ret != LOS_OK) { + if (ret != LOS_OK) { printf("delete the queue failure, error: %x\n", ret); } @@ -186,25 +185,28 @@ UINT32 ExampleQueue(VOID) { printf("start queue example.\n"); UINT32 ret = 0; - UINT32 task1, task2; - TSK_INIT_PARAM_S initParam = {0}; - - initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)SendEntry; - initParam.usTaskPrio = 9; - initParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; - initParam.pcName = "SendQueue"; + UINT32 task1; + UINT32 task2; + TSK_INIT_PARAM_S taskParam1 = { 0 }; + TSK_INIT_PARAM_S taskParam2 = { 0 }; LOS_TaskLock(); - ret = LOS_TaskCreate(&task1, &initParam); + + taskParam1.pfnTaskEntry = (TSK_ENTRY_FUNC)SendEntry; + taskParam1.usTaskPrio = 9; + taskParam1.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; + taskParam1.pcName = "SendQueue"; + ret = LOS_TaskCreate(&task1, &taskParam1); if(ret != LOS_OK) { printf("create task1 failed, error: %x\n", ret); return ret; } - initParam.pcName = "RecvQueue"; - initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)RecvEntry; - initParam.usTaskPrio = 10; - ret = LOS_TaskCreate(&task2, &initParam); + taskParam2.pfnTaskEntry = (TSK_ENTRY_FUNC)RecvEntry; + taskParam2.usTaskPrio = 10; + taskParam2.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; + taskParam2.pcName = "RecvQueue"; + ret = LOS_TaskCreate(&task2, &taskParam2); if(ret != LOS_OK) { printf("create task2 failed, error: %x\n", ret); return ret; @@ -227,7 +229,7 @@ UINT32 ExampleQueue(VOID) 编译运行得到的结果为: - + ``` start queue example. create the queue success. diff --git a/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-sem.md b/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-sem.md index 2fb49adb65c17d90504ac54465011f5099760734..b8451b04faa305154792a40778388031158a2e63 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-sem.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-sem.md @@ -11,7 +11,7 @@ - 正值,表示该信号量当前可被获取。 -以同步为目的的信号量和以互斥为目的的信号量在使用上有如下不同: +信号量可用于同步或者互斥。以同步为目的的信号量和以互斥为目的的信号量在使用上有如下不同: - 用作互斥时,初始信号量计数值不为0,表示可用的共享资源个数。在需要使用共享资源前,先获取信号量,然后使用一个共享资源,使用完毕后释放信号量。这样在共享资源被取完,即信号量计数减至0时,其他需要获取信号量的任务将被阻塞,从而保证了共享资源的互斥访问。另外,当共享资源数为1时,建议使用二值信号量,一种类似于互斥锁的机制。 @@ -23,7 +23,7 @@ ### 信号量控制块 - + ``` /** * 信号量控制块数据结构 @@ -40,7 +40,7 @@ typedef struct { ### 信号量运作原理 -信号量初始化,为配置的N个信号量申请内存(N值可以由用户自行配置,通过LOSCFG_BASE_IPC_SEM_LIMIT宏实现),并把所有信号量初始化成未使用,加入到未使用链表中供系统使用。 +信号量初始化,为配置的N个信号量申请内存(N值可以由用户自行配置,通过LOSCFG_BASE_IPC_SEM_LIMIT宏实现,按产品实际需要设定),并把所有信号量初始化成未使用,加入到未使用链表中供系统使用。 信号量创建,从未使用的信号量链表中获取一个信号量,并设定初值。 @@ -58,10 +58,10 @@ typedef struct { ## 接口说明 - | 功能分类 | 接口描述 | +| 功能分类 | 接口描述 | | -------- | -------- | -| 创建/删除信号量 | - LOS_SemCreate:创建信号量,返回信号量ID
- LOS_BinarySemCreate:创建二值信号量,其计数值最大为1
- LOS_SemDelete:删除指定的信号量 | -| 申请/释放信号量 | - LOS_SemPend:申请指定的信号量,并设置超时时间
- LOS_SemPost:释放指定的信号量 | +| 创建/删除信号量 |  LOS_SemCreate:创建信号量,返回信号量ID。
 LOS_BinarySemCreate:创建二值信号量,其计数值最大为1。
 LOS_SemDelete:删除指定的信号量。 | +| 申请/释放信号量 |  LOS_SemPend:申请指定的信号量,并设置超时时间。
 LOS_SemPost:释放指定的信号量。 | ## 开发流程 @@ -101,17 +101,11 @@ typedef struct { 示例代码如下: - -``` -#include "los_sem.h" -#include "securec.h" +本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleSem。 -/* 任务ID */ -static UINT32 g_testTaskId01; -static UINT32 g_testTaskId02; -/* 测试任务优先级 */ -#define TASK_PRIO_TEST 5 +``` +#include "los_sem.h" /* 信号量结构体id */ static UINT32 g_semId; @@ -121,19 +115,17 @@ VOID ExampleSemTask1(VOID) UINT32 ret; printf("ExampleSemTask1 try get sem g_semId, timeout 10 ticks.\n"); - /* 定时阻塞模式申请信号量,定时时间为10ticks */ ret = LOS_SemPend(g_semId, 10); - /* 申请到信号量 */ if (ret == LOS_OK) { LOS_SemPost(g_semId); return; } + /* 定时时间到,未申请到信号量 */ if (ret == LOS_ERRNO_SEM_TIMEOUT) { printf("ExampleSemTask1 timeout and try get sem g_semId wait forever.\n"); - /*永久阻塞模式申请信号量*/ ret = LOS_SemPend(g_semId, LOS_WAIT_FOREVER); printf("ExampleSemTask1 wait_forever and get sem g_semId.\n"); @@ -151,15 +143,14 @@ VOID ExampleSemTask2(VOID) /* 永久阻塞模式申请信号量 */ ret = LOS_SemPend(g_semId, LOS_WAIT_FOREVER); - if (ret == LOS_OK) { printf("ExampleSemTask2 get sem g_semId and then delay 20 ticks.\n"); } /* 任务休眠20 ticks */ LOS_TaskDelay(20); - printf("ExampleSemTask2 post sem g_semId.\n"); + /* 释放信号量 */ LOS_SemPost(g_semId); return; @@ -168,8 +159,10 @@ VOID ExampleSemTask2(VOID) UINT32 ExampleSem(VOID) { UINT32 ret; - TSK_INIT_PARAM_S task1; - TSK_INIT_PARAM_S task2; + TSK_INIT_PARAM_S task1 = { 0 }; + TSK_INIT_PARAM_S task2 = { 0 }; + UINT32 taskId1; + UINT32 taskId2; /* 创建信号量 */ LOS_SemCreate(0, &g_semId); @@ -178,24 +171,22 @@ UINT32 ExampleSem(VOID) LOS_TaskLock(); /* 创建任务1 */ - (VOID)memset_s(&task1, sizeof(TSK_INIT_PARAM_S), 0, sizeof(TSK_INIT_PARAM_S)); task1.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleSemTask1; task1.pcName = "TestTask1"; task1.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; - task1.usTaskPrio = TASK_PRIO_TEST; - ret = LOS_TaskCreate(&g_testTaskId01, &task1); + task1.usTaskPrio = 5; + ret = LOS_TaskCreate(&taskId1, &task1); if (ret != LOS_OK) { printf("task1 create failed.\n"); return LOS_NOK; } /* 创建任务2 */ - (VOID)memset_s(&task2, sizeof(TSK_INIT_PARAM_S), 0, sizeof(TSK_INIT_PARAM_S)); task2.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleSemTask2; task2.pcName = "TestTask2"; task2.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; - task2.usTaskPrio = (TASK_PRIO_TEST - 1); - ret = LOS_TaskCreate(&g_testTaskId02, &task2); + task2.usTaskPrio = 4; + ret = LOS_TaskCreate(&taskId2, &task2); if (ret != LOS_OK) { printf("task2 create failed.\n"); return LOS_NOK; @@ -221,12 +212,11 @@ UINT32 ExampleSem(VOID) 编译运行得到的结果为: - + ``` ExampleSemTask2 try get sem g_semId wait forever. -ExampleSemTask2 get sem g_semId and then delay 20 ticks. ExampleSemTask1 try get sem g_semId, timeout 10 ticks. - +ExampleSemTask2 get sem g_semId and then delay 20 ticks. ExampleSemTask1 timeout and try get sem g_semId wait forever. ExampleSemTask2 post sem g_semId. ExampleSemTask1 wait_forever and get sem g_semId. diff --git a/zh-cn/device-dev/kernel/kernel-mini-appx-data-list.md b/zh-cn/device-dev/kernel/kernel-mini-basic-list.md similarity index 58% rename from zh-cn/device-dev/kernel/kernel-mini-appx-data-list.md rename to zh-cn/device-dev/kernel/kernel-mini-basic-list.md index f0c0d1cbea02488cccc34c8959d348ef15ad7ed5..ec6ae58a9befafbe9cc7868871003073c1702f80 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-appx-data-list.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-list.md @@ -12,16 +12,16 @@ 双向链表模块为用户提供下面几种功能,接口详细信息可以查看API参考。 - | | | +| | | | -------- | -------- | -| **功能分类** | **接口描述** | -| 初始化链表 | - LOS_ListInit:将指定双向链表节点初始化为双向链表
- LOS_DL_LIST_HEAD:定义一个双向链表节点并以该节点初始化为双向链表 | -| 增加节点 | - LOS_ListAdd:将指定节点插入到双向链表头端
- LOS_ListTailInsert:将指定节点插入到双向链表尾端 | -| 删除节点 | - LOS_ListDelete:将指定节点从链表中删除
- LOS_ListDelInit:将指定节点从链表中删除,并使用该节点初始化链表 | -| 判断双向链表是否为空 | LOS_ListEmpty:判断链表是否为空 | -| 获取结构体信息 | - LOS_DL_LIST_ENTRY:获取包含链表的结构体地址,接口的第一个入参表示的是链表中的某个节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称
- LOS_OFF_SET_OF:获取指定结构体内的成员相对于结构体起始地址的偏移量 | -| 遍历双向链表 | - LOS_DL_LIST_FOR_EACH:遍历双向链表
- LOS_DL_LIST_FOR_EACH_SAFE:遍历双向链表,并存储当前节点的后继节点用于安全校验 | -| 遍历包含双向链表的结构体 | - LOS_DL_LIST_FOR_EACH_ENTRY:遍历指定双向链表,获取包含该链表节点的结构体地址
- LOS_DL_LIST_FOR_EACH_ENTRY_SAFE:遍历指定双向链表,获取包含该链表节点的结构体地址,并存储包含当前节点的后继节点的结构体地址 | +| **功能分类** | **接口描述** | +| 初始化和删除链表 |  LOS_ListInit:将指定双向链表节点初始化为双向链表。
 LOS_DL_LIST_HEAD:定义一个双向链表节点并以该节点初始化为双向链表。
LOS_ListDelInit:删除指定的双向链表。 | +| 增加节点 |  LOS_ListAdd:将指定节点插入到双向链表头端。
 LOS_ListTailInsert:将指定节点插入到双向链表尾端。 | +| 删除节点 |  LOS_ListDelete:将指定节点从链表中删除。
 LOS_ListDelInit:将指定节点从链表中删除,并使用该节点初始化链表。 | +| 判断双向链表是否为空 | LOS_ListEmpty:判断链表是否为空。 | +| 获取结构体信息 |  LOS_DL_LIST_ENTRY:获取包含链表的结构体地址,接口的第一个入参表示的是链表中的某个节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称。
 LOS_OFF_SET_OF:获取指定结构体内的成员相对于结构体起始地址的偏移量。 | +| 遍历双向链表 |  LOS_DL_LIST_FOR_EACH:遍历双向链表。
 LOS_DL_LIST_FOR_EACH_SAFE:遍历双向链表,并存储当前节点的后继节点用于安全校验。 | +| 遍历包含双向链表的结构体 |  LOS_DL_LIST_FOR_EACH_ENTRY:遍历指定双向链表,获取包含该链表节点的结构体地址。
 LOS_DL_LIST_FOR_EACH_ENTRY_SAFE:遍历指定双向链表,获取包含该链表节点的结构体地址,并存储包含当前节点的后继节点的结构体地址。 | ## 开发流程 @@ -69,22 +69,24 @@ 示例代码如下: - +本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleList。 + + ``` #include "stdio.h" #include "los_list.h" -static UINT32 ListSample(VOID) +STATIC UINT32 ExampleList(VOID) { LOS_DL_LIST listHead = {NULL,NULL}; LOS_DL_LIST listNode1 = {NULL,NULL}; LOS_DL_LIST listNode2 = {NULL,NULL}; - //首先初始化链表 + /* 初始化链表 */ printf("Initial head\n"); LOS_ListInit(&listHead); - //添加节点1和节点2,并校验他们的相互关系 + /* 添加节点1和节点2,并校验他们的相互关系 */ LOS_ListAdd(&listHead, &listNode1); if (listNode1.pstNext == &listHead && listNode1.pstPrev == &listHead) { printf("Add listNode1 success\n"); @@ -95,11 +97,11 @@ static UINT32 ListSample(VOID) printf("Tail insert listNode2 success\n"); } - //删除两个节点 + /* 删除两个节点 */ LOS_ListDelete(&listNode1); LOS_ListDelete(&listNode2); - //确认链表为空 + /* 确认链表为空 */ if (LOS_ListEmpty(&listHead)) { printf("Delete success\n"); } @@ -113,7 +115,7 @@ static UINT32 ListSample(VOID) 编译运行得到的结果为: - + ``` Initial head Add listNode1 success diff --git a/zh-cn/device-dev/kernel/kernel-mini-basic-memory.md b/zh-cn/device-dev/kernel/kernel-mini-basic-memory.md index 5071ddf325680c7d939907b5bb2fd8d8f1368e77..a95eb894ce9723b9ae74c39efd8e23fd6e87263e 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-basic-memory.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-memory.md @@ -45,12 +45,12 @@ OpenHarmony LiteOS-M的静态内存管理主要为用户提供以下功能,接 **表1** 静态内存模块接口 -| 功能分类 | 接口名 | +| 功能分类 | 接口名 | | -------- | -------- | -| 初始化静态内存池 | LOS_MemboxInit:初始化一个静态内存池,根据入参设定其起始地址、总大小及每个内存块大小。 | -| 清除静态内存块内容 | LOS_MemboxClr:清零从静态内存池中申请的静态内存块的内容。 | -| 申请、释放静态内存 | - LOS_MemboxAlloc:从指定的静态内存池中申请一块静态内存块。
- LOS_MemboxFree:释放从静态内存池中申请的一块静态内存块。 | -| 获取、打印静态内存池信息 | - LOS_MemboxStatisticsGet:获取指定静态内存池的信息,包括内存池中总内存块数量、已经分配出去的内存块数量、每个内存块的大小。
- LOS_ShowBox:打印指定静态内存池所有节点信息(打印等级是LOS_INFO_LEVEL),包括内存池起始地址、内存块大小、总内存块数量、每个空闲内存块的起始地址、所有内存块的起始地址。 | +| 初始化静态内存池 | LOS_MemboxInit:初始化一个静态内存池,根据入参设定其起始地址、总大小及每个内存块大小。 | +| 清除静态内存块内容 | LOS_MemboxClr:清零从静态内存池中申请的静态内存块的内容。 | +| 申请、释放静态内存 |  LOS_MemboxAlloc:从指定的静态内存池中申请一块静态内存块。
 LOS_MemboxFree:释放从静态内存池中申请的一块静态内存块。 | +| 获取、打印静态内存池信息 |  LOS_MemboxStatisticsGet:获取指定静态内存池的信息,包括内存池中总内存块数量、已经分配出去的内存块数量、每个内存块的大小。
 LOS_ShowBox:打印指定静态内存池所有节点信息,打印等级是LOG_INFO_LEVEL(当前打印等级配置是PRINT_LEVEL),包括内存池起始地址、内存块大小、总内存块数量、每个空闲内存块的起始地址、所有内存块的起始地址。 | > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 初始化后的内存池的内存块数量,不等于总大小除于内存块大小,因为内存池的控制块和每个内存块的控制头,都存在内存开销,设置总大小时,需要将这些因素考虑进去。 @@ -91,21 +91,26 @@ OpenHarmony LiteOS-M的静态内存管理主要为用户提供以下功能,接 6. 释放该内存块。 示例代码如下: + + 本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleStaticMem。 + - ``` #include "los_membox.h" -VOID Example_StaticMem(VOID) +#define MEMBOX_POOL_SIZE 100 +#define MEMBOX_BLOCK_SZIE 10 +#define MEMBOX_WR_TEST_NUM 828 +VOID ExampleStaticMem(VOID) { UINT32 *mem = NULL; - UINT32 blkSize = 10; - UINT32 boxSize = 100; - UINT32 boxMem[1000]; + UINT32 blkSize = MEMBOX_BLOCK_SZIE; + UINT32 poolSize = MEMBOX_POOL_SIZE; + UINT32 boxMem[MEMBOX_POOL_SIZE]; UINT32 ret; - /*内存池初始化*/ - ret = LOS_MemboxInit(&boxMem[0], boxSize, blkSize); + /* 内存池初始化 */ + ret = LOS_MemboxInit(&boxMem[0], poolSize, blkSize); if(ret != LOS_OK) { printf("Membox init failed!\n"); return; @@ -113,23 +118,23 @@ VOID Example_StaticMem(VOID) printf("Membox init success!\n"); } - /*申请内存块*/ + /* 申请内存块 */ mem = (UINT32 *)LOS_MemboxAlloc(boxMem); - if (NULL == mem) { + if (mem == NULL) { printf("Mem alloc failed!\n"); return; } printf("Mem alloc success!\n"); - /*赋值*/ - *mem = 828; + /* 内存地址读写验证 */ + *mem = MEMBOX_WR_TEST_NUM; printf("*mem = %d\n", *mem); - /*清除内存内容*/ + /* 清除内存内容 */ LOS_MemboxClr(boxMem, mem); - printf("Mem clear success \n *mem = %d\n", *mem); + printf("Mem clear success \n*mem = %d\n", *mem); - /*释放内存*/ + /* 释放内存 */ ret = LOS_MemboxFree(boxMem, mem); if (LOS_OK == ret) { printf("Mem free success!\n"); @@ -139,6 +144,7 @@ VOID Example_StaticMem(VOID) return; } + ``` @@ -146,7 +152,7 @@ VOID Example_StaticMem(VOID) 输出结果如下: - + ``` Membox init success! Mem alloc success! @@ -197,7 +203,7 @@ OpenHarmony LiteOS-M动态内存在TLSF算法的基础上,对区间的划分 2. 获取下一个内存区域的开始地址和长度,计算该内存区域和上一块内存区域的间隔大小gapSize。 -3. 把内存区域间隔部分视为虚拟的已使用节点,使用上一个内存区域的尾节点,设置其大小为gapSize+ OS_MEM_NODE_HEAD_SIZE。 +3. 把内存区域间隔部分视为虚拟的已使用节点,使用上一个内存区域的尾节点,设置其大小为gapSize + OS_MEM_NODE_HEAD_SIZE(即sizeof(struct OsMemUsedNodeHead))。 4. 把当前内存区域划分为一个空闲内存节点和一个尾节点,把空闲内存节点插入到空闲链表,并设置各个节点的前后链接关系。 @@ -218,14 +224,14 @@ OpenHarmony LiteOS-M的动态内存管理主要为用户提供以下功能,接 **表1** 动态内存模块接口 -| 功能分类 | 接口描述 | +| 功能分类 | 接口描述 | | -------- | -------- | -| 初始化和删除内存池 | - LOS_MemInit:初始化一块指定的动态内存池,大小为size。
- LOS_MemDeInit:删除指定内存池,仅打开LOSCFG_MEM_MUL_POOL时有效。 | -| 申请、释放动态内存 | - LOS_MemAlloc:从指定动态内存池中申请size长度的内存。
- LOS_MemFree:释放从指定动态内存中申请的内存。
- LOS_MemRealloc:释放从指定动态内存中申请的内存。 | -| 获取内存池信息 | - LOS_MemPoolSizeGet:获取指定动态内存池的总大小。
- LOS_MemTotalUsedGet:获取指定动态内存池的总使用量大小。
- LOS_MemInfoGet:获取指定内存池的内存结构信息,包括空闲内存大小、已使用内存大小、空闲内存块数量、已使用的内存块数量、最大的空闲内存块大小。
- LOS_MemPoolList:打印系统中已初始化的所有内存池,包括内存池的起始地址、内存池大小、空闲内存总大小、已使用内存总大小、最大的空闲内存块大小、空闲内存块数量、已使用的内存块数量。仅打开LOSCFG_MEM_MUL_POOL时有效。 | -| 获取内存块信息 | - LOS_MemFreeNodeShow:打印指定内存池的空闲内存块的大小及数量。
- LOS_MemUsedNodeShow:打印指定内存池的已使用内存块的大小及数量。 | -| 检查指定内存池的完整性 | LOS_MemIntegrityCheck:对指定内存池做完整性检查,仅打开LOSCFG_BASE_MEM_NODE_INTEGRITY_CHECK时有效。 | -| 增加非连续性内存区域 | LOS_MemRegionsAdd:支持多段非连续性内存区域,把非连续性内存区域逻辑上整合为一个统一的内存池。仅打开LOSCFG_MEM_MUL_REGIONS时有效。如果内存池指针参数pool为空,则使用多段内存的第一个初始化为内存池,其他内存区域,作为空闲节点插入;如果内存池指针参数pool不为空,则把多段内存作为空闲节点,插入到指定的内存池。 | +| 初始化和删除内存池 |  LOS_MemInit:初始化一块指定的动态内存池,大小为size。
 LOS_MemDeInit:删除指定内存池,仅打开编译控制开关LOSCFG_MEM_MUL_POOL时有效。 | +| 申请、释放动态内存 |  LOS_MemAlloc:从指定动态内存池中申请size长度的内存。
 LOS_MemFree:释放从指定动态内存中申请的内存。
 LOS_MemRealloc:释放从指定动态内存中申请的内存。 | +| 获取内存池信息 |  LOS_MemPoolSizeGet:获取指定动态内存池的总大小。
 LOS_MemTotalUsedGet:获取指定动态内存池的总使用量大小。
 LOS_MemInfoGet:获取指定内存池的内存结构信息,包括空闲内存大小、已使用内存大小、空闲内存块数量、已使用的内存块数量、最大的空闲内存块大小。
 LOS_MemPoolList:打印系统中已初始化的所有内存池,包括内存池的起始地址、内存池大小、空闲内存总大小、已使用内存总大小、最大的空闲内存块大小、空闲内存块数量、已使用的内存块数量。仅打开编译控制开关LOSCFG_MEM_MUL_POOL时有效。 | +| 获取内存块信息 |  LOS_MemFreeNodeShow:打印指定内存池的空闲内存块的大小及数量。
 LOS_MemUsedNodeShow:打印指定内存池的已使用内存块的大小及数量。 | +| 检查指定内存池的完整性 | LOS_MemIntegrityCheck:对指定内存池做完整性检查,仅打开编译控制开关LOSCFG_BASE_MEM_NODE_INTEGRITY_CHECK时有效。 | +| 增加非连续性内存区域 | LOS_MemRegionsAdd:支持多段非连续性内存区域,把非连续性内存区域逻辑上整合为一个统一的内存池。仅打开LOSCFG_MEM_MUL_REGIONS时有效。如果内存池指针参数pool为空,则使用多段内存的第一个初始化为内存池,其他内存区域,作为空闲节点插入;如果内存池指针参数pool不为空,则把多段内存作为空闲节点,插入到指定的内存池。 | > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > - 由于动态内存管理需要管理控制块数据结构来管理内存,这些数据结构会额外消耗内存,故实际用户可使用内存总量小于配置项OS_SYS_MEM_SIZE的大小。 @@ -265,18 +271,24 @@ OpenHarmony LiteOS-M的动态内存管理主要为用户提供以下功能,接 示例代码如下: - +本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleDynMem。 + + ``` #include "los_memory.h" + #define TEST_POOL_SIZE (2*1024) -__attribute__((aligned(4))) UINT8 g_testPool[TEST_POOL_SIZE]; -VOID Example_DynMem(VOID) +#define MEMBOX_WR_TEST_NUM 828 + +__attribute__((aligned(4))) UINT8 g_testDynPool[TEST_POOL_SIZE]; + +VOID ExampleDynMem(VOID) { UINT32 *mem = NULL; UINT32 ret; - /*初始化内存池*/ - ret = LOS_MemInit(g_testPool, TEST_POOL_SIZE); + /* 初始化内存池 */ + ret = LOS_MemInit(g_testDynPool, TEST_POOL_SIZE); if (LOS_OK == ret) { printf("Mem init success!\n"); } else { @@ -284,20 +296,20 @@ VOID Example_DynMem(VOID) return; } - /*分配内存*/ - mem = (UINT32 *)LOS_MemAlloc(g_testPool, 4); - if (NULL == mem) { + /* 申请内存块 */ + mem = (UINT32 *)LOS_MemAlloc(g_testDynPool, 4); + if (mem == NULL) { printf("Mem alloc failed!\n"); return; } printf("Mem alloc success!\n"); - /*赋值*/ - *mem = 828; + /* 内存地址读写验证 */ + *mem = MEMBOX_WR_TEST_NUM; printf("*mem = %d\n", *mem); - /*释放内存*/ - ret = LOS_MemFree(g_testPool, mem); + /* 释放内存 */ + ret = LOS_MemFree(g_testDynPool, mem); if (LOS_OK == ret) { printf("Mem free success!\n"); } else { @@ -313,7 +325,7 @@ VOID Example_DynMem(VOID) 输出结果如下: - + ``` Mem init success! Mem alloc success! diff --git a/zh-cn/device-dev/kernel/kernel-mini-basic-soft.md b/zh-cn/device-dev/kernel/kernel-mini-basic-soft.md index 01a3b8f011e35538fe15839b3c7b79cc017f3f53..7fddc4be0328b6c55b42c32e254d1ae242598f70 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-basic-soft.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-soft.md @@ -24,7 +24,7 @@ ## 运行机制 -软件定时器是系统资源,在模块初始化的时候已经分配了一块连续的内存,系统支持的最大定时器个数由los_config.h中的LOSCFG_BASE_CORE_SWTMR_LIMIT宏配置。 +软件定时器是系统资源,在模块初始化的时候已经分配了一块连续的内存,系统支持的最大定时器个数由los_config.h中的LOSCFG_BASE_CORE_SWTMR_LIMIT宏配置,该值按产品实际需要设定。 软件定时器使用了系统的一个队列和一个任务资源,软件定时器的触发遵循队列规则,先进先出。定时时间短的定时器总是比定时时间长的靠近队列头,满足优先被触发的准则。 @@ -64,11 +64,11 @@ OpenHarmony LiteOS-M内核的软件定时器模块提供下面几种功能,接 **表1** 软件定时器接口 -| 功能分类 | 接口描述 | +| 功能分类 | 接口描述 | | -------- | -------- | -| 创建、删除定时器 | - LOS_SwtmrCreate:创建定时器
- LOS_SwtmrDelete:删除定时器 | -| 启动、停止定时器 | - LOS_SwtmrStart:启动定时器
- LOS_SwtmrStop:停止定时器 | -| 获得软件定时器剩余Tick数 | LOS_SwtmrTimeGet:获得软件定时器剩余Tick数 | +| 创建、删除定时器 | - LOS_SwtmrCreate:创建定时器。
- LOS_SwtmrDelete:删除定时器。 | +| 启动、停止定时器 | - LOS_SwtmrStart:启动定时器。
- LOS_SwtmrStop:停止定时器。 | +| 获得软件定时器剩余Tick数 | LOS_SwtmrTimeGet:获得软件定时器剩余Tick数。 | ## 开发流程 @@ -130,86 +130,107 @@ OpenHarmony LiteOS-M内核的软件定时器模块提供下面几种功能,接 代码实现如下: - +本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleSwtmr。 + + ``` #include "los_swtmr.h" -/* Timer count */ -UINT32 g_timerCount1 = 0; -UINT32 g_timerCount2 = 0; +/* 定时器间隔时间 */ +#define SWTMR_INTERVAL_LONG 1000 +#define SWTMR_INTERVAL_SHORT 100 -/* 任务ID */ -UINT32 g_testTaskId01; +/* 定时器触发次数计数 */ +UINT32 g_timerCount1 = 0; +UINT32 g_timerCount2 = 0; -void Timer1_Callback(UINT32 arg) // 回调函数1 +/* 回调函数1,单次触发定时器的回调函数 */ +void Timer1Callback(UINT32 arg) { - UINT32 tick_last1; g_timerCount1++; - tick_last1 = (UINT32)LOS_TickCountGet(); // 获取当前Tick数 - printf("g_timerCount1=%d, tick_last1=%d\n", g_timerCount1, tick_last1); -} + printf("g_timerCount1=%d\n", g_timerCount1); +} -void Timer2_Callback(UINT32 arg) // 回调函数2 +/* 回调函数2,多次触发定时器的回调函数 */ +void Timer2Callback(UINT32 arg) { - UINT32 tick_last2; - tick_last2 = (UINT32)LOS_TickCountGet(); g_timerCount2++; - printf("g_timerCount2=%d tick_last2=%d\n", g_timerCount2, tick_last2); -} + printf("g_timerCount2=%d\n", g_timerCount2); +} -void Timer_example(void) +void SwtmrTest(void) { UINT32 ret; - UINT32 id1; // timer id1 - UINT32 id2; // timer id2 + UINT32 id1; // 定时器id1,单次触发定时器 + UINT32 id2; // 定时器id2,周期触发定时器 UINT32 tickCount; - /*创建单次软件定时器,Tick数为1000,启动到1000Tick数时执行回调函数1 */ - LOS_SwtmrCreate(1000, LOS_SWTMR_MODE_ONCE, Timer1_Callback, &id1, 1); +#if (LOSCFG_BASE_CORE_SWTMR_ALIGN == 1) + /* 创建单次软件定时器,Tick数为1000,启动到1000Tick数时执行回调函数1 */ + LOS_SwtmrCreate(SWTMR_INTERVAL_LONG, LOS_SWTMR_MODE_ONCE, Timer1Callback, &id1, 0, + OS_SWTMR_ROUSES_IGNORE, OS_SWTMR_ALIGN_SENSITIVE); - /*创建周期性软件定时器,每100Tick数执行回调函数2 */ - LOS_SwtmrCreate(100, LOS_SWTMR_MODE_PERIOD, Timer2_Callback, &id2, 1); - printf("create Timer1 success\n"); + /* 创建周期性软件定时器,每100Tick数执行回调函数2 */ + LOS_SwtmrCreate(SWTMR_INTERVAL_SHORT, LOS_SWTMR_MODE_PERIOD, Timer2Callback, &id2, 0, + OS_SWTMR_ROUSES_IGNORE, OS_SWTMR_ALIGN_SENSITIVE); +#else + /* 创建单次软件定时器,Tick数为1000,启动到1000Tick数时执行回调函数1 */ + LOS_SwtmrCreate(SWTMR_INTERVAL_LONG, LOS_SWTMR_MODE_ONCE, Timer1Callback, &id1, 0); - LOS_SwtmrStart(id1); //启动单次软件定时器 - printf("start Timer1 success\n"); + /* 创建周期性软件定时器,每100Tick数执行回调函数2 */ + LOS_SwtmrCreate(SWTMR_INTERVAL_SHORT, LOS_SWTMR_MODE_PERIOD, Timer2Callback, &id2, 0); +#endif - LOS_TaskDelay(200); //延时200Tick数 - LOS_SwtmrTimeGet(id1, &tickCount); // 获得单次软件定时器剩余Tick数 - printf("tickCount=%d\n", tickCount); + /* 启动单次软件定时器 */ + ret = LOS_SwtmrStart(id1); + printf("start Timer1 %s\n", (ret == LOS_OK) ? "success" : "failed"); - LOS_SwtmrStop(id1); // 停止软件定时器 - printf("stop Timer1 success\n"); + /* 短时间延时,定时器还未触发 */ + LOS_TaskDelay(SWTMR_INTERVAL_SHORT); + + /* 单次定时器还未到时间触发,此时停止应该成功 */ + ret = LOS_SwtmrStop(id1); + printf("stop timer1 %s\n", (ret == LOS_OK) ? "success" : "failed"); LOS_SwtmrStart(id1); - LOS_TaskDelay(1000); + + /* 长时间延时,定时器触发 */ + LOS_TaskDelay(SWTMR_INTERVAL_LONG); + + /* 单次定时器触发后自删除,此时停止失败才是正常 */ + ret = LOS_SwtmrStop(id1); + printf("timer1 self delete test %s\n", (ret != LOS_OK) ? "success" : "failed"); + + /* 启动周期性软件定时器 */ + ret = LOS_SwtmrStart(id2); + printf("start Timer2 %s\n", (ret == LOS_OK) ? "success" : "failed"); - LOS_SwtmrStart(id2); // 启动周期性软件定时器 - printf("start Timer2\n"); + /* 长时间延时,定时器周期触发 */ + LOS_TaskDelay(SWTMR_INTERVAL_LONG); - LOS_TaskDelay(1000); LOS_SwtmrStop(id2); - ret = LOS_SwtmrDelete(id2); // 删除软件定时器 + + ret = LOS_SwtmrDelete(id2); if (ret == LOS_OK) { printf("delete Timer2 success\n"); } } -UINT32 Example_TaskEntry(VOID) +UINT32 ExampleSwtmr(VOID) { UINT32 ret; - TSK_INIT_PARAM_S task1; + TSK_INIT_PARAM_S taskParam = { 0 }; + UINT32 taskId; /* 锁任务调度 */ LOS_TaskLock(); - /* 创建任务1 */ - (VOID)memset(&task1, 0, sizeof(TSK_INIT_PARAM_S)); - task1.pfnTaskEntry = (TSK_ENTRY_FUNC)Timer_example; - task1.pcName = "TimerTsk"; - task1.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; - task1.usTaskPrio = 5; - ret = LOS_TaskCreate(&g_testTaskId01, &task1); + /* 创建任务 */ + taskParam.pfnTaskEntry = (TSK_ENTRY_FUNC)SwtmrTest; + taskParam.pcName = "TimerTsk"; + taskParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; + taskParam.usTaskPrio = 5; + ret = LOS_TaskCreate(&taskId, &taskParam); if (ret != LOS_OK) { printf("TimerTsk create failed.\n"); return LOS_NOK; @@ -217,7 +238,6 @@ UINT32 Example_TaskEntry(VOID) /* 解锁任务调度 */ LOS_TaskUnlock(); - return LOS_OK; } ``` @@ -227,24 +247,22 @@ UINT32 Example_TaskEntry(VOID) 编译烧录运行,输出结果如下: - + ``` -create Timer1 success start Timer1 success -tickCount=798 -stop Timer1 success -g_timerCount1=1, tick_last1=1208 -delete Timer1 success -start Timer2 -g_timerCount2=1 tick_last2=1313 -g_timerCount2=2 tick_last2=1413 -g_timerCount2=3 tick_last2=1513 -g_timerCount2=4 tick_last2=1613 -g_timerCount2=5 tick_last2=1713 -g_timerCount2=6 tick_last2=1813 -g_timerCount2=7 tick_last2=1913 -g_timerCount2=8 tick_last2=2013 -g_timerCount2=9 tick_last2=2113 -g_timerCount2=10 tick_last2=2213 +stop timer1 success +g_timerCount1=1 +timer1 self delete test success +start Timer2 success +g_timerCount2=1 +g_timerCount2=2 +g_timerCount2=3 +g_timerCount2=4 +g_timerCount2=5 +g_timerCount2=6 +g_timerCount2=7 +g_timerCount2=8 +g_timerCount2=9 +g_timerCount2=10 delete Timer2 success ``` diff --git a/zh-cn/device-dev/kernel/kernel-mini-basic-task.md b/zh-cn/device-dev/kernel/kernel-mini-basic-task.md index 50d320e915b4262a137e2cc89e92c7d387d79861..bf246040a71e2b7b17e049126e4339292c706f25 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-basic-task.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-task.md @@ -3,7 +3,7 @@ ## 基本概念 -从系统角度看,任务是竞争系统资源的最小运行单元。任务可以使用或等待CPU、使用内存空间等系统资源,并独立于其它任务运行。 +从系统角度看,任务是竞争系统资源的最小运行单元。任务可以使用或等待CPU、使用内存空间等系统资源,各任务的运行相互独立。 OpenHarmony LiteOS-M的任务模块可以给用户提供多个任务,实现任务间的切换,帮助用户管理业务程序流程。任务模块具有如下特性: @@ -40,7 +40,9 @@ OpenHarmony LiteOS-M的任务模块可以给用户提供多个任务,实现任 ![zh-cn_image_0000001200612002](figures/zh-cn_image_0000001200612002.png) -**任务状态迁移说明:** +系统会同时存在多个任务,因此就绪态和阻塞态的任务分别会加入就绪队列和阻塞队列。队列只是相同状态任务的合集,加入队列的先后与任务状态迁移的顺序无关。运行态任务仅存在一个,不存在运行态队列。 + +**任务状态迁移说明** - 就绪态→运行态 任务创建后进入就绪态,发生任务切换时,就绪队列中最高优先级的任务被执行,从而进入运行态,同时该任务从就绪队列中移出。 @@ -48,11 +50,11 @@ OpenHarmony LiteOS-M的任务模块可以给用户提供多个任务,实现任 - 运行态→阻塞态 正在运行的任务发生阻塞(挂起、延时、读信号量等)时,将该任务插入到对应的阻塞队列中,任务状态由运行态变成阻塞态,然后发生任务切换,运行就绪队列中最高优先级任务。 -- 阻塞态→就绪态(阻塞态→运行态) +- 阻塞态→就绪态(阻塞态→运行态的前置条件) 阻塞的任务被恢复后(任务恢复、延时时间超时、读信号量超时或读到信号量等),此时被恢复的任务会被加入就绪队列,从而由阻塞态变成就绪态;此时如果被恢复任务的优先级高于正在运行任务的优先级,则会发生任务切换,该任务由就绪态变成运行态。 - 就绪态→阻塞态 - 任务也有可能在就绪态时被阻塞(挂起),此时任务状态由就绪态变为阻塞态,该任务从就绪队列中删除,不会参与任务调度,直到该任务被恢复。 + 任务也有可能在就绪态时被阻塞(挂起),此时任务状态由就绪态变为阻塞态,该任务从就绪队列中移出,不会参与任务调度,直到该任务被恢复。 - 运行态→就绪态 有更高优先级任务创建或者恢复后,会发生任务调度,此刻就绪队列中最高优先级任务变为运行态,那么原先运行的任务由运行态变为就绪态,依然在就绪队列中。 @@ -65,7 +67,7 @@ OpenHarmony LiteOS-M的任务模块可以给用户提供多个任务,实现任 **任务ID** -任务ID,在任务创建时通过参数返回给用户,是任务的重要标识。系统中的ID号是唯一的。用户可以通过任务ID对指定任务进行任务挂起、任务恢复、查询任务名等操作。 +在任务创建时通过参数返回给用户。系统中任务ID号是唯一的,是任务的重要标识。用户可以通过任务ID对指定任务进行任务挂起、任务恢复、查询任务名等操作。 **任务优先级** @@ -83,7 +85,7 @@ OpenHarmony LiteOS-M的任务模块可以给用户提供多个任务,实现任 任务在运行过程中使用的一些资源,如寄存器等,称为任务上下文。当这个任务挂起时,其他任务继续执行,可能会修改寄存器等资源中的值。如果任务切换时没有保存任务上下文,可能会导致任务恢复后出现未知错误。因此在任务切换时会将切出任务的任务上下文信息,保存在自身的任务栈中,以便任务恢复后,从栈空间中恢复挂起时的上下文信息,从而继续执行挂起时被打断的代码。 -**任务控制块TCB** +**任务控制块(TCB)** 每个任务都含有一个任务控制块(TCB)。TCB包含了任务上下文栈指针(stack pointer)、任务状态、任务优先级、任务ID、任务名、任务栈大小等信息。TCB可以反映出每个任务运行情况。 @@ -103,15 +105,14 @@ OpenHarmony LiteOS-M内核的任务管理模块提供下面几种功能,接口 **表1** 任务管理模块接口 -| 功能分类 | 接口描述 | +| 功能分类 | 接口描述 | | -------- | -------- | -| 创建和删除任务 | LOS_TaskCreateOnly:创建任务,并使该任务进入ready状态,如果就绪队列中没有更高优先级的任务,则运行该任务。
LOS_TaskCreate:创建任务,并使该任务进入ready状态,如果就绪队列中没有更高优先级的任务,则运行该任务。
LOS_TaskDelete:删除指定的任务。 | -| 控制任务状态 | LOS_TaskResume:恢复挂起的任务,使该任务进入ready状态。
LOS_TaskSuspend:挂起指定的任务,然后切换任务。
LOS_TaskJoin:挂起当前任务,等待指定任务运行结束并回收其任务控制块资源
LOS_TaskDelay:任务延时等待,释放CPU,等待时间到期后该任务会重新进入ready状态。传入参数为Tick数目。
LOS_Msleep:传入参数为毫秒数,转换为Tick数目,调用LOS_TaskDelay。
LOS_TaskYield:当前任务时间片设置为0,释放CPU,触发调度运行就绪任务队列中优先级最高的任务。 | -| 控制任务调度 | LOS_TaskLock:锁任务调度,但任务仍可被中断打断。
LOS_TaskUnlock:解锁任务调度。
LOS_Schedule:触发任务调度。 | -| 控制任务优先级 | LOS_CurTaskPriSet:设置当前任务的优先级。
LOS_TaskPriSet:设置指定任务的优先级。
LOS_TaskPriGet:获取指定任务的优先级。 | -| 获取任务信息 | LOS_CurTaskIDGet:获取当前任务的ID。
LOS_NextTaskIDGet:获取任务就绪队列中优先级最高的任务的ID。
LOS_NewTaskIDGet:等同LOS_NextTaskIDGet。
LOS_CurTaskNameGet:获取当前任务的名称。
LOS_TaskNameGet:获取指定任务的名称。
LOS_TaskStatusGet:获取指定任务的状态。
LOS_TaskInfoGet:获取指定任务的信息,包括任务状态、优先级、任务栈大小、栈顶指针SP、任务入口函数、已使用的任务栈大小等。
LOS_TaskIsRunning:获取任务模块是否已经开始调度运行。 | -| 任务信息维测 | LOS_TaskSwitchInfoGet:获取任务切换信息,需要开启宏LOSCFG_BASE_CORE_EXC_TSK_SWITCH。 | - +| 创建和删除任务 | LOS_TaskCreateOnly:创建任务,并使该任务进入suspend状态。
LOS_TaskCreate:创建任务,并使该任务进入ready状态,如果就绪队列中没有更高优先级的任务,则运行该任务。
LOS_TaskDelete:删除指定的任务。 | +| 控制任务状态 | LOS_TaskResume:恢复挂起的任务,使该任务进入ready状态。
LOS_TaskSuspend:挂起指定的任务,然后切换任务。
LOS_TaskJoin:挂起当前任务,等待指定任务运行结束并回收其任务控制块资源
LOS_TaskDelay:任务延时等待,释放CPU,等待时间到期后该任务会重新进入ready状态。传入参数为Tick数目。
LOS_Msleep:任务延时等待,释放CPU,等待时间到期后该任务会重新进入ready状态。传入参数为毫秒数。
LOS_TaskYield:当前任务时间片设置为0,释放CPU,触发调度运行就绪任务队列中优先级最高的任务。 | +| 控制任务调度 | LOS_TaskLock:锁任务调度,但任务仍可被中断打断。
LOS_TaskUnlock:解锁任务调度。
LOS_Schedule:触发任务调度。 | +| 控制任务优先级 | LOS_CurTaskPriSet:设置当前任务的优先级。
LOS_TaskPriSet:设置指定任务的优先级。
LOS_TaskPriGet:获取指定任务的优先级。 | +| 获取任务信息 | LOS_CurTaskIDGet:获取当前任务的ID。
LOS_NextTaskIDGet:获取任务就绪队列中优先级最高的任务的ID。
LOS_NewTaskIDGet:等同LOS_NextTaskIDGet。
LOS_CurTaskNameGet:获取当前任务的名称。
LOS_TaskNameGet:获取指定任务的名称。
LOS_TaskStatusGet:获取指定任务的状态。
LOS_TaskInfoGet:获取指定任务的信息,包括任务状态、优先级、任务栈大小、栈顶指针SP、任务入口函数、已使用的任务栈大小等。
LOS_TaskIsRunning:获取任务模块是否已经开始调度运行。 | +| 任务信息维测 | LOS_TaskSwitchInfoGet:获取任务切换信息,需要开启编译控制宏:LOSCFG_BASE_CORE_EXC_TSK_SWITCH。 | ## 开发流程 @@ -161,20 +162,24 @@ OpenHarmony LiteOS-M内核的任务管理模块提供下面几种功能,接口 本实例介绍基本的任务操作方法,包含2个不同优先级任务的创建、任务延时、任务锁与解锁调度、挂起和恢复等操作,阐述任务优先级调度的机制以及各接口的应用。示例代码如下: - +本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleTask。 + + ``` +#include "los_task.h" + UINT32 g_taskHiId; UINT32 g_taskLoId; -#define TSK_PRIOR_HI 4 -#define TSK_PRIOR_LO 5 +#define TSK_PRIOR_HI 3 /* 高优先级任务的优先级 */ +#define TSK_PRIOR_LO 4 /* 低优先级任务的优先级 */ -UINT32 Example_TaskHi(VOID) +UINT32 ExampleTaskHi(VOID) { UINT32 ret; printf("Enter TaskHi Handler.\n"); - /* 延时100个Ticks,延时后该任务会挂起,执行剩余任务中最高优先级的任务(TaskLo任务) */ + /* 延时100个Ticks,延时后该任务会挂起,执行剩余任务中最高优先级的任务(即TaskLo任务) */ ret = LOS_TaskDelay(100); if (ret != LOS_OK) { printf("Delay TaskHi Failed.\n"); @@ -195,7 +200,7 @@ UINT32 Example_TaskHi(VOID) } /* 低优先级任务入口函数 */ -UINT32 Example_TaskLo(VOID) +UINT32 ExampleTaskLo(VOID) { UINT32 ret; @@ -220,24 +225,25 @@ UINT32 Example_TaskLo(VOID) } /* 任务测试入口函数,创建两个不同优先级的任务 */ -UINT32 Example_TskCaseEntry(VOID) +UINT32 ExampleTask(VOID) { UINT32 ret; - TSK_INIT_PARAM_S initParam; + TSK_INIT_PARAM_S taskParam1 = { 0 }; + TSK_INIT_PARAM_S taskParam2 = { 0 }; /* 锁任务调度,防止新创建的任务比本任务高而发生调度 */ LOS_TaskLock(); printf("LOS_TaskLock() Success!\n"); - initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_TaskHi; - initParam.usTaskPrio = TSK_PRIOR_HI; - initParam.pcName = "TaskHi"; - initParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; - initParam.uwResved = 0; /* detach 属性 */ + taskParam1.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleTaskHi; + taskParam1.usTaskPrio = TSK_PRIOR_HI; + taskParam1.pcName = "TaskHi"; + taskParam1.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; + taskParam1.uwResved = LOS_TASK_ATTR_JOINABLE; /* detach 属性 */ /* 创建高优先级任务,由于锁任务调度,任务创建成功后不会马上执行 */ - ret = LOS_TaskCreate(&g_taskHiId, &initParam); + ret = LOS_TaskCreate(&g_taskHiId, &taskParam1); if (ret != LOS_OK) { LOS_TaskUnlock(); @@ -247,13 +253,13 @@ UINT32 Example_TskCaseEntry(VOID) printf("Example_TaskHi create Success!\n"); - initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_TaskLo; - initParam.usTaskPrio = TSK_PRIOR_LO; - initParam.pcName = "TaskLo"; - initParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; + taskParam2.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleTaskLo; + taskParam2.usTaskPrio = TSK_PRIOR_LO; + taskParam2.pcName = "TaskLo"; + taskParam2.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; /* 创建低优先级任务,由于锁任务调度,任务创建成功后不会马上执行 */ - ret = LOS_TaskCreate(&g_taskLoId, &initParam); + ret = LOS_TaskCreate(&g_taskLoId, &taskParam2); if (ret != LOS_OK) { LOS_TaskUnlock(); printf("Example_TaskLo create Failed!\n"); @@ -266,7 +272,7 @@ UINT32 Example_TskCaseEntry(VOID) LOS_TaskUnlock(); ret = LOS_TaskJoin(g_taskHiId, NULL); if (ret != LOS_OK) { - printf("Join Example_TaskHi Failed!\n"); + printf("Join Example_TaskHi Failed!, 0x%x\n", ret); } else { printf("Join Example_TaskHi Success!\n"); } @@ -279,8 +285,8 @@ UINT32 Example_TskCaseEntry(VOID) 编译运行得到的结果为: - -``` + +``` LOS_TaskLock() Success! Example_TaskHi create Success! Example_TaskLo create Success! diff --git a/zh-cn/device-dev/kernel/kernel-basic-mini-time.md b/zh-cn/device-dev/kernel/kernel-mini-basic-time.md similarity index 60% rename from zh-cn/device-dev/kernel/kernel-basic-mini-time.md rename to zh-cn/device-dev/kernel/kernel-mini-basic-time.md index 36c468a90bca1d1a37daaaf698647b7454f5d29c..6e96095c08f3e74684d226fc6e7c23fe655cf997 100644 --- a/zh-cn/device-dev/kernel/kernel-basic-mini-time.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-time.md @@ -29,8 +29,8 @@ OpenHarmony LiteOS-M内核的时间管理提供下面几种功能,接口详细 | 接口名 | 描述 | | -------- | -------- | -| LOS_MS2Tick | 毫秒转换成Tick | -| LOS_Tick2MS | Tick转化为毫秒 | +| LOS_MS2Tick | 毫秒转换成Tick。 | +| LOS_Tick2MS | Tick转化为毫秒。 | | OsCpuTick2MS | Cycle数目转化为毫秒,使用2个UINT32类型的数值分别表示结果数值的高、低32位。 | | OsCpuTick2US | Cycle数目转化为微秒,使用2个UINT32类型的数值分别表示结果数值的高、低32位。 | @@ -38,10 +38,23 @@ OpenHarmony LiteOS-M内核的时间管理提供下面几种功能,接口详细 | 接口名 | 描述 | | -------- | -------- | -| LOS_SysClockGet | 获取系统时钟 | -| LOS_TickCountGet | 获取自系统启动以来的Tick数 | -| LOS_CyclePerTickGet | 获取每个Tick多少Cycle数 | +| LOS_SysClockGet | 获取系统时钟。 | +| LOS_TickCountGet | 获取自系统启动以来的Tick数。 | +| LOS_CyclePerTickGet | 获取每个Tick多少Cycle数。 | +| LOS_CurrNanosec | 获取当前的时间,单位纳秒。 | + **表3** 时间注册 + +| 接口名 | 描述 | +| --------------------- | ---------------------------------------------- | +| LOS_TickTimerRegister | 重新注册系统时钟的定时器和对应的中断处理函数。 | + + **表4** 延时 + +| 接口名 | 描述 | +| ---------- | ------------------------ | +| LOS_MDelay | 延时函数,延时单位毫秒。 | +| LOS_UDelay | 延时函数,延时单位微秒。 | ## 开发流程 @@ -56,7 +69,7 @@ OpenHarmony LiteOS-M内核的时间管理提供下面几种功能,接口详细 > > - 系统的Tick数在关中断的情况下不进行计数,故系统Tick数不能作为准确时间使用。 > -> - 配置选项维护在开发板工程的文件target_config.h。 +> - 上文描述的配置选项维护在开发板工程 target_config.h 中,部分配置项未定义的缺省值定义在内核 los_config.h中。 ## 编程实例 @@ -81,17 +94,22 @@ OpenHarmony LiteOS-M内核的时间管理提供下面几种功能,接口详细 时间转换: +本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleTransformTime和ExampleGetTime。 + ``` -VOID Example_TransformTime(VOID) +VOID ExampleTransformTime(VOID) { UINT32 ms; UINT32 tick; - tick = LOS_MS2Tick(10000); // 10000ms转换为tick - dprintf("tick = %d \n", tick); - ms = LOS_Tick2MS(100); // 100tick转换为ms - dprintf("ms = %d \n", ms); + /* 10000ms转换为tick */ + tick = LOS_MS2Tick(10000); + printf("tick = %d \n", tick); + + /* 100tick转换为ms */ + ms = LOS_Tick2MS(100); + printf("ms = %d \n", ms); } ``` @@ -99,26 +117,21 @@ VOID Example_TransformTime(VOID) ``` -VOID Example_GetTime(VOID) +VOID ExampleGetTime(VOID) { UINT32 cyclePerTick; - UINT64 tickCount; + UINT64 tickCountBefore; + UINT64 tickCountAfter; cyclePerTick = LOS_CyclePerTickGet(); - if(0 != cyclePerTick) { - dprintf("LOS_CyclePerTickGet = %d \n", cyclePerTick); - } - - tickCount = LOS_TickCountGet(); - if(0 != tickCount) { - dprintf("LOS_TickCountGet = %d \n", (UINT32)tickCount); + if (0 != cyclePerTick) { + printf("LOS_CyclePerTickGet = %d \n", cyclePerTick); } + tickCountBefore = LOS_TickCountGet(); LOS_TaskDelay(200); - tickCount = LOS_TickCountGet(); - if(0 != tickCount) { - dprintf("LOS_TickCountGet after delay = %d \n", (UINT32)tickCount); - } + tickCountAfter = LOS_TickCountGet(); + printf("LOS_TickCountGet after delay rising = %d \n", (UINT32)(tickCountAfter - tickCountBefore)); } ``` @@ -138,8 +151,7 @@ ms = 1000 时间统计和时间延迟: -``` -LOS_CyclePerTickGet = 495000 -LOS_TickCountGet = 1 -LOS_TickCountGet after delay = 201 +``` +LOS_CyclePerTickGet = 250000 (根据实际运行环境,数据会有差异) +LOS_TickCountGet after delay rising = 200 ``` diff --git a/zh-cn/device-dev/kernel/kernel-standard-newip.md b/zh-cn/device-dev/kernel/kernel-standard-newip.md index c507257656f86fa1c9dcd862e22ba78ae9433940..5c1d9dade804eba1d0b9066132cd2d50298131e0 100644 --- a/zh-cn/device-dev/kernel/kernel-standard-newip.md +++ b/zh-cn/device-dev/kernel/kernel-standard-newip.md @@ -254,7 +254,7 @@ struct sockaddr_nin { ![zh-cn_image-20221009112548444](figures/zh-cn_image-20221009112548444.png) -上图中NewIP地址,路由配置程序可以参考[代码仓examples代码](https://gitee.com/openharmony-sig/communication_sfc_newip/tree/master/examples),根据CPU硬件差异更改Makefile中CC定义编译成二级制文件后推送到开发板,参考上图命令给设备配置NewIP地址和路由。 +上图中NewIP地址,路由配置程序可以参考[代码仓examples代码](https://gitee.com/openharmony/communication_sfc_newip/tree/master/examples),根据CPU硬件差异更改Makefile中CC定义编译成二级制文件后推送到开发板,参考上图命令给设备配置NewIP地址和路由。 | 文件名 | 功能 | | ------------------ | ------------------------------------------------------ | @@ -284,7 +284,7 @@ struct sockaddr_nin { ## NewIP收发包代码示例 -NewIP可变长地址配置,路由配置,UDP/TCP收发包demo代码链接如下,NewIP协议栈用户态接口使用方法可以参考[代码仓examples代码](https://gitee.com/openharmony-sig/communication_sfc_newip/tree/master/examples)。demo代码内配置固定地址和路由,执行编译后二进制程序时不需要人工指定地址和路由。 +NewIP可变长地址配置,路由配置,UDP/TCP收发包demo代码链接如下,NewIP协议栈用户态接口使用方法可以参考[代码仓examples代码](https://gitee.com/openharmony/communication_sfc_newip/tree/master/examples)。demo代码内配置固定地址和路由,执行编译后二进制程序时不需要人工指定地址和路由。 | 文件名 | 功能 | | --------------------- | ----------------------------- | @@ -383,7 +383,7 @@ allowxperm thread_xxx thread_xxx:socket ioctl { 0x8933 0x8916 0x890B }; ## WireShark报文解析模板 -Wireshark默认报文解析规则无法解析NewIP报文,在WireShark配置中添加NewIP报文解析模板可以实现NewIP报文解析,[NewIP报文解析模板](https://gitee.com/openharmony-sig/communication_sfc_newip/blob/master/tools/wireshark_cfg_for_newip.lua)详见代码仓。 +Wireshark默认报文解析规则无法解析NewIP报文,在WireShark配置中添加NewIP报文解析模板可以实现NewIP报文解析,[NewIP报文解析模板](https://gitee.com/openharmony/communication_sfc_newip/blob/master/tools/wireshark_cfg_for_newip.lua)详见代码仓。 报文解析模板配置文件的方法: diff --git a/zh-cn/device-dev/porting/porting-stm32f407-on-minisystem-eth.md b/zh-cn/device-dev/porting/porting-stm32f407-on-minisystem-eth.md index 29de44f87158ba6f2d54bbe62de2a98413161f38..2c737a460b35f81ad954e496a21467a42c8f53da 100644 --- a/zh-cn/device-dev/porting/porting-stm32f407-on-minisystem-eth.md +++ b/zh-cn/device-dev/porting/porting-stm32f407-on-minisystem-eth.md @@ -715,7 +715,7 @@ board_ld_flags :链接选项,与Makefile中的LDFLAGS变量对应。 ### 内核基础功能适配 -内核基础功能适配项包括:**[中断管理](../kernel/kernel-mini-basic-interrupt.md)**、**[任务管理](../kernel/kernel-mini-basic-task.md)**、**[内存管理](../kernel/kernel-mini-basic-memory.md)**、**[内核通信机制](../kernel/kernel-mini-basic-ipc-event.md)**、**[时间管理](../kernel/kernel-basic-mini-time.md)**、**[软件定时器](../kernel/kernel-mini-basic-soft.md)**,可以参考对应链接中的编程实例进行内核基础功能验证。在验证的过程中发现问题,针对相应问题进行具体的适配。 +内核基础功能适配项包括:**[中断管理](../kernel/kernel-mini-basic-interrupt.md)**、**[任务管理](../kernel/kernel-mini-basic-task.md)**、**[内存管理](../kernel/kernel-mini-basic-memory.md)**、**[内核通信机制](../kernel/kernel-mini-basic-ipc-event.md)**、**[时间管理](../kernel/kernel-mini-basic-time.md)**、**[软件定时器](../kernel/kernel-mini-basic-soft.md)**,可以参考对应链接中的编程实例进行内核基础功能验证。在验证的过程中发现问题,针对相应问题进行具体的适配。 从上一节中打印信息输出时间间隔可以看出,`LOS_TaskDelay`函数的延时时间不准确,我们可以在`target_config.h`中定义如下宏进行内核时钟适配: diff --git a/zh-cn/device-dev/website.md b/zh-cn/device-dev/website.md index f26f2863bbd04c491f1e4ab3b90d6057e057cf9f..23c3473248d2c2e9109b122e07dac851043bb449 100644 --- a/zh-cn/device-dev/website.md +++ b/zh-cn/device-dev/website.md @@ -166,8 +166,9 @@ - [互斥锁](kernel/kernel-mini-basic-ipc-mutex.md) - [消息队列](kernel/kernel-mini-basic-ipc-queue.md) - [信号量](kernel/kernel-mini-basic-ipc-sem.md) - - [时间管理](kernel/kernel-basic-mini-time.md) + - [时间管理](kernel/kernel-mini-basic-time.md) - [软件定时器](kernel/kernel-mini-basic-soft.md) + - [双向链表](kernel/kernel-mini-basic-list.md) - 扩展组件 - [C++支持](kernel/kernel-mini-extend-support.md) - [CPU占用率](kernel/kernel-mini-extend-cpup.md) @@ -180,7 +181,6 @@ - [LMS调测](kernel/kernel-mini-memory-lms.md) - 附录 - [内核编码规范](kernel/kernel-mini-appx-code.md) - - [双向链表](kernel/kernel-mini-appx-data-list.md) - [标准库支持](kernel/kernel-mini-appx-lib.md) - 小型系统内核(LiteOS-A) - [小型系统内核概述](kernel/kernel-small-overview.md) diff --git "a/zh-cn/readme/\347\224\250\346\210\267IAM\345\255\220\347\263\273\347\273\237.md" "b/zh-cn/readme/\347\224\250\346\210\267IAM\345\255\220\347\263\273\347\273\237.md" index 2a5c008647203981e2da766e24c29bb14173d476..123e8b3acb357954dac6cb1c00e7db9ad3a90df6 100644 --- "a/zh-cn/readme/\347\224\250\346\210\267IAM\345\255\220\347\263\273\347\273\237.md" +++ "b/zh-cn/readme/\347\224\250\346\210\267IAM\345\255\220\347\263\273\347\273\237.md" @@ -1,20 +1,12 @@ # 用户IAM子系统 -- [简介](#简介) -- [目录](#目录) -- [约束](#约束) -- [说明](#说明) - - [使用说明](#使用说明) -- [相关仓](#相关仓) - - ## 简介 用户身份和访问管理子系统,下称用户IAM(Identity and Access Management),旨在为OpenHarmony提供统一用户身份凭据信息管理和用户身份认证框架能力,支持多用户分别设置认证凭据信息,并根据用户设置的认证凭据信息提供用户身份认证功能,支撑锁屏等安全场景。同时,用户IAM子系统也提供API,支持三方开发者调用系统提供的身份认证能力来实现业务对用户的访问控制要求。 **图1** 子系统架构图 -用户IAM子系统逻辑架构 +![](figures/用户IAM子系统逻辑架构.png) 用户IAM子系统分为统一用户认证框架和认证执行器两个部分,其中**统一用户认证框架**部分包含: diff --git a/zh-cn/release-notes/OpenHarmony-v3.2-beta3.md b/zh-cn/release-notes/OpenHarmony-v3.2-beta3.md index 58f46c6929ab2f5cbcdeb4a0f3340e4cce3de5a3..16c8318d068221441622c4b6ac881424c84c6bde 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.2-beta3.md +++ b/zh-cn/release-notes/OpenHarmony-v3.2-beta3.md @@ -170,7 +170,9 @@ DeviceProfile适配分布式数据库自动同步策略,以及采集信息补 | Misc服务子系统 | 新增剪贴板、上传下载、锁屏、输入法框架等模块基础特性。
主要涉及如下需求:
I5JPMG 【request部件】【download】后台任务通知
I5NXHK 【input_method_fwk部件】输入法框架支持仅绑定输入法innerkits接口和独立控制软键盘显隐的js接口
I5NG2X 【theme_screenlock部件】支持特定系统应用请求锁定屏幕
I5IU1Z  支持向剪贴板数据增加图片内容的数据项
I5OGA3  支持设备级的跨设备剪贴板开关
I5NMKI 【pasteboard部件】支持向剪贴板数据增加二进制数据
I5MAMN  支持剪贴板数据范围限制在应用内
I5OX20 【input_method_fwk部件】输入法框架支持获取输入法扩展 | NA | | ArkUI子系统 | ArkUI组件能力增强;资源、媒体查询能力增强;内存、性能优化;DFX能力增强;工具链能力增强。
主要涉及如下需求:
I5IZZ7 【ace_engine_standard部件】panel组件支持单独设置每个角的borderRadius
I5JQ1R 【ace_engine_standard部件】支持图片复制粘贴
I5JQ3F 【ace_engine_standard部件】输入框能力增强
I5JQ3J 【ace_engine_standard部件】stack组件新增事件拓传机制
I5JQ54 【ace_engine_standard部件】指定控件获取焦点
I5MX7J 【ace_engine_standard部件】list列表支持左滑/右滑及回弹效果
I5MWS0 【ace_engine_standard部件】panel组件弹出高度通知给开发者
I5IZVY 【ace_engine_standard部件】键鼠接入时支持组件刷新
I5JQ5Y 【ace_engine_standard部件】走焦能力增强
I5IY7K 【新增需求】【ace_engine_standard部件】主题能力支持
I5MWTB 【ace_engine_standard部件】媒体查询支持vp查询
I5IZU9 【ace_engine_standard部件】ui_service常驻内存优化
I5JQ26 【ace_engine_standard部件】Vsync请求机制流程优化
I5JQ2O 【ace_engine部件】公共资源预加载
I5JQ2D 【ace_engine_standard部件】Move事件重采样优化
I5IZXS 【toolchain部件】DFX打印错误堆栈时支持显示开发者变量名称原文
I5IZYG 【toolchain部件】DFX打印错误堆栈时支持显示开发者变量名称原文
I5IZX0 【toolchain部件】编译支持解析$r新增bundleName和moduleName参数
I5J09I 【toolchain部件】\@Builder 支持export导出 | NA | +API变更请参考: +[*API差异报告*](api-change/v3.2-beta3/Readme-CN.md) ### 芯片及开发板适配 diff --git a/zh-cn/release-notes/api-change/v3.1-Release/changelog-v3.1-release.md b/zh-cn/release-notes/api-change/v3.1-Release/changelog-v3.1-release.md index 4c7289ed1c70c6171775bf34f9701689e94e5792..39a5affa00e6649dc1ebf3d54d2311bb33e7813f 100644 --- a/zh-cn/release-notes/api-change/v3.1-Release/changelog-v3.1-release.md +++ b/zh-cn/release-notes/api-change/v3.1-Release/changelog-v3.1-release.md @@ -18,4 +18,39 @@ **关键的接口/组件变更** -无 \ No newline at end of file +无 + +### 状态变量多种数据类型声明使用限制。 + +状态变量比如@State、@Provide、 @Link和@Consume等,定义数据类型时,只能同时由简单数据类型或对象引用数据类型其中一种构成。 + +示例: + +```ts +@Entry +@Component +struct Index { + //错误写法: @State message: string | Resource = 'Hello World' + @State message: string = 'Hello World' + + build() { + Row() { + Column() { + Text(`${ this.message }`) + .fontSize(50) + .fontWeight(FontWeight.Bold) + } + .width('100%') + } + .height('100%') + } +} +``` + +**变更影响** + +当定义的状态变量类型中同时包含简单类型和对象引用数据类型时,编译报错提示不支持。 + +**关键的接口/组件变更** + +当定义的状态变量类型中同时包含简单类型和对象引用数据类型时,需修改为只含有其中一种,如上述示例代码所示。 \ No newline at end of file diff --git a/zh-cn/release-notes/api-change/v3.2-beta2/changelog-v3.2-beta2.md b/zh-cn/release-notes/api-change/v3.2-beta2/changelog-v3.2-beta2.md index 0871a6dec65c5967fad00a06033d09856105182d..a655be51c328a29689b273121e163a455888959a 100644 --- a/zh-cn/release-notes/api-change/v3.2-beta2/changelog-v3.2-beta2.md +++ b/zh-cn/release-notes/api-change/v3.2-beta2/changelog-v3.2-beta2.md @@ -56,38 +56,3 @@ OpenHarmony应用沙箱组件 ![](figures/compile-change2-1.png) ![](figures/compile-change2-2.png) - -**变更3**:状态变量多种数据类型声明使用限制。 - -状态变量比如@State、@Provide、 @Link和@Consume等,定义数据类型时,只能同时由简单数据类型或对象引用数据类型其中一种构成。 - -示例: - -```ts -@Entry -@Component -struct Index { - //错误写法: @State message: string | Resource = 'Hello World' - @State message: string = 'Hello World' - - build() { - Row() { - Column() { - Text(`${ this.message }`) - .fontSize(50) - .fontWeight(FontWeight.Bold) - } - .width('100%') - } - .height('100%') - } -} -``` - -**关键的接口/组件变更** - -无 - -**适配指导** - -当定义的状态变量类型中同时包含简单类型和对象引用数据类型时,需修改为只含有其中一种,如上述示例代码所示。 \ No newline at end of file diff --git a/zh-cn/release-notes/api-change/v3.2-beta3/js-apidiff-battery.md b/zh-cn/release-notes/api-change/v3.2-beta3/js-apidiff-battery.md index 7cc610cb724ef4aaa126750f3f4781028cc5de96..f905b19e94e376e0abaf0e50718ddfb5db31320a 100644 --- a/zh-cn/release-notes/api-change/v3.2-beta3/js-apidiff-battery.md +++ b/zh-cn/release-notes/api-change/v3.2-beta3/js-apidiff-battery.md @@ -36,4 +36,6 @@ OpenHarmony 3.2 Beta3版本相较于OpenHarmony 3.2 Beta2版本,电源服务 | system.brightness | GetBrightnessOptions | complete?: () => void; | 废弃 | | system.brightness | GetBrightnessOptions | fail?: (data: string, code: number) => void; | 废弃 | | system.brightness | GetBrightnessOptions | success?: (data: BrightnessResponse) => void; | 废弃 | -| system.brightness | BrightnessResponse | value: number; | 废弃 | \ No newline at end of file +| system.brightness | BrightnessResponse | value: number; | 废弃 | +| ohos.batteryInfo | batteryInfo | ohos.batteryinfo -> ohos.batteryInfo | 模块名修改 | +