diff --git a/README_zh.md b/README_zh.md index 9a69708a95f8f16721c850d44680ee98ff89b27e..43d7cfcc6b38e45c2e62db069efcf7841ee9cd26 100644 --- a/README_zh.md +++ b/README_zh.md @@ -19,6 +19,8 @@ - master:最新开发版本。 - OpenHarmony 3.2 Release版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.2-release.md)了解版本详情。 + + 该版本已更新至OpenHarmony 3.2.2 Release,点击[此处](zh-cn/release-notes/OpenHarmony-v3.2.2-release.md)了解版本详情。 - OpenHarmony 3.1 Release版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.1-release.md)了解版本详情。 diff --git a/en/application-dev/ai/Readme-EN.md b/en/application-dev/ai/Readme-EN.md new file mode 100644 index 0000000000000000000000000000000000000000..525a9f3afe7e1e951d2216160cc23ba4c9b3335b --- /dev/null +++ b/en/application-dev/ai/Readme-EN.md @@ -0,0 +1,3 @@ +# AI + +- [Using MindSpore Lite for Model Inference (JS)](mindspore-lite-js-guidelines.md) diff --git a/en/application-dev/ai/mindspore-lite-js-guidelines.md b/en/application-dev/ai/mindspore-lite-js-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..1f309acf19ba608ac698892ed64bb2e75ffdc437 --- /dev/null +++ b/en/application-dev/ai/mindspore-lite-js-guidelines.md @@ -0,0 +1,122 @@ +# Using MindSpore Lite for Model Inference (JS) + +## Scenarios + +MindSpore Lite is an AI engine that implements AI model inference for different hardware devices. It has been used in a wide range of fields, such as image classification, target recognition, facial recognition, and character recognition. + +This document describes the general development process for implementing MindSpore Lite model inference. For details about how to use native APIs to implement model inference, see [Using MindSpore Lite for Model Inference](../napi/mindspore-lite-guidelines.md). + +## 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 basic data structure used in MindSpore Lite network operations. + +**Float16 inference mode**: a mode that uses half-precision inference. Float16 uses 16 bits to represent a number and therefore it is also called half-precision. + +## Available APIs +APIs involved in MindSpore Lite model inference are categorized into context APIs, model APIs, and tensor APIs. For more APIs, see [@ohos.ai.mindSporeLite](../reference/apis/js-apis-mindSporeLite.md). + +| API | Description | +| ------------------ | ----------------- | +|loadModelFromFile(model: string, options: Context): Promise<Model>|Loads a model from a file.| +|getInputs(): MSTensor[]|Obtains the model input.| +|predict(inputs: MSTensor[]): Promise<MSTensor>|Performs model inference.| +| getData(): ArrayBuffer | Obtains tensor data.| +| setData(inputArray: ArrayBuffer): void | Sets the tensor data.| + +## How to Develop + +The development process consists of the following main steps: + +1. Prepare the required model. You can download the required model directly or obtain the model by using the model conversion tool. The required data is read from the `bin` file. + + - If the downloaded model is in the `.ms` format, you can use it directly for inference. This document uses `mnet.caffemodel.ms` as an example. + - If the downloaded model uses a third-party framework, such as TensorFlow, TensorFlow Lite, Caffe, or ONNX, you can use the [model conversion tool](https://www.mindspore.cn/lite/docs/en/r2.0/use/downloads.html#1-8-1) to convert it to the `.ms` format. +2. Create a context, and set parameters such as the number of runtime threads and device type. +3. Load the model. In this example, the model is read from the file. +4. Load data. Before executing a model, you need to obtain the model input and then fill data in the input tensor. +5. Perform inference and print the output. Call the **predict** API to perform model inference. +```js +@State inputName: string = 'mnet_caffemodel_nhwc.bin'; +@State T_model_predict: string = 'Test_MSLiteModel_predict' +inputBuffer: any = null; +build() { + Row() { + Column() { + Text(this.T_model_predict) + .focusable(true) + .fontSize(30) + .fontWeight(FontWeight.Bold) + .onClick(async () => { + // 1. Prepare for a model. + let syscontext = globalThis.context; + syscontext.resourceManager.getRawFileContent(this.inputName).then((buffer) => { + this.inputBuffer = buffer; + console.log('=========input bin byte length: ' + this.inputBuffer.byteLength) + }).catch(error => { + console.error('Failed to get buffer, error code: ${error.code},message:${error.message}.'); + }) + // 2. Create a context. + let context: mindSporeLite.Context = {}; + context.target = ['cpu']; + context.cpu = {} + context.cpu.threadNum = 1; + context.cpu.threadAffinityMode = 0; + context.cpu.precisionMode = 'enforce_fp32'; + // 3. Load the model. + let modelFile = '/data/storage/el2/base/haps/entry/files/mnet.caffemodel.ms'; + let msLiteModel = await mindSporeLite.loadModelFromFile(modelFile, context); + // 4. Load data. + const modelInputs = msLiteModel.getInputs(); + modelInputs[0].setData(this.inputBuffer.buffer); + // 5. Perform inference and print the output. + console.log('=========MSLITE predict start=====') + msLiteModel.predict(modelInputs).then((modelOutputs) => { + let output0 = new Float32Array(modelOutputs[0].getData()); + for (let i = 0; i < output0.length; i++) { + console.log(output0[i].toString()); + } + }) + console.log('=========MSLITE predict success=====') + }) + } + .width('100%') + } + .height('100%') +} +``` + +## Debugging and Verification + +1. Connect to the rk3568 development board on DevEco Studio, click **Run entry**, and compile your own HAP. The following information is displayed: + + ```shell + Launching com.example.myapptfjs + $ hdc uninstall com.example.myapptfjs + $ hdc install -r "D:\TVOS\JSAPI\MyAppTfjs\entry\build\default\outputs\default\entry-default-signed.hap" + $ hdc shell aa start -a EntryAbility -b com.example.myapptfjs + ``` + +2. Use the hdc tool to connect to the rk3568 development board and push `mnet.caffemodel.ms` to the sandbox directory on the device. `mnet\_caffemodel\_nhwc.bin` is stored in the `rawfile` directory of the local project. + + ```shell + hdc -t 7001005458323933328a00bcdf423800 file send .\mnet.caffemodel.ms /data/app/el2/100/base/com.example.myapptfjs/haps/entry/files/ + ``` +3. Click **Test\_MSLiteModel\_predict** on the screen of the rk3568 development board to run the test case. The following information is displayed in the HiLog printing result: + + ```shell + 08-27 23:25:50.278 31782-31782/? I C03d00/JSAPP: =========MSLITE predict start===== + 08-27 23:25:51.487 31782-31782/? I C03d00/JSAPP: 0.10046602040529252 + 08-27 23:25:51.487 31782-31782/? I C03d00/JSAPP: 0.07535600662231445 + 08-27 23:25:51.487 31782-31782/? I C03d00/JSAPP: 0.06326554715633392 + 08-27 23:25:51.487 31782-31782/? I C03d00/JSAPP: 0.0015114173293113708 + 08-27 23:25:51.487 31782-31782/? I C03d00/JSAPP: -0.026745859533548355 + 08-27 23:25:51.487 31782-31782/? I C03d00/JSAPP: -0.055590517818927765 + 08-27 23:25:51.487 31782-31782/? I C03d00/JSAPP: -0.05325715243816376 + 08-27 23:25:51.487 31782-31782/? I C03d00/JSAPP: -0.04629542678594589 + ... + 08-27 23:25:52.881 31782-31782/? I C03d00/JSAPP: 0.23317644000053404 + 08-27 23:25:52.881 31782-31782/? I C03d00/JSAPP: 0.17999525368213654 + 08-27 23:25:50.372 31782-31782/? I C03d00/JSAPP: =========MSLITE predict success===== + ``` diff --git a/en/application-dev/application-models/arkts-ui-widget-update-by-status.md b/en/application-dev/application-models/arkts-ui-widget-update-by-status.md index 5fb323813741a81e01b120507561e377995b7d90..dac1faa6f344e8774b4a42538ef9c034441cce94 100644 --- a/en/application-dev/application-models/arkts-ui-widget-update-by-status.md +++ b/en/application-dev/application-models/arkts-ui-widget-update-by-status.md @@ -21,7 +21,8 @@ In the following example, two copies of the weather widget are added to the home }, "colorMode": "auto", "isDefault": true, - "updateEnabled": true,"scheduledUpdateTime": "07:00", + "updateEnabled": true, + "scheduledUpdateTime": "07:00", "updateDuration": 0, "defaultDimension": "2*2", "supportDimensions": ["2*2"] @@ -103,10 +104,15 @@ In the following example, two copies of the weather widget are added to the home let isTempCard: boolean = want.parameters[formInfo.FormParam.TEMPORARY_KEY]; if (isTempCard === false) {// If the widget is a normal one, the widget information is persisted. console.info('Not temp card, init db for:' + formId); - let storeDB = dataPreferences.getPreferences(this.context, 'mystore') - storeDB.put('A' + formId, 'false'); - storeDB.put('B' + formId, 'false'); - storeDB.flush(); + let promise = dataPreferences.getPreferences(this.context, 'myStore'); + promise.then(async (storeDB) => { + console.info("Succeeded to get preferences."); + await storeDB.put('A' + formId, 'false'); + await storeDB.put('B' + formId, 'false'); + await storeDB.flush(); + }).catch((err) => { + console.info(`Failed to get preferences. ${JSON.stringify(err)}`); + }) } let formData = {}; return formBindingData.createFormBindingData(formData); @@ -114,54 +120,71 @@ In the following example, two copies of the weather widget are added to the home onRemoveForm(formId) { console.info('onRemoveForm, formId:' + formId); - let storeDB = dataPreferences.getPreferences(this.context, 'mystore') - storeDB.delete('A' + formId); - storeDB.delete('B' + formId); + let promise = dataPreferences.getPreferences(this.context, 'myStore'); + promise.then(async (storeDB) => { + console.info("Succeeded to get preferences."); + await storeDB.delete('A' + formId); + await storeDB.delete('B' + formId); + }).catch((err) => { + console.info(`Failed to get preferences. ${JSON.stringify(err)}`); + }) } // If the widget is a temporary one, it is recommended that the widget information be persisted when the widget is converted to a normal one. onCastToNormalForm(formId) { console.info('onCastToNormalForm, formId:' + formId); - let storeDB = dataPreferences.getPreferences(this.context, 'myStore') - storeDB.put('A' + formId, 'false'); - storeDB.put('B' + formId, 'false'); - storeDB.flush(); + let promise = dataPreferences.getPreferences(this.context, 'myStore'); + promise.then(async (storeDB) => { + console.info("Succeeded to get preferences."); + await storeDB.put('A' + formId, 'false'); + await storeDB.put('B' + formId, 'false'); + await storeDB.flush(); + }).catch((err) => { + console.info(`Failed to get preferences. ${JSON.stringify(err)}`); + }) } onUpdateForm(formId) { - let storeDB = dataPreferences.getPreferences(this.context, 'myStore') - let stateA = storeDB.get('A' + formId, 'false').toString() - let stateB = storeDB.get('B' + formId, 'false').toString() - // Update textA in state A. - if (stateA === 'true') { - let formInfo = formBindingData.createFormBindingData({ - 'textA': 'AAA' - }) - formProvider.updateForm(formId, formInfo) - } - // Update textB in state B. - if (stateB === 'true') { - let formInfo = formBindingData.createFormBindingData({ - 'textB': 'BBB' - }) - formProvider.updateForm(formId, formInfo) - } + let promise = dataPreferences.getPreferences(this.context, 'myStore'); + promise.then(async (storeDB) => { + console.info("Succeeded to get preferences."); + let stateA = await storeDB.get('A' + formId, 'false'); + let stateB = await storeDB.get('B' + formId, 'false'); + // Update textA in state A. + if (stateA === 'true') { + let formInfo = formBindingData.createFormBindingData({'textA': 'AAA'}); + await formProvider.updateForm(formId, formInfo); + } + // Update textB in state B. + if (stateB === 'true') { + let formInfo = formBindingData.createFormBindingData({'textB': 'BBB'}); + await formProvider.updateForm(formId, formInfo); + } + console.info(`Update form success stateA:${stateA} stateB:${stateB}.`); + }).catch((err) => { + console.info(`Failed to get preferences. ${JSON.stringify(err)}`); + }) } onFormEvent(formId, message) { // Store the widget state. console.info('onFormEvent formId:' + formId + 'msg:' + message); - let storeDB = dataPreferences.getPreferences(this.context, 'myStore') - let msg = JSON.parse(message) - if (msg.selectA != undefined) { - console.info('onFormEvent selectA info:' + msg.selectA); - storeDB.put('A' + formId, msg.selectA); - } - if (msg.selectB != undefined) { - console.info('onFormEvent selectB info:' + msg.selectB); - storeDB.put('B' + formId, msg.selectB); - } - storeDB.flush(); + let promise = dataPreferences.getPreferences(this.context, 'myStore'); + promise.then(async (storeDB) => { + console.info("Succeeded to get preferences."); + let msg = JSON.parse(message); + if (msg.selectA != undefined) { + console.info('onFormEvent selectA info:' + msg.selectA); + await storeDB.put('A' + formId, msg.selectA); + } + if (msg.selectB != undefined) { + console.info('onFormEvent selectB info:' + msg.selectB); + await storeDB.put('B' + formId, msg.selectB); + } + await storeDB.flush(); + }).catch((err) => { + console.info(`Failed to get preferences. ${JSON.stringify(err)}`); + }) } }; ``` diff --git a/en/application-dev/faqs/Readme-EN.md b/en/application-dev/faqs/Readme-EN.md index 21effd689817299aabdaaab34724edd8349622dc..d7316d5a25c20f4cd076b8ebca4ed700d7c387c7 100644 --- a/en/application-dev/faqs/Readme-EN.md +++ b/en/application-dev/faqs/Readme-EN.md @@ -2,6 +2,7 @@ - [Full SDK Compilation](full-sdk-compile-guide.md) - [Switching to Full SDK](full-sdk-switch-guide.md) +- [Using Native APIs (NDK) of the OpenHarmony SDK in a CMake Project](howto-migrate-cmake-with-ohosndk.md) - [Application Model Development](faqs-ability.md) - ArkUI Development (ArkTS) - [ArkTS Syntax Usage](faqs-arkui-arkts.md) diff --git a/en/application-dev/faqs/figures/ci_download.png b/en/application-dev/faqs/figures/ci_download.png new file mode 100644 index 0000000000000000000000000000000000000000..da0d306e0f95a4fa114af51ca010d9109ae7e029 Binary files /dev/null and b/en/application-dev/faqs/figures/ci_download.png differ diff --git a/en/application-dev/faqs/figures/en-us_image_0000001655129041.png b/en/application-dev/faqs/figures/en-us_image_0000001655129041.png index 408bf7d9864352d03f1603b0e1c68741401e016f..8912b2b2b7527ae0e3e8f3c5a62346a5a4e7e947 100644 Binary files a/en/application-dev/faqs/figures/en-us_image_0000001655129041.png and b/en/application-dev/faqs/figures/en-us_image_0000001655129041.png differ diff --git a/en/application-dev/faqs/figures/images.png b/en/application-dev/faqs/figures/images.png new file mode 100644 index 0000000000000000000000000000000000000000..037e72b015f4f8bbfff818516a65cc51cb4e2944 Binary files /dev/null and b/en/application-dev/faqs/figures/images.png differ diff --git a/en/application-dev/faqs/figures/sdk-structure.png b/en/application-dev/faqs/figures/sdk-structure.png new file mode 100644 index 0000000000000000000000000000000000000000..18a9315151bc7b184a87c2f95b23238bbefc2b82 Binary files /dev/null and b/en/application-dev/faqs/figures/sdk-structure.png differ diff --git a/en/application-dev/faqs/howto-migrate-cmake-with-ohosndk.md b/en/application-dev/faqs/howto-migrate-cmake-with-ohosndk.md new file mode 100644 index 0000000000000000000000000000000000000000..36f339529c78327f2698f90ce199e758ba06485f --- /dev/null +++ b/en/application-dev/faqs/howto-migrate-cmake-with-ohosndk.md @@ -0,0 +1,191 @@ +# Using Native APIs (NDK) of the OpenHarmony SDK in a CMake Project + +## What Is Native API + +For details, see [Native APIs](../reference/native-api-intro.md). + +## Downloading the NDK + +You download the Native API Development Kit (NDK) by downloading the OHOS SDK, where the NDK is included. To download the OHOS SDK, use any of the following modes: + +- (Recommended) Acquire source code from mirrors for an officially released version. For details, see [release notes](../../release-notes/OpenHarmony-v3.2-release.md). +- Download the SDK from the SDK Manager in DevEco Studio. +- Download the SDK from the [daily build](http://ci.openharmony.cn/dailys/dailybuilds), by clicking the download link to the **ohos-sdk-full** component. + +![Download from Daily Build](figures/ci_download.png) + +## Decompressing the NDK + +Place the downloaded NDK in a folder you prefer and decompress it. Below shows the directory structure after decompression. +![SDK Directory Structure](figures/sdk-structure.png) + +Configure the Linux environment as follows: (Skip them if the NDK is downloaded from DevEco Studio.) + +1. Add the CMake tool that comes with the NDK to the environment variables. + +``` + # Open the .bashrc file. + vim ~/.bashrc + # Append the custom CMake path to the file. Save the file and exit. + export PATH=~/ohos-sdk/ohos-sdk/linux/native/build-tools/cmake/bin:$PATH + # Run the source ~/.bashrc command to make the environment variables take effect. + source ~/.bashrc +``` + +2. Check the default CMake path. + +``` + # Run the which cmake command. + which cmake + # The result should be the same as the custom path previously appended to the file. + ~/ohos-sdk/ohos-sdk/linux/native/build-tools/cmake/bin/cmake +``` + +## Using the NDK to Compile a Native Program + +You can use the NDK to quickly develop a native program, including native dynamic libraries, static libraries, and executable files. The ArkUI application framework can call the native dynamic libraries through the NAPI framework. The following exemplifies how to use the NDK to compile a C/C++ dynamic library in a C/C++ demo project. + +### Folders in the NDK + +#### build Folder: ohos.toolchain.cmake file + +The **ohos.toolchain.cmake** file contains the attributes of the CMake compilation target. Its path must be specified in the **CMAKE_TOOLCHAIN_FILE** parameter so that it can be located during CMake compilation. For details about the mandatory parameters in the **ohos.toolchain.cmake** file, see [Key Parameters in ohos.toolchain.cmake](#key-parameters-in-ohostoolchaincmake). + +#### build-tools folder: Build Tool Provided by the NDK + +``` + # Run the following command to view the CMake version: + cmake -version + # Result + cmake version 3.16.5 + + CMake suite maintained and supported by Kitware (kitware.com/cmake). +``` + +#### llvm Folder: Compiler Provided by the NDK + +![](figures/images.png) + +### Demo Project for the NDK + +#### Demo Project Directory + +``` + demo + ├── CMakeLists.txt + ├── include + └── sum.h + └── src + ├── CMakeLists.txt + ├── sum.cpp + └── hello.cpp +``` + +#### CMakeLists.txt in the demo Directory + +``` + # Specify the minimum CMake version. + CMAKE_MINIMUM_REQUIRED(VERSION 3.16) + + # Set the project name, which is HELLO in this example. + PROJECT(HELLO) + + # Add a subdirectory and build the subdirectory. + ADD_SUBDIRECTORY(src bin) +``` + +#### CMakeLists.txt in the src Directory + +``` + SET(LIBHELLO_SRC hello.cpp) + + # Set compilation flags. + SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O0") + + # Set the link parameter. The value below is only for exemplary purposes. + SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,--emit-relocs --verbose") + + # Add a libsum dynamic library target. If the compilation is successful, a libsum.so file is generated. + ADD_LIBRARY(sum SHARED sum.cpp) + + # Add the executable target called Hello. If the compilation is successful, a Hello executable is generated. + ADD_EXECUTABLE(Hello ${LIBHELLO_SRC}) + + # Specify the path to the include directory of the Hello target. + TARGET_INCLUDE_DIRECTORIES(Hello PUBLIC ../include) + + # Specify the name of the library to be linked to the Hello target. + TARGET_LINK_LIBRARIES(Hello PUBLIC sum) +``` + +For details about CMake, see [CMake Tutorial](https://cmake.org/cmake/help/v3.16/guide/tutorial/). + +#### Source Code + +**hello.cpp** source code: + +``` + #include + #include "sum.h" + + int main(int argc,const char **argv) + { + std::cout<< "hello world!" < lock(signal->inMutex_); + signal->inQueue_.push(index); + signal->inBufferQueue_.push(data); + signal->inCond_.notify_all(); + } + // Set the OnOutputBufferAvailable callback function, which is used to send the encoded stream to the OutputBuffer queue. + static void OnOutputBufferAvailable(OH_AVCodec *codec, uint32_t index, OH_AVMemory *data, OH_AVCodecBufferAttr *attr, + void *userData) + { + (void)codec; + // The index of the output buffer is sent to the OutputQueue. + // The encoded data is sent to the OutputBuffer queue. + AEncSignal *signal = static_cast(userData); + unique_lock lock(signal->outMutex_); + signal->outQueue_.push(index); + signal->outBufferQueue_.push(data); + if (attr) { + signal->attrQueue_.push(*attr); + } + } + OH_AVCodecAsyncCallback cb = {&OnError, &OnOutputFormatChanged, &OnInputBufferAvailable, &OnOutputBufferAvailable}; + // Set the asynchronous callbacks. + int32_t ret = OH_AudioEncoder_SetCallback(audioEnc, cb, userData); + ``` + +3. Call **OH_AudioEncoder_Configure** to configure the encoder. + + The following options are mandatory: sampling rate, bit rate, number of audio channels, audio channel type, and bit depth. The maximum input length is optional. + + For FLAC encoding, the compliance level and sampling precision are also mandatory. + + ```cpp + enum AudioFormatType : int32_t { + TYPE_AAC = 0, + TYPE_FLAC = 1, + }; + int32_t ret; + // (Mandatory) Configure the audio sampling rate. + constexpr uint32_t DEFAULT_SMAPLERATE = 44100; + // (Mandatory) Configure the audio bit rate. + constexpr uint32_t DEFAULT_BITRATE = 32000; + // (Mandatory) Configure the number of audio channels. + constexpr uint32_t DEFAULT_CHANNEL_COUNT = 2; + // (Mandatory) Configure the audio channel type. + constexpr AudioChannelLayout CHANNEL_LAYOUT =AudioChannelLayout::STEREO; + // (Mandatory) Configure the audio bit depth. Only SAMPLE_S16LE and SAMPLE_S32LE are available for FLAC encoding. + constexpr OH_BitsPerSample SAMPLE_FORMAT =OH_BitsPerSample::SAMPLE_S32LE; + // (Mandatory) Configure the audio bit depth. Only SAMPLE_S32P is available for AAC encoding. + constexpr OH_BitsPerSample SAMPLE_AAC_FORMAT =OH_BitsPerSample::SAMPLE_S32P; + // Configure the audio compliance level. The default value is 0, and the value ranges from -2 to 2. + constexpr int32_t COMPLIANCE_LEVEL = 0; + // (Mandatory) Configure the audio sampling precision. SAMPLE_S16LE, SAMPLE_S24LE, and SAMPLE_S32LE are available. + constexpr BITS_PER_CODED_SAMPLE BITS_PER_CODED_SAMPLE =OH_BitsPerSample::SAMPLE_S24LE; + // (Optional) Configure the maximum input length. + constexpr uint32_t DEFAULT_MAX_INPUT_SIZE = 1024*DEFAULT_CHANNEL_COUNT *sizeof(float);//aac + OH_AVFormat *format = OH_AVFormat_Create(); + // Set the format. + OH_AVFormat_SetIntValue(format,MediaDescriptionKey::MD_KEY_SAMPLE_RATE.data(),DEFAULT_SMAPLERATE); + OH_AVFormat_SetIntValue(format,MediaDescriptionKey::MD_KEY_BITRATE.data(), DEFAULT_BITRATE); + OH_AVFormat_SetIntValue(format,MediaDescriptionKey::MD_KEY_CHANNEL_COUNT.data(),DEFAULT_CHANNEL_COUNT); + OH_AVFormat_SetIntValue(format,MediaDescriptionKey::MD_KEY_MAX_INPUT_SIZE.data(),DEFAULT_MAX_INPUT_SIZE); + OH_AVFormat_SetLongValue(format,MediaDescriptionKey::MD_KEY_CHANNEL_LAYOUT.data(),CHANNEL_LAYOUT); + OH_AVFormat_SetIntValue(format,MediaDescriptionKey::MD_KEY_AUDIO_SAMPLE_FORMAT.data(),SAMPLE_FORMAT); + if(audioType == TYPE_AAC){ + OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_AUDIO_SAMPLE_FORMAT.data(), SAMPLE_AAC_FORMAT); + } + if (audioType == TYPE_FLAC) { + OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_BITS_PER_CODED_SAMPLE.data(), BITS_PER_CODED_SAMPLE); + OH_AVFormat_SetLongValue(format, MediaDescriptionKey::MD_KEY_COMPLIANCE_LEVEL.data(), COMPLIANCE_LEVEL); + } + // Configure the encoder. + ret = OH_AudioEncoder_Configure(audioEnc, format); + if (ret != AV_ERR_OK) { + // Exception handling. + } + ``` + +4. Call **OH_AudioEncoder_Prepare()** to prepare internal resources for the encoder. + + ```c++ + OH_AudioEncoder_Prepare(audioEnc); + ``` + +5. Call **OH_AudioEncoder_Start()** to start the encoder. + + ```c++ + inputFile_ = std::make_unique(); + // Open the path of the binary file to be encoded. + inputFile_->open(inputFilePath.data(), std::ios::in |std::ios::binary); + // Configure the path of the output file. + outFile_ = std::make_unique(); + outFile_->open(outputFilePath.data(), std::ios::out |std::ios::binary); + // Start encoding. + ret = OH_AudioEncoder_Start(audioEnc); + if (ret != AV_ERR_OK) { + // Exception handling. + } + ``` + +6. Call **OH_AudioEncoder_PushInputData()** to write the data to encode. + + To indicate the End of Stream (EOS), pass in the **AVCODEC_BUFFER_FLAGS_EOS** flag. + + For AAC encoding, **FRAME_SIZE** (number of sampling points) is fixed at **1024**. + + For FLAC encoding, set **FRAME_SIZE** based on the table below. + + | Sampling Rate| FRAME_SIZE| + | :----: | :----: | + | 8000 | 576 | + | 16000 | 1152 | + | 22050 | 2304 | + | 24000 | 2304 | + | 32000 | 2304 | + | 44100 | 4608 | + | 48000 | 4608 | + | 88200 | 8192 | + | 96000 | 8192 | + + **NOTE**: If **FRAME_SIZE** is not set to **1024** for AAC encoding, an error code is returned. In the case of FLAC encoding, if **FRAME_SIZE** is set to a value greater than the value listed in the table for a given sampling rate, an error code is returned; if **FRAME_SIZE** is set to a value less than the value listed, the encoded file may be damaged. + + ```c++ + constexpr int32_t FRAME_SIZE = 1024; // AAC encoding + constexpr int32_t DEFAULT_CHANNEL_COUNT =2; + constexpr int32_t INPUT_FRAME_BYTES = DEFAULT_CHANNEL_COUNT * FRAME_SIZE * sizeof(float); // AAC encoding + // Configure the buffer information. + OH_AVCodecBufferAttr info; + // Set the package size, offset, and timestamp. + info.size = pkt_->size; + info.offset = 0; + info.pts = pkt_->pts; + info.flags = AVCODEC_BUFFER_FLAGS_CODEC_DATA; + auto buffer = signal_->inBufferQueue_.front(); + if (inputFile_->eof()){ + info.size = 0; + info.flags = AVCODEC_BUFFER_FLAGS_EOS; + }else{ + inputFile_->read((char *)OH_AVMemory_GetAddr(buffer), INPUT_FRAME_BYTES); + } + uint32_t index = signal_->inQueue_.front(); + // Send the data to the input queue for encoding. The index is the subscript of the queue. + int32_t ret = OH_AudioEncoder_PushInputData(audioEnc, index,info); + if (ret != AV_ERR_OK) { + // Exception handling. + } + ``` + +7. Call **OH_AudioEncoder_FreeOutputData()** to output the encoded stream. + + ```c++ + OH_AVCodecBufferAttr attr = signal_->attrQueue_.front(); + OH_AVMemory *data = signal_->outBufferQueue_.front(); + uint32_t index = signal_->outQueue_.front(); + // Write the encoded data (specified by data) to the output file. + outFile_->write(reinterpret_cast(OH_AVMemory_GetAdd(data)), attr.size); + // Release the output buffer. + ret = OH_AudioEncoder_FreeOutputData(audioEnc, index); + if (ret != AV_ERR_OK) { + // Exception handling. + } + if (attr.flags == AVCODEC_BUFFER_FLAGS_EOS) { + cout << "decode eos" << endl; + isRunning_.store(false); + break; + } + ``` + +8. (Optional) Call **OH_AudioEncoder_Flush()** to refresh the encoder. + + After **OH_AudioEncoder_Flush()** is called, the current encoding queue is cleared. + + To continue encoding, you must call **OH_AudioEncoder_Start()** again. + + You need to call **OH_AudioEncoder_Flush()** in the following cases: + + * The EOS of the file is reached. + * An error with **OH_AudioEncoder_IsValid** set to **true** (indicating that the execution can continue) occurs. + + ```c++ + // Refresh the encoder. + ret = OH_AudioEncoder_Flush(audioEnc); + if (ret != AV_ERR_OK) { + // Exception handling. + } + // Start encoding again. + ret = OH_AudioEncoder_Start(audioEnc); + if (ret != AV_ERR_OK) { + // Exception handling. + } + ``` + +9. (Optional) Call **OH_AudioEncoder_Reset()** to reset the encoder. + + After **OH_AudioEncoder_Reset()** is called, the encoder returns to the initialized state. To continue encoding, you must call **OH_AudioEncoder_Configure()** and then **OH_AudioEncoder_Start()**. + + ```c++ + // Reset the encoder. + ret = OH_AudioEncoder_Reset(audioEnc); + if (ret != AV_ERR_OK) { + // Exception handling. + } + // Reconfigure the encoder. + ret = OH_AudioEncoder_Configure(audioEnc, format); + if (ret != AV_ERR_OK) { + // Exception handling. + } + ``` +10. Call **OH_AudioEncoder_Stop()** to stop the encoder. + + ```c++ + // Stop the encoder. + ret = OH_AudioEncoder_Stop(audioEnc); + if (ret != AV_ERR_OK) { + // Exception handling. + } + return ret; + ``` +11. Call **OH_AudioEncoder_Destroy()** to destroy the encoder instance and release resources. + + **NOTE**: You only need to call this API once. + + ```c++ + // Call OH_AudioEncoder_Destroy to destroy the encoder. + ret = OH_AudioEncoder_Destroy(audioEnc); + if (ret != AV_ERR_OK) { + // Exception handling. + } else { + audioEnc = NULL; // The encoder cannot be destroyed repeatedly. + } + return ret; + ``` diff --git a/en/application-dev/media/audio-video-decapsulation.md b/en/application-dev/media/audio-video-decapsulation.md new file mode 100644 index 0000000000000000000000000000000000000000..0ab39804737c3c00e49e476243c66b1ceefeae24 --- /dev/null +++ b/en/application-dev/media/audio-video-decapsulation.md @@ -0,0 +1,200 @@ +# Audio and Video Decapsulation + +You can call the native APIs provided by the **AVDemuxer** module to decapsulate audio and video, that is, to extract audio and video frame data from bit stream data. + +Currently, two data input types are supported: remote connection (over HTTP) and File Descriptor (FD). + +The following decapsulation formats are supported: + +| Media Format | Encapsulation Format | +| -------- | :----------------------------| +| Video | MP4, MPEG TS | +| Audio | M4A, AAC, MP3, OGG, FLAC, WAV| + + + +**Usage Scenario** + +- Audio and video playback + + Decapsulate audio and video streams, decode the frame data obtained through decapsulation, and play the decoded data. + +- Audio and video editing + + Decapsulate audio and video streams, and edit the specified frames. + +- Media file format conversion + + Decapsulate audio and video streams, and encapsulate them into a new file format. + +## How to Develop +Read [AVDemuxer](../reference/native-apis/_a_v_demuxer.md) and [AVSource](../reference/native-apis/_a_v_source.md) for the API reference. + +> **NOTE** +> +> - To call the decapsulation APIs to parse a network playback path, request the **ohos.permission.INTERNET** permission by following the instructions provided in [Applying for Permissions](../security/accesstoken-guidelines.md). +> - To call the decapsulation APIs to parse a local file, request the **ohos.permission.READ_MEDIA** permission by following the instructions provided in [Applying for Permissions](../security/accesstoken-guidelines.md). +> - You can also use **ResourceManager.getRawFd** to obtain the FD of a file packed in the HAP file. For details, see [ResourceManager API Reference](../reference/apis/js-apis-resource-manager.md#getrawfd9). + +1. Create a demuxer instance. + + ``` c++ + // Create the FD. You must have the read permission on the file handle when opening the file. + std::string fileName = "test.mp4"; + int fd = open(fileName.c_str(), O_RDONLY); + struct stat fileStatus {}; + size_t fileSize = 0; + if (stat(fileName.c_str(), &fileStatus) == 0) { + fileSize = static_cast(fileStatus.st_size); + } else { + printf("get stat failed"); + return; + } + // Create a source resource object for the FD resource file. If offset is not the start position of the file or size is not the actual file size, the data obtained may be incomplete. Consequently, the source resource object may fail to create or subsequent decapsulation may fail. + OH_AVSource *source = OH_AVSource_CreateWithFD(fd, 0, fileSize); + if (source == nullptr) { + printf("create source failed"); + return; + } + // (Optional) Create a source resource object for the URI resource file. + // OH_AVSource *source = OH_AVSource_CreateWithURI(uri); + ``` + ```c++ + // Create a demuxer for the resource object. + OH_AVDemuxer *demuxer = OH_AVDemuxer_CreateWithSource(source); + if (demuxer == nullptr) { + printf("create demuxer failed"); + return; + } + ``` + + + +2. (Optional) Obtain the number of tracks. If you know the track information, skip this step. + + ``` c++ + // Obtain the number of tracks from the file source information. + OH_AVFormat *sourceFormat = OH_AVSource_GetSourceFormat(source); + if (sourceFormat == nullptr) { + printf("get source format failed"); + return; + } + int32_t trackCount = 0; + OH_AVFormat_GetIntValue(sourceFormat, OH_MD_KEY_TRACK_COUNT, &trackCount); + OH_AVFormat_Destroy(sourceFormat); + ``` + + + +3. (Optional) Obtain the track index and format. If you know the track information, skip this step. + + ``` c++ + uint32_t audioTrackIndex = 0; + uint32_t videoTrackIndex = 0; + int32_t w = 0; + int32_t h = 0; + int32_t trackType; + for (uint32_t index = 0; index < (static_cast(trackCount)); index++) { + // Obtain the track format. + OH_AVFormat *trackFormat = OH_AVSource_GetTrackFormat(source, index); + if (trackFormat == nullptr) { + printf("get track format failed"); + return; + } + OH_AVFormat_GetIntValue(trackFormat, OH_MD_KEY_TRACK_TYPE, &trackType); + static_cast(trackType) == OH_MediaType::MEDIA_TYPE_AUD ? audioTrackIndex = index : videoTrackIndex = index; + // Obtain the width and height of the video track. + if (trackType == OH_MediaType::MEDIA_TYPE_VID) { + OH_AVFormat_GetIntValue(trackFormat, OH_MD_KEY_WIDTH, &w); + OH_AVFormat_GetIntValue(trackFormat, OH_MD_KEY_HEIGHT, &h); + } + OH_AVFormat_Destroy(trackFormat); + } + ``` + + + +4. Select a track, from which the demuxer reads data. + + ``` c++ + if(OH_AVDemuxer_SelectTrackByID(demuxer, audioTrackIndex) != AV_ERR_OK){ + printf("select audio track failed: %d", audioTrackIndex); + return; + } + if(OH_AVDemuxer_SelectTrackByID(demuxer, videoTrackIndex) != AV_ERR_OK){ + printf("select video track failed: %d", videoTrackIndex); + return; + } + // (Optional) Deselect the track. + // OH_AVDemuxer_UnselectTrackByID(demuxer, audioTrackIndex); + ``` + + + +5. (Optional) Seek to the specified time for the selected track. + + ``` c++ + // Decapsulation is performed from this time. + // Note: + // 1. If OH_AVDemuxer_SeekToTime is called for an MPEG TS file, the target position may be a non-key frame. You can then call OH_AVDemuxer_ReadSample to check whether the current frame is a key frame based on the obtained OH_AVCodecBufferAttr. If it is a non-key frame, which causes display issues on the application side, cyclically read the frames until you reach the first key frame, where you can perform processing such as decoding. + // 2. If OH_AVDemuxer_SeekToTime is called for an OGG file, the file seeks to the start of the time interval (second) where the input parameter millisecond is located, which may cause a certain number of frame errors. + OH_AVDemuxer_SeekToTime(demuxer, 0, OH_AVSeekMode::SEEK_MODE_CLOSEST_SYNC); + ``` + +6. Start decapsulation and cyclically obtain frame data. The code snippet below uses a file that contains audio and video tracks as an example. + + ``` c++ + // Create a buffer to store the data obtained after decapsulation. + OH_AVMemory *buffer = OH_AVMemory_Create(w * h * 3 >> 1); + if (buffer == nullptr) { + printf("build buffer failed"); + return; + } + OH_AVCodecBufferAttr info; + bool videoIsEnd = false; + bool audioIsEnd = false; + int32_t ret; + while (!audioIsEnd || !videoIsEnd) { + // Before calling OH_AVDemuxer_ReadSample, call OH_AVDemuxer_SelectTrackByID to select the track from which the demuxer reads data. + // Obtain audio frame data. + if(!audioIsEnd) { + ret = OH_AVDemuxer_ReadSample(demuxer, audioTrackIndex, buffer, &info); + if (ret == AV_ERR_OK) { + // Obtain the process the audio frame data in the buffer. + printf("audio info.size: %d\n", info.size); + if (info.flags == OH_AVCodecBufferFlags::AVCODEC_BUFFER_FLAGS_EOS) { + audioIsEnd = true; + } + } + } + if(!videoIsEnd) { + ret = OH_AVDemuxer_ReadSample(demuxer, videoTrackIndex, buffer, &info); + if (ret == AV_ERR_OK) { + // Obtain the process the video frame data in the buffer. + printf("video info.size: %d\n", info.size); + if (info.flags == OH_AVCodecBufferFlags::AVCODEC_BUFFER_FLAGS_EOS) { + videoIsEnd = true; + } + } + } + } + OH_AVMemory_Destroy(buffer); + ``` + + + +7. Destroy the demuxer instance. + + ``` c++ + // Manually set the instance to NULL after OH_AVSource_Destroy is called. Do not call this API repeatedly for the same instance; otherwise, a program error occurs. + if (OH_AVSource_Destroy(source) != AV_ERR_OK) { + printf("destroy source pointer error"); + } + source = NULL; + // Manually set the instance to NULL after OH_AVDemuxer_Destroy is called. Do not call this API repeatedly for the same instance; otherwise, a program error occurs. + if (OH_AVDemuxer_Destroy(demuxer) != AV_ERR_OK) { + printf("destroy demuxer pointer error"); + } + demuxer = NULL; + close(fd); + ``` diff --git a/en/application-dev/media/audio-video-encapsulation.md b/en/application-dev/media/audio-video-encapsulation.md new file mode 100644 index 0000000000000000000000000000000000000000..965774d51c473e03eea1bd317bb9bad8010959f9 --- /dev/null +++ b/en/application-dev/media/audio-video-encapsulation.md @@ -0,0 +1,201 @@ +# Audio and Video Encapsulation + +You can call the native APIs provided by the **AVMuxer** module to encapsulate audio and video, that is, to store encoded audio and video data to a file in a certain format. + +Currently, the following encapsulation capabilities are supported: + +| Encapsulation Format| Video Codec Type | Audio Codec Type | Cover Type | +| -------- | --------------------- | ---------------- | -------------- | +| mp4 | MPEG-4, AVC (H.264)| AAC, MPEG (MP3)| jpeg, png, bmp| +| m4a | MPEG-4, AVC (H.264)| AAC | jpeg, png, bmp| + +**Usage Scenario** + +- Video and audio recording + + After you encode audio and video streams, encapsulate them into files. + +- Audio and video editing + + After you edit audio and video, encapsulate them into files. + +- Audio and video transcoding + + After transcode audio and video, encapsulate them into files. + +## How to Develop + +Read [AVMuxer](../reference/native-apis/_a_v_muxer.md) for the API reference. + +> **NOTE** +> +> To call the encapsulation APIs to write a local file, request the **ohos.permission.READ_MEDIA** and **ohos.permission.WRITE_MEDIA** permissions by following the instructions provided in [Applying for Permissions](../security/accesstoken-guidelines.md). + +The following walks you through how to implement the entire process of audio and video encapsulation. It uses the MP4 format as an example. + +1. Call **OH_AVMuxer_Create()** to create an **OH_AVMuxer** instance. + + ``` c++ + // Set the encapsulation format to MP4. + OH_AVOutputFormat format = AV_OUTPUT_FORMAT_MPEG_4; + // Create a File Descriptor (FD) in read/write mode. + int32_t fd = open("test.mp4", O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR); + OH_AVMuxer *muxer = OH_AVMuxer_Create(fd, format); + ``` + +2. (Optional) Call **OH_AVMuxer_SetRotation()** to set the rotation angle. + + ``` c++ + // Set the rotation angle when a video image needs to be rotated. + OH_AVMuxer_SetRotation(muxer, 0); + ``` + +3. Add an audio track. + + **Method 1: Use OH_AVFormat_Create to create the format.** + + ``` c++ + int audioTrackId = -1; + OH_AVFormat *formatAudio = OH_AVFormat_Create(); + OH_AVFormat_SetStringValue(formatAudio, OH_MD_KEY_CODEC_MIME, OH_AVCODEC_MIMETYPE_AUDIO_AAC); // Mandatory. + OH_AVFormat_SetIntValue(formatAudio, OH_MD_KEY_AUD_SAMPLE_RATE, 44100); // Mandatory. + OH_AVFormat_SetIntValue(formatAudio, OH_MD_KEY_AUD_CHANNEL_COUNT, 2); // Mandatory. + + int ret = OH_AVMuxer_AddTrack(muxer, &audioTrackId, formatAudio); + if (ret != AV_ERR_OK || audioTrackId < 0) { + // Failure to add the audio track. + } + OH_AVFormat_Destroy (formatAudio); // Destroy the format. + ``` + + **Method 2: Use OH_AVFormat_CreateAudioFormat to create the format.** + + ``` c++ + int audioTrackId = -1; + OH_AVFormat *formatAudio = OH_AVFormat_CreateAudioFormat(OH_AVCODEC_MIMETYPE_AUDIO_AAC, 44100, 2); + + int ret = OH_AVMuxer_AddTrack(muxer, &audioTrackId, formatAudio); + if (ret != AV_ERR_OK || audioTrackId < 0) { + // Failure to add the audio track. + } + OH_AVFormat_Destroy (formatAudio); // Destroy the format. + ``` + +4. Add a video track. + + **Method 1: Use OH_AVFormat_Create to create the format.** + + ``` c++ + int videoTrackId = -1; + char *buffer = ...; // Encoding configuration data. If there is no configuration data, leave the parameter unspecified. + size_t size =...; // Length of the encoding configuration data. Set this parameter based on project requirements. + OH_AVFormat *formatVideo = OH_AVFormat_Create(); + OH_AVFormat_SetStringValue(formatVideo, OH_MD_KEY_CODEC_MIME, OH_AVCODEC_MIMETYPE_VIDEO_MPEG4); // Mandatory. + OH_AVFormat_SetIntValue(formatVideo, OH_MD_KEY_WIDTH, 1280); // Mandatory. + OH_AVFormat_SetIntValue(formatVideo, OH_MD_KEY_HEIGHT, 720); // Mandatory. + OH_AVFormat_SetBuffer(formatVideo, OH_MD_KEY_CODEC_CONFIG, buffer, size); // Optional + + int ret = OH_AVMuxer_AddTrack(muxer, &videoTrackId, formatVideo); + if (ret != AV_ERR_OK || videoTrackId < 0) { + // Failure to add the video track. + } + OH_AVFormat_Destroy(formatVideo); // Destroy the format. + ``` + + **Method 2: Use OH_AVFormat_CreateVideoFormat to create the format.** + + ``` c++ + int videoTrackId = -1; + char *buffer = ...; // Encoding configuration data. If there is no configuration data, leave the parameter unspecified. + size_t size =...; // Length of the encoding configuration data. Set this parameter based on project requirements. + OH_AVFormat *formatVideo = OH_AVFormat_CreateVideoFormat(OH_AVCODEC_MIMETYPE_VIDEO_MPEG4, 1280, 720); + OH_AVFormat_SetBuffer(formatVideo, OH_MD_KEY_CODEC_CONFIG, buffer, size); // Optional + + ] + if (ret != AV_ERR_OK || videoTrackId < 0) { + // Failure to add the video track. + } + OH_AVFormat_Destroy(formatVideo); // Destroy the format. + ``` + +5. Add a cover track. + + **Method 1: Use OH_AVFormat_Create to create the format.** + + ``` c++ + int coverTrackId = -1; + OH_AVFormat *formatCover = OH_AVFormat_Create(); + OH_AVFormat_SetStringValue(formatCover, OH_MD_KEY_CODEC_MIME, OH_AVCODEC_MIMETYPE_IMAGE_JPG); + OH_AVFormat_SetIntValue(formatCover, OH_MD_KEY_WIDTH, 1280); + OH_AVFormat_SetIntValue(formatCover, OH_MD_KEY_HEIGHT, 720); + + int ret = OH_AVMuxer_AddTrack(muxer, &coverTrackId, formatCover); + if (ret != AV_ERR_OK || coverTrackId < 0) { + // Failure to add the cover track. + } + OH_AVFormat_Destroy(formatCover); // Destroy the format. + ``` + + **Method 2: Use OH_AVFormat_CreateVideoFormat to create the format.** + + ``` c++ + int coverTrackId = -1; + OH_AVFormat *formatCover = OH_AVFormat_CreateVideoFormat(OH_AVCODEC_MIMETYPE_IMAGE_JPG, 1280, 720); + + int ret = OH_AVMuxer_AddTrack(muxer, &coverTrackId, formatCover); + if (ret != AV_ERR_OK || coverTrackId < 0) { + // Failure to add the cover track. + } + OH_AVFormat_Destroy(formatCover); // Destroy the format. + ``` + +6. Call **OH_AVMuxer_Start()** to start encapsulation. + + ``` c++ + // Call Start() to write the file header. After this API is called, you cannot set media parameters or add tracks. + if (OH_AVMuxer_Start(muxer) != AV_ERR_OK) { + // Exception handling. + } + ``` + +7. Call **OH_AVMuxer_WriteSample()** to write data, including video, audio, and cover data. + + ``` c++ + // Data can be written only after Start() is called. + int size = ...; + OH_AVMemory *sample = OH_AVMemory_Create (size); // Create an AVMemory instance. + // Write data to the sample buffer. For details, see the usage of OH_AVMemory. + // Encapsulate the cover. One image must be written at a time. + + // Set buffer information. + OH_AVCodecBufferAttr info; + info.pts =...; // Playback start time of the current data, in microseconds. + info.size = size; // Length of the current data. + info.offset = 0; // Offset. Generally, the value is 0. + info.flags |= AVCODEC_BUFFER_FLAGS_SYNC_FRAME; // Flag of the current data. For details, see OH_AVCodecBufferFlags. + int trackId = audioTrackId; // Select the track to be written. + + int ret = OH_AVMuxer_WriteSample(muxer, trackId, sample, info); + if (ret != AV_ERR_OK) { + // Exception handling. + } + ``` + +8. Call **OH_AVMuxer_Stop()** to stop encapsulation. + + ``` c++ + // Call Stop() to write the file trailer. After this API is called, you cannot write media data. + if (OH_AVMuxer_Stop(muxer) != AV_ERR_OK) { + // Exception handling. + } + ``` + +9. Call **OH_AVMuxer_Destroy()** to release the instance. + + ``` c++ + if (OH_AVMuxer_Destroy(muxer) != AV_ERR_OK) { + // Exception handling. + } + muxer = NULL; + close(fd); // Close the FD. + ``` diff --git a/en/application-dev/media/avplayer-avrecorder-overview.md b/en/application-dev/media/avplayer-avrecorder-overview.md index 3bf9b785b93a32b60b73c902449b9b019e651a2b..2415217bfc4cd6cfbbee1e12d039d9654c4ab5fd 100644 --- a/en/application-dev/media/avplayer-avrecorder-overview.md +++ b/en/application-dev/media/avplayer-avrecorder-overview.md @@ -77,6 +77,7 @@ The table below lists the supported audio playback formats. | Video Format| Mandatory or Not| | -------- | -------- | +| H.26510+ | Yes| | H.264 | Yes| | MPEG-2 | No| | MPEG-4 | No| @@ -87,10 +88,10 @@ The table below lists the supported playback formats and mainstream resolutions. | Video Container Format| Description| Resolution| | -------- | -------- | -------- | -| MP4| Video formats: H.264, MPEG-2, MPEG-4, and H.263
Audio formats: AAC and MP3| Mainstream resolutions, such as 4K, 1080p, 720p, 480p, and 270p| -| MKV| Video formats: H.264, MPEG-2, MPEG-4, and H.263
Audio formats: AAC and MP3| Mainstream resolutions, such as 4K, 1080p, 720p, 480p, and 270p| -| TS| Video formats: H.264, MPEG-2, and MPEG-4
Audio formats: AAC and MP3| Mainstream resolutions, such as 4K, 1080p, 720p, 480p, and 270p| -| WebM| Video format: VP8
Audio format: VORBIS| Mainstream resolutions, such as 4K, 1080p, 720p, 480p, and 270p| +| MP4| Video formats: H.26510+, H.264, MPEG2, MPEG4, and H.263
Audio formats: AAC and MP3| Mainstream resolutions, such as 4K, 1080p, 720p, 480p, and 270p| +| MKV| Video formats: H.26510+, H.264, MPEG2, MPEG4, and H.263
Audio formats: AAC and MP3| Mainstream resolutions, such as 4K, 1080p, 720p, 480p, and 270p| +| TS| Video formats: H.26510+, H.264, MPEG2, and MPEG4
Audio formats: AAC and MP3| Mainstream resolutions, such as 4K, 1080p, 720p, 480p, and 270p| +| WebM| Video format: VP8
Audio format: VORBIS| Mainstream resolutions, such as 4K, 1080p, 720p, 480p, and 270p| ## AVRecorder diff --git a/en/application-dev/media/camera-recording.md b/en/application-dev/media/camera-recording.md index 208b0664204ef2f74bb1160702053bde61fdf316..9d872d6b323f84718ac045be83cebda268b08d8c 100644 --- a/en/application-dev/media/camera-recording.md +++ b/en/application-dev/media/camera-recording.md @@ -34,7 +34,7 @@ Read [Camera](../reference/apis/js-apis-camera.md) for the API reference. console.log('prepare failed and error is ' + err.message); } }) - + let videoSurfaceId = null; AVRecorder.getInputSurface().then((surfaceId) => { console.info('getInputSurface success'); @@ -66,7 +66,7 @@ Read [Camera](../reference/apis/js-apis-camera.md) for the API reference. videoFrameRate: 30 // Video frame rate. }, url: 'fd://35', - rotation: 0 + rotation: 90 // 90° is the default vertical display angle. You can use other values based on project requirements. } // Create an AVRecorder instance. let avRecorder; diff --git a/en/application-dev/media/figures/audio-decode.png b/en/application-dev/media/figures/audio-decode.png new file mode 100644 index 0000000000000000000000000000000000000000..f76febe618c2529b3530436ddab6cb954a42d3b2 Binary files /dev/null and b/en/application-dev/media/figures/audio-decode.png differ diff --git a/en/application-dev/media/figures/audio-encode.png b/en/application-dev/media/figures/audio-encode.png new file mode 100644 index 0000000000000000000000000000000000000000..06be355cc372f7d8fc5614268f4358bbcea1e1a3 Binary files /dev/null and b/en/application-dev/media/figures/audio-encode.png differ diff --git a/en/application-dev/media/image-decoding.md b/en/application-dev/media/image-decoding.md index 00665aa430fb0d2ab95007f29d39b8adc5c5433c..59ca7a523f857b15aaf91e90c3ef6ed52aa5216f 100644 --- a/en/application-dev/media/image-decoding.md +++ b/en/application-dev/media/image-decoding.md @@ -13,7 +13,7 @@ Read [Image](../reference/apis/js-apis-image.md#imagesource) for APIs related to ``` 2. Obtain an image. - - Method 1: Obtain the sandbox path. For details about how to obtain the sandbox path, see [Obtaining the Application Development Path](../application-models/application-context-stage.md#obtaining-the-application-development-path). For details about the application sandbox and how to push files to the application sandbox, see [File Management](../file-management/app-sandbox-directory.md). + - Method 1: Obtain the sandbox path. For details about how to obtain the sandbox path, see [Obtaining Application File Paths](../application-models/application-context-stage.md#obtaining-application-file-paths). For details about the application sandbox and how to push files to the application sandbox, see [File Management](../file-management/app-sandbox-directory.md). ```ts // Code on the stage model @@ -110,6 +110,11 @@ Read [Image](../reference/apis/js-apis-image.md#imagesource) for APIs related to After the decoding is complete and the pixel map is obtained, you can perform subsequent [image processing](image-transformation.md). +5. Release the **PixelMap** instance. + ```ts + pixelMap.release(); + ``` + ## Sample Code - Decoding an Image in Resource Files 1. Obtain a resource manager. @@ -140,4 +145,7 @@ Read [Image](../reference/apis/js-apis-image.md#imagesource) for APIs related to const pixelMap = await imageSource.createPixelMap(); ``` - \ No newline at end of file +5. Release the **PixelMap** instance. + ```ts + pixelMap.release(); + ``` diff --git a/en/application-dev/media/obtain-supported-codecs.md b/en/application-dev/media/obtain-supported-codecs.md new file mode 100644 index 0000000000000000000000000000000000000000..82dd513666730eff160ca192b8e2a06ce2a455ec --- /dev/null +++ b/en/application-dev/media/obtain-supported-codecs.md @@ -0,0 +1,156 @@ +# Obtaining Supported Codecs + +Different devices support different codecs. Before invoking or configuring a codec, you need to query the codec specifications supported. + +You can call the native APIs provided by the **AVCapability** module to check whether related capabilities are supported. + +## How to Develop + +Read [AVCapability](../reference/native-apis/_a_v_capability.md) for the API reference. + +1. Obtain a codec capability instance. + + ```c + // Obtain a codec capability instance based on the MIME type and encoder flag. + OH_AVCapability *capability = OH_AVCodec_GetCapability(OH_AVCODEC_MIMETYPE_VIDEO_AVC, false); + + // Obtain a codec capability instance based on the MIME type, encoder flag, and software/hardware type. + OH_AVCapability *capability = OH_AVCodec_GetCapabilityByCategory(OH_AVCODEC_MIMETYPE_VIDEO_AVC, false, SOFTWARE); + ``` + +2. Query the specifications provided by the codec capability instance. + ```c + // Check whether the codec capability instance describes a hardware codec. + bool isHardware = OH_AVCapability_IsHardware(capability); + + // Obtain the codec name of the codec capability instance. + const char *codecName = OH_AVCapability_GetName(capability); + + // Obtain the maximum number of instances supported by the codec capability instance. + int32_t maxSupportedInstances = OH_AVCapability_GetMaxSupportedInstances(capability); + + // Obtain the bit rate range supported by the encoder. + OH_AVRange bitrateRange; + int32_t ret = OH_AVCapability_GetEncoderBitrateRange(capability, &bitrateRange); + if (ret != AV_ERR_OK) { + // Exception processing. + } + + // Check whether the codec capability instance supports a specific bit rate mode. + bool isEncoderBitrateModeSupported = OH_AVCapability_IsEncoderBitrateModeSupported(capability, &bitrateMode); + + // Obtain the quality range supported by the encoder. + OH_AVRange qualityRange; + int32_t ret = OH_AVCapability_GetEncoderQualityRange(capability, &qualityRange); + if (ret != AV_ERR_OK) { + // Exception processing. + } + + // Obtain the complexity range supported by the encoder. + OH_AVRange complexityRange; + int32_t ret = OH_AVCapability_GetEncoderComplexityRange(capability, &complexityRange); + if (ret != AV_ERR_OK) { + // Exception processing. + } + + // Obtain the supported audio sampling rates. + const int32_t *sampleRates; + uint32_t sampleRateNum = 0; + int32_t ret = OH_AVCapability_GetAudioSupportedSampleRates(capability, &sampleRates, &sampleRateNum); + if (ret != AV_ERR_OK) { + // Exception processing. + } + + // Obtain the number of audio channels supported. + OH_AVRange channelCountRange; + int32_t ret = OH_AVCapability_GetAudioChannelCountRange(capability, &channelCountRange); + if (ret != AV_ERR_OK) { + // Exception processing. + } + + // Obtain the width alignment value supported. + int32_t widthAlignment; + int32_t ret = OH_AVCapability_GetVideoWidthAlignment(capability, &widthAlignment); + if (ret != AV_ERR_OK) { + // Exception processing. + } + + // Obtain the high alignment value supported. + int32_t heightAlignment; + int32_t ret = OH_AVCapability_GetVideoHeightAlignment(capability, &heightAlignment); + if (ret != AV_ERR_OK) { + // Exception processing. + } + + // Obtain the width range when the height is 1080. + OH_AVRange widthRange; + int32_t ret = OH_AVCapability_GetVideoWidthRangeForHeight(capability, 1080, &widthRange); + if (ret != AV_ERR_OK) { + // Exception processing. + } + + // Obtain the height range when the width is 1920. + OH_AVRange heightRange; + int32_t ret = OH_AVCapability_GetVideoHeightRangeForWidth(capability, 1920, &heightRange); + if (ret != AV_ERR_OK) { + // Exception processing. + } + + // Obtain the width range supported. + OH_AVRange widthRange; + int32_t ret = OH_AVCapability_GetVideoWidthRange(capability, &widthRange); + if (ret != AV_ERR_OK) { + // Exception processing. + } + + // Obtain the height range supported. + OH_AVRange heightRange; + int32_t ret = OH_AVCapability_GetVideoWidthRange(capability, &heightRange); + if (ret != AV_ERR_OK) { + // Exception processing. + } + + // Check whether the codec capability instance supports the 1080p resolution. + bool isVideoSizeSupported = OH_AVCapability_IsVideoSizeSupported(capability, 1920, 1080); + + // Obtain the video frame rate range supported. + OH_AVRange frameRateRange; + int32_t ret = OH_AVCapability_GetVideoFrameRateRange(capability, &frameRateRange); + if (ret != AV_ERR_OK) { + // Exception processing. + } + + // Obtain the video frame rate range when the resolution is 1920 x 1080. + OH_AVRange frameRateRange; + int32_t ret = OH_AVCapability_GetVideoFrameRateRangeForSize(capability, 1920, 1080, &frameRateRange); + if (ret != AV_ERR_OK) { + // Exception processing. + } + + // Check whether the codec capability instance supports the scenario where the resolution is 1080p and the frame rate is 30 fps. + bool areVideoSizeAndFrameRateSupported = OH_AVCapability_AreVideoSizeAndFrameRateSupported(capability, 1920, 1080, 30); + + // Obtain the supported color formats and the number of supported color formats. + const int32_t *pixFormats; + uint32_t pixFormatNum = 0; + int32_t ret = OH_AVCapability_GetVideoSupportedPixelFormats(capability, &pixFormats, &pixFormatNum); + if (ret != AV_ERR_OK) { + // Exception processing. + } + + // Obtain the profiles supported. + const int32_t *profiles; + uint32_t profileNum = 0; + int32_t ret = OH_AVCapability_GetSupportedProfiles(capability, &profiles, &profileNum); + if (ret != AV_ERR_OK) { + // Exception processing. + } + + // Obtain the level range of a specific profile. + const int32_t *levels; + uint32_t levelNum = 0; + int32_t ret = OH_AVCapability_GetSupportedLevelsForProfile(capability, 0, &levels, &levelNum); + + // Check whether the codec capability instance supports the scenario where the resolution is 1080p and the frame rate is 30 fps. + bool areVideoSizeAndFrameRateSupported = OH_AVCapability_AreVideoSizeAndFrameRateSupported(capability, 1920, 1080, 30); + ``` diff --git a/en/application-dev/media/using-ohaudio-for-playback.md b/en/application-dev/media/using-ohaudio-for-playback.md new file mode 100644 index 0000000000000000000000000000000000000000..d63468342a25627e95e3e82b210b36a3dedff685 --- /dev/null +++ b/en/application-dev/media/using-ohaudio-for-playback.md @@ -0,0 +1,92 @@ +# Using OHAudio for Audio Playback + +**OHAudio** is a set of native APIs introduced in API version 10. These APIs are normalized in design and support both common and low-latency audio channels. + +## Prerequisites + +To use the playback or recording capability of **OHAudio**, you must first import the corresponding header files. + +Specifically, to use APIs for audio playback, import <[native_audiostreambuilder.h](../reference/native-apis/native__audiostreambuilder_8h.md)> and <[native_audiorenderer.h](../reference/native-apis/native__audiorenderer_8h.md)>. + +## Audio Stream Builder + +**OHAudio** provides the **OH_AudioStreamBuilder** class, which complies with the builder design pattern and is used to build audio streams. You need to specify [OH_AudioStream_Type](../reference/native-apis/_o_h_audio.md#oh_audiostream_type) based on your service scenarios. + +**OH_AudioStream_Type** can be set to either of the following: + +- AUDIOSTREAM_TYPE_RENDERER +- AUDIOSTREAM_TYPE_CAPTURER + +The following code snippet shows how to use [OH_AudioStreamBuilder_Create](../reference/native-apis/_o_h_audio.md#oh_audiostreambuilder_create) to create a builder: + +``` +OH_AudioStreamBuilder* builder; +OH_AudioStreamBuilder_Create(&builder, streamType); +``` + +After the audio service is complete, call [OH_AudioStreamBuilder_Destroy](../reference/native-apis/_o_h_audio.md#oh_audiostreambuilder_destroy) to destroy the builder. + +``` +OH_AudioStreamBuilder_Destroy(builder); +``` + +## How to Develop + +Read [OHAudio](../reference/native-apis/_o_h_audio.md) for the API reference. + +The following walks you through how to implement simple playback: + +1. Create an audio stream builder. + + ```c++ + OH_AudioStreamBuilder* builder; + OH_AudioStreamBuilder_Create(&builder, AUDIOSTREAM_TYPE_RENDERER); + ``` + +2. Set audio stream parameters. + + After creating the builder for audio playback, set the parameters required. + + ```c++ + OH_AudioStreamBuilder_SetSamplingRate(builder, rate); + OH_AudioStreamBuilder_SetChannelCount(builder, channelCount); + OH_AudioStreamBuilder_SetSampleFormat(builder, format); + OH_AudioStreamBuilder_SetEncodingType(builder, encodingType); + OH_AudioStreamBuilder_SetRendererInfo(builder, usage); + ``` + + Note that the audio data to play is written through callbacks. You must call **OH_AudioStreamBuilder_SetRendererCallback** to implement the callbacks. For details about the declaration of the callback functions, see [OH_AudioRenderer_Callbacks](../reference/native-apis/_o_h_audio.md#oh_audiorenderer_callbacks). + + +3. Set the callback functions. + + ```c++ + OH_AudioStreamBuilder_SetRendererCallback(builder, callbacks, nullptr); + ``` + +4. Create an audio renderer instance. + + ```c++ + OH_AudioRenderer* audioRenderer; + OH_AudioStreamBuilder_GenerateRenderer(builder, &audioRenderer); + ``` + +5. Use the audio renderer. + + You can use the APIs listed below to control the audio streams. + + | API | Description | + | ------------------------------------------------------------ | ------------ | + | OH_AudioStream_Result OH_AudioRenderer_Start(OH_AudioRenderer* renderer) | Starts the audio renderer. | + | OH_AudioStream_Result OH_AudioRenderer_Pause(OH_AudioRenderer* renderer) | Pauses the audio renderer. | + | OH_AudioStream_Result OH_AudioRenderer_Stop(OH_AudioRenderer* renderer) | Stops the audio renderer. | + | OH_AudioStream_Result OH_AudioRenderer_Flush(OH_AudioRenderer* renderer) | Flushes written audio data.| + | OH_AudioStream_Result OH_AudioRenderer_Release(OH_AudioRenderer* renderer) | Releases the audio renderer instance.| + +6. Destroy the audio stream builder. + + When the builder is no longer used, release related resources. + + ```c++ + OH_AudioStreamBuilder_Destroy(builder); + ``` diff --git a/en/application-dev/media/using-ohaudio-for-recording.md b/en/application-dev/media/using-ohaudio-for-recording.md new file mode 100644 index 0000000000000000000000000000000000000000..8521821735d3faea1f30a0894c869e4b98b8a595 --- /dev/null +++ b/en/application-dev/media/using-ohaudio-for-recording.md @@ -0,0 +1,92 @@ +# Using OHAudio for Audio Recording + +**OHAudio** is a set of native APIs introduced in API version 10. These APIs are normalized in design and support both common and low-latency audio channels. + +## Prerequisites + +To use the playback or recording capability of **OHAudio**, you must first import the corresponding header files. + +To use APIs for audio recording, import <[native_audiostreambuilder.h](../reference/native-apis/native__audiostreambuilder_8h.md)> and <[native_audiocapturer.h](../reference/native-apis/native__audiocapturer_8h.md)>. + +## Audio Stream Builder + +**OHAudio** provides the **OH_AudioStreamBuilder** class, which complies with the builder design pattern and is used to build audio streams. You need to specify [OH_AudioStream_Type](../reference/native-apis/_o_h_audio.md#oh_audiostream_type) based on your service scenarios. + +**OH_AudioStream_Type** can be set to either of the following: + +- AUDIOSTREAM_TYPE_RENDERER +- AUDIOSTREAM_TYPE_CAPTURER + +The following code snippet shows how to use [OH_AudioStreamBuilder_Create](../reference/native-apis/_o_h_audio.md#oh_audiostreambuilder_create) to create a builder: + +``` +OH_AudioStreamBuilder* builder; +OH_AudioStreamBuilder_Create(&builder, streamType); +``` + +After the audio service is complete, call [OH_AudioStreamBuilder_Destroy](../reference/native-apis/_o_h_audio.md#oh_audiostreambuilder_destroy) to destroy the builder. + +``` +OH_AudioStreamBuilder_Destroy(builder); +``` + +## How to Develop + +Read [OHAudio](../reference/native-apis/_o_h_audio.md) for the API reference. + +The following walks you through how to implement simple recording: + + +1. Create an audio stream builder. + + ```c++ + OH_AudioStreamBuilder* builder; + OH_AudioStreamBuilder_Create(&builder, AUDIOSTREAM_TYPE_CAPTURER); + ``` + +2. Set audio stream parameters. + + After creating the builder for audio recording, set the parameters required. + + ```c++ + OH_AudioStreamBuilder_SetSamplingRate(builder, rate); + OH_AudioStreamBuilder_SetChannelCount(builder, channelCount); + OH_AudioStreamBuilder_SetSampleFormat(builder, format); + OH_AudioStreamBuilder_SetEncodingType(builder, encodingType); + OH_AudioStreamBuilder_SetCapturerInfo(builder, sourceType); + ``` + + Note that the audio data to record is written through callbacks. You must call **OH_AudioStreamBuilder_SetCapturerCallback** to implement the callbacks. For details about the declaration of the callback functions, see [OH_AudioCapturer_Callbacks](../reference/native-apis/_o_h_audio.md#oh_audiocapturer_callbacks). + +3. Set the callback functions. + + ```c++ + OH_AudioStreamBuilder_SetCapturerCallback(builder, callbacks, nullptr); + ``` + +4. Create an audio capturer instance. + + ```c++ + OH_AudioCapturer* audioCapturer; + OH_AudioStreamBuilder_GenerateCapturer(builder, &audioCapturer); + ``` + +5. Use the audio capturer. + + You can use the APIs listed below to control the audio streams. + + | API | Description | + | ------------------------------------------------------------ | ------------ | + | OH_AudioStream_Result OH_AudioCapturer_Start(OH_AudioCapturer* capturer) | Starts the audio capturer. | + | OH_AudioStream_Result OH_AudioCapturer_Pause(OH_AudioCapturer* capturer) | Pauses the audio capturer. | + | OH_AudioStream_Result OH_AudioCapturer_Stop(OH_AudioCapturer* capturer) | Stops the audio capturer. | + | OH_AudioStream_Result OH_AudioCapturer_Flush(OH_AudioCapturer* capturer) | Flushes obtained audio data.| + | OH_AudioStream_Result OH_AudioCapturer_Release(OH_AudioCapturer* capturer) | Releases the audio capturer instance.| + +6. Destroy the audio stream builder. + + When the builder is no longer used, release related resources. + + ```c++ + OH_AudioStreamBuilder_Destroy(builder); + ``` diff --git a/en/application-dev/media/video-decoding.md b/en/application-dev/media/video-decoding.md new file mode 100644 index 0000000000000000000000000000000000000000..7e1dd04c05bb519b1c16cb480050f4625967a474 --- /dev/null +++ b/en/application-dev/media/video-decoding.md @@ -0,0 +1,264 @@ +# Video Decoding + +You can call the native APIs provided by the **VideoDecoder** module to decode video, that is, to decode media data into a YUV file or send it for display. + +Currently, the following decoding capabilities are supported: + +| Container Specification| Video Hardware Decoding Type | Video Software Decoding Type | +| -------- | --------------------- | ---------------- | +| mp4 | AVC (H.264), HEVC (H.265)|AVC (H.264) | + + +Video software decoding and hardware decoding are different. When a decoder is created based on the MIME type, only H.264 (video/avc) is supported for software decoding, and H.264 (video/avc) and H.265 (video/hevc) are supported for hardware decoding. + +## How to Develop + +Read [VideoDecoder](../reference/native-apis/_video_decoder.md) for the API reference. + +1. Create a decoder instance. + + You can create a decoder by name or MIME type. + + ``` c++ + // Create a decoder by name. + OH_AVCapability *capability = OH_AVCodec_GetCapability(OH_AVCODEC_MIMETYPE_VIDEO_AVC, false); + const char *name = OH_AVCapability_GetName(capability); + OH_AVCodec *videoDec = OH_VideoDecoder_CreateByName(name); // name:"OH.Media.Codec.Decoder.Video.AVC" + ``` + ```c++ + // Create a decoder by MIME type. + // Create an H.264 decoder for software/hardware decoding. + OH_AVCodec *videoDec = OH_VideoDecoder_CreateByMime(OH_AVCODEC_MIMETYPE_VIDEO_AVC); + // Create a decoder by MIME type. + // Create an H.265 decoder for hardware decoding. + OH_AVCodec *videoDec = OH_VideoDecoder_CreateByMime(OH_AVCODEC_MIMETYPE_VIDEO_HEVC); + ``` + ``` c++ + // Initialize the queues. + class VDecSignal { + public: + std::mutex inMutex_; + std::mutex outMutex_; + std::condition_variable inCond_; + std::condition_variable outCond_; + std::queue inQueue_; + std::queue outQueue_; + std::queue inBufferQueue_; + std::queue outBufferQueue_; + std::queue attrQueue_; + }; + VDecSignal *signal_; + ``` + +2. Call **OH_VideoDecoder_SetCallback()** to set callback functions. + + Register the **OH_AVCodecAsyncCallback** struct that defines the following callback function pointers: + + - **OnError**, a callback used to report a codec operation error + - **OnOutputFormatChanged**, a callback used to report a codec stream change, for example, stream width or height change. + - **OnInputBufferAvailable**, a callback used to report input data required, which means that the decoder is ready for receiving data + - **OnOutputBufferAvailable**, a callback used to report output data generated, which means that decoding is complete (Note: The **data** parameter in the callback function is empty in surface output mode.) + + You need to process the callback functions to ensure that the decoder runs properly. + + ``` c++ + // Set the OnError callback function. + static void OnError(OH_AVCodec *codec, int32_t errorCode, void *userData) + { + (void)codec; + (void)errorCode; + (void)userData; + } + // Set the OnOutputFormatChanged callback function. + static void OnOutputFormatChanged(OH_AVCodec *codec, OH_AVFormat *format, void *userData) + { + (void)codec; + (void)format; + (void)userData; + } + // Set the OnInputBufferAvailable callback function, which is used to obtain the input frame information. + static void OnInputBufferAvailable(OH_AVCodec *codec, uint32_t index, OH_AVMemory *data, void *userData) + { + (void)codec; + VDecSignal *signal_ = static_cast(userData); + unique_lock lock(signal_->inMutex_); + // The ID of the input frame is sent to inQueue_. + signal_->inQueue_.push(index); + // The input frame data is sent to inBufferQueue_. + signal_->inBufferQueue_.push(data); + signal_->inCond_.notify_all(); + } + // Set the OnOutputBufferAvailable callback function, which is used to obtain the output frame information. + static void OnOutputBufferAvailable(OH_AVCodec *codec, uint32_t index, OH_AVMemory *data, OH_AVCodecBufferAttr *attr, + void *userData) + { + (void)codec; + VDecSignal *signal_ = static_cast(userData); + unique_lock lock(signal_->outMutex_); + // The index of the output buffer is sent to outQueue_. + signal_->outQueue_.push(index); + // The decoded data (specified by data) is sent to outBufferQueue_. (Note: data is empty in surface output mode.) + signal_->outBufferQueue_.push(data); + signal_->attrQueue_.push(*attr); + signal_->outCond_.notify_all(); + } + OH_AVCodecAsyncCallback cb = {&OnError, &OnOutputFormatChanged, &OnInputBufferAvailable, &OnOutputBufferAvailable}; + // Set the asynchronous callbacks. + int32_t ret = OH_VideoDecoder_SetCallback(videoDec, cb, signal_); + ``` + +3. Call **OH_VideoDecoder_Configure()** to configure the decoder. + + The following options are mandatory: video frame width, video frame height, and video color format. + + ``` c++ + // (Mandatory) Configure the video frame width. + constexpr uint32_t DEFAULT_WIDTH = 320; + // (Mandatory) Configure the video frame height. + constexpr uint32_t DEFAULT_HEIGHT = 240; + OH_AVFormat *format = OH_AVFormat_Create(); + // Set the format. + OH_AVFormat_SetIntValue(format, OH_MD_KEY_WIDTH, DEFAULT_WIDTH); + OH_AVFormat_SetIntValue(format, OH_MD_KEY_HEIGHT, DEFAULT_HEIGHT); + OH_AVFormat_SetIntValue(format, OH_MD_KEY_PIXEL_FORMAT, AV_PIXEL_FORMAT_NV21); + // Configure the decoder. + int32_t ret = OH_VideoDecoder_Configure(videoDec, format); + OH_AVFormat_Destroy(format); + ``` + +4. (Optional) Set the surface. + + This step is required only when the surface is used to send the data for display. + + ``` c++ + // Set the parameters of the display window. + sptr window = nullptr; + sptr option = new Rosen::WindowOption(); + option->SetWindowRect({0, 0, DEFAULT_WIDTH, DEFAULT_HEIGHT}); + option->SetWindowType(Rosen::WindowType::WINDOW_TYPE_APP_LAUNCHING); + option->SetWindowMode(Rosen::WindowMode::WINDOW_MODE_FLOATING); + window = Rosen::Window::Create("video-decoding", option); + window->Show(); + sptr ps = window->GetSurfaceNode()->GetSurface(); + OHNativeWindow *nativeWindow = CreateNativeWindowFromSurface(&ps); + int32_t ret = OH_VideoDecoder_SetSurface(videoDec, window); + bool isSurfaceMode = true; + ``` + +5. (Optional) Configure the surface parameters of the decoder. This step is required only when the surface is used. + + ``` c++ + OH_AVFormat *format = OH_AVFormat_Create(); + // Configure the display rotation angle. + OH_AVFormat_SetIntValue(format, OH_MD_KEY_ROTATION, 90); + // Configure the matching mode (scaling or cropping) between the video and the display screen. + OH_AVFormat_SetIntValue(format, OH_MD_KEY_SCALING_MODE, SCALING_MODE_SCALE_CROP); + int32_t ret = OH_VideoDecoder_SetParameter(videoDec, format); + OH_AVFormat_Destroy(format); + ``` + +6. Call **OH_VideoDecoder_Start()** to start the decoder. + + ``` c++ + string_view outputFilePath = "/*yourpath*.yuv"; + std::unique_ptr inputFile = std::make_unique(); + // Open the path of the binary file to be decoded. + inputFile->open(inputFilePath.data(), std::ios::in | std::ios::binary); + // Configure the parameter in buffer mode. + if(!isSurfaceMode) { + // Configure the output file path in buffer mode. + std::unique_ptr outFile = std::make_unique(); + outFile->open(outputFilePath.data(), std::ios::out | std::ios::binary); + } + // Start decoding. + int32_t ret = OH_VideoDecoder_Start(videoDec); + ``` + +7. Call **OH_VideoDecoder_PushInputData()** to push the stream to the input queue for decoding. + + ``` c++ + // Configure the buffer information. + OH_AVCodecBufferAttr info; + // Call av_packet_alloc to initialize and return a container packet. + AVPacket pkt = av_packet_alloc(); + // Configure the input size, offset, and timestamp of the buffer. + info.size = pkt->size; + info.offset = 0; + info.pts = pkt->pts; + info.flags = AVCODEC_BUFFER_FLAGS_NONE; + // Send the data to the input queue for decoding. The index is the subscript of the queue. + int32_t ret = OH_VideoDecoder_PushInputData(videoDec, index, info); + ``` + +8. Call **OH_VideoDecoder_FreeOutputData()** to output the decoded frames. + + ``` c++ + int32_t ret; + // Write the decoded data (specified by data) to the output file. + outFile->write(reinterpret_cast(OH_AVMemory_GetAddr(data)), data.size); + // Free the buffer that stores the output data. The index is the subscript of the surface/buffer queue. + if (isSurfaceMode) { + ret = OH_VideoDecoder_RenderOutputData(videoDec, index); + } else { + ret = OH_VideoDecoder_FreeOutputData(videoDec, index); + } + if (ret != AV_ERR_OK) { + // Exception handling. + } + ``` + +9. (Optional) Call **OH_VideoDecoder_Flush()** to refresh the decoder. + + After **OH_VideoDecoder_Flush()** is called, the decoder remains in the running state, but the current queue is cleared and the buffer storing the decoded data is freed. + + To continue decoding, you must call **OH_VideoDecoder_Start()** again. + + ``` c++ + int32_t ret; + // Refresh the decoder. + ret = OH_VideoDecoder_Flush(videoDec); + if (ret != AV_ERR_OK) { + // Exception handling. + } + // Start decoding again. + ret = OH_VideoDecoder_Start(videoDec); + ``` + +10. (Optional) Call **OH_VideoDecoder_Reset()** to reset the decoder. + + After **OH_VideoDecoder_Reset()** is called, the decoder returns to the initialized state. To continue decoding, you must call **OH_VideoDecoder_Configure()** and then **OH_VideoDecoder_Start()**. + + ``` c++ + int32_t ret; + // Reset the decoder. + ret = OH_VideoDecoder_Reset(videoDec); + if (ret != AV_ERR_OK) { + // Exception handling. + } + // Reconfigure the decoder. + ret = OH_VideoDecoder_Configure(videoDec, format); + ``` + +11. Call **OH_VideoDecoder_Stop()** to stop the decoder. + + ``` c++ + int32_t ret; + // Stop the decoder. + ret = OH_VideoDecoder_Stop(videoDec); + if (ret != AV_ERR_OK) { + // Exception handling. + } + return AV_ERR_OK; + ``` + +12. Call **OH_VideoDecoder_Destroy()** to destroy the decoder instance and release resources. + + ``` c++ + int32_t ret; + // Call OH_VideoDecoder_Destroy to destroy the decoder. + ret = OH_VideoDecoder_Destroy(videoDec); + if (ret != AV_ERR_OK) { + // Exception handling. + } + return AV_ERR_OK; + ``` diff --git a/en/application-dev/media/video-encoding.md b/en/application-dev/media/video-encoding.md new file mode 100644 index 0000000000000000000000000000000000000000..410922d95b5e66cb2ceab1aee20640a13283d54b --- /dev/null +++ b/en/application-dev/media/video-encoding.md @@ -0,0 +1,565 @@ +# Video Encoding + +You can call the native APIs provided by the **VideoEncoder** module to encode a video, that is, to compress audio and video data into an audio and video stream. + +Currently, the following encoding capabilities are supported: + +| Container Specification| Video Encoding Type | Audio Encoding Type | +| -------- | --------------------- | ---------------- | +| mp4 | HEVC (H.265), AVC (H.264)| AAC, MPEG (MP3)| +| m4a | HEVC (H.265), AVC (H.264)| AAC | + +## Surface Input and Buffer Input + +Surface input and buffer input differ in data sources. + +Surface input contains information such as pixel data and pixel format, for example, a recorded video stream directly transferred by the camera module. It is more applicable to scenarios such as real-time video capture. + +Buffer input refers to a memory space, which is generally a byte array or a pointer to the memory. It is more applicable to scenarios such as reading audio and video data from files or real-time streaming transmission. + +The two also differ slightly in the API calling modes: + +- In buffer input mode, an application calls **OH_VideoEncoder_PushInputData()** to input data. In surface input mode, an application, before the encoder starts, calls **OH_VideoEncoder_GetSurface()** to obtain the surface for video data transmission. + +- In buffer input mode, an application calls **OH_VideoEncoder_PushInputData()** to pass in the End of Stream (EOS) flag, and the encoder stops when it reads the last frame. In surface input mode, an application calls **OH_VideoEncoder_NotifyEndOfStream()** to notify the encoder of EOS. + +For details about the development procedure, see [Buffer Input](#buffer-input) and [Surface Input](#surface-input). + +## How to Develop + +Read [VideoEncoder](../reference/native-apis/_video_encoder.md) for the API reference. + +### Buffer Input + +The following walks you through how to implement the entire video encoding process in buffer input mode. It uses the YUV file input and H.264 encoding format as an example. +Currently, the **VideoEncoder** module supports only data transferring in asynchronous mode. + +1. Create an encoder instance. + + You can create an encoder by name or Multipurpose Internet Mail Extensions (MIME) type. + + ``` c++ + // To create an encoder by MIME type, call OH_VideoEncoder_CreateByMime. The system creates the most appropriate encoder based on the MIME type. + OH_AVCodec *videoEnc = OH_VideoEncoder_CreateByMime(CodecMimeType::VIDEO_AVC.data()); + ``` + + ```c++ + // To create an encoder by name, call OH_AVCapability_GetName to obtain the codec names available and then call OH_VideoEncoder_CreateByName. If your application has special requirements, for example, expecting an encoder that supports a certain resolution, you can call OH_AVCodec_GetCapability to query the capability first. + OH_AVCapability *capability = OH_AVCodec_GetCapability(CodecMimeType::VIDEO_AVC.data(), true); + const char *codecName = OH_AVCapability_GetName(capability); + OH_AVCodec *videoEnc = OH_VideoEncoder_CreateByName(codecName); + ``` + +2. Call **OH_VideoEncoder_SetCallback()** to set callback functions. + + > **NOTE** + > + > In the callback functions, pay attention to the multi-thread conflict for operations on the data queue. + + Register the **OH_AVCodecAsyncCallback** struct that defines the following callback function pointers: + + - **OnError**, a callback used to report a codec operation error + - **OnStreamChanged**, a callback used to report a codec stream change, for example, audio channel change + - **OnNeedInputData**, a callback used to report input data required, which means that the encoder is ready for receiving PCM data + - **OnNeedOutputData**, a callback used to report output data generated, which means that encoding is complete + + You need to process the callback functions to ensure that the encoder runs properly. + + ``` c++ + // Set the OnError callback function. + static void OnError(OH_AVCodec *codec, int32_t errorCode, void *userData) + { + (void)codec; + (void)errorCode; + (void)userData; + } + + // Set the OnStreamChanged callback function. + static void OnStreamChanged(OH_AVCodec *codec, OH_AVFormat *format, void *userData) + { + (void)codec; + (void)format; + (void)userData; + } + + // Set the OnNeedInputData callback function, which is used to send an input frame to the data queue. + static void OnNeedInputData(OH_AVCodec *codec, uint32_t index, OH_AVMemory *mem, void *userData) + { + (void)userData; + // The index of the input frame buffer is sent to InIndexQueue. + // The input frame data (specified by mem) is sent to InBufferQueue. + // Perform data processing. For details, see + // 7. Write the stream to encode. + // 8. Notify the encoder of EOS. + } + + // Set the OnNeedOutputData callback function, which is used to send an encoded frame to the output queue. + static void OnNeedOutputData(OH_AVCodec *codec, uint32_t index, OH_AVMemory *mem, + OH_AVCodecBufferAttr *attr, void *userData) + { + (void)userData; + // The index of the output frame buffer is sent to outIndexQueue. + // The encoded frame data (specified by mem) is sent to outBufferQueue. + // The data format of the encoded frame is sent to outAttrQueue. + // Perform data processing. For details, see + // 9. Output the encoded frames. + } + + // Call OH_VideoEncoder_SetCallback to set the asynchronous callback functions. + OH_AVCodecAsyncCallback cb = {&OnError, &OnStreamChanged, &OnNeedInputData, &OnNeedOutputData}; + int32_t ret = OH_VideoEncoder_SetCallback(videoEnc, cb, userData); + if (ret != AV_ERR_OK) { + // Exception handling. + } + ``` + +3. Call **OH_VideoEncoder_Configure()** to configure the encoder. + + Currently, the following options must be configured for all supported formats: video frame width, video frame height, and video pixel format. + + In the code snippet below, the following data is used: + - **DEFAULT_WIDTH**: 320 pixels + - **DEFAULT_HEIGHT**: 240 pixels + - **DEFAULT_PIXELFORMAT**: **VideoPixelFormat::YUV420P** (the pixel format of the YUV file is YUV420P) + + ``` c++ + // (Mandatory) Configure the video frame width. + constexpr uint32_t DEFAULT_WIDTH = 320; + // (Mandatory) Configure the video frame height. + constexpr uint32_t DEFAULT_HEIGHT = 240; + // (Mandatory) Configure the video pixel format. + constexpr VideoPixelFormat DEFAULT_PIXELFORMAT = VideoPixelFormat::YUV420P; + OH_AVFormat *format = OH_AVFormat_Create(); + // Set the format. + OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_WIDTH.data(), DEFAULT_WIDTH); + OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_HEIGHT.data(), DEFAULT_HEIGHT); + OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_PIXEL_FORMAT.data(), DEFAULT_PIXELFORMAT); + // Configure the encoder. + int32_t ret = OH_VideoEncoder_Configure(videoEnc, format); + if (ret != AV_ERR_OK) { + // Exception handling. + } + ``` + +4. Call **OH_VideoEncoder_Prepare()** to prepare internal resources for the encoder. + + ``` c++ + ret = OH_VideoEncoder_Prepare(videoEnc); + if (ret != AV_ERR_OK) { + // Exception handling. + } + ``` + +5. Call **OH_VideoEncoder_Start()** to start the encoder. + + As soon as the encoder starts, the callback functions will be triggered to respond to events. Therefore, you must configure the input file and output file first. + + ``` c++ + // Configure the paths of the input and output files. + string_view inputFilePath = "/*yourpath*.yuv"; + string_view outputFilePath = "/*yourpath*.h264"; + std::unique_ptr inputFile = std::make_unique(); + std::unique_ptr outputFile = std::make_unique(); + inputFile->open(inputFilePath.data(), std::ios::in | std::ios::binary); + outputFile->open(outputFilePath.data(), std::ios::out | std::ios::binary | std::ios::ate); + // Start the encoder to start encoding. + int32_t ret = OH_VideoEncoder_Start(videoEnc); + if (ret != AV_ERR_OK) { + // Exception handling. + } + ``` + +6. (Optional) Dynamically configure the encoder instance. + + ``` c++ + OH_AVFormat *format = OH_AVFormat_Create(); + // Configure the video frame rate. + double frameRate = 30.0; + // Configure the video YUV range flag. + bool rangeFlag = false; + // Configure the video primary color. + int32_t primary = static_cast(OH_ColorPrimary::COLOR_PRIMARY_BT709); + // Configure the transfer features. + int32_t transfer = static_cast(OH_TransferCharacteristic::TRANSFER_CHARACTERISTIC_BT709); + // Configure the maximum matrix coefficient. + int32_t matrix = static_cast(OH_MaxtrixCoefficient::MATRIX_COFFICIENT_IDENTITY); + // Configure the encoding profile. + int32_t profile = static_cast(AVCProfile::AVC_PROFILE_BASELINE); + // Configure the encoding bit rate mode. + int32_t rateMode = static_cast(VideoEncodeBitrateMode::CBR); + // Configure the key frame interval, in milliseconds. + int32_t iFrameInterval = 23000; + // Configure the required encoding quality. Only an encoder in constant quality mode supports this configuration. + int32_t quality = 0; + // Configure the bit rate. + int64_t bitRate = 3000000; + // Set the format. + OH_AVFormat_SetDoubleValue(format, MediaDescriptionKey::MD_KEY_FRAME_RATE, frameRate); + OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_RANGE_FLAG, rangeFlag); + OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_COLOR_PRIMARIES, primary); + OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_TRANSFER_CHARACTERISTICS, transfer); + OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_MATRIX_COEFFICIENTS, matrix); + + OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_I_FRAME_INTERVAL, iFrameInterval); + OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_PROFILE, profile); + OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_VIDEO_ENCODE_BITRATE_MODE, rateMode); + OH_AVFormat_SetLongValue(format, MediaDescriptionKey::MD_KEY_BITRATE, bitRate); + OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_QUALITY, quality); + + int32_t ret = OH_VideoEncoder_SetParameter(videoEnc, format); + if (ret != AV_ERR_OK) { + // Exception handling. + } + ``` + +7. Call **OH_VideoEncoder_PushInputData()** to push the stream to the input queue for encoding. + + In the code snippet below, the following parameters are used: + - **GetOneFrameSize()**: function for calculating the frame length of the YUV file. For details about the calculation process, see related YUV documents. + - **mem**: parameter passed in by the callback function **OnNeedInputData**. You can call **OH_AVMemory_GetAddr** to obtain the pointer to the shared memory address. + - **index**: index of the data queue, which is passed in by the callback function **OnNeedInputData**. + + ``` c++ + // Process the file stream and obtain the frame length, and then write the data to encode to the memory of the specified index. + int32_t frameSize = GetOneFrameSize(); + inputFile->read(reinterpret_cast(OH_AVMemory_GetAddr(mem)), frameSize); + // Configure the buffer information. + OH_AVCodecBufferAttr info; + info.size = frameSize; + info.offset = 0; + info.pts = 0; + info.flags = AVCODEC_BUFFER_FLAGS_CODEC_DATA; + // Send the data to the input queue for encoding. The index is the subscript of the input queue. + int32_t ret = OH_VideoEncoder_PushInputData(videoEnc, index, info); + if (ret != AV_ERR_OK) { + // Exception handling. + } + ``` + +8. Notify the encoder of EOS. + + In the code snippet below, the following parameter is used: + + **index**: index of the data queue, which is passed in by the callback function **OnNeedInputData**. + + The API **OH_VideoEncoder_PushInputData** is used to notify the encoder of EOS. This API is also used in step 7 to push the stream to the input queue for encoding. Therefore, in the current step, you must pass in the **AVCODEC_BUFFER_FLAGS_EOS** flag. + + ``` c++ + int32_t ret; + OH_AVCodecBufferAttr info; + info.size = 0; + info.offset = 0; + info.pts = 0; + info.flags = AVCODEC_BUFFER_FLAG_EOS; + ret = OH_VideoEncoder_PushInputData(videoEnc, index, info); + if (ret != AV_ERR_OK) { + // Exception handling. + } + ``` + +9. Call **OH_VideoEncoder_FreeOutputData()** to output the encoded frames. + + In the code snippet below, the following parameters are used: + - **index**: index of the data queue, which is passed in by the callback function **OnNeedOutputData**. + - **attr**: buffer storing the output data, which is passed in by the callback function **OnNeedOutputData**. + - **mem**: parameter passed in by the callback function **OnNeedOutputData**. You can call **OH_AVMemory_GetAddr** to obtain the pointer to the shared memory address. + + ``` c++ + // Write the encoded frame data (specified by mem) to the output file. + outputFile->write(reinterpret_cast(OH_AVMemory_GetAddr(mem)), attr->size); + // Free the output buffer. The index is the subscript of the output queue. + int32_t ret = OH_VideoEncoder_FreeOutputData(videoEnc, index); + if (ret != AV_ERR_OK) { + // Exception handling. + } + ``` + +10. (Optional) Call **OH_VideoEncoder_Flush()** to refresh the encoder. + + After **OH_VideoEncoder_Flush()** is called, the encoder remains in the running state, but the current queue is cleared and the buffer storing the encoded data is freed. + + To continue encoding, you must call **OH_VideoEncoder_Start()** again. + + ``` c++ + int32_t ret; + // Refresh the encoder. + ret = OH_VideoEncoder_Flush(videoEnc); + if (ret != AV_ERR_OK) { + // Exception handling. + } + // Start encoding again. + ret = OH_VideoEncoder_Start(videoEnc); + if (ret != AV_ERR_OK) { + // Exception handling. + } + ``` + +11. (Optional) Call **OH_VideoEncoder_Reset()** to reset the encoder. + + After **OH_VideoEncoder_Reset()** is called, the encoder returns to the initialized state. To continue encoding, you must call **OH_VideoEncoder_Configure()** and then **OH_VideoEncoder_Start()**. + + ``` c++ + int32_t ret; + // Reset the encoder. + ret = OH_VideoEncoder_Reset(videoEnc); + if (ret != AV_ERR_OK) { + // Exception handling. + } + // Reconfigure the encoder. + ret = OH_VideoEncoder_Configure(videoEnc, format); + if (ret != AV_ERR_OK) { + // Exception handling. + } + ``` + +12. Call **OH_VideoEncoder_Stop()** to stop the encoder. + + ``` c++ + int32_t ret; + // Stop the encoder. + ret = OH_VideoEncoder_Stop(videoEnc); + if (ret != AV_ERR_OK) { + // Exception handling. + } + ``` + +13. Call **OH_VideoEncoder_Destroy()** to destroy the encoder instance and release resources. + + > **NOTE** + > + > After the call, you must set a null pointer to the encoder to prevent program errors caused by wild pointers. + + ``` c++ + int32_t ret; + // Call OH_VideoEncoder_Destroy to destroy the encoder. + ret = OH_VideoEncoder_Destroy(videoEnc); + videoEnc = nullptr; + if (ret != AV_ERR_OK) { + // Exception handling. + } + ``` + +### Surface Input + +The following walks you through how to implement the entire video encoding process in surface input mode. It uses the video data input and H.264 encoding format as an example. +Currently, the **VideoEncoder** module supports only data transferring in asynchronous mode. + +1. Create an encoder instance. + + You can create an encoder by name or MIME type. + + ``` c++ + // To create an encoder by MIME type, call OH_VideoEncoder_CreateByMime. The system creates the most appropriate encoder based on the MIME type. + OH_AVCodec *videoEnc = OH_VideoEncoder_CreateByMime(CodecMimeType::VIDEO_AVC.data()); + ``` + + ```c++ + // To create an encoder by name, call OH_AVCapability_GetName to obtain the codec names available and then call OH_VideoEncoder_CreateByName. If your application has special requirements, for example, expecting an encoder that supports a certain resolution, you can call OH_AVCodec_GetCapability to query the capability first. + OH_AVCapability *capability = OH_AVCodec_GetCapability(CodecMimeType::VIDEO_AVC.data(), true); + const char *codecName = OH_AVCapability_GetName(capability); + OH_AVCodec *videoEnc = OH_VideoEncoder_CreateByName(codecName); + ``` + +2. Call **OH_VideoEncoder_SetCallback()** to set callback functions. + + > **NOTE** + > + > In the callback functions, pay attention to the multi-thread conflict for operations on the data queue. + + Register the **OH_AVCodecAsyncCallback** struct that defines the following callback function pointers: + + - **OnError**, a callback used to report a codec operation error + - **OnStreamChanged**, a callback used to report a codec stream change, for example, audio channel change + - **OnNeedInputData**, a callback used to report input data required, which means that the encoder is ready for receiving PCM data + - **onNeedOutputData**, a callback used to report output data generated, which means that encoding is complete + + ``` c++ + // Set the OnError callback function. + static void OnError(OH_AVCodec *codec, int32_t errorCode, void *userData) + { + (void)codec; + (void)errorCode; + (void)userData; + } + + // Set the OnStreamChanged callback function. + static void OnStreamChanged(OH_AVCodec *codec, OH_AVFormat *format, void *userData) + { + (void)codec; + (void)format; + (void)userData; + } + + // Set the OnNeedInputData callback function, which is used to send an input frame to the data queue. + static void OnNeedInputData(OH_AVCodec *codec, uint32_t index, OH_AVMemory *mem, void *userData) + { + (void)userData; + (void)index; + (void)mem; + // In surface mode, this callback function does not take effect. You can input data by using the surface. + } + + // Set the OnNeedOutputData callback function, which is used to send an encoded frame to the output queue. + static void OnNeedOutputData(OH_AVCodec *codec, uint32_t index, OH_AVMemory *mem, + OH_AVCodecBufferAttr *attr, void *userData) + { + (void)userData; + // The index of the output frame buffer is sent to outIndexQueue. + // The encoded frame data (specified by mem) is sent to outBufferQueue. + // The data format of the encoded frame is sent to outAttrQueue. + // Perform data processing. For details, see + // 10. Output the encoded frames. + } + + // Call OH_VideoEncoder_SetCallback to set the asynchronous callback functions. + OH_AVCodecAsyncCallback cb = {&OnError, &OnStreamChanged, &OnNeedInputData, &OnNeedOutputData}; + int32_t ret = OH_VideoEncoder_SetCallback(videoEnc, cb, userData); + if (ret != AV_ERR_OK) { + // Exception handling. + } + ``` + +3. Call **OH_VideoEncoder_Configure()** to configure the encoder. + + Currently, the following options must be configured for all supported formats: video frame width, video frame height, and video pixel format. + + In the code snippet below, the following data is used: + - **DEFAULT_WIDTH**: 320 pixels + - **DEFAULT_HEIGHT**: 240 pixels + - **DEFAULT_PIXELFORMAT**: **VideoPixelFormat::YUV420P** (the pixel format of the YUV file is YUV420P) + + ``` c++ + // (Mandatory) Configure the video frame width. + constexpr uint32_t DEFAULT_WIDTH = 320; + // (Mandatory) Configure the video frame height. + constexpr uint32_t DEFAULT_HEIGHT = 240; + // (Mandatory) Configure the video pixel format. + constexpr VideoPixelFormat DEFAULT_PIXELFORMAT = VideoPixelFormat::YUV420P; + OH_AVFormat *format = OH_AVFormat_Create(); + // Set the format. + OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_WIDTH.data(), DEFAULT_WIDTH); + OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_HEIGHT.data(), DEFAULT_HEIGHT); + OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_PIXEL_FORMAT.data(), DEFAULT_PIXELFORMAT); + // Configure the encoder. + int32_t ret = OH_VideoEncoder_Configure(videoEnc, format); + if (ret != AV_ERR_OK) { + // Exception handling. + } + ``` + +4. Call **OH_VideoEncoder_Prepare()** to prepare internal resources for the encoder. + + ``` c++ + ret = OH_VideoEncoder_Prepare(videoEnc); + if (ret != AV_ERR_OK) { + // Exception handling. + } + ``` + +5. Obtain a surface. + + Obtain the **OHNativeWindow** input in surface input mode. The surface must be obtained before the encoder starts. + + ``` c++ + int32_t ret; + // Obtain the surface used for data input. + OHNativeWindow *nativeWindow; + ret = OH_VideoEncoder_GetSurface(videoEnc, &nativeWindow); + if (ret != AV_ERR_OK) { + // Exception handling. + } + // Configure the surface of the input data through the OHNativeWindow* variable type. + ``` + + For details about how to use the OHNativeWindow* variable type, see Graphics Subsystem/foundation/graphic/graphic_2d. + +6. Call **OH_VideoEncoder_Start()** to start the encoder. + + ``` c++ + int32_t ret; + // Start the encoder to start encoding. + ret = OH_VideoEncoder_Start(videoEnc); + if (ret != AV_ERR_OK) { + // Exception handling. + } + ``` + +7. (Optional) Dynamically configure the encoder instance. + + ``` c++ + OH_AVFormat *format = OH_AVFormat_Create(); + // Configure the video frame rate. + double frameRate = 30.0; + // Configure the video YUV range flag. + bool rangeFlag = false; + // Configure the video primary color. + int32_t primary = static_cast(OH_ColorPrimary::COLOR_PRIMARY_BT709); + // Configure the transfer features. + int32_t transfer = static_cast(OH_TransferCharacteristic::TRANSFER_CHARACTERISTIC_BT709); + // Configure the maximum matrix coefficient. + int32_t matrix = static_cast(OH_MaxtrixCoefficient::MATRIX_COFFICIENT_IDENTITY); + // Configure the encoding profile. + int32_t profile = static_cast(AVCProfile::AVC_PROFILE_BASELINE); + // Configure the encoding bit rate mode. + int32_t rateMode = static_cast(VideoEncodeBitrateMode::CBR); + // Configure the key frame interval, in milliseconds. + int32_t iFrameInterval = 23000; + // Configure the required encoding quality. Only an encoder in constant quality mode supports this configuration. + int32_t quality = 0; + // Configure the bit rate. + int64_t bitRate = 3000000; + // Set the format. + OH_AVFormat_SetDoubleValue(format, MediaDescriptionKey::MD_KEY_FRAME_RATE, frameRate); + OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_RANGE_FLAG, rangeFlag); + OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_COLOR_PRIMARIES, primary); + OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_TRANSFER_CHARACTERISTICS, transfer); + OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_MATRIX_COEFFICIENTS, matrix); + + OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_I_FRAME_INTERVAL, iFrameInterval); + OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_PROFILE, profile); + OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_VIDEO_ENCODE_BITRATE_MODE, rateMode); + OH_AVFormat_SetLongValue(format, MediaDescriptionKey::MD_KEY_BITRATE, bitRate); + OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_QUALITY, quality); + + int32_t ret = OH_VideoEncoder_SetParameter(videoEnc, format); + if (ret != AV_ERR_OK) { + // Exception handling. + } + ``` + +8. Write the stream to encode. + + In step 5, you have configured the **OHNativeWindow*** variable type returned by **OH_VideoEncoder_GetSurface**. + + The data required for encoding is continuously input by the surface. Therefore, you do not need to process the **OnNeedInputData** callback function or use **OH_VideoEncoder_PushInputData** to input data. + +9. Call **OH_VideoEncoder_NotifyEndOfStream()** to notify the encoder of EOS. + + ``` c++ + int32_t ret; + // In surface input mode, you only need to call this API to notify the encoder of EOS. + // In buffer input mode, you need to set the AVCODEC_BUFFER_FLAGS_EOS flag and then call OH_VideoEncoder_PushInputData to notify the encoder of EOS. + ret = OH_VideoEncoder_NotifyEndOfStream(videoEnc); + if (ret != AV_ERR_OK) { + // Exception handling. + } + ``` + +10. Call **OH_VideoEncoder_FreeOutputData()** to output the encoded frames. + + In the code snippet below, the following parameters are used: + - **index**: index of the data queue, which is passed in by the callback function **OnNeedOutputData**. + - **attr**: buffer storing the output data, which is passed in by the callback function **OnNeedOutputData**. + - **mem**: parameter passed in by the callback function **OnNeedOutputData**. You can call **OH_AVMemory_GetAddr** to obtain the pointer to the shared memory address. + + ``` c++ + // Write the encoded frame data (specified by mem) to the output file. + outputFile->write(reinterpret_cast(OH_AVMemory_GetAddr(mem)), attr->size); + // Free the output buffer. The index is the subscript of the output queue. + int32_t ret = OH_VideoEncoder_FreeOutputData(videoEnc, index); + if (ret != AV_ERR_OK) { + // Exception handling. + } + ``` + +The subsequent processes (including refreshing, resetting, stopping, and destroying the encoder) are the same as those in buffer input mode. For details, see steps 9-12 in [Buffer Input](#buffer-input). diff --git a/en/application-dev/napi/mindspore-lite-guidelines.md b/en/application-dev/napi/mindspore-lite-guidelines.md index 8dd76e32683a9a8fd6369cb4f4f53863c4e85607..e175c3750b7c0f445f570b742073e67824726537 100644 --- a/en/application-dev/napi/mindspore-lite-guidelines.md +++ b/en/application-dev/napi/mindspore-lite-guidelines.md @@ -85,7 +85,7 @@ The development process consists of the following main steps: 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/zh-CN/r1.5/use/downloads.html#id1) to convert it to the .ms format. + - 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/downloads.html#id1) to convert it to the .ms format. 2. Create a context, and set parameters such as the number of runtime threads and device type. @@ -280,7 +280,3 @@ The development process consists of the following main steps: 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 ``` - -## Samples -The following sample is provided to help you better understand how to use MindSpore Lite: -- [Simple MindSpore Lite Tutorial](https://gitee.com/openharmony/third_party_mindspore/tree/OpenHarmony-3.2-Release/mindspore/lite/examples/quick_start_c) diff --git a/en/application-dev/quick-start/app-configuration-file.md b/en/application-dev/quick-start/app-configuration-file.md index f60bb688a99df3a2c753b61e2137fa857b85f2c2..6977c5c7cc53085d66e38ec8edd33bddb0623ff7 100644 --- a/en/application-dev/quick-start/app-configuration-file.md +++ b/en/application-dev/quick-start/app-configuration-file.md @@ -1,7 +1,7 @@ # app.json5 Configuration File -This topic gives an overview of the **app.json5** configuration file. To start with, let's go through an example of what this file contains. +This document gives an overview of the **app.json5** configuration file. To start with, let's go through an example of what this file contains. ```json { @@ -35,7 +35,7 @@ As shown above, the **app.json5** file contains several tags. | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | | bundleName | Bundle name, which uniquely identifies an application. The value must comply with the following rules:
- Consists of letters, digits, underscores (_), and periods (.).
- Starts with a letter.
- Contains 7 to 127 bytes.
You are advised to use the reverse domain name notation, for example, *com.example.demo*, where the first part is the domain suffix **com**, the second part is the vendor/individual name, and the third part is the application name, which can be of multiple levels.
If an application is built with the system source code, you are advised to name it in *com.ohos.demo* notation, where **ohos** signifies that the application is an OpenHarmony system application.| String| No| -| bundleType| Bundle type, which is used to distinguish applications and atomic services.
- **app**: The bundle is a common application.
- **atomicService**: The bundle is an atomic service.
- **shared**: The bundle is a shared object application.| String| Yes (initial value: **"app"**)| +| bundleType| Bundle type, which is used to distinguish applications and atomic services.
- **app**: The bundle is a common application.
- **atomicService**: The bundle is an atomic service.
- **shared**: The bundle is a shared object application.| String| Yes (initial value: **"app"**)| | debug | Whether the application can be debugged. This tag is generated during compilation and building in DevEco Studio.
- **true**: The application can be debugged.
- **false**: The application cannot be debugged.| Boolean| Yes (initial value: **false**)| | icon | [Icon of the application](../application-models/application-component-configuration-stage.md). The value is an icon resource index.| String| No| | label | [Name of the application](../application-models/application-component-configuration-stage.md). The value is a string resource index.| String| No| @@ -47,7 +47,7 @@ As shown above, the **app.json5** file contains several tags. | minAPIVersion | Minimum API version required for running the application.| Number| Yes (initial value: value of **compatibleSdkVersion** in **build-profile.json5**)| | targetAPIVersion | Target API version required for running the application.| Number| Yes (initial value: value of **compileSdkVersion** in **build-profile.json5**)| | apiReleaseType | Type of the target API version required for running the application. The value can be **"CanaryN"**, **"BetaN"**, or **"Release"**, where **N** represents a positive integer.
- **Canary**: indicates a restricted release.
- **Beta**: indicates a publicly released beta version.
- **Release**: indicates a publicly released official version.
The value is set by DevEco Studio reading the stage of the SDK in use.| String| Yes (initial value: set by DevEco Studio)| -| multiProjects | Whether the application supports joint development of multiple projects.
- **true**: The application supports joint development of multiple projects.
- **false**: The application does not support joint development of multiple projects. For details about multi-project development, see [Multi-Project Build](https://developer.harmonyos.com/en/docs/documentation/doc-guides-V3/ohos-building-overview-0000001263360495-V3#section71471033104216).| Boolean| Yes (initial value: **false**)| +| multiProjects | Whether the application supports joint development of multiple projects.
- **true**: The application supports joint development of multiple projects.
- **false**: The application does not support joint development of multiple projects. | Boolean| Yes (initial value: **false**)| | asanEnabled | Whether to enable AddressSanitizer (ASan) to detect memory corruption issues such as buffer overflows.
- **true**: ASan is enabled.
- **false**: ASan is disabled. Note that ASan is not available in the Release version.| Boolean| Yes (initial value: **false**)| | tablet | Tablet-specific configuration, which includes the **minAPIVersion** attribute.
When running on tablets, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)| | tv | TV-specific configuration, which includes the **minAPIVersion** attribute.
When running on TVs, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)| @@ -56,4 +56,4 @@ As shown above, the **app.json5** file contains several tags. | default | Default device–specific configuration, which includes the **minAPIVersion** attribute.
When running on default devices, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)| |targetBundleName|Target application name of the bundle. The value rule and range are the same as those of **bundleName**.|String|Yes (if the initial value is used, the target application is not an application with the overlay feature)| |targetPriority|Priority of the application. When **targetBundleName** is set, the application is an application with the overlay feature. The value ranges from 1 to 100.|Number|Yes (initial value: **1**)| -|generateBuildHash |Whether the hash values of all HAP and HSP files of the application are generated by the packaging tool. The hash values (if any) are used to determine whether the application needs to be updated when the system is updated in OTA mode but the **versionCode** value of the application remains unchanged.
If this tag is set to **true**, the packaging tool generates hash values for all HAP and HSP files of the application.
**NOTE**
This tag applies only to system applications.|Boolean|Yes (initial value: **false**)| +|generateBuildHash |Whether the hash values of all HAP and HSP files of the application are generated by the packaging tool. The hash values (if any) are used to determine whether the application needs to be updated when the system is updated in OTA mode but the **versionCode** value of the application remains unchanged.
If this tag is set to **true**, the packaging tool generates hash values for all HAP and HSP files of the application.
**NOTE**
**This tag applies only to system applications.**|Boolean|Yes (initial value: **false**)| diff --git a/en/application-dev/quick-start/arkts-extend.md b/en/application-dev/quick-start/arkts-extend.md index fba84d8154592ba5c61b2106ab130b4ff92991ce..321ccf5a93aec3e5acd154fe4e8db164e4b02a26 100644 --- a/en/application-dev/quick-start/arkts-extend.md +++ b/en/application-dev/quick-start/arkts-extend.md @@ -5,6 +5,7 @@ Apart from\@Styles used to extend styles, AkrUI also provides \@Extend, which al > **NOTE** +> > Since API version 9, this decorator is supported in ArkTS widgets. @@ -169,7 +170,7 @@ struct FancyUse { Text(`${this.label}`) .fancyText(200, Color.Pink) Text(`${this.label}`) - .fancyText(200, Color.Orange) + .fancyText(300, Color.Orange) }.margin('20%') } } diff --git a/en/application-dev/quick-start/arkts-localstorage.md b/en/application-dev/quick-start/arkts-localstorage.md index 3c3e4853f8aac66be1afc1ef47d295ecc7528830..6be9a62d0c84043783c75d29e4af3e7d252829c0 100644 --- a/en/application-dev/quick-start/arkts-localstorage.md +++ b/en/application-dev/quick-start/arkts-localstorage.md @@ -9,7 +9,7 @@ This topic describes only the LocalStorage application scenarios and related dec > **NOTE** > -> This module is supported since API version 9. +> LocalStorage is supported since API version 9. ## Overview diff --git a/en/application-dev/quick-start/deviceconfig-structure.md b/en/application-dev/quick-start/deviceconfig-structure.md index bc15571c43fdb5c0be860098cd4ad4c799a6ea16..848d55f1adc12859b9ad6c98c078ba8532ae2c84 100644 --- a/en/application-dev/quick-start/deviceconfig-structure.md +++ b/en/application-dev/quick-start/deviceconfig-structure.md @@ -27,7 +27,7 @@ Table 2 describes the internal structure of the **deviceConfig** attributes. | process | Name of the process running the application or ability. If the **process** attribute is configured in the **deviceConfig** tag, all abilities of the application run in this process. You can set the **process** attribute for a specific ability in the **abilities** attribute, so that the ability can run in the particular process. The value can contain a maximum of 31 characters.| String| Yes (initial value: left empty)| | keepAlive | Whether the application is always running. This attribute applies only to system applications and does not take effect for third-party applications. The value **true** means that the application will start during the OS startup and keep alive. If the application process exits, the OS will restart it.| Boolean| Yes (initial value: **false**)| | supportBackup | Whether the application supports backup and restoration. The value **false** means that the application does not support backup or restoration.| Boolean| Yes (initial value: **false**)| -| compressNativeLibs | Whether the **libs** libraries are packaged in the HAP file after being compressed. The value **false** means that the **libs** libraries are stored without being compressed and will be directly loaded during the installation of the HAP file.| Boolean| Yes (initial value: **false**)| +| compressNativeLibs | Whether the **libs** libraries are packaged in the HAP file after being compressed. The value **false** means that the **libs** libraries are stored without being compressed and will be directly loaded during the installation of the HAP file.| Boolean| Yes (initial value: **true**)| | network | Network security configuration. You can customize the network security settings of the application in the security statement of the configuration file without modifying the application code.| Object| Yes (initial value: left empty)| ## Internal Structure of the network Attribute diff --git a/en/application-dev/quick-start/module-configuration-file.md b/en/application-dev/quick-start/module-configuration-file.md index 3320ab86ce4ff0c6527b06390459551a853df8da..60a0baa6a6046da92101a1dcff891a6ed16d774d 100644 --- a/en/application-dev/quick-start/module-configuration-file.md +++ b/en/application-dev/quick-start/module-configuration-file.md @@ -380,7 +380,7 @@ The **extensionAbilities** tag represents the configuration of extensionAbilitie | type | Type of the ExtensionAbility component. The options are as follows:
- **form**: ExtensionAbility of a widget.
- **workScheduler**: ExtensionAbility of a Work Scheduler task.
- **inputMethod**: ExtensionAbility of an input method.
- **service**: service component running in the background.
- **accessibility**: ExtensionAbility of an accessibility feature.
- **dataShare**: ExtensionAbility for data sharing.
- **fileShare**: ExtensionAbility for file sharing.
- **staticSubscriber**: ExtensionAbility for static broadcast.
- **wallpaper**: ExtensionAbility of the wallpaper.
- **backup**: ExtensionAbility for data backup.
- **window**: ExtensionAbility of a window. This type of ExtensionAbility creates a window during startup for which you can develop the GUI. The window is then combined with other application windows through **abilityComponent**.
- **thumbnail**: ExtensionAbility for obtaining file thumbnails. You can provide thumbnails for files of customized file types.
- **preview**: ExtensionAbility for preview. This type of ExtensionAbility can parse the file and display it in a window. You can combine the window with other application windows.
- **print**: ExtensionAbility for the print framework.
- **push**: ExtensionAbility to be pushed.
- **driver**: ExtensionAbility for the driver framework.
**NOTE**
The **service** and **dataShare** types apply only to system applications and do not take effect for third-party applications.| String| No| | permissions | Permissions required for another application to access the ExtensionAbility component.
The value is generally in the reverse domain name notation and contains a maximum of 255 bytes. It is an array of permission names predefined by the system or customized. The name of a customized permission must be the same as the **name** value of a permission defined in the **defPermissions** attribute.| String array| Yes (initial value: left empty)| | uri | Data URI provided by the ExtensionAbility component. The value is a string with a maximum of 255 bytes, in the reverse domain name notation.
**NOTE**
This attribute is mandatory when the type of the ExtensionAbility component is set to **dataShare**.| String| Yes (initial value: left empty)| -|skills | Feature set of [wants](../application-models/want-overview.md) that can be received by the ExtensionAbility component.
Configuration rule: In an entry package, you can configure multiple **skills** attributes with the entry capability. (A **skills** attribute with the entry capability is the one that has **ohos.want.action.home** and **entity.system.home** configured.) The **label** and **icon** in the first ExtensionAbility that has **skills** configured are used as the **label** and **icon** of the entire OpenHarmony service/application.
**NOTE**
The **skills** attribute with the entry capability can be configured for the feature package of an OpenHarmony application,
but not for an OpenHarmony service.| Array| Yes (initial value: left empty)| +|skills | Feature set of [wants](../application-models/want-overview.md) that can be received by the ExtensionAbility component.
Configuration rule: In an entry package, you can configure multiple **skills** attributes with the entry capability. (A **skills** attribute with the entry capability is the one that has **ohos.want.action.home** and **entity.system.home** configured.) The **label** and **icon** in the first ExtensionAbility that has **skills** configured are used as the **label** and **icon** of the entire OpenHarmony service/application.
**NOTE**
The **skills** attribute with the entry capability can be configured for the feature package of an OpenHarmony application, but not for an OpenHarmony service.| Array| Yes (initial value: left empty)| | [metadata](#metadata)| Metadata of the ExtensionAbility component.| Object| Yes (initial value: left empty)| | exported | Whether the ExtensionAbility component can be called by other applications.
- **true**: The ExtensionAbility component can be called by other applications.
- **false**: The ExtensionAbility component cannot be called by other applications.| Boolean| Yes (initial value: **false**)| diff --git a/en/application-dev/quick-start/module-structure.md b/en/application-dev/quick-start/module-structure.md index 830848bba13635f6e2b2a24aab3b8d634db6aebf..0ecf733d7fb4a71a6bb507ba1f808b87e360cf5c 100644 --- a/en/application-dev/quick-start/module-structure.md +++ b/en/application-dev/quick-start/module-structure.md @@ -7,24 +7,24 @@ The **module** tag contains the HAP configuration. | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | -| mainAbility | Ability whose icon is displayed in the Service Center. When the resident process is started, the **mainAbility** is started.| String| Yes (initial value: left empty)| -| package | Package name of the HAP file, which must be unique in the application. The value is a string with a maximum of 127 bytes, in the reverse domain name notation. It is recommended that the value be the same as the project directory of the HAP file. | String| No| -| name | Class name of the HAP file. The value is a string with a maximum of 255 bytes, in the reverse domain name notation. The prefix must be the same as the **package** value specified for this module. Alternatively, the value can start with a period (.) followed by the class name.| String| Yes (initial value: left empty)| -| description | Description of the HAP file. The value is a string with a maximum of 255 bytes. If the value exceeds the limit or needs to support multiple languages, you can use a resource index to the description.| String| Yes (initial value: left empty)| -| supportedModes | Modes supported by the application. Currently, only the **drive** mode is defined. This attribute applies only to head units.| String array| Yes (initial value: left empty)| -|deviceType | Type of device on which the ability can run. The device types predefined in the system include **tablet**, **tv**, **car**, and **wearable**.| String array| No| -|distro | Distribution description of the HAP file.| Object| No| -|metaData | Metadata of the HAP file.| Object| Yes (initial value: left empty)| -| abilities | All abilities in the current module. The value is an array of objects, each of which represents an ability.| Object array| Yes (initial value: left empty)| -| js | A set of JS modules developed using ArkUI. The value is an array of objects, each of which represents a JS module.| Object array| Yes (initial value: left empty)| -| shortcuts | Shortcuts of the application. The value is an array of objects, each of which represents a shortcut object.| Object array| Yes (initial value: left empty)| -| reqPermissions | Permissions that the application requests from the system when it is running.| Object array| Yes (initial value: left empty)| -| colorMode | Color mode of the application. The options are as follows:
- **dark**: Resources applicable for the dark mode are used.
- **light**: Resources applicable for the light mode are used.
- **auto**: Resources are used based on the color mode of the system.| String| Yes (initial value: **auto**)| -| distributionFilter | Distribution rules of the application. This attribute defines the rules for distributing HAP files based on different device specifications, so that precise matching can be performed when the application market distributes applications. Distribution rules cover three factors: API version, screen shape, and screen resolution. During distribution, a unique HAP is determined based on the mapping between **deviceType** and these three factors.| Object| Yes (initial value: left empty) Set this attribute when an application has multiple entry modules.| -|commonEvents | Information about the common event static subscriber, which must contain the subscriber name, required permissions, and list of the common events subscribed to. When a subscribed event is sent, the static subscriber is started. Unlike the dynamic subscriber, the static subscriber does not need to proactively call the common event subscription API in the service code, and may not be running when the common event is published.| Object array| Yes (initial value: left empty)| -| entryTheme | Keyword of an OpenHarmony internal theme. Set it to the resource index of the name.| String| Yes (initial value: left empty)| -|testRunner | Test runner configuration.| Object| Yes (initial value: left empty)| -|generateBuildHash | Whether the hash value of the HAP or HSP file is generated by the packaging tool. The hash value (if any) is used to determine whether the application needs to be updated when the system is updated in OTA mode but the value of [code](#internal-structure-of-the-apiversion-attribute) in **version** of the application remains unchanged.
**NOTE**
This tag applies only to system applications.|Boolean|Yes (initial value: **false**)| +| mainAbility | Ability whose icon is displayed in the Service Center. When the resident process is started, the **mainAbility** is started.| String| Yes (initial value: left empty)| +| package | Package name of the HAP file, which must be unique in the application. The value is a string with a maximum of 127 bytes, in the reverse domain name notation. It is recommended that the value be the same as the project directory of the HAP file. | String| No| +| name | Class name of the HAP file. The value is a string with a maximum of 255 bytes, in the reverse domain name notation. The prefix must be the same as the **package** value specified for this module. Alternatively, the value can start with a period (.) followed by the class name.| String| Yes (initial value: left empty)| +| description | Description of the HAP file. The value is a string with a maximum of 255 bytes. If the value exceeds the limit or needs to support multiple languages, you can use a resource index to the description.| String| Yes (initial value: left empty)| +| supportedModes | Modes supported by the application. Currently, only the **drive** mode is defined. This attribute applies only to head units.| String array| Yes (initial value: left empty)| +|deviceType | Type of device on which the ability can run. The device types predefined in the system include **tablet**, **tv**, **car**, and **wearable**.| String array| No| +|distro | Distribution description of the HAP file.| Object| No| +|metaData | Metadata of the HAP file.| Object| Yes (initial value: left empty)| +| abilities | All abilities in the current module. The value is an array of objects, each of which represents an ability.| Object array| Yes (initial value: left empty)| +| js | A set of JS modules developed using ArkUI. The value is an array of objects, each of which represents a JS module.| Object array| Yes (initial value: left empty)| +| shortcuts | Shortcuts of the application. The value is an array of objects, each of which represents a shortcut object.| Object array| Yes (initial value: left empty)| +| reqPermissions | Permissions that the application requests from the system when it is running.| Object array| Yes (initial value: left empty)| +| colorMode | Color mode of the application. The options are as follows:
- **dark**: Resources applicable for the dark mode are used.
- **light**: Resources applicable for the light mode are used.
- **auto**: Resources are used based on the color mode of the system.| String| Yes (initial value: **auto**)| +| distributionFilter | Rules for distributing HAP files based on different device specifications, so that precise matching can be performed when the application market distributes applications. All sub-attributes under this attribute are optional. This attribute must be configured in the **/resource/profile** directory. During distribution, a unique HAP is determined based on the mapping between **deviceType** and attributes listed in the table below.| Object| Yes (initial value: left empty) Set this attribute when an application has multiple entry modules.| +|commonEvents | Information about the common event static subscriber, which must contain the subscriber name, required permissions, and list of the common events subscribed to. When a subscribed event is sent, the static subscriber is started. Unlike the dynamic subscriber, the static subscriber does not need to proactively call the common event subscription API in the service code, and may not be running when the common event is published.| Object array| Yes (initial value: left empty)| +| entryTheme | Keyword of an OpenHarmony internal theme. Set it to the resource index of the name.| String| Yes (initial value: left empty)| +|testRunner | Test runner configuration.| Object| Yes (initial value: left empty)| +|generateBuildHash |Whether the hash value of the HAP or HSP file is generated by the packaging tool. The hash value (if any) is used to determine whether the application needs to be updated when the system is updated in OTA mode but the value of [code](#internal-structure-of-the-apiversion-attribute) in **version** of the application remains unchanged.
**NOTE**
**This tag applies only to system applications.**|Boolean|Yes (initial value: **false**)| Example of the **module** tag structure: @@ -96,7 +96,7 @@ Example of the **module** tag structure: | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | -| moduleName | Name of the HAP file. The maximum length is 31 bytes.| String| No| +| moduleName | Name of the HAP file. The maximum length is 31 bytes. During application upgrade, this name can be changed. If it is changed, migration of module-related directories is required for the application. You can use the [file operation API](../reference/apis/js-apis-file-fs.md#fscopydir10) for migration.| String| No| | moduleType | Type of the HAP file, which can **entry**, **feature**, or **har**.| String| No| | installationFree | Whether the HAP file supports the installation-free feature. **true**: The HAP file supports the installation-free feature and meets installation-free constraints. **false**: The HAP file does not support the installation-free feature. If this tag is set to **true** for an entry-type HAP file (**entry.hap**), it must also be set to **true** for feature-type HAP files (**feature.hap**) of the same application. If this tag is set to **false** for an entry-type HAP file, it can be set to **true** or **false** for feature-type modules of the same application based on service requirements.| Boolean| No| | deliveryWithInstall | Whether the HAP file will be installed when the user installs the application. **true**: The HAP file will be installed when the user installs the application. **false**: The HAP file will not be installed when the user installs the application.| Boolean| No| @@ -196,10 +196,10 @@ Example of the metadata attribute: | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | | process | Name of the process running the application or ability. If the **process** attribute is configured in the **deviceConfig** tag, all abilities of the application run in this process. You can set the **process** attribute for a specific ability in the **abilities** attribute, so that the ability can run in the particular process. If this attribute is set to the name of the process running other applications, all these applications can run in the same process, provided they have the same unified user ID and the same signature. The value can contain a maximum of 31 bytes.| String| Yes (initial value: left empty)| -| name | Ability name. The value can be a reverse domain name, in the format of "*bundleName*.*className*", for example, **"com.example.myapplication.EntryAbility"**. Alternatively, the value can start with a period (.) followed by the class name, for example, **".EntryAbility"**.
The ability name must be unique in an application.
**NOTE**
If you use DevEco Studio to create the project, an ability named **EntryAbility** will be created by default, and its configuration will be saved to the **config.json** file. If you use other IDEs, the value of this attribute can be customized. The value can contain a maximum of 127 bytes. | String| No| +| name | Ability name. The value can be a reverse domain name, in the format of "*bundleName*.*className*", for example, **"com.example.myapplication.EntryAbility"**. Alternatively, the value can start with a period (.) followed by the class name, for example, **".EntryAbility"**.
The ability name must be unique in an application.
**NOTE**
If you use DevEco Studio to create the project, an ability named **EntryAbility** will be created by default, and its configuration will be saved to the **config.json** file. If you use other IDEs, the value of this attribute can be customized. The value can contain a maximum of 127 bytes.| String| No| | description | Description of the ability. The value can be a string or a resource index to descriptions in multiple languages. The value can contain a maximum of 255 bytes.| String| Yes (initial value: left empty)| -| icon | Index to the ability icon file. Example value: **$media:ability_icon**. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the icon of the ability is also used as the icon of the application. If multiple abilities address this condition, the icon of the first candidate ability is used as the application icon.
**NOTE**
The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels. | String| Yes (initial value: left empty)| -| label | Ability name displayed to users. The value can be a name string or a resource index to names in multiple languages, for example, **$string:ability_label**. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the label of the ability is also used as the label of the application. If multiple abilities address this condition, the label of the first candidate ability is used as the application label.
**NOTE**
The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels. The value can be a reference to a string defined in a resource file or a string enclosed in brackets ({}). The value can contain a maximum of 255 bytes. | String| Yes (initial value: left empty)| +| icon | Index to the ability icon file. Example value: **$media:ability_icon**. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the icon of the ability is also used as the icon of the application. If multiple abilities address this condition, the icon of the first candidate ability is used as the application icon.
**NOTE**
The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels.| String| Yes (initial value: left empty)| +| label | Ability name displayed to users. The value can be a name string or a resource index to names in multiple languages, for example, **$string:ability_label**. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the label of the ability is also used as the label of the application. If multiple abilities address this condition, the label of the first candidate ability is used as the application label.
**NOTE**
The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels. The value can be a reference to a string defined in a resource file or a string enclosed in brackets ({}). The value can contain a maximum of 255 bytes.| String| Yes (initial value: left empty)| | uri | Uniform Resource Identifier (URI) of the ability. The value can contain a maximum of 255 bytes.| String| Yes (No for abilities using the Data template)| | launchType | Launch type of the ability. The value can be **standard** or **singleton**.
**standard**: Multiple **Ability** instances can be created during startup. Most abilities can use this type.
**singleton**: Only a single **Ability** instance can be created across all task stacks during startup. For example, a globally unique incoming call screen uses the singleton launch type. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String| Yes (initial value: **"singleton"**)| | visible | Whether the ability can be called by other applications.
**true**: The ability can be called by other applications.
**false**: The ability cannot be called by other applications.| Boolean| Yes (initial value: **false**)| diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index e9cdf59666c6c9a27af9484ecbc401f131bd0bfc..9c225026165d18d24c17bbae3f3ded66cc4c5d83 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -381,6 +381,7 @@ - Account Management - [@ohos.account.appAccount (App Account Management)](js-apis-appAccount.md) + - [@ohos.account.appAccount.AuthorizationExtensionAbility (App Account AuthorizationExtensionAbility)](js-apis-appAccount-authorizationExtensionAbility.md) - [@ohos.account.distributedAccount (Distributed Account Management)](js-apis-distributed-account.md) - [@ohos.account.osAccount (OS Account Management)](js-apis-osAccount.md) diff --git a/en/application-dev/reference/apis/commonEvent-definitions.md b/en/application-dev/reference/apis/commonEvent-definitions.md index 24c133a68f2e0166a514cb5afc645178b103150b..5ae926c7df430fa61af12a5d79093754f1690cc3 100644 --- a/en/application-dev/reference/apis/commonEvent-definitions.md +++ b/en/application-dev/reference/apis/commonEvent-definitions.md @@ -880,10 +880,8 @@ Indicates that the airplane mode of the device has changed. - Required subscriber permissions: none -## COMMON_EVENT_SPLIT_SCREEN8+ +## [COMMON_EVENT_SPLIT_SCREEN8+](./common_event/commonEvent-window.md) Indicates that the screen has been split. -- Value: **usual.event.SPLIT_SCREEN** -- Required subscriber permissions: none ## COMMON_EVENT_SLOT_CHANGE9+ @@ -907,3 +905,5 @@ Indicates the result of applying a quick fix to the application. Indicates that the user information has been updated. - Value: **usual.event.USER_INFO_UPDATED** - Required subscriber permissions: none +## [COMMON_EVENT_SMS_RECEIVE_COMPLETED](./common_event/commonEvent-mms.md) +Indicates that a new SMS message has been received. diff --git a/en/application-dev/reference/apis/commonEventManager-definitions.md b/en/application-dev/reference/apis/commonEventManager-definitions.md index f0695d7a98d24babd68c20f0bf554ff916026490..d43c0cc0aab7edef6c28384f1f0af0381634be74 100644 --- a/en/application-dev/reference/apis/commonEventManager-definitions.md +++ b/en/application-dev/reference/apis/commonEventManager-definitions.md @@ -476,6 +476,9 @@ Indicates that the system starts charging the battery. ## [COMMON_EVENT_CHARGE_TYPE_CHANGED](./common_event/commonEvent-powermgr.md) Indicates that the system charging type has changed. This event is available only for system applications. +## [COMMON_EVENT_CHARGE_IDLE_MODE_CHANGED](./common_event/commonEvent-powermgr.md) +Indicates that the device enters the charging idle mode. + ## [COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED](./common_event/commonEvent-resourceschedule.md) Indicates that the system idle mode has changed. ## [COMMON_EVENT_DEVICE_IDLE_EXEMPTION_LIST_UPDATED10+](./common_event/commonEvent-resourceschedule.md) diff --git a/en/application-dev/reference/apis/common_event/commonEvent-powermgr.md b/en/application-dev/reference/apis/common_event/commonEvent-powermgr.md index d2829f06383208c93abbdadec23dea9f0f44e1f9..21cc0da389e284bcf7891e528b11a7c03fe083d1 100644 --- a/en/application-dev/reference/apis/common_event/commonEvent-powermgr.md +++ b/en/application-dev/reference/apis/common_event/commonEvent-powermgr.md @@ -65,6 +65,14 @@ Indicates that the system charging type has changed. This event is available onl When the system charging type changes, the event notification service is triggered to publish this event. +## COMMON_EVENT_CHARGE_IDLE_MODE_CHANGED +Indicates that the device enters the charging idle mode. + +- Value: usual.event.CHARGE_IDLE_MODE_CHANGED +- Required subscriber permissions: none + +When the device starts charging in idle mode, and the temperature rise is acceptable, the event notification service is triggered to publish this event. + ## COMMON_EVENT_SHUTDOWN Indicates that the device is being and will be shut down. diff --git a/en/application-dev/reference/apis/figures/Cursor_Circle.png b/en/application-dev/reference/apis/figures/Cursor_Circle.png new file mode 100644 index 0000000000000000000000000000000000000000..75b942a03da161b31d717fcfcb0a6ede1d65e76b Binary files /dev/null and b/en/application-dev/reference/apis/figures/Cursor_Circle.png differ diff --git a/en/application-dev/reference/apis/figures/Cursor_Cross.png b/en/application-dev/reference/apis/figures/Cursor_Cross.png new file mode 100644 index 0000000000000000000000000000000000000000..1b8391c4dc617e07270489643c03eede068882d1 Binary files /dev/null and b/en/application-dev/reference/apis/figures/Cursor_Cross.png differ diff --git a/en/application-dev/reference/apis/figures/Horizontal_Text_Cursor.png b/en/application-dev/reference/apis/figures/Horizontal_Text_Cursor.png new file mode 100644 index 0000000000000000000000000000000000000000..6911b3a2c702613239bef39a7101832f5343ccdb Binary files /dev/null and b/en/application-dev/reference/apis/figures/Horizontal_Text_Cursor.png differ diff --git a/en/application-dev/reference/apis/js-apis-accessibility-config.md b/en/application-dev/reference/apis/js-apis-accessibility-config.md index 09fb6c49bf265b0a4ef22ddd38dc46370097304d..9a7eb35e202d8fc5a8e73c76f9caee04e5f7776e 100644 --- a/en/application-dev/reference/apis/js-apis-accessibility-config.md +++ b/en/application-dev/reference/apis/js-apis-accessibility-config.md @@ -31,6 +31,8 @@ import config from '@ohos.accessibility.config'; | shortkeyTarget | [Config](#config)\| Yes| Yes| Target application for the accessibility extension shortcut key. The value format is 'bundleName/abilityName'.| | captions | [Config](#config)\| Yes| Yes| Whether to enable captions.| | captionsStyle | [Config](#config)\<[accessibility.CaptionsStyle](js-apis-accessibility.md#captionsstyle8)>| Yes| Yes| Captions style.| +| audioMono| [Config](#config)\| Yes| Yes| Whether to enable mono audio. The value **True** means to enable mono audio, and **False** means the opposite.| +| audioBalance| [Config](#config)\| Yes| Yes| Audio balance for the left and right audio channels. The value ranges from -1.0 to 1.0.| ## enableAbility diff --git a/en/application-dev/reference/apis/js-apis-accessibility.md b/en/application-dev/reference/apis/js-apis-accessibility.md index 2f92eaaf3052bd34f76baefc6a04de7a8d59b4a4..12d03127205e38c462aeaa275f286adecf0fe34e 100644 --- a/en/application-dev/reference/apis/js-apis-accessibility.md +++ b/en/application-dev/reference/apis/js-apis-accessibility.md @@ -137,11 +137,11 @@ Describes the style of captions. | Name | Type | Readable | Writable | Description | | --------------- | ---------------------------------------- | ---- | ---- | ----------- | | fontFamily | [CaptionsFontFamily](#captionsfontfamily8) | Yes | No | Font family of captions. | -| fontScale | number | Yes | No | Font scale of captions.| -| fontColor | number \| string | Yes | No | Font color of captions. | +| fontScale | number | Yes | No | Font scale factor of captions, in percentage. The value ranges from 1 to 200.| +| fontColor | number \| string | Yes | No | Font color of captions. For example, red corresponds to #FF0000. | | fontEdgeType | [CaptionsFontEdgeType](#captionsfontedgetype8) | Yes | No | Font edge type of captions. | -| backgroundColor | number \| string | Yes | No | Background color of captions. | -| windowColor | number \| string | Yes | No | Window color of captions. | +| backgroundColor | number \| string | Yes | No | Background color of captions. For example, red corresponds to #FF0000. | +| windowColor | number \| string | Yes | No | Window color of captions. For example, red corresponds to #FF0000. | ## CaptionsManager8+ @@ -162,6 +162,8 @@ on(type: 'enableChange', callback: Callback<boolean>): void; Enables listening for the enabled status changes of captions configuration. This API uses an asynchronous callback to return the result. +**System capability**: SystemCapability.BarrierFree.Accessibility.Hearing + **Parameters** | Name | Type | Mandatory | Description | @@ -188,6 +190,8 @@ on(type: 'styleChange', callback: Callback<CaptionsStyle>): void; Enables listening for captions style changes. This API uses an asynchronous callback to return the result. +**System capability**: SystemCapability.BarrierFree.Accessibility.Hearing + **Parameters** | Name | Type | Mandatory | Description | @@ -216,6 +220,8 @@ off(type: 'enableChange', callback?: Callback<boolean>): void; Disables listening for the enabled status changes of captions configuration. This API uses an asynchronous callback to return the result. +**System capability**: SystemCapability.BarrierFree.Accessibility.Hearing + **Parameters** | Name | Type | Mandatory | Description | @@ -242,6 +248,8 @@ off(type: 'styleChange', callback?: Callback<CaptionsStyle>): void; Disables listening for captions style changes. This API uses an asynchronous callback to return the result. +**System capability**: SystemCapability.BarrierFree.Accessibility.Hearing + **Parameters** | Name | Type | Mandatory | Description | @@ -573,7 +581,7 @@ on(type: 'accessibilityStateChange', callback: Callback<boolean>): void Enables listening for the enabled status changes of the accessibility application. This API uses an asynchronous callback to return the result. - +**System capability**: SystemCapability.BarrierFree.Accessibility.Core **Parameters** @@ -600,7 +608,7 @@ on(type: 'touchGuideStateChange', callback: Callback<boolean>): void Enables listening for the enabled status changes of the touch guide mode. This API uses an asynchronous callback to return the result. - +**System capability**: SystemCapability.BarrierFree.Accessibility.Vision **Parameters** @@ -627,13 +635,13 @@ off(type: 'accessibilityStateChange', callback?: Callback<boolean>): void Disables listening for the enabled status changes of the accessibility application. This API uses an asynchronous callback to return the result. - +**System capability**: SystemCapability.BarrierFree.Accessibility.Core **Parameters** | Name | Type | Mandatory | Description | | -------- | ----------------------- | ---- | ---------------------------------------- | -| type | string | No | Type of the event to listen for, which is set to **'accessibilityStateChange'** in this API.| +| type | string | Yes | Type of the event to listen for, which is set to **'accessibilityStateChange'** in this API.| | callback | Callback<boolean> | No | Callback for the event. | **Example** @@ -654,13 +662,13 @@ off(type: 'touchGuideStateChange', callback?: Callback<boolean>): void Disables listening for the enabled status changes of the touch guide mode. This API uses an asynchronous callback to return the result. - +**System capability**: SystemCapability.BarrierFree.Accessibility.Core **Parameters** | Name | Type | Mandatory | Description | | -------- | ----------------------- | ---- | ---------------------------------------- | -| type | string | No | Type of the event to listen for, which is set to **'touchGuideStateChange'** in this API.| +| type | string | Yes | Type of the event to listen for, which is set to **'touchGuideStateChange'** in this API.| | callback | Callback<boolean> | No | Callback for the event. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md index 0217f6d04cb40c4048170fc7e69a2a63c0231bc2..334d1f36db45e2ad9c5fc4aa15748bc05b579de8 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md @@ -64,8 +64,14 @@ Enumerates the reasons for the last exit. You can use it together with [onCreate | Name | Value | Description | | ----------------------------- | ---- | ------------------------------------------------------------ | | UNKNOWN | 0 | Unknown reason.| -| ABILITY_NOT_RESPONDING | 1 | The ability does not respond.| -| NORMAL | 2 | The ability exits normally.| +| ABILITY_NOT_RESPONDING | 1 | The ability does not respond. This enum is supported since API version 9 and deprecated since API version 10. You are advised to use **APP_FREEZE**.| +| NORMAL | 2 | The ability exits normally because the user closes the application.| +| CPP_CRASH10+ | 3 | The ability exits due to abnormal signals on the local host.| +| JS_ERROR10+ | 4 | The ability exits due to a JS_ERROR fault triggered when an application has a JS syntax error that is not captured by developers.| +| APP_FREEZE10+ | 5 | The ability exits because watchdog detects that the application is frozen.| +| PERFORMANCE_CONTROL10+ | 6 | The ability exits due to system performance problems, for example, insufficient device memory.| +| RESOURCE_CONTROL10+ | 7 | The ability exits because the system resource usage (CPU, I/O, or memory usage) exceeds the upper limit.| +| UPGRADE10+ | 8 | The ability exits due to an update.| **Example** @@ -218,3 +224,24 @@ class MyAbility extends UIAbility { } } ``` + +## AbilityConstant.ContinueState10+ + +Enumerates the mission continuation states of the application. It is used in the [setMissionContinueState](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissioncontinuestate10) API of [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ------------- | --------- | ------------------------------------------------------------ | +| ACTIVE | 0 | Mission continuation is activated for the current application. | +| INACTIVE | 1 | Mission continuation is not activated for the current application. | + +**Example** + +```ts + import AbilityConstant from '@ohos.app.ability.AbilityConstant'; + + this.context.setMissionContinueState(AbilityConstant.ContinueState.INACTIVE, (result) => { + console.info(`setMissionContinueState: ${JSON.stringify(result)}`); + }); +``` diff --git a/en/application-dev/reference/apis/js-apis-appAccount-authorizationExtensionAbility.md b/en/application-dev/reference/apis/js-apis-appAccount-authorizationExtensionAbility.md new file mode 100644 index 0000000000000000000000000000000000000000..dd40fcecca457706871fa85fd8ed4dded9734d67 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-appAccount-authorizationExtensionAbility.md @@ -0,0 +1,70 @@ +# @ohos.account.appAccount.AuthorizationExtensionAbility (App AuthorizationExtensionAbility) + +The **AuthorizationExtensionAbility** module provides APIs for implementing authorization to app accounts based on the ExtensionAbility framework. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```ts +import AuthorizationExtensionAbility, { AuthorizationRequest, AuthorizationCallback } from '@ohos.account.appAccount.AuthorizationExtensionAbility'; +``` + +## AuthorizationRequest + +Defines the app account authorization request. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Account.AppAccount + +| Name | Type | Readable| Writable| Description | +| --------- | ------------------------------- | ---- | ---- | ------------------------------------ | +| callerUid | number | Yes | No | UID of the caller.| +| parameters | [appAccount.AccountCapabilityRequest](js-apis-appAccount.md#accountcapabilityrequest10) | Yes | No | Service parameters.| + +## AuthorizationCallback + +Provides callbacks to be invoked during the app account authorization. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Account.AppAccount + +| Name | Type | Readable| Writable| Description | +| --------- | ------------------------------- | ---- | ---- | ------------------------------------ | +| onResult | AsyncCallback<[appAccount.AccountCapabilityResponse](js-apis-appAccount.md#accountcapabilityresponse10), { [key: string]: object }> | Yes | No | Callback invoked to return the authorization result.| + +## AuthorizationExtensionAbility.onStartAuthorization + +onStartAuthorization(request: AuthorizationRequest, callback: AuthorizationCallback): void + +Called when an authorization request is received. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------------------- | +| request | [AuthorizationRequest](#authorizationrequest) | Yes | Authorization request information.| +| callback | [AuthorizationCallback](#authorizationcallback) | Yes | Authorization callback object.| + +**Example** + +```ts +class MyAuthorizationExtensionAbility extends AuthorizationExtensionAbility { + onStartAuthorization(request: AuthorizationRequest, callback: AuthorizationCallback) { + console.log('onStartAuthorization, callerUid: ' + request.callerUid + ', parameters: ' + request.parameters); + let response = { + name: 'xxxx', + scopes: ['xxx', 'xxx'] + }; + callback.onResult(null, response); + } +}; +``` diff --git a/en/application-dev/reference/apis/js-apis-appAccount.md b/en/application-dev/reference/apis/js-apis-appAccount.md index 6bb26ca37ab1d320d904cdaa17c5a100291f322c..ddf515f985c2f34bad319ddceb564307f73f1b95 100644 --- a/en/application-dev/reference/apis/js-apis-appAccount.md +++ b/en/application-dev/reference/apis/js-apis-appAccount.md @@ -132,7 +132,7 @@ Creates an app account with custom data. This API uses a promise to return the r | Name | Type | Mandatory | Description | | --------- | ------ | ---- | ---------------------------------------- | | name | string | Yes | Name of the app account to create. | -| options | [CreateAccountOptions](#createaccountoptions9) | No | Options for creating the app account. You can customize data based on service requirements, but do not add sensitive data (such as passwords and tokens).
By default, no value is passed, which means no additional information needs to be added for the account.| +| options | [CreateAccountOptions](#createaccountoptions9) | No | Options for creating the app account. You can customize data based on service requirements, but do not add sensitive data (such as passwords and tokens).
By default, no value is passed, which means no additional information needs to be added for the account.| **Return value** @@ -730,7 +730,7 @@ Sets a credential for an app account. This API uses an asynchronous callback to | ID| Error Message| | ------- | -------| | 12300001 | System service exception. | -| 12300002 | Invalid name or credentialType or credential. | +| 12300002 | Invalid name, credentialType, or credential. | | 12300003 | Account not found. | **Example** @@ -776,7 +776,7 @@ Sets a credential for an app account. This API uses a promise to return the resu | ID| Error Message| | ------- | -------| | 12300001 | System service exception. | -| 12300002 | Invalid name or credentialType or credential. | +| 12300002 | Invalid name, credentialType, or credential. | | 12300003 | Account not found. | **Example** @@ -2780,7 +2780,7 @@ Adds an app account name and additional information. This API uses an asynchrono | Name | Type | Mandatory | Description | | --------- | ------ | ---- | ---------------------------------------- | | name | string | Yes | Name of the target app account. | -| extraInfo | string | No | Additional information (information that can be converted to the string type).
The additional information cannot be sensitive information (such as the password and token) of the app account.
By default, no value is passed, which means no additional information needs to be added for the account.| +| extraInfo | string | No | Additional information (information that can be converted to the string type).
The additional information cannot be sensitive information (such as the password and token) of the app account.
By default, no value is passed, which means no additional information needs to be added for the account.| **Return value** @@ -4982,3 +4982,298 @@ Obtains the remote object of an authenticator. This API cannot be overloaded. } } ``` + +## AccountCapabilityType10+ + +Enumerates the account capability types. + +**System capability**: SystemCapability.Account.AppAccount + +| Name | Value | Description | +| ---------------- | ----- | ----------------------- | +| AUTHORIZATION | 1 | Authorization capability. | + +## AccountCapabilityProvider10+ + +Represents the **AccountCapabilityProvider** class. + +### Attributes + +**System capability**: SystemCapability.Account.AppAccount + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| capabilityType | [AccountCapabilityType](#accountcapabilitytype10) | Yes| No| Capability type of the account.| + +### constructor10+ + +constructor(capabilityType: AccountCapabilityType) + +A constructor used to create an **AccountCapabilityProvider** instance. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------- | +| capabilityType | [AccountCapabilityType](#accountcapabilitytype10) | Yes | Capability type of the account. | + +**Example** + +```ts +class MyAuthorizationProvider extends account_appAccount.AccountCapabilityProvider { + constructor() { + super(account_appAccount.AccountCapabilityType.AUTHORIZATION); + } +} + +try { + let provider = new MyAuthorizationProvider(); + if (provider instanceof account_appAccount.AccountCapabilityProvider) { + console.log("the provider is an instance of AccountCapabilityProvider"); + } +} catch (err) { + console.error('catch error: ' + JSON.stringify(err)); +} +``` + +## AccountCapabilityRequest10+ + +Represents the **AccountCapabilityRequest** class. + +### constructor10+ + +constructor(provider: AccountCapabilityProvider) + +A constructor used to create an **AccountCapabilityRequest** instance. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------- | +| provider | [AccountCapabilityProvider](#accountcapabilityprovider10) | Yes | Provider of the account capability. | + +**Example** + +```ts +class MyAuthorizationProvider extends account_appAccount.AccountCapabilityProvider { + constructor() { + super(account_appAccount.AccountCapabilityType.AUTHORIZATION); + } +} + +class MyAuthorizationRequest extends account_appAccount.AccountCapabilityRequest { + constructor() { + let provider = new MyAuthorizationProvider(); + super(provider); + } +} + +try { + let request = new MyAuthorizationRequest(); + if (request instanceof account_appAccount.AccountCapabilityRequest) { + console.log("the request is an instance of AccountCapabilityRequest"); + } +} catch (err) { + console.error('catch error: ' + JSON.stringify(err)); +} +``` + +## AccountCapabilityResponse10+ + +Represents the **AccountCapabilityResponse** class. + +### Attributes + +**System capability**: SystemCapability.Account.AppAccount + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| request | [AccountCapabilityRequest](#accountcapabilityrequest10) | Yes| No| Account capability request corresponding to the response.| + +### constructor10+ + +constructor(request: AccountCapabilityRequest) + +A constructor used to create an **AccountCapabilityResponse** instance. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------- | +| request | [AccountCapabilityRequest](#accountcapabilityrequest10) | Yes | Account capability request corresponding to the response.| + +**Example** + +```ts +class MyAuthorizationProvider extends account_appAccount.AccountCapabilityProvider { + constructor() { + super(account_appAccount.AccountCapabilityType.AUTHORIZATION); + } +} + +class MyAuthorizationRequest extends account_appAccount.AccountCapabilityRequest { + constructor() { + let provider = new MyAuthorizationProvider(); + super(provider); + } +} + +class MyAuthorizationResponse extends account_appAccount.AccountCapabilityResponse { + constructor(request) { + super(request) + } +} + +try { + let request = new MyAuthorizationRequest(); + let response = new MyAuthorizationResponse(request); + if (response instanceof account_appAccount.AccountCapabilityResponse) { + console.log("the response is an instance of AccountCapabilityResponse"); + } +} catch (err) { + console.error('catch error: ' + JSON.stringify(err)); +} +``` + +## AuthorizationProviderInfo10+ + +Defines information about the authorization provider. + +**System capability**: SystemCapability.Account.AppAccount + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | --- | ---------- | +| bundleName | string | Yes| No| Bundle name of the authorization provider.| +| abilityName | string | Yes| No| Ability name of the authorization provider.| + +## AuthorizationProvider10+ + +Represents the **AuthorizationProvider** class. + +### constructor10+ + +constructor(info: AuthorizationProviderInfo) + +A constructor used to create an **AuthorizationProvider** instance. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------- | +| info | [AuthorizationProviderInfo](#authorizationproviderinfo10) | Yes | Information about the authorization provider.| + +**Example** + +```ts +class MyAuthorizationProvider extends account_appAccount.AuthorizationProvider { + constructor() { + super({bundleName: 'xxx', abilityName: 'xxx'}); + } +} + +try { + let provider = new MyAuthorizationProvider(); + if (provider instanceof account_appAccount.AuthorizationProvider) { + console.log("the provider is an instance of AuthorizationProvider"); + } +} catch (err) { + console.error("catch error: " + JSON.stringify(err)); +} +``` + +## AccountCapabilityScheduler10+ + +Represents the **AccountCapabilityScheduler** class. + +### executeRequest10+ + +executeRequest(request: AccountCapabilityRequest, callback: AsyncCallback<AccountCapabilityResponse, { [key: string]: object }>): void + +Executes an account capability request. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ------------------------- | ---- | ------------------------- | +| request | [AccountCapabilityRequest](#accountcapabilityrequest10) | Yes | Account capability request to execute. | +| callback | AsyncCallback<[AccountCapabilityResponse](#accountcapabilityresponse10), { [key: string]: object }> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object. | + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid request. | + +**Example** + +```ts +let scheduler = new account_appAccount.AccountCapabilityScheduler(); +let provider = new account_appAccount.AuthorizationProvider({ bundleName: 'xxx', abilityName: 'xxx' }); +let request = new account_appAccount.AccountCapabilityRequest(provider); +try { + scheduler.executeRequest(request, (err, response) => { + if (err != null) { + console.log('executeRequest failed, error: ' + JSON.stringify(err)); + } else { + console.log('executeRequest response: ' + JSON.stringify(response)); + } + }); +} catch (err) { + console.log('executeRequest exception: ' + JSON.stringify(err)); +} +``` + +### executeRequest10+ + +executeRequest(request: AccountCapabilityRequest): Promise<AccountCapabilityResponse> + +Executes an account capability request. This API uses a promise to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ------- | ---- | ------------ | +| request | [AccountCapabilityRequest](#accountcapabilityrequest10) | Yes | Account capability request to execute.| + +**Return value** + +| Type | Description | +| ------------------- | --------------------- | +| Promise<[AccountCapabilityResponse](#accountcapabilityresponse10)> | Promise used to return the result. | + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid request. | + +**Example** + +```ts +let scheduler = new account_appAccount.AccountCapabilityScheduler(); +let provider = new account_appAccount.AuthorizationProvider({ bundleName: 'xxx', abilityName: 'xxx' }); +let request = new account_appAccount.AccountCapabilityRequest(provider); +try { + scheduler.executeRequest(request).then((response) => { + console.log('executeRequest response: ' + JSON.stringify(response)); + }).catch((err) => { + console.log('executeRequest failed, error: ' + JSON.stringify(err)); + }); +} catch (err) { + console.log('executeRequest exception: ' + JSON.stringify(err)); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md index f90ebe121ecd896a3f63425ec1b7f79d277c7d8e..6691b47577dae3f00b30cda0b70b6725b5ea9495 100644 --- a/en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md @@ -1,6 +1,6 @@ -# @ohos.application.DataShareExtensionAbility (DataShare Extension Ability) +# @ohos.application.DataShareExtensionAbility (DataShare ExtensionAbility) -The **DataShareExtensionAbility** module provides data share services based on the Extension ability. +The **DataShareExtensionAbility** module provides data share services based on the ExtensionAbility. >**NOTE** > @@ -23,7 +23,7 @@ import DataShareExtensionAbility from '@ohos.application.DataShareExtensionAbili | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| context | [ExtensionContext](js-apis-inner-application-extensionContext.md) | Yes| No|Context of the DataShare Extension ability.| +| context10+ | [ExtensionContext](js-apis-inner-application-extensionContext.md) | Yes| No|DataShareExtensionAbility context, inherited from [ExtensionContext](js-apis-inner-application-extensionContext.md).| ## onCreate @@ -215,7 +215,7 @@ Queries data from the database. This API can be overridden as required. | uri | string | Yes | URI of the data to query.| | predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for querying data.| | columns | Array<string> | Yes| Columns to query. If this parameter is empty, all columns will be queried.| -| callback | AsyncCallback<Object> | Yes| Callback invoked to return the result set.| +| callback | AsyncCallback<Object> | Yes| Callback invoked to return the result set obtained.| **Example** @@ -275,18 +275,17 @@ let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS ' let rdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { - batchInsert(uri, valueBuckets, callback) { - if (valueBuckets === null || valueBuckets.length === undefined) { - console.error('invalid valueBuckets'); - return; - } - rdbStore.batchInsert(TBL_NAME, valueBuckets, function (err, ret) { - if (callback !== undefined) { - callback(err, ret); - } - }); - }); + batchInsert(uri, valueBuckets, callback) { + if (valueBuckets === null || valueBuckets.length === undefined) { + console.error('invalid valueBuckets'); + return; } + rdbStore.batchInsert(TBL_NAME, valueBuckets, function (err, ret) { + if (callback !== undefined) { + callback(err, ret); + } + }); + }; }; ``` diff --git a/en/application-dev/reference/apis/js-apis-bundleManager.md b/en/application-dev/reference/apis/js-apis-bundleManager.md index f6a93974ae9bd73a144b93b42213720ebdad228f..0b869f14bb861a49f54cd2a7ef79976bedb7a84b 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager.md @@ -20,6 +20,7 @@ import bundleManager from '@ohos.bundle.bundleManager'; | ohos.permission.GET_BUNDLE_INFO_PRIVILEGED| system_basic | Permission to query information about all bundles.| | ohos.permission.REMOVE_CACHE_FILES | system_basic | Permission to clear cache files of a bundle. | |ohos.permission.CHANGE_ABILITY_ENABLED_STATE| system_basic | Permission to enable or disable an application or ability. | +| ohos.permission.GET_INSTALLED_BUNDLE_LIST | system_basic | Permission to read installed application list.| For details, see [Permission Levels](../../security/accesstoken-overview.md#permission-levels). @@ -115,7 +116,7 @@ Enumerates the types of Extension abilities. | PRINT10+ | 15 | PrintExtensionAbility: provides APIs for printing images. Printing documents is not supported yet.| | PUSH10+ | 17 | PushExtensionAbility: provides APIs for pushing scenario-specific messages. This ability is reserved.| | DRIVER10+ | 18 | DriverExtensionAbility: provides APIs for the peripheral driver. This type of ability is not supported yet.| -| APP_ACCOUNT_AUTHORIZATION10+ | 19 | AuthorizationExtensionAbility: provides APIs to process authorization requests for application accounts and allow account authorization from a third-party (relative to the operating system vendor) ecosystem platform.| +| APP_ACCOUNT_AUTHORIZATION10+ | 19 | [AuthorizationExtensionAbility](js-apis-appAccount-authorizationExtensionAbility.md): provides APIs to process authorization requests for application accounts and allow account authorization from a third-party (relative to the operating system vendor) ecosystem platform.| | UNSPECIFIED | 255 | No type is specified. It is used together with **queryExtensionAbilityInfo** to query all types of Extension abilities.| @@ -677,7 +678,7 @@ Obtains the information about all bundles based on the given bundle flags and us **System API**: This is a system API. -**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED +**Required permissions**: ohos.permission.GET_INSTALLED_BUNDLE_LIST **System capability**: SystemCapability.BundleManager.BundleFramework.Core @@ -726,7 +727,7 @@ Obtains the information about all bundles based on the given bundle flags. This **System API**: This is a system API. -**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED +**Required permissions**: ohos.permission.GET_INSTALLED_BUNDLE_LIST **System capability**: SystemCapability.BundleManager.BundleFramework.Core @@ -765,7 +766,7 @@ Obtains the information about all bundles based on the given bundle flags and us **System API**: This is a system API. -**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED +**Required permissions**: ohos.permission.GET_INSTALLED_BUNDLE_LIST **System capability**: SystemCapability.BundleManager.BundleFramework.Core @@ -816,7 +817,7 @@ Obtains the information about all applications based on the given application fl **System API**: This is a system API. -**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED +**Required permissions**: ohos.permission.GET_INSTALLED_BUNDLE_LIST **System capability**: SystemCapability.BundleManager.BundleFramework.Core @@ -865,7 +866,7 @@ Obtains the information about all applications based on the given application fl **System API**: This is a system API. -**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED +**Required permissions**: ohos.permission.GET_INSTALLED_BUNDLE_LIST **System capability**: SystemCapability.BundleManager.BundleFramework.Core @@ -904,7 +905,7 @@ Obtains the information about all applications based on the given application fl **System API**: This is a system API. -**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED +**Required permissions**: ohos.permission.GET_INSTALLED_BUNDLE_LIST **System capability**: SystemCapability.BundleManager.BundleFramework.Core @@ -1752,7 +1753,7 @@ Enables or disables an ability. This API uses an asynchronous callback to return | Name | Type | Mandatory| Description | | -------- | ----------- | ---- | ------------------------------------- | | info | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | Yes | Information about the target ability. | -| isEnabled| boolean | Yes | Whether to enable the ability. The value **true** means to enable the ability, and **false** means to disable the ability.| +| isEnabled| boolean | Yes | Whether to enable the ability. The value **true** means to enable the ability, and **false** means to disable the application.| | callback | AsyncCallback\ | Yes| Callback used to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| **Error codes** @@ -1814,7 +1815,7 @@ Enables or disables an ability. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | -------- | ----------- | ---- | ------------------------------------- | | info | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | Yes | Information about the target ability. | -| isEnabled| boolean | Yes | Whether to enable the ability. The value **true** means to enable the ability, and **false** means to disable the ability.| +| isEnabled| boolean | Yes | Whether to enable the ability. The value **true** means to enable the ability, and **false** means to disable the application.| **Return value** @@ -3213,3 +3214,129 @@ try { hilog.error(0x0000, 'testTag', 'getAppProvisionInfo failed. Cause: %{public}s', err.message); } ``` + +### bundleManager.getSpecifiedDistributionType10+ + +getSpecifiedDistributionType(bundleName: string): string; + +Obtains the distribution type of a bundle in synchronous mode. The return value is the **specifiedDistributionType** field value in [InstallParam](./js-apis-installer.md#installparam) passed when **install** is called. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ----------------------------------- | ---- | ---------------------------- | +| bundleName | string | Yes | Bundle name.| + +**Return value** + +| Type | Description | +| ------------- | -------------------------------------- | +| string | Distribution type of the bundle.| + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17700001 | The specified bundleName is not found. | + +**Example** +```ts +import bundleManager from '@ohos.bundle.bundleManager'; +let bundleName = "com.example.myapplication"; + +try { + let type = bundleManager.getSpecifiedDistributionType(bundleName); + console.info('getSpecifiedDistributionType successfully, type:' + type); +} catch (error) { + console.error('getSpecifiedDistributionType failed. Cause: ' + error.message); +} +``` + + +### bundleManager.getAdditionalInfo10+ + +getAdditionalInfo(bundleName: string): string; + +Obtains additional information about a bundle in synchronous mode. The return value is the **additionalInfo** field value in [InstallParam](./js-apis-installer.md#installparam) passed when **install** is called. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ----------------------------------- | ---- | ---------------------------- | +| bundleName | string | Yes | Bundle name.| + +**Return value** + +| Type | Description | +| ------------- | -------------------------------------- | +| string | Additional information about the bundle.| + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17700001 | The specified bundleName is not found. | + +**Example** + +```ts +import bundleManager from '@ohos.bundle.bundleManager'; +let bundleName = "com.example.myapplication"; + +try { + let info = bundleManager.getAdditionalInfo(bundleName); + console.info('getAdditionalInfo successfully, additionInfo:' + info); +} catch (error) { + console.error('getAdditionalInfo failed. Cause: ' + error.message); +} +``` + +### bundleManager.getBundleInfoForSelfSync10+ + +getBundleInfoForSelfSync(bundleFlags: number): BundleInfo; + +Obtains the bundle information of this bundle based on the given bundle flags in synchronous mode. + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | --------------------- | +| bundleFlags | [number](#bundleflag) | Yes | Type of the bundle information to obtain.| + +**Return value** + +| Type | Description | +| ------------------------------------------------- | -------------------- | +| [BundleInfo](js-apis-bundleManager-bundleInfo.md) | Bundle information obtained.| + +**Example** + +```ts +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; +let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION; +try { + let data = bundleManager.getBundleInfoForSelfSync(bundleFlags); + hilog.info(0x0000, 'testTag', 'getBundleInfoForSelfSync successfully: %{public}s', JSON.stringify(data)); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getBundleInfoForSelfSync failed: %{public}s', err.message); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-cert.md b/en/application-dev/reference/apis/js-apis-cert.md index 9b4aac5ba2690b202ed83cf6386fff3394017ca3..bd2479de2399427cab87c95afe13d1d71e4d5956 100644 --- a/en/application-dev/reference/apis/js-apis-cert.md +++ b/en/application-dev/reference/apis/js-apis-cert.md @@ -1,6 +1,6 @@ # @ohos.security.cert (Certificate) -The **certificate** module provides APIs for performing certificate operations. For details about the APIs for implementing the basic algorithm capabilities based on the cryptographic (crypto) framework, see [Crypto Framework](js-apis-cryptoFramework.md). +The certificate algorithm library framework provides certificate-related APIs. For details about the APIs for implementing the basic algorithm capabilities based on the cryptographic (crypto) framework, see [Crypto Framework](js-apis-cryptoFramework.md). > **NOTE** > @@ -59,6 +59,43 @@ Defines a list of data arrays. | FORMAT_DER | 0 | Distinguished Encoding Rules (DER) format.| | FORMAT_PEM | 1 | Privacy-Enhanced Mail (PEM) format.| +## CertItemType10+ + + Enumerates the certificate fields that can be obtained. + + **System capability**: SystemCapability.Security.Cert + +| Name | Value | Description | +| -------------------------------- | ---- | ------------------------------ | +| CERT_ITEM_TYPE_TBS | 0 | Information to be signed. | +| CERT_ITEM_TYPE_PUBLIC_KEY | 1 | Public key of the certificate. | +| CERT_ITEM_TYPE_ISSUER_UNIQUE_ID | 2 | Unique ID of the certificate issuer.| +| CERT_ITEM_TYPE_SUBJECT_UNIQUE_ID | 3 | Unique ID of the certificate subject. | +| CERT_ITEM_TYPE_EXTENSIONS | 4 | Certificate extensions, each of which is identified by a unique object identifier (OID). | + +## ExtensionOidType10+ + + Enumerates the OID types of the certificate extensions that can be obtained. + + **System capability**: SystemCapability.Security.Cert + +| Name | Value | Description | +| ----------------------------- | ---- | --------------------------------------------- | +| EXTENSION_OID_TYPE_ALL | 0 | All object identifiers. | +| EXTENSION_OID_TYPE_CRITICAL | 1 | Object identifier whose **critical** is **true**. | +| EXTENSION_OID_TYPE_UNCRITICAL | 2 | Object identifier whose **critical** is **false**.| + +## ExtensionEntryType10+ + + Enumerates the object types in certificate extensions that can be obtained. + + **System capability**: SystemCapability.Security.Cert + +| Name | Value | Description | +| ----------------------------------- | ---- | ---------------------------- | +| EXTENSION_ENTRY_TYPE_ENTRY | 0 | Entire object. | +| EXTENSION_ENTRY_TYPE_ENTRY_CRITICAL | 1 | Critical attribute of the object.| +| EXTENSION_ENTRY_TYPE_ENTRY_VALUE | 2 | Data of the object. | ## EncodingBlob @@ -99,16 +136,16 @@ Creates an **X509Cert** instance. This API uses an asynchronous callback to retu **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------- | ---- | -------------------------- | -| inStream | [EncodingBlob](#encodingblob) | Yes | X.509 certificate serialization data. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. **X509Cert** instance created.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | -------------------------- | +| inStream | [EncodingBlob](#encodingblob) | Yes | X.509 certificate serialization data. | +| callback | AsyncCallback\<[X509Cert](#x509cert)> | Yes | Callback invoked to return the result. **X509Cert** instance created.| **Error codes** | ID| Error Message | | -------- | ------------- | -| 19020001 | Memory error. | +| 19020001 | memory error. | **Example** @@ -149,13 +186,13 @@ Creates an **X509Cert** instance. This API uses a promise to return the result. | Type | Description | | ------- | ---------------- | -| Promise\ | **X509Cert** instance created.| +| Promise\<[X509Cert](#x509cert)> | **X509Cert** instance created.| **Error codes** | ID| Error Message | | -------- | ------------- | -| 19020001 | Memory error. | +| 19020001 | memory error. | **Example** @@ -184,7 +221,7 @@ Provides APIs for X.509 certificate operations. verify(key : cryptoFramework.PubKey, callback : AsyncCallback\) : void -Verifies the certificate signature. This API uses an asynchronous callback to return the result. +Verifies the signature of an X.509 certificate. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Cert @@ -199,7 +236,7 @@ Verifies the certificate signature. This API uses an asynchronous callback to re | ID| Error Message | | -------- | ------------------ | -| 19030001 | Crypto operation error. | +| 19030001 | crypto operation error. | **Example** @@ -235,7 +272,7 @@ cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { verify(key : cryptoFramework.PubKey) : Promise\ -Verifies the certificate signature. This API uses a promise to return the result. +Verifies the signature of an X.509 certificate. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Cert @@ -255,7 +292,7 @@ Verifies the certificate signature. This API uses a promise to return the result | ID| Error Message | | -------- | ------------------ | -| 19030001 | Crypto operation error. | +| 19030001 | crypto operation error. | **Example** @@ -301,9 +338,9 @@ Obtains the serialized X.509 certificate data. This API uses an asynchronous cal | ID| Error Message | | -------- | ------------------------------------------------- | -| 19020001 | Memory error. | -| 19020002 | Runtime error. | -| 19030001 | Crypto operation error.| +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error.| **Example** @@ -351,9 +388,9 @@ Obtains the serialized X.509 certificate data. This API uses a promise to return | ID| Error Message | | -------- | ------------------------------------------------- | -| 19020001 | Memory error. | -| 19020002 | Runtime error. | -| 19030001 | Crypto operation error.| +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error.| **Example** @@ -397,8 +434,8 @@ Obtains the public key of this X.509 certificate. This API uses an asynchronous | ID| Error Message | | -------- | ------------------------------------------------- | -| 19020001 | Memory error. | -| 19030001 | Crypto operation error.| +| 19020001 | memory error. | +| 19030001 | crypto operation error.| **Example** @@ -446,10 +483,10 @@ Checks the validity period of this X.509 certificate. This API uses an asynchron | ID| Error Message | | -------- | ------------------------------------------------- | -| 19020001 | Memory error. | -| 19030001 | Crypto operation error.| -| 19030003 | The certificate has not taken effect. | -| 19030004 | The certificate has expired.| +| 19020001 | memory error. | +| 19030001 | crypto operation error.| +| 19030003 | the certificate has not taken effect. | +| 19030004 | the certificate has expired.| **Example** @@ -570,9 +607,9 @@ Obtains the X.509 certificate issuer. | ID| Error Message | | -------- | ------------------------------------------------- | -| 19020001 | Memory error. | -| 19020002 | Runtime error. | -| 19030001 | Crypto operation error.| +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error.| **Example** @@ -614,9 +651,9 @@ Obtains the subject of this X.509 certificate. | ID| Error Message | | -------- | ------------------------------------------------- | -| 19020001 | Memory error. | -| 19020002 | Runtime error. | -| 19030001 | Crypto operation error.| +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error.| **Example** @@ -658,9 +695,9 @@ Obtains the start time of this X.509 certificate. | ID| Error Message | | -------- | ------------------------------------------------- | -| 19020001 | Memory error. | -| 19020002 | Runtime error. | -| 19030001 | Crypto operation error.| +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error.| **Example** @@ -702,9 +739,9 @@ Obtains the expiration time of this X.509 certificate. | ID| Error Message | | -------- | ------------------------------------------------- | -| 19020001 | Memory error. | -| 19020002 | Runtime error. | -| 19030001 | Crypto operation error.| +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error.| **Example** @@ -746,9 +783,9 @@ Obtains the signature data of this X.509 certificate. | ID| Error Message | | -------- | ------------------------------------------------- | -| 19020001 | Memory error. | -| 19020002 | Runtime error. | -| 19030001 | Crypto operation error.| +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error.| **Example** @@ -790,9 +827,9 @@ Obtains the signing algorithm of this X.509 certificate. | ID| Error Message | | -------- | ------------------------------------------------- | -| 19020001 | Memory error. | -| 19020002 | Runtime error. | -| 19030001 | Crypto operation error.| +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error.| **Example** @@ -834,9 +871,9 @@ Obtains the object identifier (OID) of the X.509 certificate signing algorithm. | ID| Error Message | | -------- | ------------------------------------------------- | -| 19020001 | Memory error. | -| 19020002 | Runtime error. | -| 19030001 | Crypto operation error.| +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error.| **Example** @@ -878,9 +915,9 @@ Obtains the signing algorithm parameters of this X.509 certificate. | ID| Error Message | | -------- | ------------------------------------------------- | -| 19020001 | Memory error. | -| 19020002 | Runtime error. | -| 19030001 | Crypto operation error.| +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error.| **Example** @@ -922,8 +959,8 @@ Obtains the key usage of this X.509 certificate. | ID| Error Message | | -------- | ------------------------------------------------- | -| 19020001 | Memory error. | -| 19030001 | Crypto operation error.| +| 19020001 | memory error. | +| 19030001 | crypto operation error.| **Example** @@ -965,9 +1002,9 @@ Obtains the usage of the extended key of this X.509 certificate. | ID| Error Message | | -------- | ------------------------------------------------- | -| 19020001 | Memory error. | -| 19020002 | Runtime error. | -| 19030001 | Crypto operation error.| +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error.| **Example** @@ -1045,9 +1082,9 @@ Obtains the Subject Alternative Names (SANs) of this X.509 certificate. | ID| Error Message | | -------- | ------------------------------------------------- | -| 19020001 | Memory error. | -| 19020002 | Runtime error. | -| 19030001 | Crypto operation error.| +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error.| **Example** @@ -1089,9 +1126,9 @@ Obtains the Issuer Alternative Names (IANs) of this X.509 certificate. | ID| Error Message | | -------- | ------------------------------------------------- | -| 19020001 | Memory error. | -| 19020002 | Runtime error. | -| 19030001 | Crypto operation error.| +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error.| **Example** @@ -1115,6 +1152,336 @@ cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { }); ``` +### getItem10+ + +getItem(itemType: CertItemType) : DataBlob + +Obtains the fields in the X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | ----------------------------------------- | +| [DataBlob](#datablob) | Returns the obtained fields in DER format.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let tbs = x509Cert.getItem(cryptoCert.CertItemType.CERT_ITEM_TYPE_TBS); + let pubKey = x509Cert.getItem(cryptoCert.CertItemType.CERT_ITEM_TYPE_PUBLIC_KEY); + } +}); +``` + +## cryptoCert.createCertExtension10+ + +createCertExtension(inStream : EncodingBlob, callback : AsyncCallback\) : void + +Creates a **CertExtension** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------- | ---- | -------------------------- | +| inStream | [EncodingBlob](#encodingblob) | Yes | Serialized data of the certificate extension.| +| callback | AsyncCallback\<[CertExtension](#certextension10)> | Yes | Callback invoked to return the **CertExtension** instance created.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------- | +| 19020001 | memory error. | + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the certificate extension, which needs to be assigned by the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Assign a value based on the encodingData format. Currently, only FORMAT_DER is supported. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_DER +}; +cryptoCert.createCertExtension(encodingBlob, function (error, certExt) { + if (error != null) { + console.log("createCertExtension failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createCertExtension success"); + } +}); +``` + +## cryptoCert.createCertExtension10+ + +createCertExtension(inStream : EncodingBlob) : Promise\ + +Creates a **CertExtension** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | -------------------------- | +| inStream | [EncodingBlob](#encodingblob) | Yes | Serialized data of the certificate extension.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | -------------------- | +| Promise\<[CertExtension](#certextension10)> | Promise used to return the **CertExtension** instance created.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------- | +| 19020001 | memory error. | + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the certificate extension, which needs to be assigned by the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Assign a value based on the encodingData format. Currently, only FORMAT_DER is supported. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_DER +}; +cryptoCert.createCertExtension(encodingBlob).then(certExt => { + console.log("createCertExtension success"); +}, error => { + console.log("createCertExtension failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +## CertExtension10+ + +Provides APIs for operating the certificate extensions. + +### getEncoded10+ + +getEncoded() : EncodingBlob + +Obtains the serialized data of the certificate extensions. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ----------------------------- | ---------------------------- | +| [EncodingBlob](#encodingblob) | Returns the serialized data obtained.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the certificate extension, which needs to be assigned by the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Assign a value based on the encodingData format. Currently, only FORMAT_DER is supported. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_DER +}; +cryptoCert.createCertExtension(encodingBlob, function (error, certExt) { + if (error != null) { + console.log("createCertExtension failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createCertExtension success"); + let encodingBlob = certExt.getEncoded() + } +}); +``` + +### getOidList10+ + +getOidList(valueType : ExtensionOidType) : DataArray + +Obtains the OIDs of the certificate extensions. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------- | ---- | ------------------------------ | +| valueType | [ExtensionOidType](#extensionoidtype) | Yes | Type of the OIDs to obtain.| + +**Return value** + +| Type | Description | +| ----------------------- | -------------------------------- | +| [DataArray](#dataarray) | Returns a list of the OIDs obtained.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the certificate extension, which needs to be assigned by the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Assign a value based on the encodingData format. Currently, only FORMAT_DER is supported. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_DER +}; +cryptoCert.createCertExtension(encodingBlob, function (error, certExt) { + if (error != null) { + console.log("createCertExtension failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createCertExtension success"); + let oidList = certExt.getOidList(cryptoCert.ExtensionOidType.EXTENSION_OID_TYPE_ALL) + } +}); +``` + +### getEntry10+ + +getEntry(valueType: ExtensionEntryType, oid : DataBlob) : DataBlob + +Obtains the certificate extension object information. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ----------------------------------------- | ---- | -------------------------------- | +| valueType | [ExtensionEntryType](#extensionentrytype) | Yes | Type of the information to obtain. | +| oid | [DataBlob](#datablob) | Yes | OID of the certificate extension to obtain.| + +**Return value** + +| Type | Description | +| --------------------- | ---------------------------- | +| [DataBlob](#datablob) | Returns the certificate extension object information obtained.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the certificate extension, which needs to be assigned by the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Assign a value based on the encodingData format. Currently, only FORMAT_DER is supported. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_DER +}; +cryptoCert.createCertExtension(encodingBlob, function (error, certExt) { + if (error != null) { + console.log("createCertExtension failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createCertExtension success"); + let oid = new Uint8Array([0x31, 0x2e, 0x32, 0x2e, 0x38, 0x2e, 0x31]) + let oidBlob = { + data: oid + } + let entry = certExt.getEntry(cryptoCert.ExtensionEntryType.EXTENSION_ENTRY_TYPE_ENTRY, oidBlob) + } +}); +``` + + +### checkCA10+ + +checkCA() : number + +Checks whether the certificate is a CA certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ------------------------------------------------------------ | +| number | If the key purpose in the certificate extension contains signing and the CA field in the basic constraints is **true**, the certificate is a CA certificate.
Returns **-1** if the certificate is not a CA certificate; returns the path length in the basic constraints otherwise.
Returns **-2** if the certificate is a CA certificate but the path length is not specified in the basic constraints, which means the path length is not limited. | + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------- | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the certificate extension, which needs to be assigned by the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Assign a value based on the encodingData format. Currently, only FORMAT_DER is supported. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_DER +}; +cryptoCert.createCertExtension(encodingBlob, function (error, certExt) { + if (error != null) { + console.log("createCertExtension failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createCertExtension success"); + let res = certExt.checkCA() + } +}); +``` + ## cryptoCert.createX509Crl createX509Crl(inStream : EncodingBlob, callback : AsyncCallback\) : void @@ -1125,16 +1492,16 @@ Creates an **X509Crl** instance. This API uses an asynchronous callback to retur **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------- | ---- | ------------------------------ | -| inStream | [EncodingBlob](#encodingblob) | Yes | Serialized certificate revocation list (CRL) data. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. Promise used to return the **X509Crl** instance created.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | ------------------------------ | +| inStream | [EncodingBlob](#encodingblob) | Yes | Serialized certificate revocation list (CRL) data. | +| callback | AsyncCallback\<[X509Crl](#x509crl)> | Yes | Callback invoked to return the result. Promise used to return the **X509Crl** instance created.| **Error codes** | ID| Error Message | | -------- | ------------- | -| 19020001 | Memory error. | +| 19020001 | memory error. | **Example** @@ -1173,15 +1540,15 @@ Creates an **X509Crl** instance. This API uses a promise to return the result. **Return value** -| Type | Description | -| ----------------- | -------------------- | -| Promise\ | Promise used to return the **X509Crl** instance created.| +| Type | Description | +| ----------------------------- | -------------------- | +| Promise\<[X509Crl](#x509crl)> | Promise used to return the **X509Crl** instance created.| **Error codes** | ID| Error Message | | -------- | ------------- | -| 19020001 | Memory error. | +| 19020001 | memory error. | **Example** @@ -1308,9 +1675,9 @@ Obtains the serialized X.509 CRL data. This API uses an asynchronous callback to | ID| Error Message | | -------- | ----------------------- | -| 19020001 | Memory error. | -| 19020002 | Runtime error. | -| 19030001 | Crypto operation error. | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | **Example** @@ -1358,9 +1725,9 @@ Obtains the serialized X.509 CRL data. This API uses a promise to return the res | ID| Error Message | | -------- | ----------------------- | -| 19020001 | Memory error. | -| 19020002 | Runtime error. | -| 19030001 | Crypto operation error. | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | **Example** @@ -1405,7 +1772,7 @@ Verifies the signature of the X.509 CRL. This API uses an asynchronous callback | ID| Error Message | | -------- | ----------------------- | -| 19030001 | Crypto operation error. | +| 19030001 | crypto operation error. | **Example** @@ -1462,7 +1829,7 @@ Verifies the signature of the X.509 CRL. This API uses a promise to return the r | ID| Error Message | | -------- | ----------------------- | -| 19030001 | Crypto operation error. | +| 19030001 | crypto operation error. | **Example** @@ -1545,9 +1912,9 @@ Obtains the issuer of the X.509 CRL. | ID| Error Message | | -------- | ----------------------- | -| 19020001 | Memory error. | -| 19020002 | Runtime error. | -| 19030001 | Crypto operation error. | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | **Example** @@ -1589,9 +1956,9 @@ Obtains the date when the X.509 CRL was last updated. | ID| Error Message | | -------- | ----------------------- | -| 19020001 | Memory error. | -| 19020002 | Runtime error. | -| 19030001 | Crypto operation error. | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | **Example** @@ -1633,9 +2000,9 @@ Obtains the date when the CRL will be updated the next time. | ID| Error Message | | -------- | ----------------------- | -| 19020001 | Memory error. | -| 19020002 | Runtime error. | -| 19030001 | Crypto operation error. | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | **Example** @@ -1677,14 +2044,14 @@ Obtains the revoked X.509 certificate based on the specified serial number of th | Type | Description | | ---------------------- | --------------------- | -| X509CrlEntry | Promise used to return the revoked X.509 certificate obtained.| +| [X509CrlEntry](#x509crlentry) | Promise used to return the revoked X.509 certificate obtained.| **Error codes** | ID| Error Message | | -------- | ----------------------- | -| 19020001 | Memory error. | -| 19030001 | Crypto operation error. | +| 19020001 | memory error. | +| 19030001 | crypto operation error. | **Example** @@ -1724,22 +2091,22 @@ Obtains the revoked X.509 certificate based on the specified certificate. This A **Parameters** -| Name| Type | Mandatory| Description | -| ------ | -------- | ---- | ------------ | -| cert | X509Cert | Yes | Certificate based on which the revoked certificate is obtained.| +| Name| Type | Mandatory| Description | +| ------ | --------------------- | ---- | ------------ | +| cert | [X509Cert](#x509cert) | Yes | Certificate based on which the revoked certificate is obtained.| **Return value** | Type | Description | | ------------ | -------------------- | -| X509CrlEntry | Promise used to return the revoked X.509 certificate obtained.| +| [X509CrlEntry](#x509crlentry) | Promise used to return the revoked X.509 certificate obtained.| **Error codes** | ID| Error Message | | -------- | ----------------------- | -| 19020001 | Memory error. | -| 19030001 | Crypto operation error. | +| 19020001 | memory error. | +| 19030001 | crypto operation error. | **Example** @@ -1779,16 +2146,16 @@ Obtains all the revoked X.509 certificates. This API uses an asynchronous callba **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------- | ---- | -------------------------------- | -| callback | AsyncCallback> | Yes | Callback invoked to return the result. Promise used to return a list of revoked X.509 certificates.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | -------------------------------- | +| callback | AsyncCallback> | Yes | Callback invoked to return the result. Promise used to return a list of revoked X.509 certificates.| **Error codes** | ID| Error Message | | -------- | ----------------------- | -| 19020001 | Memory error. | -| 19030001 | Crypto operation error. | +| 19020001 | memory error. | +| 19030001 | crypto operation error. | **Example** @@ -1828,16 +2195,16 @@ Obtains all the revoked X.509 certificates. This API uses a promise to return th **Return value** -| Type | Description | -| ----------------------------- | ---------------------- | -| Promise> | Promise used to return a list of revoked X.509 certificates.| +| Type | Description | +| ---------------------------------------------- | ---------------------- | +| Promise> | Promise used to return a list of revoked X.509 certificates.| **Error codes** | ID| Error Message | | -------- | ----------------------- | -| 19020001 | Memory error. | -| 19030001 | Crypto operation error. | +| 19020001 | memory error. | +| 19030001 | crypto operation error. | **Example** @@ -1881,9 +2248,9 @@ Obtains the DER-encoded CRL information, the **tbsCertList** from this CRL. This | ID| Error Message | | -------- | ----------------------- | -| 19020001 | Memory error. | -| 19020002 | Runtime error. | -| 19030001 | Crypto operation error. | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | **Example** @@ -1929,9 +2296,9 @@ Obtains the signature data of the X.509 CRL. | ID| Error Message | | -------- | ----------------------- | -| 19020001 | Memory error. | -| 19020002 | Runtime error. | -| 19030001 | Crypto operation error. | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | **Example** @@ -1973,9 +2340,9 @@ Obtains the signing algorithm of the X.509 CRL. | ID| Error Message | | -------- | ----------------------- | -| 19020001 | Memory error. | -| 19020002 | Runtime error. | -| 19030001 | Crypto operation error. | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | **Example** @@ -2017,9 +2384,9 @@ Obtains the OID of the X.509 CRL signing algorithm. OIDs are allocated by the In | ID| Error Message | | -------- | ----------------------- | -| 19020001 | Memory error. | -| 19020002 | Runtime error. | -| 19030001 | Crypto operation error. | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | **Example** @@ -2061,9 +2428,9 @@ Obtains the parameters of the X.509 CRL signing algorithm. | ID| Error Message | | -------- | ----------------------- | -| 19020001 | Memory error. | -| 19020002 | Runtime error. | -| 19030001 | Crypto operation error. | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | **Example** @@ -2111,9 +2478,9 @@ Creates a **CertChainValidator** object. | ID| Error Message | | -------- | ----------------------- | -| 19020001 | Memory error. | -| 19020002 | Runtime error. | -| 19030001 | Crypto operation error. | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | **Example** @@ -2157,15 +2524,15 @@ The certificate chain validator does not verify the certificate validity period | ID| Error Message | | -------- | ------------------------------------------------- | -| 19020001 | Memory error. | -| 19020002 | Runtime error. | -| 19030001 | Crypto operation error. | -| 19030002 | The certificate signature verification failed. | -| 19030003 | The certificate has not taken effect. | -| 19030004 | The certificate has expired. | -| 19030005 | Failed to obtain the certificate issuer. | -| 19030006 | The key cannot be used for signing a certificate. | -| 19030007 | The key cannot be used for digital signature. | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | +| 19030002 | the certificate signature verification failed. | +| 19030003 | the certificate has not taken effect. | +| 19030004 | the certificate has expired. | +| 19030005 | failed to obtain the certificate issuer. | +| 19030006 | the key cannot be used for signing a certificate. | +| 19030007 | the key cannot be used for digital signature. | **Example** @@ -2217,15 +2584,15 @@ The certificate chain validator does not verify the certificate validity period | ID| Error Message | | -------- | ------------------------------------------------- | -| 19020001 | Memory error. | -| 19020002 | Runtime error. | -| 19030001 | Crypto operation error. | -| 19030002 | The certificate signature verification failed. | -| 19030003 | The certificate has not taken effect. | -| 19030004 | The certificate has expired. | -| 19030005 | Failed to obtain the certificate issuer. | -| 19030006 | The key cannot be used for signing a certificate. | -| 19030007 | The key cannot be used for digital signature. | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | +| 19030002 | the certificate signature verification failed. | +| 19030003 | the certificate has not taken effect. | +| 19030004 | the certificate has expired. | +| 19030005 | failed to obtain the certificate issuer. | +| 19030006 | the key cannot be used for signing a certificate. | +| 19030007 | the key cannot be used for digital signature. | **Example** @@ -2295,9 +2662,9 @@ Obtains the serialized data of this revoked certificate. This API uses an asynch | ID| Error Message | | -------- | ----------------------- | -| 19020001 | Memory error. | -| 19020002 | Runtime error. | -| 19030001 | Crypto operation error. | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | **Example** @@ -2333,9 +2700,9 @@ Obtains the serialized data of this revoked certificate. This API uses a promise | ID| Error Message | | -------- | ----------------------- | -| 19020001 | Memory error. | -| 19020002 | Runtime error. | -| 19030001 | Crypto operation error. | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | **Example** @@ -2393,8 +2760,8 @@ Obtains the issuer of this revoked certificate. This API uses an asynchronous ca | ID| Error Message | | -------- | -------------- | -| 19020001 | Memory error. | -| 19020002 | Runtime error. | +| 19020001 | memory error. | +| 19020002 | runtime error. | **Example** @@ -2428,9 +2795,9 @@ Obtains the date when the certificate was revoked. This API uses an asynchronous | ID| Error Message | | -------- | ----------------------- | -| 19020001 | Memory error. | -| 19020002 | Runtime error. | -| 19030001 | Crypto operation error. | +| 19020001 | memory error. | +| 19020002 | runtime error. | +| 19030001 | crypto operation error. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-curve.md b/en/application-dev/reference/apis/js-apis-curve.md index dc0fdd5742cee370e7caa76bb6600fbf4b34ee98..c09e42bbe96a4dca2c0e5c336fa393ee71423894 100644 --- a/en/application-dev/reference/apis/js-apis-curve.md +++ b/en/application-dev/reference/apis/js-apis-curve.md @@ -25,9 +25,9 @@ Implements initialization for the interpolation curve, which is used to create a **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----------------------------------------------- | ---- | ----------------------------------- | -| curve | [Curve](../arkui-ts/ts-appendix-enums.md#curve) | No | Curve type.
Default value: **Curve.Linear**| +| Name| Type | Mandatory| Description | +| ------ | --------------- | ---- | ----------------------------------- | +| curve | [Curve](#curve) | No | Curve type.
Default value: **Curve.Linear**| **Return value** @@ -35,6 +35,28 @@ Implements initialization for the interpolation curve, which is used to create a | ---------------------------------- | ---------------- | | [ICurve](#icurve) | Interpolation curve.| +## Curve + +Since API version 9, this API is supported in ArkTS widgets. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Description: | +| ------------------- | ------------------------------------------------------------ | +| Linear | The animation speed keeps unchanged. | +| Ease | The animation starts slowly, accelerates, and then slows down towards the end. The cubic-bezier curve (0.25, 0.1, 0.25, 1.0) is used.| +| EaseIn | The animation starts at a low speed and then picks up speed until the end. The cubic-bezier curve (0.42, 0.0, 1.0, 1.0) is used. | +| EaseOut | The animation ends at a low speed. The cubic-bezier curve (0.0, 0.0, 0.58, 1.0) is used. | +| EaseInOut | The animation starts and ends at a low speed. The cubic-bezier curve (0.42, 0.0, 0.58, 1.0) is used.| +| FastOutSlowIn | The animation uses the standard cubic-bezier curve (0.4, 0.0, 0.2, 1.0). | +| LinearOutSlowIn | The animation uses the deceleration cubic-bezier curve (0.0, 0.0, 0.2, 1.0). | +| FastOutLinearIn | The animation uses the acceleration cubic-bezier curve (0.4, 0.0, 1.0, 1.0). | +| ExtremeDeceleration | The animation uses the extreme deceleration cubic-bezier curve (0.0, 0.0, 0.0, 1.0). | +| Sharp | The animation uses the sharp cubic-bezier curve (0.33, 0.0, 0.67, 1.0). | +| Rhythm | The animation uses the rhythm cubic-bezier curve (0.7, 0.0, 0.2, 1.0). | +| Smooth | The animation uses the smooth cubic-bezier curve (0.4, 0.0, 0.4, 1.0). | +| Friction | The animation uses the friction cubic-bezier curve (0.2, 0.0, 0.2, 1.0). | + **Example** ```ts @@ -153,14 +175,14 @@ Creates a spring animation curve. If multiple spring animations are applied to t | --------- | ------ | ---- | ----- | | response | number | No | Duration of one complete oscillation.
Default value: **0.55**
Unit: second
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value **0.55**.| | dampingFraction | number | No | Damping coefficient.
**0**: undamped. In this case, the spring oscillates forever.
> 0 and < 1: underdamped. In this case, the spring overshoots the equilibrium position.
**1**: critically damped.
> 1: overdamped. In this case, the spring approaches equilibrium gradually.
Default value: **0.825**
Unit: second
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value **0.55**.| -| overlapDuration | number | No | Duration for animations to overlap, in seconds. When animations overlap, if the **response** values of the two animations are different, they will transit smoothly over this duration.

Default value: **0**
Unit: second
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value **0**.
The spring animation curve is physics-based. Its duration depends on the **springMotion** parameters and the previous velocity, rather than the **duration** parameter in [animation](../arkui-ts/ts-animatorproperty.md) or [animateTo](../arkui-ts/ts-explicit-animation.md). The time cannot be normalized. Therefore, the interpolation cannot be obtained by using the **interpolate** function of the curve.| +| overlapDuration | number | No | Duration for animations to overlap, in seconds. When animations overlap, the **response** values of these animations will transit smoothly over this duration if they are different.
Default value: **0**
Unit: second
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value **0**.
The spring animation curve is physics-based. Its duration depends on the **springMotion** parameters and the previous velocity, rather than the **duration** parameter in [animation](../arkui-ts/ts-animatorproperty.md) or [animateTo](../arkui-ts/ts-explicit-animation.md). The time cannot be normalized. Therefore, the interpolation cannot be obtained using the **interpolate** function of the curve.| **Return value** | Type | Description | | ---------------------------------- | ---------------- | -| [ICurve](#icurve)| Curve.
**NOTE**
The spring animation curve is physics-based. Its duration depends on the **springMotion** parameters and the previous velocity, rather than the **duration** parameter in [animation](../arkui-ts/ts-animatorproperty.md) or [animateTo](../arkui-ts/ts-explicit-animation.md). The time cannot be normalized. Therefore, the interpolation cannot be obtained by using the **interpolate** function of the curve.| +| [ICurve](#icurve)| Curve.
**NOTE**
The spring animation curve is physics-based. Its duration depends on the **springMotion** parameters and the previous velocity, rather than the **duration** parameter in [animation](../arkui-ts/ts-animatorproperty.md) or [animateTo](../arkui-ts/ts-explicit-animation.md). The time cannot be normalized. Therefore, the interpolation cannot be obtained using the [interpolate](#interpolate9) function of the curve.| **Example** @@ -187,13 +209,13 @@ Creates a responsive spring animation curve. It is a special case of [springMoti | --------- | ------ | ---- | ----- | | response | number | No | See **response** in **springMotion**.
Default value: **0.15**
Unit: second
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value **0.15**.| | dampingFraction | number | No | See **dampingFraction** in **springMotion**.
Default value: **0.86**
Unit: second
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value **0.86**.| -| overlapDuration | number | No | See **overlapDuration** in **springMotion**.
Default value: **0.25**
Unit: second
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value **0.25**.
To apply custom settings for a spring animation, you are advised to use **springMotion**. When using **responsiveSpringMotion**, you are advised to retain the default settings.
The duration of the responsive spring animation depends on the **responsiveSpringMotion** parameters and the previous velocity, rather than the **duration** parameter in [animation](../arkui-ts/ts-animatorproperty.md) or [animateTo](../arkui-ts/ts-explicit-animation.md). In addition, the interpolation cannot be obtained by using the **interpolate** function of the curve.| +| overlapDuration | number | No | See **overlapDuration** in **springMotion**.
Default value: **0.25**
Unit: second
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value **0.25**.
To apply custom settings for a spring animation, you are advised to use **springMotion**. When using **responsiveSpringMotion**, you are advised to retain the default settings.
The duration of the responsive spring animation depends on the **responsiveSpringMotion** parameters and the previous velocity, rather than the **duration** parameter in [animation](../arkui-ts/ts-animatorproperty.md) or [animateTo](../arkui-ts/ts-explicit-animation.md). In addition, the interpolation cannot be obtained using the **interpolate** function of the curve. | **Return value** | Type | Description | | ---------------------------------- | ---------------- | -| [ICurve](#icurve)| Curve.
**NOTE**
1. To apply custom settings for a spring animation, you are advised to use **springMotion**. When using **responsiveSpringMotion**, you are advised to retain the default settings.
2. The duration of the responsive spring animation depends on the **responsiveSpringMotion** parameters and the previous velocity, rather than the **duration** parameter in **animation** or **animateTo**. In addition, the interpolation cannot be obtained by using the [interpolate](#interpolate9) function of the curve.| +| [ICurve](#icurve)| Curve.
**NOTE**
1. To apply custom settings for a spring animation, you are advised to use **springMotion**. When using **responsiveSpringMotion**, you are advised to retain the default settings.
2. The duration of the responsive spring animation depends on the **responsiveSpringMotion** parameters and the previous velocity, rather than the **duration** parameter in **animation** or **animateTo**. In addition, the interpolation cannot be obtained using the [interpolate](#interpolate9) function of the curve.| **Example** @@ -310,9 +332,9 @@ Implements initialization to create a curve. This API is deprecated since API ve **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----------------------------------------------- | ---- | ----------------------------------- | -| curve | [Curve](../arkui-ts/ts-appendix-enums.md#curve) | No | Curve type.
Default value: **Curve.Linear**| +| Name| Type | Mandatory| Description | +| ------ | --------------- | ---- | ----------------------------------- | +| curve | [Curve](#curve) | No | Curve type.
Default value: **Curve.Linear**| ## Curves.steps(deprecated) diff --git a/en/application-dev/reference/apis/js-apis-data-dataShare.md b/en/application-dev/reference/apis/js-apis-data-dataShare.md index 991aa683273c5c1408c0574bffa48c8cd342a96a..fcb1e22348a8bd6714c7b4c707f7da3a521cd870 100644 --- a/en/application-dev/reference/apis/js-apis-data-dataShare.md +++ b/en/application-dev/reference/apis/js-apis-data-dataShare.md @@ -4,11 +4,11 @@ The **DataShare** module allows an application to manage its own data and share > **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 initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > -> The APIs provided by this module are system APIs. -> -> The APIs of this module can be used only in the stage model. +> +>- The APIs provided by this module are system APIs and can be used only in the stage model. +> ## Modules to Import @@ -34,7 +34,7 @@ Observe the following when using this API: | Name | Type | Mandatory| Description | | -------- | -------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| context | [Context](js-apis-inner-application-context.md#context) | Yes | Context of an application. | +| context | [Context](js-apis-inner-application-context.md#context) | Yes | Context of the application. | | uri | string | Yes | Uniform Resource Identifier (URI) of the server application to connect. | | callback | AsyncCallback<[DataShareHelper](#datasharehelper)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the **DataShareHelper** instance created. Otherwise, **err** is an error object.| @@ -82,8 +82,8 @@ Observe the following when using this API: | Name | Type | Mandatory| Description | | -------- | -------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| context | [Context](js-apis-inner-application-context.md#context) | Yes | Context of an application. | -| uri | string | Yes | Uniform Resource Identifier (URI) of the server application to connect. | +| context | [Context](js-apis-inner-application-context.md#context) | Yes | Context of the application. | +| uri | string | Yes | URI of the server application to connect. | | options | [DataShareHelperOptions](#datasharehelperoptions10)| Yes | Configuration specifying whether [DataShareHelper](#datasharehelper) is in proxy mode.| | callback | AsyncCallback<[DataShareHelper](#datasharehelper)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the **DataShareHelper** instance created. Otherwise, **err** is an error object.| @@ -133,8 +133,8 @@ Observe the following when using this API: | Name | Type | Mandatory| Description | | ------- | ------------------------------------------------- | ---- | ------------------------------ | | context | [Context](js-apis-inner-application-context.md#context) | Yes | Context of an application. | -| uri | string | Yes | Uniform Resource Identifier (URI) of the server application to connect.| -| options | [DataShareHelperOptions](#datasharehelperoptions10) | No| Optional configuration of the **DataShareHelper** instance. This parameter is supported from API version 10. If it is not set, [DataShareHelper](#datasharehelper) is not in proxy mode.| +| uri | string | Yes | URI of the server application to connect. | +| options | [DataShareHelperOptions](#datasharehelperoptions10) | No| Configuration of the **DataShareHelper** instance. This parameter is supported from API version 10. If it is not set, [DataShareHelper](#datasharehelper) is not in proxy mode. | **Return value** @@ -177,7 +177,7 @@ Defines whether [DataShareHelper](#datasharehelper) is in proxy mode. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| isProxy | boolean | No| Whether the [DataShareHelper](#datasharehelper) is in proxy mode. The default value is **false**.
If the value is **true**, the [DataShareHelper](#datasharehelper) to be created is in proxy mode, and all operations will not open the data provider application unless the database does not exist. If the database does not exist, [createDataShareHelper] (#datasharecreatedatasharehelper10) will start the data provider to create a database.| +| isProxy | boolean | No| Whether the [DataShareHelper](#datasharehelper) is in proxy mode.
The default value is **false**.
If the value is **true**, the [DataShareHelper](#datasharehelper) to be created is in proxy mode, and all operations will not open the data provider application unless the database does not exist. If the database does not exist, [createDataShareHelper](#datasharecreatedatasharehelper10) will start the data provider to create a database. | ## TemplateId10+ @@ -192,14 +192,14 @@ Defines the **TemplateId** struct. **TemplateId** is generated by [**addTemplate ## PublishedItem10+ -Defines the type of the data to publish. +Defines the data to publish. **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | key | string | Yes| Key of the data to publish.| -| data | string \| [Ashmem](js-apis-rpc.md#ashmem8) | Yes| Data to publish. If the data volume is large, use **Ashmem**.| +| data | string \| ArrayBuffer | Yes| Data to publish. If the data to publish exceeds 20 KB, you are advised to use **data** of the ArrayBuffer type. | | subscriberId | string | Yes| Subscriber ID.| ## RdbDataChangeNode10+ @@ -245,7 +245,7 @@ Defines the result of the operation for subscribing to or unsubscribing from the | Name| Type| Mandatory| Description| | -------- | -------- | ----- | -------- | | key | string | Yes| Key of the operation result.| -| result | number | Yes| Operation result. | +| result | number | Yes| Operation result. If the operation is successful, **0** is returned; otherwise, an error code is returned. | ## DataShareHelper Provides a **DataShareHelper** instance to access or manage data on the server. Before calling an API provided by **DataShareHelper**, you must create a **DataShareHelper** instance using [createDataShareHelper](#datasharecreatedatasharehelper). @@ -393,7 +393,7 @@ Subscribes to the changes of the data corresponding to the specified URI and tem | Name | Type | Mandatory| Description | | -------- | ----------------------------------| ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of the event to subscribe to. The value is **rdbDataChange**, which indicates the RDB data change event. | +| type | string | Yes | Type of the event to subscribe to. The value is **rdbDataChange**, which indicates the RDB data change event. If **type** is any other value, there is no response to this API. | | uris | Array<string> | Yes | URIs of the data to operate. | | templateId | [TemplateId](#templateid10) | Yes | ID of the template that triggers the callback. | | callback | AsyncCallback<[RdbDataChangeNode](#rdbdatachangenode10)> | Yes | Callback invoked to return the result when the specified data changes. The **err** is **undefined**, and **node** is the new data. Otherwise, this callback is not triggered or **err** is an error object. | @@ -478,18 +478,15 @@ Subscribes to the changes of the published data. **Example** ```ts -import rpc from '@ohos.rpc'; - function onPublishCallback(err, node:dataShare.PublishedDataChangeNode) { console.info("onPublishCallback node bundleName " + JSON.stringify(node.bundleName)); console.info("onPublishCallback node data size" + node.data.length); for (let i = 0; i < node.data.length; i++) { console.info("onPublishCallback node " + typeof node.data[i].data); if (typeof node.data[i].data != 'string') { - let ash:rpc.Ashmem = node.data[i].data; - ash.mapReadonlyAshmem(); - console.info("onPublishCallback " + JSON.stringify(ash.readAshmem(ash.getAshmemSize()/4, 0))); - ash.closeAshmem(); + let array:ArrayBuffer = node.data[i].data; + let data:Uint8Array = new Uint8Array(array); + console.info("onPublishCallback " + i + " " + JSON.stringify(data)); } console.info("onPublishCallback data " + i + " " + JSON.stringify(node.data[i])); } @@ -561,29 +558,13 @@ For details about the error codes, see [DataShare Error Codes](../errorcodes/err **Example** ```ts -import rpc from '@ohos.rpc'; - -let ashmem = null; -let subscriberId = '11'; +let arrayBuffer = new ArrayBuffer(1); let version = 1; -let data : Array = [ - {key:"city", subscriberId:"11", data:"xian"}, - {key:"datashareproxy://com.acts.ohos.data.datasharetest/appInfo", subscriberId:"11", data:"appinfo is just a test app"}, - {key:"empty", subscriberId:"11", data:"nobody sub"}]; -let nums:number[] = [1,2,3]; +let data : Array = [{key:"key2", subscriberId:"11", data:arrayBuffer}]; function publishCallback(err, result: Array) { console.info("publishCallback " + JSON.stringify(result)); - ashmem.closeAshmem(); } try { - ashmem = rpc.Ashmem.create("ashmem", (nums.length) * 4); - ashmem.mapReadWriteAshmem(); - ashmem.writeAshmem(nums, nums.length, 0); - data.push({ - "key" : "key2", - "data" : ashmem, - "subscriberId" : "11", - }); console.info("data length is:", data.length); dataShareHelper.publish(data, "com.acts.ohos.data.datasharetest", version, publishCallback); } catch (e) { @@ -1066,7 +1047,7 @@ try { batchInsert(uri: string, values: Array<ValuesBucket>, callback: AsyncCallback<number>): void -Batch inserts data into the database. This API uses an asynchronous callback to return the result. +Batch inserts data into the database. This API uses an asynchronous callback to return the result. Silent access is not supported currently. **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer @@ -1102,7 +1083,7 @@ try { batchInsert(uri: string, values: Array<ValuesBucket>): Promise<number> -Batch inserts data into the database. This API uses a promise to return the result. +Batch inserts data into the database. This API uses a promise to return the result. Silent access is not supported currently. **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer @@ -1141,7 +1122,7 @@ try { normalizeUri(uri: string, callback: AsyncCallback<string>): void -Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the local device, but the normalized URI can be used across devices. This API uses an asynchronous callback to return the result. +Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the local device, but the normalized URI can be used across devices. This API uses an asynchronous callback to return the result. Silent access is not supported currently. **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer @@ -1169,7 +1150,7 @@ dataShareHelper.normalizeUri(uri, (err, data) => { normalizeUri(uri: string): Promise<string> -Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the local device, but the normalized URI can be used across devices. This API uses a promise to return the result. +Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the local device, but the normalized URI can be used across devices. This API uses a promise to return the result. Silent access is not supported currently. **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer @@ -1200,7 +1181,7 @@ dataShareHelper.normalizeUri(uri).then((data) => { denormalizeUri(uri: string, callback: AsyncCallback<string>): void -Denormalizes a URI. This API uses an asynchronous callback to return the result. +Denormalizes a URI. This API uses an asynchronous callback to return the result. Silent access is not supported currently. **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer @@ -1228,7 +1209,7 @@ dataShareHelper.denormalizeUri(uri, (err, data) => { denormalizeUri(uri: string): Promise<string> -Denormalizes a URI. This API uses a promise to return the result. +Denormalizes a URI. This API uses a promise to return the result. Silent access is not supported currently. **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer @@ -1259,7 +1240,7 @@ dataShareHelper.denormalizeUri(uri).then((data) => { notifyChange(uri: string, callback: AsyncCallback<void>): void -Notifies the registered observer of data changes. This API uses an asynchronous callback to return the result. +Notifies the registered observer of data changes. This API uses an asynchronous callback to return the result. Silent access is not supported currently. **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer @@ -1283,7 +1264,7 @@ dataShareHelper.notifyChange(uri, () => { notifyChange(uri: string): Promise<void> -Notifies the registered observer of data changes. This API uses a promise to return the result. +Notifies the registered observer of data changes. This API uses a promise to return the result. Silent access is not supported currently. **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer diff --git a/en/application-dev/reference/apis/js-apis-device-info.md b/en/application-dev/reference/apis/js-apis-device-info.md index 2827737f79a76c23b04ecc12233774a30f34b39a..c8fd363f26d82c5758600f2ea2f329c1ee3b266c 100644 --- a/en/application-dev/reference/apis/js-apis-device-info.md +++ b/en/application-dev/reference/apis/js-apis-device-info.md @@ -27,7 +27,7 @@ import deviceInfo from '@ohos.deviceInfo' | softwareModel | string | Yes| No| Software model.| | hardwareModel | string | Yes| No| Hardware model.| | hardwareProfile | string | Yes| No| Hardware profile.| -| serial | string | Yes| No| Device serial number.
**Required permissions**: ohos.permission.sec.ACCESS_UDID (a system permission)| +| serial | string | Yes| No| Device serial number.
**Required permissions**: ohos.permission.sec.ACCESS_UDID| | bootloaderVersion | string | Yes| No| Bootloader version.| | abiList | string | Yes| No| Application binary interface (Abi) list.| | securityPatchTag | string | Yes| No| Security patch tag.| @@ -47,4 +47,117 @@ import deviceInfo from '@ohos.deviceInfo' | buildHost | string | Yes| No| Build host.| | buildTime | string | Yes| No| Build time.| | buildRootHash | string | Yes| No| Build root hash.| -| udid7+ | string | Yes| No| Device UDID.
**Required permissions**: ohos.permission.sec.ACCESS_UDID (a system permission)| +| udid7+ | string | Yes| No| Device UDID.
**Required permissions**: ohos.permission.sec.ACCESS_UDID| +| distributionOSName10+ | String | Yes| No| Name of the distribution OS.| +| distributionOSVersion10+ | String | Yes| No| Version number of the distribution OS.| +| distributionOSApiVersion10+ | number| Yes| No| API version of the distribution OS.| +| distributionOSReleaseType10+ | String | Yes| No| Type of the distribution OS.| + +**Example** + +``` + import deviceinfo from '@ohos.deviceInfo' + + let deviceTypeInfo = deviceinfo.deviceType; + console.info('the value of the deviceType is :' + deviceTypeInfo); + + let manufactureInfo = deviceinfo.manufacture; + console.info('the value of the manufactureInfo is :' + manufactureInfo); + + let brandInfo = deviceinfo.brand; + console.info('the value of the device brand is :' + brandInfo); + + let marketNameInfo = deviceinfo.marketName; + console.info('the value of the deviceinfo marketName is :' + marketNameInfo); + + let productSeriesInfo = deviceinfo.productSeries; + console.info('the value of the deviceinfo productSeries is :' + productSeriesInfo); + + let productModelInfo = deviceinfo.productModel; + console.info('the value of the deviceinfo productModel is :' + productModelInfo); + + let softwareModelInfo = deviceinfo.softwareModel; + console.info('the value of the deviceinfo softwareModel is :' + softwareModelInfo); + + let hardwareModelInfo = deviceinfo.hardwareModel; + console.info('the value of the deviceinfo hardwareModel is :' + hardwareModelInfo); + + let hardwareProfileInfo = deviceinfo.hardwareProfile; + console.info('the value of the deviceinfo hardwareProfile is :' + hardwareProfileInfo); + + let serialInfo = deviceinfo.serial; + console.info('the value of the deviceinfo serial is :' + serialInfo); + + let bootloaderVersionInfo = deviceinfo.bootloaderVersion; + console.info('the value of the deviceinfo bootloaderVersion is :' + bootloaderVersionInfo); + + let abiListInfo = deviceinfo.abiList; + console.info('the value of the deviceinfo abiList is :' + abiListInfo); + + let securityPatchTagInfo = deviceinfo.securityPatchTag; + console.info('the value of the deviceinfo securityPatchTag is :' + securityPatchTagInfo); + + let displayVersionInfo = deviceinfo.displayVersion; + console.info('the value of the deviceinfo displayVersion is :' + displayVersionInfo); + + let incrementalVersionInfo = deviceinfo.incrementalVersion; + console.info('the value of the deviceinfo incrementalVersion is :' + incrementalVersionInfo); + + let osReleaseTypeInfo = deviceinfo.osReleaseType; + console.info('the value of the deviceinfo osReleaseType is :' + osReleaseTypeInfo); + + let osFullNameInfo = deviceinfo.osFullName; + console.info('the value of the deviceinfo osFullName is :' + osFullNameInfo); + + let majorVersionInfo = deviceinfo.majorVersion; + console.info('the value of the deviceinfo majorVersion is :' + majorVersionInfo); + + let seniorVersionInfo = deviceinfo.seniorVersion; + console.info('the value of the deviceinfo seniorVersion is :' + seniorVersionInfo); + + let featureVersionInfo = deviceinfo.featureVersion; + console.info('the value of the deviceinfo featureVersion is :' + featureVersionInfo); + + let buildVersionInfo = deviceinfo.buildVersion; + console.info('the value of the deviceinfo buildVersion is :' + buildVersionInfo); + + let sdkApiVersionInfo = deviceinfo.sdkApiVersion; + console.info('the value of the deviceinfo sdkApiVersion is :' + sdkApiVersionInfo); + + let firstApiVersionInfo = deviceinfo.firstApiVersion; + console.info('the value of the deviceinfo firstApiVersion is :' + firstApiVersionInfo); + + let versionIdInfo = deviceinfo.versionId; + console.info('the value of the deviceinfo versionId is :' + versionIdInfo); + + let buildTypeInfo = deviceinfo.buildType; + console.info('the value of the deviceinfo buildType is :' + buildTypeInfo); + + let buildUserInfo = deviceinfo.buildUser; + console.info('the value of the deviceinfo buildUser is :' + buildUserInfo); + + let buildHostInfo = deviceinfo.buildHost; + console.info('the value of the deviceinfo buildHost is :' + buildHostInfo); + + let buildTimeInfo = deviceinfo.buildTime; + console.info('the value of the deviceinfo buildTime is :' + buildTimeInfo); + + let buildRootHashInfo = deviceinfo.buildRootHash; + console.info('the value of the deviceinfo buildRootHash is :' + buildRootHashInfo); + + let udid = deviceinfo.udid; + console.info('the value of the deviceinfo udid is :' + udid); + + let distributionOSName = deviceinfo.distributionOSName + console.info('the value of the deviceinfo distributionOSName is :' + distributionOSName); + + let distributionOSVersion = deviceinfo.distributionOSVersion + console.info('the value of the deviceinfo distributionOSVersion is :' + distributionOSVersion); + + let distributionOSApiVersion = deviceinfo.distributionOSApiVersion + console.info('the value of the deviceinfo distributionOSApiVersion is :' + distributionOSApiVersion); + + let distributionOSReleaseType = deviceinfo.distributionOSReleaseType + console.info('the value of the deviceinfo distributionOSReleaseType is :' + distributionOSReleaseType); + +``` diff --git a/en/application-dev/reference/apis/js-apis-device-manager.md b/en/application-dev/reference/apis/js-apis-device-manager.md index 8528ceff015caa6e24cbec8ed4acd87098a67da1..4b1c3da7a0a38a1a7f6c1a6e730dcd4b1fbbbde1 100644 --- a/en/application-dev/reference/apis/js-apis-device-manager.md +++ b/en/application-dev/reference/apis/js-apis-device-manager.md @@ -125,8 +125,8 @@ Defines subscription information. | mode | [DiscoverMode ](#discovermode) | Yes | Device discovery mode. | | medium | [ExchangeMedium](#exchangemedium) | Yes | Medium used for device discovery. | | freq | [ExchangeFreq](#exchangefreq) | Yes | Frequency of device discovery. | -| isSameAccount | boolean | Yes | Whether the same account is used on the discovered device. | -| isWakeRemote | boolean | Yes | Whether to wake up the discovered device. | +| isSameAccount | boolean | No | Whether the same account is used on the discovered device. | +| isWakeRemote | boolean | No | Whether to wake up the discovered device. | | capability | [SubscribeCap](#subscribecap) | Yes | Discovery capability. | @@ -227,6 +227,8 @@ release(): void Releases this **DeviceManager** instance when it is no longer used. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Error codes** @@ -253,6 +255,8 @@ getTrustedDeviceListSync(): Array<DeviceInfo> Obtains all trusted devices synchronously. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Return value** @@ -279,12 +283,54 @@ For details about the error codes, see [Device Management Error Codes](../errorc } ``` +### getTrustedDeviceListSync10+ + +getTrustedDeviceListSync(isRefresh: boolean): Array<DeviceInfo> + +Enables the DSoftBus heartbeat mode to quickly bring offline trusted devices online and updates the list of online trusted devices. + +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | --------------------------------- | ---- | ---------------------------------- | +| isRefresh | boolean | Yes | Whether to enable the heartbeat mode and update the list of online trusted devices. | + +**Return value** + +| Name | Description | +| -------------------------------------- | ---------------- | +| Array<[DeviceInfo](#deviceinfo)> | List of trusted devices obtained.| + +**Error codes** + +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). + +| ID| Error Message | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | + +**Example** + + ```js + try { + var deviceInfoList = dmInstance.getTrustedDeviceListSync(true); + } catch (err) { + console.error("getTrustedDeviceListSync errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + ### getTrustedDeviceList8+ getTrustedDeviceList(callback:AsyncCallback<Array<DeviceInfo>>): void Obtains all trusted devices. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -315,6 +361,8 @@ getTrustedDeviceList(): Promise<Array<DeviceInfo>> Obtains all trusted devices. This API uses a promise to return the result. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Return value** @@ -323,14 +371,6 @@ Obtains all trusted devices. This API uses a promise to return the result. | ---------------------------------------- | --------------------- | | Promise<Array<[DeviceInfo](#deviceinfo)>> | Promise used to return the result.| -**Error codes** - -For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). - -| ID| Error Message | -| -------- | --------------------------------------------------------------- | -| 11600101 | Failed to execute the function. | - **Example** ```js @@ -347,6 +387,8 @@ getLocalDeviceInfoSync(): [DeviceInfo](#deviceinfo) Obtains local device information synchronously. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Return value** @@ -379,6 +421,8 @@ getLocalDeviceInfo(callback:AsyncCallback<DeviceInfo>): void Obtains local device information. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -409,6 +453,8 @@ getLocalDeviceInfo(): Promise<DeviceInfo> Obtains local device information. This API uses a promise to return the result. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Return value** @@ -417,14 +463,6 @@ Obtains local device information. This API uses a promise to return the result. | ---------------------------------------- | --------------------- | | Promise<[DeviceInfo](#deviceinfo)> | Promise used to return the result.| -**Error codes** - -For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). - -| ID| Error Message | -| ------- | --------------------------------------------------------------- | -| 11600101| Failed to execute the function. | - **Example** ```js @@ -441,6 +479,8 @@ getDeviceInfo(networkId: string, callback:AsyncCallback<DeviceInfo>): void Obtains the information about a specific device based on the network ID. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -474,6 +514,8 @@ getDeviceInfo(networkId: string): Promise<DeviceInfo> Obtains the information about a specific device based on the network ID. This API uses a promise to return the result. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -506,6 +548,8 @@ startDeviceDiscovery(subscribeInfo: SubscribeInfo): void Starts to discover peripheral devices. The discovery process automatically stops when 2 minutes have elapsed. A maximum of 99 devices can be discovered. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -550,6 +594,8 @@ startDeviceDiscovery(subscribeInfo: SubscribeInfo, filterOptions?: string): void Starts to discover peripheral devices and filters discovered devices. The discovery process automatically stops when 2 minutes have elapsed. A maximum of 99 devices can be discovered. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -604,6 +650,8 @@ stopDeviceDiscovery(subscribeId: number): void Stops device discovery. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -638,6 +686,8 @@ publishDeviceDiscovery(publishInfo: PublishInfo): void Publishes device information for discovery purposes. The publish process automatically stops when 2 minutes have elapsed. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -679,6 +729,8 @@ unPublishDeviceDiscovery(publishId: number): void Stops publishing device information. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -713,6 +765,8 @@ authenticateDevice(deviceInfo: DeviceInfo, authParam: AuthParam, callback: Async Authenticates a device. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -764,6 +818,8 @@ unAuthenticateDevice(deviceInfo: DeviceInfo): void Deauthenticates a device. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -803,6 +859,8 @@ verifyAuthInfo(authInfo: AuthInfo, callback: AsyncCallback<{deviceId: string, Verifies authentication information. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -839,6 +897,8 @@ setUserOperation(operateAction: number, params: string): void; Sets a user operation. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -873,6 +933,8 @@ requestCredentialRegisterInfo(requestInfo: string, callback: AsyncCallback<{regi Obtains the registration information of the credential. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -908,6 +970,8 @@ importCredential(credentialInfo: string, callback: AsyncCallback<{resultInfo: st Imports credential information. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -959,6 +1023,8 @@ deleteCredential(queryInfo: string, callback: AsyncCallback<{resultInfo: string} Deletes credential information. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -995,6 +1061,8 @@ on(type: 'uiStateChange', callback: Callback<{ param: string}>): void; Subscribes to UI status changes. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -1025,6 +1093,8 @@ off(type: 'uiStateChange', callback?: Callback<{ param: string}>): void; Unsubscribes from UI status changes. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -1050,6 +1120,8 @@ on(type: 'deviceStateChange', callback: Callback<{ action: DeviceStateChange Subscribes to changes in the device state. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -1077,6 +1149,8 @@ off(type: 'deviceStateChange', callback?: Callback<{ action: DeviceStateChang Unsubscribes from changes in the device state. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -1104,6 +1178,8 @@ on(type: 'deviceFound', callback: Callback<{ subscribeId: number, device: Dev Subscribes to device discovery events. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -1131,6 +1207,8 @@ off(type: 'deviceFound', callback?: Callback<{ subscribeId: number, device: D Unsubscribes from device discovery events. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -1158,6 +1236,8 @@ on(type: 'discoverFail', callback: Callback<{ subscribeId: number, reason: nu Subscribes to device discovery failures. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -1185,6 +1265,8 @@ off(type: 'discoverFail', callback?: Callback<{ subscribeId: number, reason: Unsubscribes from device discovery failures. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -1212,6 +1294,8 @@ on(type: 'publishSuccess', callback: Callback<{ publishId: number }>): voi Subscribes to device information publication success events. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -1240,6 +1324,8 @@ off(type: 'publishSuccess', callback?: Callback<{ publishId: number }>): v Unsubscribes from device information publication success events. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -1267,6 +1353,8 @@ on(type: 'publishFail', callback: Callback<{ publishId: number, reason: numbe Subscribes to device information publication failures. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -1294,6 +1382,8 @@ off(type: 'publishFail', callback?: Callback<{ publishId: number, reason: num Unsubscribes from device information publication failures. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -1321,6 +1411,8 @@ on(type: 'serviceDie', callback: () => void): void Subscribes to dead events of the **DeviceManager** service. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -1348,6 +1440,8 @@ off(type: 'serviceDie', callback?: () => void): void Unsubscribes from dead events of the **DeviceManager** service. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** diff --git a/en/application-dev/reference/apis/js-apis-display.md b/en/application-dev/reference/apis/js-apis-display.md index 62bfa800173c03c08c1402d79a9174b3778375ca..ac00730414338a128f9c5d5a20ba540fb3b3a8e6 100644 --- a/en/application-dev/reference/apis/js-apis-display.md +++ b/en/application-dev/reference/apis/js-apis-display.md @@ -49,10 +49,10 @@ Describes a rectangle on the display. | Name | Type| Readable| Writable| Description | | ------ | -------- | ---- | ---- | ------------------ | -| left | number | Yes | Yes | Left boundary of the rectangle, in pixels.| -| top | number | Yes | Yes | Top boundary of the rectangle, in pixels.| -| width | number | Yes | Yes | Width of the rectangle, in pixels. | -| height | number | Yes | Yes | Height of the rectangle, in pixels. | +| left | number | Yes | Yes | Left boundary of the rectangle, in pixels. The value must be an integer.| +| top | number | Yes | Yes | Top boundary of the rectangle, in pixels. The value must be an integer.| +| width | number | Yes | Yes | Width of the rectangle, in pixels. The value must be an integer. | +| height | number | Yes | Yes | Height of the rectangle, in pixels. The value must be an integer. | ## WaterfallDisplayAreaRects9+ @@ -196,7 +196,7 @@ Checks whether there is a visible privacy window on a display. The privacy windo | Name| Type | Mandatory| Description | | ------ | ------------------------- | ---- |----------| -| id | number | Yes | ID of the display.| +| id | number | Yes | ID of the display. The value must be an integer.| **Return value** @@ -248,10 +248,10 @@ Subscribes to display changes. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | +| Name| Type| Mandatory| Description | +| -------- | -------- | -------- |---------------------------------------------------------------------------------------------------------------------------------| | type | string | Yes| Event type.
- **add**, indicating the display addition event. Example: event that a display is connected.
- **remove**, indicating the display removal event. Example: event that a display is disconnected.
- **change**, indicating the display change event. Example: event that the display orientation is changed.| -| callback | Callback<number> | Yes| Callback used to return the ID of the display.| +| callback | Callback<number> | Yes| Callback used to return the ID of the display, which is an integer. | **Example** @@ -279,7 +279,7 @@ Unsubscribes from display changes. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type.
- **add**, indicating the display addition event. Example: event that a display is connected.
- **remove**, indicating the display removal event. Example: event that a display is disconnected.
- **change**, indicating the display change event. Example: event that the display orientation is changed.| -| callback | Callback<number> | No| Callback used to return the ID of the display.| +| callback | Callback<number> | No| Callback used to return the ID of the display, which is an integer.| **Example** @@ -335,7 +335,7 @@ Unsubscribes from privacy mode changes of this display. When there is a privacy | Name | Type | Mandatory| Description | | -------- |------------------------------------------| ---- | ------------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'privateModeChange'**, indicating the event of display private mode changes.| +| type | string | Yes | Event type. The value is fixed at **'privateModeChange'**, indicating the event of display privacy mode changes.| | callback | Callback<boolean> | No | Callback used to return whether the privacy mode of the display is changed. The value **true** means that the display changes to the privacy mode, and **false** means the opposite.| **Example** @@ -479,22 +479,22 @@ Before calling any API in **Display**, you must use [getAllDisplays()](#displayg **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| id | number | Yes| No| ID of the display.| -| name | string | Yes| No| Name of the display.| -| alive | boolean | Yes| No| Whether the display is alive.| -| state | [DisplayState](#displaystate) | Yes| No| State of the display.| -| refreshRate | number | Yes| No| Refresh rate of the display.| +| Name| Type| Readable| Writable| Description | +| -------- | -------- | -------- | -------- |---------------------------------------------------------------------------------------------------------------| +| id | number | Yes| No| ID of the display. The value must be an integer. | +| name | string | Yes| No| Name of the display. | +| alive | boolean | Yes| No| Whether the display is alive. | +| state | [DisplayState](#displaystate) | Yes| No| State of the display. | +| refreshRate | number | Yes| No| Refresh rate of the display. The value must be an integer. | | rotation | number | Yes| No| Screen rotation angle of the display.
The value **0** indicates that the screen of the display rotates by 0°.
The value **1** indicates that the screen of the display rotates by 90°.
The value **2** indicates that the screen of the display rotates by 180°.
The value **3** indicates that the screen of the display rotates by 270°.| -| width | number | Yes| No| Width of the display, in pixels.| -| height | number | Yes| No| Height of the display, in pixels.| -| densityDPI | number | Yes| No| Screen density of the display, that is, the number of dots per inch. Generally, the value is **160** or **480**.| -| orientation10+ | [Orientation](#orientation10) | Yes| No| Orientation of the display.| -| densityPixels | number | Yes| No| Logical density of the display, which is a scaling coefficient independent of the pixel unit. Generally, the value is **1** or **3**.| -| scaledDensity | number | Yes| No| Scaling factor for fonts displayed on the display. Generally, the value is the same as that of **densityPixels**.| -| xDPI | number | Yes| No| Exact physical dots per inch of the screen in the horizontal direction.| -| yDPI | number | Yes| No| Exact physical dots per inch of the screen in the vertical direction.| +| width | number | Yes| No| Width of the display, in pixels. The value must be an integer. | +| height | number | Yes| No| Height of the display, in pixels. The value must be an integer. | +| densityDPI | number | Yes| No| Screen density of the display, that is, the number of dots per inch. The value must be a floating point number. Generally, the value is **160.0** or **480.0**. | +| orientation10+ | [Orientation](#orientation10) | Yes| No| Orientation of the display. | +| densityPixels | number | Yes| No| Logical density of the display, which is a scaling coefficient independent of the pixel unit. The value must be a floating point number. Generally, the value is **1.0** or **3.0**. | +| scaledDensity | number | Yes| No| Scaling factor for fonts displayed on the display. The value must be a floating point number. Generally, the value is the same as that of **densityPixels**. | +| xDPI | number | Yes| No| Exact physical dots per inch of the screen in the horizontal direction. The value must be a floating point number. | +| yDPI | number | Yes| No| Exact physical dots per inch of the screen in the vertical direction. The value must be a floating point number. | ### getCutoutInfo9+ getCutoutInfo(callback: AsyncCallback<CutoutInfo>): void diff --git a/en/application-dev/reference/apis/js-apis-fileio.md b/en/application-dev/reference/apis/js-apis-fileio.md index 1723208acd9d746a72a360142ad3b890bccbddd8..3a1a597403b6c8ce5e89cb73047867e3478b5ddb 100644 --- a/en/application-dev/reference/apis/js-apis-fileio.md +++ b/en/application-dev/reference/apis/js-apis-fileio.md @@ -16,7 +16,7 @@ import fileio from '@ohos.fileio'; ## Guidelines -Before using the APIs provided by this module to perform operations on files or directories, obtain the path of the application sandbox as follows: +Before using the APIs provided by this module to perform operations on a file or directory, obtain the application sandbox path of the file or directory as follows: **Stage Model** @@ -44,7 +44,7 @@ export default class EntryAbility extends UIAbility { }) ``` - For details about how to obtain the FA model context, see [Contex](js-apis-inner-app-context.md#context). + For details about how to obtain the FA model context, see [Context](js-apis-inner-app-context.md#context). ## fileio.stat @@ -52,6 +52,10 @@ stat(path: string): Promise<Stat> Obtains file information. This API uses a promise to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.stat](js-apis-file-fs.md#stat) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -62,8 +66,8 @@ Obtains file information. This API uses a promise to return the result. **Return value** -| Type | Description | -| ---------------------------- | ---------- | + | Type | Description | + | ---------------------------- | ---------- | | Promise<[Stat](#stat)> | Promise used to return the file information obtained.| **Example** @@ -84,6 +88,10 @@ stat(path: string, callback: AsyncCallback<Stat>): void Obtains file information. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.stat](js-apis-file-fs.md#fsstat-1) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -108,6 +116,10 @@ statSync(path: string): Stat Synchronously obtains file information. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.statSync](js-apis-file-fs.md#fsstatsync) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -119,9 +131,9 @@ Synchronously obtains file information. **Return value** -| Type | Description | -| ------------- | ---------- | -| [Stat](#stat) | File information obtained.| + | Type | Description | + | ------------- | ---------- | + | [Stat](#stat) | File information obtained.| **Example** @@ -137,6 +149,10 @@ opendir(path: string): Promise<Dir> Opens a file directory. This API uses a promise to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.listFile](js-apis-file-fs.md#fslistfile) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -147,8 +163,8 @@ Opens a file directory. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------------------- | -------- | + | Type | Description | + | -------------------------- | -------- | | Promise<[Dir](#dir)> | Promise used to return the **Dir** object.| **Example** @@ -162,13 +178,17 @@ Opens a file directory. This API uses a promise to return the result. }); ``` - + ## fileio.opendir opendir(path: string, callback: AsyncCallback<Dir>): void Opens a file directory. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.listFile](js-apis-file-fs.md#fslistfile-1) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -194,8 +214,11 @@ opendirSync(path: string): Dir Synchronously opens a directory. -**System capability**: SystemCapability.FileManagement.File.FileIO +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.listFileSync](js-apis-file-fs.md#fslistfilesync) instead. +**System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -205,9 +228,9 @@ Synchronously opens a directory. **Return value** -| Type | Description | -| ----------- | -------- | -| [Dir](#dir) | A **Dir** instance corresponding to the directory.| + | Type | Description | + | ----------- | -------- | + | [Dir](#dir) | A **Dir** instance corresponding to the directory.| **Example** @@ -224,6 +247,10 @@ access(path: string, mode?: number): Promise<void> Checks whether the current process can access a file. This API uses a promise to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.access](js-apis-file-fs.md#fsaccess) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -235,9 +262,9 @@ Checks whether the current process can access a file. This API uses a promise to **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **Example** @@ -257,6 +284,10 @@ access(path: string, mode?: number, callback: AsyncCallback<void>): void Checks whether the current process can access a file. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.access](js-apis-file-fs.md#fsaccess-1) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -283,6 +314,10 @@ accessSync(path: string, mode?: number): void Synchronously checks whether the current process can access the specified file. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.accessSync](js-apis-file-fs.md#fsaccesssync) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -310,19 +345,23 @@ close(fd: number): Promise<void> Closes a file. This API uses a promise to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.close](js-apis-file-fs.md#fsclose) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ------------ | -| fd | number | Yes | File descriptor of the file to close.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor of the file to close.| **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **Example** @@ -343,14 +382,18 @@ close(fd: number, callback: AsyncCallback<void>): void Closes a file. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.close](js-apis-file-fs.md#fsclose-1) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | ---- | ------------ | -| fd | number | Yes | File descriptor of the file to close.| -| callback | AsyncCallback<void> | Yes | Callback invoked when the file is closed asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ------------ | + | fd | number | Yes | File descriptor of the file to close.| + | callback | AsyncCallback<void> | Yes | Callback invoked immediately after the file is closed.| **Example** @@ -369,13 +412,17 @@ closeSync(fd: number): void Synchronously closes a file. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.closeSync](js-apis-file-fs.md#fsclosesync) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ------------ | -| fd | number | Yes | File descriptor of the file to close.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor of the file to close.| **Example** @@ -392,21 +439,25 @@ copyFile(src: string|number, dest: string|number, mode?: number): Promise<voi Copies a file. This API uses a promise to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.copyFile](js-apis-file-fs.md#fscopyfile) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ---- | -------------------------- | ---- | ---------------------------------------- | -| src | string\|number | Yes | Path or file descriptor of the file to copy. | -| dest | string\|number | Yes | Path or file descriptor of the new file. | + | Name | Type | Mandatory | Description | + | ---- | -------------------------- | ---- | ---------------------------------------- | + | src | string\|number | Yes | Path or file descriptor of the file to copy. | + | dest | string\|number | Yes | Path or file descriptor of the new file. | | mode | number | No | Option for overwriting the file of the same name in the destination path. The default value is **0**, which is the only value supported.
**0**: Completely overwrite the file with the same name and truncate the part that is not overwritten. | **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **Example** @@ -427,16 +478,20 @@ copyFile(src: string|number, dest: string|number, mode: number, callback: AsyncC Copies a file. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.copyFile](js-apis-file-fs.md#fscopyfile-1) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------------- | ---- | ---------------------------------------- | -| src | string\|number | Yes | Path or file descriptor of the file to copy. | -| dest | string\|number | Yes | Path or file descriptor of the new file. | + | Name | Type | Mandatory | Description | + | -------- | -------------------------- | ---- | ---------------------------------------- | + | src | string\|number | Yes | Path or file descriptor of the file to copy. | + | dest | string\|number | Yes | Path or file descriptor of the new file. | | mode | number | No | Option for overwriting the file of the same name in the destination path. The default value is **0**, which is the only value supported.
**0**: Completely overwrite the file with the same name and truncate the part that is not overwritten.| -| callback | AsyncCallback<void> | Yes | Callback invoked when the file is copied asynchronously. | + | callback | AsyncCallback<void> | Yes | Callback invoked immediately after the file is copied. | **Example** @@ -455,14 +510,18 @@ copyFileSync(src: string|number, dest: string|number, mode?: number): void Synchronously copies a file. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.copyFileSync](js-apis-file-fs.md#fscopyfilesync) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ---- | -------------------------- | ---- | ---------------------------------------- | -| src | string\|number | Yes | Path or file descriptor of the file to copy. | -| dest | string\|number | Yes | Path or file descriptor of the new file. | + | Name | Type | Mandatory | Description | + | ---- | -------------------------- | ---- | ---------------------------------------- | + | src | string\|number | Yes | Path or file descriptor of the file to copy. | + | dest | string\|number | Yes | Path or file descriptor of the new file. | | mode | number | No | Option for overwriting the file of the same name in the destination path. The default value is **0**, which is the only value supported.
**0**: Completely overwrite the file with the same name and truncate the part that is not overwritten.| **Example** @@ -480,6 +539,10 @@ mkdir(path: string, mode?: number): Promise<void> Creates a directory. This API uses a promise to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.mkdir](js-apis-file-fs.md#fsmkdir) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -491,9 +554,9 @@ Creates a directory. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **Example** @@ -513,6 +576,10 @@ mkdir(path: string, mode: number, callback: AsyncCallback<void>): void Creates a directory. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.mkdir](js-apis-file-fs.md#fsmkdir-1) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -539,6 +606,10 @@ mkdirSync(path: string, mode?: number): void Synchronously creates a directory. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.mkdirSync](js-apis-file-fs.md#fsmkdirsync) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -562,6 +633,10 @@ open(path: string, flags?: number, mode?: number): Promise<number> Opens a file. This API uses a promise to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.open](js-apis-file-fs.md#fsopen) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -569,13 +644,13 @@ Opens a file. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | | path | string | Yes | Application sandbox path of the file. | -| flags | number | No | Option for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.
- **0o0**: Open the file in read-only mode.
- **0o1**: Open the file in write-only mode.
- **0o2**: Open the file in read/write mode.
In addition, you can specify the following options, separated using a bitwise OR operator (|). By default, no additional option is specified.
- **0o100**: If the file does not exist, create a file. The third parameter **mode** must also be specified.
- **0o200**: If **0o100** is added and the file already exists, throw an exception.
- **0o1000**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **0o2000**: Open the file in append mode. New data will be appended to the file (written to the end of the file).
- **0o4000**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
- **0o200000**: If **path** does not point to a directory, throw an exception.
- **0o400000**: If **path** points to a symbolic link, throw an exception.
- **0o4010000**: Open the file in synchronous I/O mode.| +| flags | number | No | Option for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.
- **0o0**: Open the file in read-only mode.
- **0o1**: Open the file in write-only mode.
- **0o2**: Open the file in read/write mode.
In addition, you can specify the following options, separated using a bitwise OR operator (|). By default, no additional option is specified.
- **0o100**: If the file does not exist, create it. If you use this option, you must also specify **mode**.
- **0o200**: If **0o100** is added and the file already exists, throw an exception.
- **0o1000**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **0o2000**: Open the file in append mode. New data will be appended to the file (added to the end of the file).
- **0o4000**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
- **0o200000**: If **path** does not point to a directory, throw an exception.

- **0o400000**: If **path** points to a symbolic link, throw an exception.
- **0o4010000**: Open the file in synchronous I/O mode.| | mode | number | No | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o660**.
- **0o660**: The owner and user group have the read and write permissions.
- **0o700**: The owner has the read, write, and execute permissions.
- **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| **Return value** -| Type | Description | -| --------------------- | ----------- | + | Type | Description | + | --------------------- | ----------- | | Promise<number> | Promise used to return the file descriptor of the file opened.| **Example** @@ -596,6 +671,10 @@ open(path: string, flags: number, mode: number, callback: AsyncCallback<numbe Opens a file. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.open](js-apis-file-fs.md#fsopen-1) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -603,7 +682,7 @@ Opens a file. This API uses an asynchronous callback to return the result. | Name | Type | Mandatory| Description | | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | | path | string | Yes | Application sandbox path of the file. | -| flags | number | No | Option for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.
- **0o0**: Open the file in read-only mode.
- **0o1**: Open the file in write-only mode.
- **0o2**: Open the file in read/write mode.
In addition, you can specify the following options, separated using a bitwise OR operator (|). By default, no additional option is specified.
- **0o100**: If the file does not exist, create a file. The third parameter **mode** must also be specified.
- **0o200**: If **0o100** is added and the file already exists, throw an exception.
- **0o1000**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **0o2000**: Open the file in append mode. New data will be appended to the file (written to the end of the file).
- **0o4000**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
- **0o200000**: If **path** does not point to a directory, throw an exception.
- **0o400000**: If **path** points to a symbolic link, throw an exception.
- **0o4010000**: Open the file in synchronous I/O mode.| +| flags | number | No | Option for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.
- **0o0**: Open the file in read-only mode.
- **0o1**: Open the file in write-only mode.
- **0o2**: Open the file in read/write mode.
In addition, you can specify the following options, separated using a bitwise OR operator (|). By default, no additional option is specified.
- **0o100**: If the file does not exist, create it. If you use this option, you must also specify **mode**.
- **0o200**: If **0o100** is added and the file already exists, throw an exception.
- **0o1000**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **0o2000**: Open the file in append mode. New data will be appended to the file (added to the end of the file).
- **0o4000**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
- **0o200000**: If **path** does not point to a directory, throw an exception.

- **0o400000**: If **path** points to a symbolic link, throw an exception.
- **0o4010000**: Open the file in synchronous I/O mode.| | mode | number | No | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o660**.
- **0o660**: The owner and user group have the read and write permissions.
- **0o700**: The owner has the read, write, and execute permissions.
- **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| | callback | AsyncCallback<number> | Yes | Callback invoked when the file is open asynchronously. | @@ -623,6 +702,10 @@ openSync(path: string, flags?: number, mode?: number): number Synchronously opens a file. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.openSync](js-apis-file-fs.md#fsopensync) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -630,14 +713,14 @@ Synchronously opens a file. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | | path | string | Yes | Application sandbox path of the file. | -| flags | number | No | Option for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.
- **0o0**: Open the file in read-only mode.
- **0o1**: Open the file in write-only mode.
- **0o2**: Open the file in read/write mode.
In addition, you can specify the following options, separated using a bitwise OR operator (|). By default, no additional option is specified.
- **0o100**: If the file does not exist, create a file. The third parameter **mode** must also be specified.
- **0o200**: If **0o100** is added and the file already exists, throw an exception.
- **0o1000**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **0o2000**: Open the file in append mode. New data will be appended to the file (written to the end of the file).
- **0o4000**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
- **0o200000**: If **path** does not point to a directory, throw an exception.
- **0o400000**: If **path** points to a symbolic link, throw an exception.
- **0o4010000**: Open the file in synchronous I/O mode.| +| flags | number | No | Option for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.
- **0o0**: Open the file in read-only mode.
- **0o1**: Open the file in write-only mode.
- **0o2**: Open the file in read/write mode.
In addition, you can specify the following options, separated using a bitwise OR operator (|). By default, no additional option is specified.
- **0o100**: If the file does not exist, create it. If you use this option, you must also specify **mode**.
- **0o200**: If **0o100** is added and the file already exists, throw an exception.
- **0o1000**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **0o2000**: Open the file in append mode. New data will be appended to the file (added to the end of the file).
- **0o4000**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
- **0o200000**: If **path** does not point to a directory, throw an exception.

- **0o400000**: If **path** points to a symbolic link, throw an exception.
- **0o4010000**: Open the file in synchronous I/O mode.| | mode | number | No | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o660**.
- **0o660**: The owner and user group have the read and write permissions.
- **0o640**: The owner has the read and write permissions, and the user group has the read permission.
- **0o700**: The owner has the read, write, and execute permissions.
- **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.
The file permissions on newly created files are affected by umask, which is set as the process starts. Currently, the modification of umask is not open.| **Return value** -| Type | Description | -| ------ | ----------- | -| number | File descriptor of the file opened.| + | Type | Description | + | ------ | ----------- | + | number | File descriptor of the file opened.| **Example** @@ -662,6 +745,10 @@ read(fd: number, buffer: ArrayBuffer, options?: { offset?: number; length?: numb Reads data from a file. This API uses a promise to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.read](js-apis-file-fs.md#fsread) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -674,9 +761,9 @@ Reads data from a file. This API uses a promise to return the result. **Return value** -| Type | Description | -| ---------------------------------- | ------ | -| Promise<[ReadOut](#readout)> | Promise used to return the data read.| + | Type | Description | + | ---------------------------------- | ------ | + | Promise<[ReadOut](#readout)> | Promise used to return the data read.| **Example** @@ -699,16 +786,20 @@ read(fd: number, buffer: ArrayBuffer, options: { offset?: number; length?: numbe Reads data from a file. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.read](js-apis-file-fs.md#fsread-1) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| fd | number | Yes | File descriptor of the file to read. | -| buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | -| options | Object | No | The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
Constraints: offset + length <= Buffer size | -| callback | AsyncCallback<[ReadOut](#readout)> | Yes | Callback invoked when the data is read asynchronously. | + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the file to read. | + | buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | + | options | Object | No | The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
Constraints: offset + length <= Buffer size | + | callback | AsyncCallback<[ReadOut](#readout)> | Yes | Callback invoked when the data is read asynchronously. | **Example** @@ -731,21 +822,25 @@ readSync(fd: number, buffer: ArrayBuffer, options?: { offset?: number; length?: Synchronously reads data from a file. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.readSync](js-apis-file-fs.md#fsreadsync) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ----------- | ---- | ---------------------------------------- | -| fd | number | Yes | File descriptor of the file to read. | -| buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | -| options | Object | No | The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
Constraints: offset + length <= Buffer size | + | Name | Type | Mandatory | Description | + | ------- | ----------- | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the file to read. | + | buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | + | options | Object | No | The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
Constraints: offset + length <= Buffer size | **Return value** -| Type | Description | -| ------ | -------- | -| number | Length of the data read.| + | Type | Description | + | ------ | -------- | + | number | Length of the data read.| **Example** @@ -763,6 +858,10 @@ rmdir(path: string): Promise<void> Deletes a directory. This API uses a promise to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.rmdir](js-apis-file-fs.md#fsrmdir) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -773,9 +872,9 @@ Deletes a directory. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **Example** @@ -795,6 +894,10 @@ rmdir(path: string, callback: AsyncCallback<void>): void Deletes a directory. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.rmdir](js-apis-file-fs.md#fsrmdir-1) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -821,6 +924,10 @@ rmdirSync(path: string): void Synchronously deletes a directory. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.rmdirSync](js-apis-file-fs.md#fsrmdirsync) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -843,6 +950,10 @@ unlink(path: string): Promise<void> Deletes a file. This API uses a promise to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.unlink](js-apis-file-fs.md#fsunlink) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -853,9 +964,9 @@ Deletes a file. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **Example** @@ -875,6 +986,10 @@ unlink(path: string, callback: AsyncCallback<void>): void Deletes a file. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.unlink](js-apis-file-fs.md#fsunlink-1) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -882,7 +997,7 @@ Deletes a file. This API uses an asynchronous callback to return the result. | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | -------------------------- | | path | string | Yes | Application sandbox path of the file.| -| callback | AsyncCallback<void> | Yes | Callback invoked when the file is deleted asynchronously. | +| callback | AsyncCallback<void> | Yes | Callback invoked immediately after the file is deleted. | **Example** @@ -900,6 +1015,10 @@ unlinkSync(path: string): void Synchronously deletes a file. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.unlinkSync](js-apis-file-fs.md#fsunlinksync) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -922,21 +1041,25 @@ write(fd: number, buffer: ArrayBuffer|string, options?: { offset?: number; lengt Writes data into a file. This API uses a promise to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.write](js-apis-file-fs.md#fswrite) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------------------------------- | ---- | ---------------------------------------- | -| fd | number | Yes | File descriptor of the file to write. | -| buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | -| options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.
Constraints: offset + length <= Buffer size| + | Name | Type | Mandatory | Description | + | ------- | ------------------------------- | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the file to write. | + | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | + | options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **utf-8**, which is the only value supported.
Constraints: offset + length <= Buffer size| **Return value** -| Type | Description | -| --------------------- | -------- | -| Promise<number> | Promise used to return the length of the data written.| + | Type | Description | + | --------------------- | -------- | + | Promise<number> | Promise used to return the length of the data written.| **Example** @@ -957,16 +1080,20 @@ write(fd: number, buffer: ArrayBuffer|string, options: { offset?: number; length Writes data into a file. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.write](js-apis-file-fs.md#fswrite-1) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------- | ---- | ---------------------------------------- | -| fd | number | Yes | File descriptor of the file to write. | -| buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | -| options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.
Constraints: offset + length <= Buffer size| -| callback | AsyncCallback<number> | Yes | Callback invoked when the data is written asynchronously. | + | Name | Type | Mandatory | Description | + | -------- | ------------------------------- | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the file to write. | + | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | + | options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **utf-8**, which is the only value supported.
Constraints: offset + length <= Buffer size| + | callback | AsyncCallback<number> | Yes | Callback invoked when the data is written asynchronously. | **Example** @@ -987,21 +1114,25 @@ writeSync(fd: number, buffer: ArrayBuffer|string, options?: { offset?: number; l Synchronously writes data into a file. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.writeSync](js-apis-file-fs.md#fswritesync) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------------------------------- | ---- | ---------------------------------------- | -| fd | number | Yes | File descriptor of the file to write. | -| buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | -| options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.
Constraints: offset + length <= Buffer size| + | Name | Type | Mandatory | Description | + | ------- | ------------------------------- | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the file to write. | + | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | + | options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **utf-8**, which is the only value supported.
Constraints: offset + length <= Buffer size| **Return value** -| Type | Description | -| ------ | -------- | -| number | Length of the data written in the file.| + | Type | Description | + | ------ | -------- | + | number | Length of the data written in the file.| **Example** @@ -1018,6 +1149,10 @@ hash(path: string, algorithm: string): Promise<string> Calculates the hash value of a file. This API uses a promise to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [hash.write](js-apis-file-hash.md#hashhash) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -1029,8 +1164,8 @@ Calculates the hash value of a file. This API uses a promise to return the resul **Return value** -| Type | Description | -| --------------------- | -------------------------- | + | Type | Description | + | --------------------- | -------------------------- | | Promise<string> | Promise used to return the hash value obtained. The hash value is a hexadecimal string consisting of digits and uppercase letters.| **Example** @@ -1051,6 +1186,10 @@ hash(path: string, algorithm: string, callback: AsyncCallback<string>): vo Calculates the hash value of a file. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [hash.write](js-apis-file-hash.md#hashhash-1) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -1079,6 +1218,10 @@ chmod(path: string, mode: number): Promise<void> Changes file permissions. This API uses a promise to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -1090,9 +1233,9 @@ Changes file permissions. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **Example** @@ -1112,6 +1255,10 @@ chmod(path: string, mode: number, callback: AsyncCallback<void>): void Changes file permissions. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -1138,6 +1285,10 @@ chmodSync(path: string, mode: number): void Synchronously changes file permissions. +> **NOTE** +> +> This API is deprecated since API version 9. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -1161,18 +1312,22 @@ fstat(fd: number): Promise<Stat> Obtains file information based on the file descriptor. This API uses a promise to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.stat](js-apis-file-fs.md#fsstat) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ------------ | -| fd | number | Yes | Descriptor of the target file.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | Descriptor of the target file.| **Return value** -| Type | Description | -| ---------------------------- | ---------- | + | Type | Description | + | ---------------------------- | ---------- | | Promise<[Stat](#stat)> | Promise used to return the file information obtained.| **Example** @@ -1194,14 +1349,18 @@ fstat(fd: number, callback: AsyncCallback<Stat>): void Obtains file information based on the file descriptor. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.stat](js-apis-file-fs.md#fsstat-1) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------- | ---- | ---------------- | + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------- | ---- | ---------------- | | fd | number | Yes | File descriptor of the target file. | -| callback | AsyncCallback<[Stat](#stat)> | Yes | Callback invoked to return the file information obtained.| + | callback | AsyncCallback<[Stat](#stat)> | Yes | Callback invoked to return the file information obtained.| **Example** @@ -1220,18 +1379,22 @@ fstatSync(fd: number): Stat Synchronously obtains file information based on the file descriptor. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.statSync](js-apis-file-fs.md#fsstatsync) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ------------ | + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | | fd | number | Yes | File descriptor of the target file.| **Return value** -| Type | Description | -| ------------- | ---------- | + | Type | Description | + | ------------- | ---------- | | [Stat](#stat) | File information obtained.| **Example** @@ -1249,20 +1412,24 @@ ftruncate(fd: number, len?: number): Promise<void> Truncates a file based on the file descriptor. This API uses a promise to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.truncate](js-apis-file-fs.md#fstruncate) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ---------------- | -| fd | number | Yes | File descriptor of the file to truncate. | -| len | number | No | File length, in bytes, after truncation.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------- | + | fd | number | Yes | File descriptor of the file to truncate. | + | len | number | No | File length, in bytes, after truncation.| **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **Example** @@ -1283,15 +1450,19 @@ ftruncate(fd: number, len?: number, callback: AsyncCallback<void>): void Truncates a file based on the file descriptor. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.truncate](js-apis-file-fs.md#fstruncate-1) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | ---- | ---------------- | -| fd | number | Yes | File descriptor of the file to truncate. | -| len | number | No | File length, in bytes, after truncation.| -| callback | AsyncCallback<void> | Yes | Callback that returns no value. | + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ---------------- | + | fd | number | Yes | File descriptor of the file to truncate. | + | len | number | No | File length, in bytes, after truncation.| + | callback | AsyncCallback<void> | Yes | Callback that returns no value. | **Example** @@ -1311,14 +1482,18 @@ ftruncateSync(fd: number, len?: number): void Synchronously truncates a file based on the file descriptor. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.truncateSync](js-apis-file-fs.md#fstruncatesync) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ---------------- | -| fd | number | Yes | File descriptor of the file to truncate. | -| len | number | No | File length, in bytes, after truncation.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------- | + | fd | number | Yes | File descriptor of the file to truncate. | + | len | number | No | File length, in bytes, after truncation.| **Example** @@ -1336,6 +1511,10 @@ truncate(path: string, len?: number): Promise<void> Truncates a file based on the file path. This API uses a promise to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.truncate](js-apis-file-fs.md#fstruncate) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -1347,9 +1526,9 @@ Truncates a file based on the file path. This API uses a promise to return the r **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **Example** @@ -1370,6 +1549,10 @@ truncate(path: string, len?: number, callback: AsyncCallback<void>): void Truncates a file based on the file path. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.truncate](js-apis-file-fs.md#fstruncate-1) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -1397,6 +1580,10 @@ truncateSync(path: string, len?: number): void Synchronously truncates a file based on the file path. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.truncateSync](js-apis-file-fs.md#fstruncatesync) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -1421,6 +1608,10 @@ readText(filePath: string, options?: { position?: number; length?: number; encod Reads the text content of a file. This API uses a promise to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.readText](js-apis-file-fs.md#fsreadtext) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -1428,13 +1619,13 @@ Reads the text content of a file. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | | filePath | string | Yes | Application sandbox path of the file to read. | -| options | Object | No | The options are as follows:
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **encoding** (string): format of the string to be encoded. The default value is **'utf-8'**, which is the only value supported.| +| options | Object | No | The options are as follows:
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **encoding** (string): format of the string to be encoded. The default value is **utf-8**, which is the only value supported.| **Return value** -| Type | Description | -| --------------------- | ---------- | -| Promise<string> | Promise used to return the content read.| + | Type | Description | + | --------------------- | ---------- | + | Promise<string> | Promise used to return the file content read.| **Example** @@ -1454,6 +1645,10 @@ readText(filePath: string, options: { position?: number; length?: number; encodi Reads the text content of a file. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.readText](js-apis-file-fs.md#fsreadtext-1) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -1461,8 +1656,8 @@ Reads the text content of a file. This API uses an asynchronous callback to retu | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | ------------------------------------------------------------ | | filePath | string | Yes | Application sandbox path of the file to read. | -| options | Object | No | The options are as follows:
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **encoding** (string): format of the string to be encoded. The default value is **'utf-8'**, which is the only value supported.| -| callback | AsyncCallback<string> | Yes | Callback used to return the content read. | +| options | Object | No | The options are as follows:
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **encoding** (string): format of the string to be encoded. The default value is **utf-8**, which is the only value supported.| +| callback | AsyncCallback<string> | Yes | Callback invoked to return the content read. | **Example** @@ -1480,6 +1675,10 @@ readTextSync(filePath: string, options?: { position?: number; length?: number; e Synchronously reads the text of a file. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.readTextSync](js-apis-file-fs.md#fsreadtextsync) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -1487,13 +1686,13 @@ Synchronously reads the text of a file. | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | | filePath | string | Yes | Application sandbox path of the file to read. | -| options | Object | No | The options are as follows:
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **encoding** (string): format of the string to be encoded. The default value is **'utf-8'**, which is the only value supported.| +| options | Object | No | The options are as follows:
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **encoding** (string): format of the string to be encoded. The default value is **utf-8**, which is the only value supported.| **Return value** -| Type | Description | -| ------ | -------------------- | -| string | Promise used to return the content of the file read.| + | Type | Description | + | ------ | -------------------- | + | string | File content read.| **Example** @@ -1509,6 +1708,10 @@ lstat(path: string): Promise<Stat> Obtains link information. This API uses a promise to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.lstat](js-apis-file-fs.md#fslstat) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -1519,9 +1722,9 @@ Obtains link information. This API uses a promise to return the result. **Return value** -| Type | Description | -| ---------------------------- | ---------- | -| Promise<[Stat](#stat)> | Promise used to return the link information obtained. For details, see [Stat](#stat).| + | Type | Description | + | ---------------------------- | ---------- | + | Promise<[Stat](#stat)> | Promise used to return the symbolic link information obtained. For details, see **stat**.| **Example** @@ -1541,6 +1744,10 @@ lstat(path: string, callback: AsyncCallback<Stat>): void Obtains link information. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.lstat](js-apis-file-fs.md#fslstat-1) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -1548,7 +1755,7 @@ Obtains link information. This API uses an asynchronous callback to return the r | Name | Type | Mandatory| Description | | -------- | ---------------------------------- | ---- | -------------------------------------- | | path | string | Yes | Application sandbox path of the target file.| -| callback | AsyncCallback<[Stat](#stat)> | Yes | Callback used to return the link information obtained. | +| callback | AsyncCallback<[Stat](#stat)> | Yes | Callback invoked to return the symbolic link information obtained. | **Example** @@ -1566,6 +1773,10 @@ lstatSync(path: string): Stat Synchronously obtains the link information. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.lstatSync](js-apis-file-fs.md#fslstatsync) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -1576,8 +1787,8 @@ Synchronously obtains the link information. **Return value** -| Type | Description | -| ------------- | ---------- | + | Type | Description | + | ------------- | ---------- | | [Stat](#stat) | Link information obtained.| **Example** @@ -1594,6 +1805,10 @@ rename(oldPath: string, newPath: string): Promise<void> Renames a file. This API uses a promise to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.rename](js-apis-file-fs.md#fsrename) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -1605,9 +1820,9 @@ Renames a file. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **Example** @@ -1628,6 +1843,10 @@ rename(oldPath: string, newPath: string, callback: AsyncCallback<void>): v Renames a file. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.rename](js-apis-file-fs.md#fsrename-1) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -1647,13 +1866,16 @@ Renames a file. This API uses an asynchronous callback to return the result. }); ``` - ## fileio.renameSync7+ renameSync(oldPath: string, newPath: string): void Synchronously renames a file. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.renameSync](js-apis-file-fs.md#fsrenamesync) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -1678,19 +1900,23 @@ fsync(fd: number): Promise<void> Flushes data of a file to disk. This API uses a promise to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.fsync](js-apis-file-fs.md#fsfsync) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ------------ | -| fd | number | Yes | File descriptor of the file to flush.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor of the file to flush.| **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **Example** @@ -1711,14 +1937,18 @@ fsync(fd: number, callback: AsyncCallback<void>): void Flushes data of a file to disk. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.fsync](js-apis-file-fs.md#fsfsync-1) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | ---- | --------------- | -| fd | number | Yes | File descriptor of the file to flush. | -| Callback | AsyncCallback<void> | Yes | Callback invoked when the file is synchronized in asynchronous mode.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | --------------- | + | fd | number | Yes | File descriptor of the file to flush. | + | Callback | AsyncCallback<void> | Yes | Callback invoked when the file data is synchronized in asynchronous mode.| **Example** @@ -1735,15 +1965,19 @@ Flushes data of a file to disk. This API uses an asynchronous callback to return fsyncSync(fd: number): void -Flushes data of a file to disk in synchronous mode. +Flushes data of a file to disk synchronously. + +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.fsyncSync](js-apis-file-fs.md#fsfsyncsync) instead. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ------------ | -| fd | number | Yes | File descriptor of the file to flush.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor of the file to flush.| **Example** @@ -1760,19 +1994,23 @@ fdatasync(fd: number): Promise<void> Flushes data of a file to disk. This API uses a promise to return the result. **fdatasync()** is similar to **fsync()**, but does not flush modified metadata unless that metadata is needed. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.fdatasync](js-apis-file-fs.md#fsfdatasync) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ------------ | -| fd | number | Yes | File descriptor of the file to flush.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor of the file to flush.| **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **Example** @@ -1793,14 +2031,18 @@ fdatasync(fd: number, callback: AsyncCallback<void>): void Flushes data of a file to disk. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.fdatasync](js-apis-file-fs.md#fsfdatasync-1) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------- | ---- | ----------------- | -| fd | number | Yes | File descriptor of the file to synchronize. | -| callback | AsyncCallback<void> | Yes | Callback invoked when the file data is synchronized in asynchronous mode.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------------- | ---- | ----------------- | + | fd | number | Yes | File descriptor of the file to synchronize. | + | callback | AsyncCallback<void> | Yes | Callback invoked when the file data is synchronized in asynchronous mode.| **Example** @@ -1817,15 +2059,19 @@ Flushes data of a file to disk. This API uses an asynchronous callback to return fdatasyncSync(fd: number): void -Synchronizes data in a file in synchronous mode. +Synchronizes data in a file synchronously. + +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.fdatasyncSync](js-apis-file-fs.md#fsfdatasyncsync) instead. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ------------ | -| fd | number | Yes | File descriptor of the file to flush.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor of the file to flush.| **Example** @@ -1842,6 +2088,10 @@ symlink(target: string, srcPath: string): Promise<void> Creates a symbolic link based on the file path. This API uses a promise to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.symlink](js-apis-file-fs.md#fssymlink) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -1849,13 +2099,13 @@ Creates a symbolic link based on the file path. This API uses a promise to retur | Name | Type | Mandatory| Description | | ------- | ------ | ---- | ---------------------------- | | target | string | Yes | Application sandbox path of the target file. | -| srcPath | string | Yes | Application sandbox path of the symbolic link file.| +| srcPath | string | Yes | Application sandbox path of the symbolic link.| **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **Example** @@ -1876,6 +2126,10 @@ symlink(target: string, srcPath: string, callback: AsyncCallback<void>): v Creates a symbolic link based on the file path. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.symlink](js-apis-file-fs.md#fssymlink-1) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -1883,7 +2137,7 @@ Creates a symbolic link based on the file path. This API uses an asynchronous ca | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | -------------------------------- | | target | string | Yes | Application sandbox path of the target file. | -| srcPath | string | Yes | Application sandbox path of the symbolic link file. | +| srcPath | string | Yes | Application sandbox path of the symbolic link. | | callback | AsyncCallback<void> | Yes | Callback invoked when the symbolic link is created asynchronously.| **Example** @@ -1903,6 +2157,10 @@ symlinkSync(target: string, srcPath: string): void Synchronously creates a symbolic link based on a specified path. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.symlinkSync](js-apis-file-fs.md#fssymlinksync) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -1910,7 +2168,7 @@ Synchronously creates a symbolic link based on a specified path. | Name | Type | Mandatory| Description | | ------- | ------ | ---- | ---------------------------- | | target | string | Yes | Application sandbox path of the target file. | -| srcPath | string | Yes | Application sandbox path of the symbolic link file.| +| srcPath | string | Yes | Application sandbox path of the symbolic link.| **Example** @@ -1927,6 +2185,10 @@ chown(path: string, uid: number, gid: number): Promise<void> Changes the file owner based on the file path. This API uses a promise to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -1939,9 +2201,9 @@ Changes the file owner based on the file path. This API uses a promise to return **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **Example** @@ -1962,6 +2224,10 @@ chown(path: string, uid: number, gid: number, callback: AsyncCallback<void> Changes the file owner based on the file path. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -1983,13 +2249,16 @@ Changes the file owner based on the file path. This API uses an asynchronous cal }); ``` - ## fileio.chownSync7+ chownSync(path: string, uid: number, gid: number): void Synchronously changes the file owner based on its path. +> **NOTE** +> +> This API is deprecated since API version 9. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -2015,18 +2284,22 @@ mkdtemp(prefix: string): Promise<string> Creates a temporary directory. This API uses a promise to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.mkdtemp](js-apis-file-fs.md#fsmkdtemp) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | --------------------------- | -| prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| **Return value** -| Type | Description | -| --------------------- | ---------- | + | Type | Description | + | --------------------- | ---------- | | Promise<string> | Promise used to return the unique directory generated.| **Example** @@ -2046,14 +2319,18 @@ mkdtemp(prefix: string, callback: AsyncCallback<string>): void Creates a temporary directory. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.mkdtemp](js-apis-file-fs.md#fsmkdtemp-1) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------- | ---- | --------------------------- | -| prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| -| callback | AsyncCallback<string> | Yes | Callback invoked when a temporary directory is created asynchronously. | + | Name | Type | Mandatory | Description | + | -------- | --------------------------- | ---- | --------------------------- | + | prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| + | callback | AsyncCallback<string> | Yes | Callback invoked when a temporary directory is created asynchronously. | **Example** @@ -2070,19 +2347,23 @@ mkdtempSync(prefix: string): string Synchronously creates a temporary directory. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.mkdtempSync](js-apis-file-fs.md#fsmkdtempsync) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | --------------------------- | -| prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| **Return value** -| Type | Description | -| ------ | ---------- | -| string | Unique path generated.| + | Type | Description | + | ------ | ---------- | + | string | Unique path generated.| **Example** @@ -2097,20 +2378,24 @@ fchmod(fd: number, mode: number): Promise<void> Changes file permissions based on the file descriptor. This API uses a promise to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ---------------------------------------- | -| fd | number | Yes | File descriptor of the target file. | -| mode | number | Yes | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
- **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the target file. | + | mode | number | Yes | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
- **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **Example** @@ -2132,15 +2417,19 @@ fchmod(fd: number, mode: number, callback: AsyncCallback<void>): void Changes file permissions based on the file descriptor. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------- | ---- | ---------------------------------------- | -| fd | number | Yes | File descriptor of the target file. | -| mode | number | Yes | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
- **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| -| callback | AsyncCallback<void> | Yes | Callback invoked when the file permissions are changed asynchronously. | + | Name | Type | Mandatory | Description | + | -------- | ------------------------------- | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the target file. | + | mode | number | Yes | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
- **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| + | callback | AsyncCallback<void> | Yes | Callback invoked when the file permissions are changed asynchronously. | **Example** @@ -2160,14 +2449,18 @@ fchmodSync(fd: number, mode: number): void Synchronously changes the file permissions based on the file descriptor. +> **NOTE** +> +> This API is deprecated since API version 9. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ---------------------------------------- | -| fd | number | Yes | File descriptor of the target file. | -| mode | number | Yes | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
- **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the target file. | + | mode | number | Yes | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
- **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| **Example** @@ -2183,7 +2476,11 @@ Synchronously changes the file permissions based on the file descriptor. createStream(path: string, mode: string): Promise<Stream> -Opens a file stream based on the file path. This API uses a promise to return the result. +Creates a stream based on the file path. This API uses a promise to return the result. + +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.createStream](js-apis-file-fs.md#fscreatestream) instead. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -2196,9 +2493,9 @@ Opens a file stream based on the file path. This API uses a promise to return th **Return value** -| Type | Description | -| --------------------------------- | --------- | -| Promise<[Stream](#stream)> | Promise used to return the result.| + | Type | Description | + | --------------------------------- | --------- | + | Promise<[Stream](#stream)> | Promise used to return the stream opened.| **Example** @@ -2216,7 +2513,11 @@ Opens a file stream based on the file path. This API uses a promise to return th createStream(path: string, mode: string, callback: AsyncCallback<Stream>): void -Opens a file stream based on the file path. This API uses an asynchronous callback to return the result. +Creates a stream based on the file path. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.createStream](js-apis-file-fs.md#fscreatestream-1) instead. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -2226,7 +2527,7 @@ Opens a file stream based on the file path. This API uses an asynchronous callba | -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | | path | string | Yes | Application sandbox path of the file. | | mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| -| callback | AsyncCallback<[Stream](#stream)> | Yes | Callback invoked when the stream is open asynchronously. | +| callback | AsyncCallback<[Stream](#stream)> | Yes | Callback invoked when the stream is created asynchronously. | **Example** @@ -2242,7 +2543,11 @@ Opens a file stream based on the file path. This API uses an asynchronous callba createStreamSync(path: string, mode: string): Stream -Synchronously opens a stream based on the file path. +Synchronously creates a stream based on the file path. + +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.createStreamSync](js-apis-file-fs.md#fscreatestreamsync) instead. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -2255,9 +2560,9 @@ Synchronously opens a stream based on the file path. **Return value** -| Type | Description | -| ------------------ | --------- | -| [Stream](#stream) | Stream opened.| + | Type | Description | + | ------------------ | --------- | +| [Stream](#stream) | Stream created.| **Example** @@ -2271,22 +2576,26 @@ Synchronously opens a stream based on the file path. fdopenStream(fd: number, mode: string): Promise<Stream> -Opens a file stream based on the file descriptor. This API uses a promise to return the result. +Opens a stream based on the file descriptor. This API uses a promise to return the result. + +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.fdopenStream](js-apis-file-fs.md#fsfdopenstream) instead. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ---------------------------------------- | -| fd | number | Yes | File descriptor of the target file. | -| mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the target file. | + | mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| **Return value** -| Type | Description | -| --------------------------------- | --------- | -| Promise<[Stream](#stream)> | Promise used to return the result.| + | Type | Description | + | --------------------------------- | --------- | + | Promise<[Stream](#stream)> | Promise used to return the stream opened.| **Example** @@ -2305,16 +2614,20 @@ Opens a file stream based on the file descriptor. This API uses a promise to ret fdopenStream(fd: number, mode: string, callback: AsyncCallback<Stream>): void -Opens a file stream based on the file descriptor. This API uses an asynchronous callback to return the result. +Opens a stream based on the file descriptor. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.fdopenStream](js-apis-file-fs.md#fsfdopenstream-1) instead. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| fd | number | Yes | File descriptor of the target file. | -| mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the target file. | + | mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| | callback | AsyncCallback<[Stream](#stream)> | Yes | Callback invoked when the stream is open asynchronously. | **Example** @@ -2334,19 +2647,23 @@ fdopenStreamSync(fd: number, mode: string): Stream Synchronously opens a stream based on the file descriptor. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.fdopenStreamSync](js-apis-file-fs.md#fsfdopenstreamsync) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ---------------------------------------- | -| fd | number | Yes | File descriptor of the target file. | -| mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the target file. | + | mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| **Return value** -| Type | Description | -| ------------------ | --------- | + | Type | Description | + | ------------------ | --------- | | [Stream](#stream) | Stream opened.| **Example** @@ -2364,21 +2681,25 @@ fchown(fd: number, uid: number, gid: number): Promise<void> Changes the file owner based on the file descriptor. This API uses a promise to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ------------ | -| fd | number | Yes | File descriptor of the target file.| -| uid | number | Yes | New UID. | -| gid | number | Yes | New GID. | + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor of the target file.| + | uid | number | Yes | New UID. | + | gid | number | Yes | New GID. | **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **Example** @@ -2400,16 +2721,20 @@ fchown(fd: number, uid: number, gid: number, callback: AsyncCallback<void> Changes the file owner based on the file descriptor. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | ---- | --------------- | -| fd | number | Yes | File descriptor of the target file. | -| uid | number | Yes | New UID. | -| gid | number | Yes | New GID. | -| callback | AsyncCallback<void> | Yes | Callback invoked when the file owner is changed asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | --------------- | + | fd | number | Yes | File descriptor of the target file. | + | uid | number | Yes | New UID. | + | gid | number | Yes | New GID. | + | callback | AsyncCallback<void> | Yes | Callback invoked when the file owner is changed asynchronously.| **Example** @@ -2429,15 +2754,19 @@ fchownSync(fd: number, uid: number, gid: number): void Synchronously changes the file owner based on the file descriptor. +> **NOTE** +> +> This API is deprecated since API version 9. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ------------ | -| fd | number | Yes | File descriptor of the target file.| -| uid | number | Yes | New UID. | -| gid | number | Yes | New GID. | + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor of the target file.| + | uid | number | Yes | New UID. | + | gid | number | Yes | New GID. | **Example** @@ -2455,6 +2784,10 @@ lchown(path: string, uid: number, gid: number): Promise<void> Changes the file owner (owner of the symbolic link, not the file referred to by the symbolic link) based on the file path. This API uses a promise to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -2467,9 +2800,9 @@ Changes the file owner (owner of the symbolic link, not the file referred to by **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **Example** @@ -2490,6 +2823,10 @@ lchown(path: string, uid: number, gid: number, callback: AsyncCallback<void&g Changes the file owner (owner of the symbolic link, not the file referred to by the symbolic link) based on the file path. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -2518,6 +2855,10 @@ lchownSync(path: string, uid: number, gid: number): void Synchronously changes the file owner based on the file path and changes the owner of the symbolic link (not the referenced file). +> **NOTE** +> +> This API is deprecated since API version 9. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** @@ -2550,13 +2891,13 @@ Listens for file or directory changes. This API uses an asynchronous callback to | Name | Type | Mandatory| Description | | -------- | --------------------------------- | ---- | ------------------------------------------------------------ | | filePath | string | Yes | Application sandbox path of the file. | -| events | number | Yes | -**1**: The file or directory is renamed.
- **2**: The file or directory is modified.
- **3**: The file or directory is modified and renamed.| +| events | number | Yes | - **1**: The file or directory is renamed.
- **2**: The file or directory is modified.
- **3**: The file or directory is modified and renamed.| | callback | AsyncCallback<number> | Yes | Called each time a change is detected. | **Return value** -| Type | Description | -| -------------------- | ---------- | + | Type | Description | + | -------------------- | ---------- | | [Watcher](#watcher7) | Promise used to return the **Watcher** instance.| **Example** @@ -2574,6 +2915,10 @@ Listens for file or directory changes. This API uses an asynchronous callback to Obtains the file read result. This class applies only to the **read()** method. +> **NOTE** +> +> This API is deprecated since API version 9. + **System capability**: SystemCapability.FileManagement.File.FileIO | Name | Type | Readable | Writable | Description | @@ -2587,6 +2932,10 @@ Obtains the file read result. This class applies only to the **read()** method. Provides detailed file information. Before calling a method of the **Stat** class, use the [stat()](#fileiostat) method synchronously or asynchronously to create a **Stat** instance. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.Stat](js-apis-file-fs.md#stat) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO ### Attributes @@ -2595,7 +2944,7 @@ Provides detailed file information. Before calling a method of the **Stat** clas | ------ | ------ | ---- | ---- | ---------------------------------------- | | dev | number | Yes | No | Major device number. | | ino | number | Yes | No | File ID. Different files on the same device have different **ino**s. | -| mode | number | Yes | No | File type and permissions. The first four bits indicate the file type, and the last 12 bits indicate the permissions. The bit fields are described as follows:
- **0o170000**: mask used to obtain the file type.
- **0o140000**: The file is a socket.
- **0o120000**: The file is a symbolic link.
- **0o100000**: The file is a regular file.
- **0o060000**: The file is a block device.
- **0o040000**: The file is a directory.
- **0o020000**: The file is a character device.
- **0o010000**: The file is a named pipe, that is, FIFO.
- **0o0700**: mask used to obtain owner permissions.
- **0o0400**: The owner has the read permission on a regular file or a directory entry.
- **0o0200**: The owner has the permission to write a regular file or create and delete a directory entry.
- **0o0100**: The owner has the permission to execute a regular file or has the permission to search for the specified path in a directory.
- **0o0070**: mask used to obtain user group permissions.
- **0o0040**: The user group has the read permission on a regular file or a directory entry.
- **0o0020**: The user group has the permission to write a regular file or has the permission to create and delete a directory entry.
- **0o0010**: The user group has the permission to execute a regular file or has the permission to search for the specified path in a directory.
- **0o0007**: mask used to obtain permissions of other users.
- **0o0004**: Other user groups have the read permission on a regular file or a directory entry.
- **0o0002**: Other user groups have the permission to write a regular file or have the permission to create and delete a directory entry.
- **0o0001**: Other users have the permission to execute a regular file or search for the specified path in a directory.| +| mode | number | Yes | No | File type and permissions. The first four bits indicate the file type, and the last 12 bits indicate the permissions. The bit fields are described as follows:
- **0o170000**: mask used to obtain the file type.
- **0o140000**: The file is a socket.
- **0o120000**: The file is a symbolic link.
- **0o100000**: The file is a regular file.
- **0o060000**: The file is a block device.
- **0o040000**: The file is a directory.
- **0o020000**: The file is a character device.
- **0o010000**: The file is a named pipe (FIFO).
- **0o0700**: mask used to obtain the owner permissions.
- **0o0400**: The owner has the permission to read a regular file or a directory entry.
- **0o0200**: The owner has the permission to write a regular file or create and delete a directory entry.
- **0o0100**: The owner has the permission to execute a regular file or search for the specified path in a directory.
- **0o0070**: mask used to obtain the user group permissions.
- **0o0040**: The user group has the permission to read a regular file or a directory entry.
- **0o0020**: The user group has the permission to write a regular file or create and delete a directory entry.
- **0o0010**: The user group has the permission to execute a regular file or search for the specified path in a directory.
- **0o0007**: mask used to obtain the permissions of other users.
- **0o0004**: Other users have the permission to read a regular file or a directory entry.
- **0o0002**: Other users have the permission to write a regular file or create and delete a directory entry.
- **0o0001**: Other users have the permission to execute a regular file or search for the specified path in a directory.| | nlink | number | Yes | No | Number of hard links in the file. | | uid | number | Yes | No | User ID, that is ID of the file owner. | | gid | number | Yes | No | Group ID, that is, ID of the user group of the file. | @@ -2613,13 +2962,17 @@ isBlockDevice(): boolean Checks whether this file is a block special file. A block special file supports access by block only, and it is cached when accessed. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.Stat.isBlockDevice](js-apis-file-fs.md#isblockdevice) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** -| Type | Description | -| ------- | ---------------- | -| boolean | Whether the file is a block special file.| + | Type | Description | + | ------- | ---------------- | + | boolean | Whether the file is a block special file.| **Example** @@ -2635,13 +2988,17 @@ isCharacterDevice(): boolean Checks whether this file is a character special file. A character special file supports random access, and it is not cached when accessed. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.Stat.isCharacterDevice](js-apis-file-fs.md#ischaracterdevice) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** -| Type | Description | -| ------- | ----------------- | -| boolean | Whether the file is a character special file.| + | Type | Description | + | ------- | ----------------- | + | boolean | Whether the file is a character special file.| **Example** @@ -2657,13 +3014,17 @@ isDirectory(): boolean Checks whether this file is a directory. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.Stat.isDirectory](js-apis-file-fs.md#isdirectory) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** -| Type | Description | -| ------- | ------------- | -| boolean | Whether the file is a directory.| + | Type | Description | + | ------- | ------------- | + | boolean | Whether the file is a directory.| **Example** @@ -2679,13 +3040,17 @@ isFIFO(): boolean Checks whether this file is a named pipe (or FIFO). Named pipes are used for inter-process communication. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.Stat.isFIFO](js-apis-file-fs.md#isfifo) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** -| Type | Description | -| ------- | --------------------- | -| boolean | Whether the file is an FIFO.| + | Type | Description | + | ------- | --------------------- | + | boolean | Whether the file is an FIFO.| **Example** @@ -2701,13 +3066,17 @@ isFile(): boolean Checks whether this file is a regular file. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.Stat.isFile](js-apis-file-fs.md#isfile) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** -| Type | Description | -| ------- | --------------- | -| boolean | Whether the file is a regular file.| + | Type | Description | + | ------- | --------------- | + | boolean | Whether the file is a regular file.| **Example** @@ -2723,13 +3092,17 @@ isSocket(): boolean Checks whether this file is a socket. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.Stat.isSocket](js-apis-file-fs.md#issocket) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** -| Type | Description | -| ------- | -------------- | -| boolean | Whether the file is a socket.| + | Type | Description | + | ------- | -------------- | + | boolean | Whether the file is a socket.| **Example** @@ -2745,13 +3118,17 @@ isSymbolicLink(): boolean Checks whether this file is a symbolic link. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.Stat.isSymbolicLink](js-apis-file-fs.md#issymboliclink) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** -| Type | Description | -| ------- | --------------- | -| boolean | Whether the file is a symbolic link.| + | Type | Description | + | ------- | --------------- | + | boolean | Whether the file is a symbolic link.| **Example** @@ -2797,9 +3174,9 @@ Stops the **watcher** instance. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | ---- | ---------------------- | -| callback | AsyncCallback<void> | Yes | Callback invoked when **watcher** is stopped asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ---------------------- | + | callback | AsyncCallback<void> | Yes | Callback invoked when **watcher** is stopped asynchronously.| **Example** @@ -2816,8 +3193,11 @@ Stops the **watcher** instance. This API uses an asynchronous callback to return ## Stream -Provides file stream management. Before calling a method of the **Stream** class, use the **createStream()** method synchronously or asynchronously to create a **Stream** instance. +Provides a stream for file operations. Before calling any API of the **Stream** class, use **createStream()** to create a **Stream** instance synchronously or asynchronously. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.Stream](js-apis-file-fs.md#stream) instead. ### close7+ @@ -2825,12 +3205,16 @@ close(): Promise<void> Closes the stream. This API uses a promise to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.Stream.close](js-apis-file-fs.md#close) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** -| Type | Description | -| ------------------- | ------------- | + | Type | Description | + | ------------------- | ------------- | | Promise<void> | Promise used to return the stream close result.| **Example** @@ -2852,13 +3236,17 @@ close(callback: AsyncCallback<void>): void Closes the stream. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.Stream.close](js-apis-file-fs.md#close-1) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | ---- | ------------- | -| callback | AsyncCallback<void> | Yes | Callback invoked when the stream is closed asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ------------- | + | callback | AsyncCallback<void> | Yes | Callback invoked immediately after the stream is closed.| **Example** @@ -2877,6 +3265,10 @@ closeSync(): void Synchronously closes the stream. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.Stream.closeSync](js-apis-file-fs.md#closesync) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Example** @@ -2894,13 +3286,17 @@ flush(): Promise<void> Flushes the stream. This API uses a promise to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.Stream.flush](js-apis-file-fs.md#flush) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** -| Type | Description | -| ------------------- | ------------- | -| Promise<void> | Promise used to return the stream flushing result.| + | Type | Description | + | ------------------- | ------------- | + | Promise<void> | Promise used to return the result.| **Example** @@ -2921,13 +3317,17 @@ flush(callback: AsyncCallback<void>): void Flushes the stream. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.Stream.flush](js-apis-file-fs.md#flush-1) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | ---- | -------------- | -| callback | AsyncCallback<void> | Yes | Callback invoked when the stream is asynchronously flushed.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | -------------- | + | callback | AsyncCallback<void> | Yes | Callback invoked when the stream is asynchronously flushed.| **Example** @@ -2946,6 +3346,10 @@ flushSync(): void Synchronously flushes the stream. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.Stream.flushSync](js-apis-file-fs.md#flushsync) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Example** @@ -2963,20 +3367,24 @@ write(buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; Writes data into the stream. This API uses a promise to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.Stream.write](js-apis-file-fs.md#write) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------------------------------- | ---- | ---------------------------------------- | -| buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | -| options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.
Constraints: offset + length <= Buffer size | + | Name | Type | Mandatory | Description | + | ------- | ------------------------------- | ---- | ---------------------------------------- | + | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | + | options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **utf-8**, which is the only value supported.
Constraints: offset + length <= Buffer size | **Return value** -| Type | Description | -| --------------------- | -------- | -| Promise<number> | Promise used to return the length of the data written.| + | Type | Description | + | --------------------- | -------- | + | Promise<number> | Promise used to return the length of the data written.| **Example** @@ -2997,15 +3405,19 @@ write(buffer: ArrayBuffer|string, options: { offset?: number; length?: number; p Writes data into the stream. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.Stream.write](js-apis-file-fs.md#write-1) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------- | ---- | ------------------------------------------------------------ | -| buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | -| options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.
Constraints: offset + length <= Buffer size| -| callback | AsyncCallback<number> | Yes | Callback invoked when the data is written asynchronously. | + | Name | Type | Mandatory| Description | + | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | + | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | + | options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **utf-8**, which is the only value supported.
Constraints: offset + length <= Buffer size| + | callback | AsyncCallback<number> | Yes | Callback invoked when the data is written asynchronously. | **Example** @@ -3027,20 +3439,24 @@ writeSync(buffer: ArrayBuffer|string, options?: { offset?: number; length?: numb Synchronously writes data into the stream. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.Stream.writeSync](js-apis-file-fs.md#writesync) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------------------------------- | ---- | ---------------------------------------- | -| buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | -| options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.
Constraints: offset + length <= Buffer size | + | Name | Type | Mandatory | Description | + | ------- | ------------------------------- | ---- | ---------------------------------------- | + | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | + | options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **utf-8**, which is the only value supported.
Constraints: offset + length <= Buffer size | **Return value** -| Type | Description | -| ------ | -------- | -| number | Length of the data written in the file.| + | Type | Description | + | ------ | -------- | + | number | Length of the data written in the file.| **Example** @@ -3057,20 +3473,24 @@ read(buffer: ArrayBuffer, options?: { position?: number; offset?: number; length Reads data from the stream. This API uses a promise to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.Stream.read](js-apis-file-fs.md#read) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ----------- | ---- | ---------------------------------------- | -| buffer | ArrayBuffer | Yes | Buffer used to store the file read. | -| options | Object | No | The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
Constraints: offset + length <= Buffer size | + | Name | Type | Mandatory | Description | + | ------- | ----------- | ---- | ---------------------------------------- | + | buffer | ArrayBuffer | Yes | Buffer used to store the file read. | + | options | Object | No | The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
Constraints: offset + length <= Buffer size | **Return value** -| Type | Description | -| ---------------------------------- | ------ | -| Promise<[ReadOut](#readout)> | Promise used to return the data read.| + | Type | Description | + | ---------------------------------- | ------ | + | Promise<[ReadOut](#readout)> | Promise used to return the data read.| **Example** @@ -3092,15 +3512,19 @@ read(buffer: ArrayBuffer, options: { position?: number; offset?: number; length? Reads data from the stream. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.Stream.read](js-apis-file-fs.md#read-1) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| buffer | ArrayBuffer | Yes | Buffer used to store the file read. | -| options | Object | No | The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
Constraints: offset + length <= Buffer size | -| callback | AsyncCallback<[ReadOut](#readout)> | Yes | Callback invoked when data is read asynchronously from the stream. | + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ---------------------------------------- | + | buffer | ArrayBuffer | Yes | Buffer used to store the file read. | + | options | Object | No | The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
Constraints: offset + length <= Buffer size | + | callback | AsyncCallback<[ReadOut](#readout)> | Yes | Callback invoked when data is read asynchronously from the stream. | **Example** @@ -3122,20 +3546,24 @@ readSync(buffer: ArrayBuffer, options?: { position?: number; offset?: number; le Synchronously reads data from the stream. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.Stream.readSync](js-apis-file-fs.md#readsync) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ----------- | ---- | ---------------------------------------- | -| buffer | ArrayBuffer | Yes | Buffer used to store the file read. | -| options | Object | No | The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
Constraints: offset + length <= Buffer size | + | Name | Type | Mandatory | Description | + | ------- | ----------- | ---- | ---------------------------------------- | + | buffer | ArrayBuffer | Yes | Buffer used to store the file read. | + | options | Object | No | The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
Constraints: offset + length <= Buffer size | **Return value** -| Type | Description | -| ------ | -------- | -| number | Length of the data read.| + | Type | Description | + | ------ | -------- | + | number | Length of the data read.| **Example** @@ -3150,6 +3578,9 @@ Synchronously reads data from the stream. Manages directories. Before calling a method of the **Dir** class, use the **opendir()** method synchronously or asynchronously to create a **Dir** instance. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.listFile](js-apis-file-fs.md#fslistfile) instead. ### read @@ -3157,12 +3588,16 @@ read(): Promise<Dirent> Reads the next directory entry. This API uses a promise to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.listFile](js-apis-file-fs.md#fslistfile) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** -| Type | Description | -| -------------------------------- | ------------- | + | Type | Description | + | -------------------------------- | ------------- | | Promise<[Dirent](#dirent)> | Promise used to return the directory entry read.| **Example** @@ -3182,13 +3617,17 @@ read(callback: AsyncCallback<Dirent>): void Reads the next directory entry. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.listFile](js-apis-file-fs.md#fslistfile-1) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------------------------- | ---- | ---------------- | -| callback | AsyncCallback<[Dirent](#dirent)> | Yes | Callback invoked when the next directory entry is asynchronously read.| + | Name | Type | Mandatory | Description | + | -------- | -------------------------------------- | ---- | ---------------- | + | callback | AsyncCallback<[Dirent](#dirent)> | Yes | Callback invoked when the next directory entry is asynchronously read.| **Example** @@ -3208,13 +3647,17 @@ readSync(): Dirent Synchronously reads the next directory entry. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.listFileSync](js-apis-file-fs.md#fslistfilesync) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** -| Type | Description | -| ----------------- | -------- | -| [Dirent](#dirent) | Directory entry read.| + | Type | Description | + | ----------------- | -------- | + | [Dirent](#dirent) | Directory entry read.| **Example** @@ -3229,6 +3672,10 @@ close(): Promise<void> Closes a directory. This API uses a promise to return the result. After a directory is closed, the file descriptor in Dir will be released and no directory entry can be read from Dir. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.listFile](js-apis-file-fs.md#fslistfile) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Example** @@ -3240,12 +3687,16 @@ Closes a directory. This API uses a promise to return the result. After a direct ``` - ### close7+ +### close7+ close(callback: AsyncCallback<void>): void Closes a directory. This API uses an asynchronous callback to return the result. After a directory is closed, the file descriptor in Dir will be released and no directory entry can be read from Dir. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.listFile](js-apis-file-fs.md#fslistfile-1) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Example** @@ -3263,6 +3714,10 @@ closeSync(): void Closes a directory. After a directory is closed, the file descriptor in Dir will be released and no directory entry can be read from Dir. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.listFileSync](js-apis-file-fs.md#fslistfilesync) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO **Example** @@ -3276,6 +3731,10 @@ Closes a directory. After a directory is closed, the file descriptor in Dir will Provides information about files and directories. Before calling a method of the **Dirent** class, use the [dir.read()](#read) method synchronously or asynchronously to create a **Dirent** instance. +> **NOTE** +> +> This API is deprecated since API version 9. Use [fs.listFile](js-apis-file-fs.md#fslistfile) instead. + **System capability**: SystemCapability.FileManagement.File.FileIO ### Attributes @@ -3291,13 +3750,17 @@ isBlockDevice(): boolean Checks whether this directory entry is a block special file. A block special file supports access by block only, and it is cached when accessed. +> **NOTE** +> +> This API is deprecated since API version 9. + **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** -| Type | Description | -| ------- | ---------------- | -| boolean | Whether the directory entry is a block special file.| + | Type | Description | + | ------- | ---------------- | + | boolean | Whether the directory entry is a block special file.| **Example** @@ -3313,13 +3776,17 @@ isCharacterDevice(): boolean Checks whether a directory entry is a character special file. A character special file supports random access, and it is not cached when accessed. +> **NOTE** +> +> This API is deprecated since API version 9. + **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** -| Type | Description | -| ------- | ----------------- | -| boolean | Whether the directory entry is a character special file.| + | Type | Description | + | ------- | ----------------- | + | boolean | Whether the directory entry is a character special file.| **Example** @@ -3335,13 +3802,17 @@ isDirectory(): boolean Checks whether a directory entry is a directory. +> **NOTE** +> +> This API is deprecated since API version 9. + **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** -| Type | Description | -| ------- | ------------- | -| boolean | Whether the directory entry is a directory.| + | Type | Description | + | ------- | ------------- | + | boolean | Whether the directory entry is a directory.| **Example** @@ -3357,13 +3828,17 @@ isFIFO(): boolean Checks whether this directory entry is a named pipe (or FIFO). Named pipes are used for inter-process communication. +> **NOTE** +> +> This API is deprecated since API version 9. + **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** -| Type | Description | -| ------- | --------------- | -| boolean | Whether the directory entry is a FIFO.| + | Type | Description | + | ------- | --------------- | + | boolean | Whether the directory entry is a FIFO.| **Example** @@ -3379,13 +3854,17 @@ isFile(): boolean Checks whether a directory entry is a regular file. +> **NOTE** +> +> This API is deprecated since API version 9. + **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** -| Type | Description | -| ------- | --------------- | -| boolean | Whether the directory entry is a regular file.| + | Type | Description | + | ------- | --------------- | + | boolean | Whether the directory entry is a regular file.| **Example** @@ -3401,13 +3880,17 @@ isSocket(): boolean Checks whether a directory entry is a socket. +> **NOTE** +> +> This API is deprecated since API version 9. + **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** -| Type | Description | -| ------- | -------------- | -| boolean | Whether the directory entry is a socket.| + | Type | Description | + | ------- | -------------- | + | boolean | Whether the directory entry is a socket.| **Example** @@ -3423,13 +3906,17 @@ isSymbolicLink(): boolean Checks whether a directory entry is a symbolic link. +> **NOTE** +> +> This API is deprecated since API version 9. + **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** -| Type | Description | -| ------- | --------------- | -| boolean | Whether the directory entry is a symbolic link.| + | Type | Description | + | ------- | --------------- | + | boolean | Whether the directory entry is a symbolic link.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-font.md b/en/application-dev/reference/apis/js-apis-font.md index 9b6d462358a52c439117f0025c440a9cb710259b..f63ae0b839e472b9b6c11db6b6da4684507b11c6 100644 --- a/en/application-dev/reference/apis/js-apis-font.md +++ b/en/application-dev/reference/apis/js-apis-font.md @@ -6,8 +6,6 @@ The **font** module provides APIs for registering custom fonts. > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > -> The APIs provided by this module are system APIs. -> > The functionality of this module depends on UI context. This means that the APIs of this module cannot be used where the UI context is unclear. For details, see [UIContext](./js-apis-arkui-UIContext.md#uicontext). > > Since API version 10, you can use the [getFont](./js-apis-arkui-UIContext.md#getfont) API in [UIContext](./js-apis-arkui-UIContext.md#uicontext) to obtain the [Font](./js-apis-arkui-UIContext.md#font) object associated with the current UI context. @@ -38,8 +36,8 @@ Registers a custom font with the font manager. | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ------------ | -| familyName | string | Yes | Name of the custom font to register. | -| familySrc | string | Yes | Path of the custom font to register.| +| familyName | string \| [Resource](../arkui-ts/ts-types.md#resource)10+ | Yes | Name of the custom font to register. | +| familySrc | string \| [Resource](../arkui-ts/ts-types.md#resource)10+ | Yes | Path of the custom font to register.| **Example** @@ -53,10 +51,23 @@ struct FontExample { @State message: string =' Hello, World' aboutToAppear() { + // Both familyName and familySrc support the string type. font.registerFont({ familyName: 'medium', familySrc: '/font/medium.ttf' }) + + // Both familyName and familySrc support the Resource type. + font.registerFont({ + familyName: $r('app.string.mediumFamilyName'), + familySrc: $r('app.string.mediumFamilySrc') + }) + + // familySrc supports the $rawfile type. + font.registerFont({ + familyName: 'mediumRawFile', + familySrc: $rawfile('font/medium.ttf') + }) } build() { @@ -64,7 +75,7 @@ struct FontExample { Text(this.message) .align(Alignment.Center) .fontSize(20) - .fontFamily('medium') // medium: name of the custom font to register. + .fontFamily('medium') // medium: name of the custom font to register. (Registered fonts such as $r('app.string.mediumFamilyName') and 'mediumRawFile' can also be used.) .height('100%') }.width('100%') } diff --git a/en/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md index 4f94686f60f8964beac0159a44a476c13904ce52..998c4b61c624a7022d41de924b93603e31c7c003 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md @@ -241,6 +241,14 @@ Obtains the focus element. This API uses an asynchronous callback to return the | isAccessibilityFocus | boolean | Yes | Whether the obtained focus element is an accessibility focus. | | callback | AsyncCallback<AccessibilityElement> | Yes | Callback used to return the current focus element.| +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID | Error Message | +| ------- | ---------------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + **Example** ```ts diff --git a/en/application-dev/reference/apis/js-apis-inner-notification-notificationCommonDef.md b/en/application-dev/reference/apis/js-apis-inner-notification-notificationCommonDef.md index 48f8c4cc28912aab4b3cc0446c951fe539b6ba4e..51f5ce812c2824a4355a5a210399f23af3cda315 100644 --- a/en/application-dev/reference/apis/js-apis-inner-notification-notificationCommonDef.md +++ b/en/application-dev/reference/apis/js-apis-inner-notification-notificationCommonDef.md @@ -10,7 +10,7 @@ Provides the bundle information of an application. **System capability**: SystemCapability.Notification.Notification -| Name | Type | Read-only| Mandatory| Description | -| ------ | ------ | ---- | ---- | ------ | -| bundle | string | No | Yes| Bundle information of the application.| -| uid | number | No | No| User ID.| +| Name | Type | Mandatory| Description | +| ------ | ------ | ------ | ------ | +| bundle | string | Yes| Bundle information of the application.| +| uid | number | No| User ID.| diff --git a/en/application-dev/reference/apis/js-apis-inputmethod.md b/en/application-dev/reference/apis/js-apis-inputmethod.md index a9da8c45a00184fad7554b021bd1497d9b4f4645..553c448b9a148406d548ae6bae0fcfe864d95eb9 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethod.md +++ b/en/application-dev/reference/apis/js-apis-inputmethod.md @@ -154,15 +154,15 @@ Switches to another input method. This API uses a promise to return the result. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - |target | [InputMethodProperty](#inputmethodproperty8)| Yes| Input method to switch to.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +|target | [InputMethodProperty](#inputmethodproperty8)| Yes| Input method to switch to.| **Return value** - | Type | Description | - | ----------------------------------------- | ---------------------------- | - | Promise\ | Promise used to return the result. The value **true** means that the switching is successful, and **false** means the opposite.| +| Type | Description | +| ----------------------------------------- | ---------------------------- | +| Promise\ | Promise used to return the result. The value **true** means that the switching is successful, and **false** means the opposite.| **Error codes** @@ -218,7 +218,12 @@ switchCurrentInputMethodSubtype(target: InputMethodSubtype, callback: AsyncCallb Switches to another subtype of the current input method. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.CONNECT_IME_ABILITY
**NOTE**
- API version 10 and later: This API can be called by system applications and the current input method application.
- API version 9: This API can be called by system applications only. +**Required permissions**: ohos.permission.CONNECT_IME_ABILITY + +> **NOTE** +> +> - API version 10 and later: This API can be called by system applications and the current input method application. +> - API version 9: This API can be called by system applications only. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -274,7 +279,12 @@ switchCurrentInputMethodSubtype(target: InputMethodSubtype): Promise<boolean& Switches to another subtype of the current input method. This API uses a promise to return the result. -**Required permissions**: ohos.permission.CONNECT_IME_ABILITY
**NOTE**
- API version 10 and later: This API can be called by system applications and the current input method application.
- API version 9: This API can be called by system applications only. +**Required permissions**: ohos.permission.CONNECT_IME_ABILITY + +> **NOTE** +> +> - API version 10 and later: This API can be called by system applications and the current input method application. +> - API version 9: This API can be called by system applications only. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -705,7 +715,7 @@ try { attach(showKeyboard: boolean, textConfig: TextConfig): Promise<void> -Attaches a self-drawing component to the input method. This API uses an asynchronous callback to return the result. +Attaches a self-drawing component to the input method. This API uses a promise to return the result. An input method can use the features provided by the input method framework only when it has a self-drawing component attached to it. @@ -797,7 +807,7 @@ showTextInput(): Promise<void> Enters the text editing mode. This API uses a promise to return the result. -This API can be called to start the soft keyboard after the editor component is bound to the input method. +This API can be called to start the soft keyboard after the editor component is attached to the input method. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -1692,11 +1702,11 @@ Disables listening for the text insertion event of the input method. inputMethodController.off('insertText'); ``` -### on('deleteLeft' | 'deleteRight')10+ +### on('deleteLeft')10+ -on(type: 'deleteLeft' | 'deleteRight', callback: (length: number) => void): void +on(type: 'deleteLeft', callback: (length: number) => void): void -Enables listening for the delete-to-the-left or delete-to-the-right event of the input method. This API uses an asynchronous callback to return the result. +Enables listening for the backward delete event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -1704,8 +1714,8 @@ Enables listening for the delete-to-the-left or delete-to-the-right event of the | Name | Type| Mandatory| Description| | -------- | ----- | ---- | ----- | -| type | string | Yes | Listening type.
- The value **'deleteLeft'** indicates the delete-to-the-left event.
- The value **'deleteRight'** indicates the delete-to-the-right event.| -| callback | (length: number) => void | Yes | Callback used to return the length of the text to be deleted to the left or to the right.
Your application needs to operate the content in the edit box based on the length returned in the callback.| +| type | string | Yes | Listening type.
The value **'deleteLeft'** indicates the backward delete event.| +| callback | (length: number) => void | Yes | Callback used to return the length of the text to be deleted backward.
Your application needs to operate the content in the edit box based on the length returned in the callback.| **Error codes** @@ -1725,7 +1735,34 @@ try { } catch(err) { console.error(`Failed to subscribe deleteLeft: ${JSON.stringify(err)}`); } +``` + +### on('deleteRight')10+ + +on(type: 'deleteRight', callback: (length: number) => void): void + +Enables listening for the forward delete event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type| Mandatory| Description| +| -------- | ----- | ---- | ----- | +| type | string | Yes | Listening type.
The value **'deleteRight'** indicates the forward delete event.| +| callback | (length: number) => void | Yes | Callback used to return the length of the text to be deleted forward.
Your application needs to operate the content in the edit box based on the length returned in the callback.| + +**Error codes** +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------------------- | +| 12800009 | input method client is detached. | + +**Example** + +```js try { inputMethodController.on('deleteRight', (length) => { console.log(`Succeeded in subscribing deleteRight, length: ${length}`); @@ -1734,12 +1771,11 @@ try { console.error(`Failed to subscribe deleteRight: ${JSON.stringify(err)}`); } ``` +### off('deleteLeft')10+ -### off('deleteLeft' | 'deleteRight')10+ - -off(type: 'deleteLeft' | 'deleteRight'): void +off(type: 'deleteLeft'): void -Disables listening for the delete-to-the-left or delete-to-the-right event of the input method. +Disables listening for the backward delete event. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -1747,12 +1783,31 @@ Disables listening for the delete-to-the-left or delete-to-the-right event of th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
- The value **'deleteLeft'** indicates the delete-to-the-left event.
- The value **'deleteRight'** indicates the delete-to-the-right event.| +| type | string | Yes | Listening type.
The value **'deleteLeft'** indicates the backward delete event.| **Example** ```js inputMethodController.off('deleteLeft'); +``` + +### off('deleteRight')10+ + +off(type: 'deleteRight'): void + +Disables listening for the forward delete event. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
The value **'deleteRight'** indicates the forward delete event.| + +**Example** + +```js inputMethodController.off('deleteRight'); ``` @@ -2062,6 +2117,180 @@ Disables listening for the select-by-cursor-movement event. inputMethodController.off('selectByMovement'); ``` +### on('getLeftTextOfCursor')10+ + +on(type: 'getLeftTextOfCursor', callback: (length: number) => string): void; + +Enables listening for the event of obtaining the length of text deleted backward. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----- | ---- | ------ | +| type | string | Yes | Listening type.
The value **'getLeftTextOfCursor'** indicates the event of obtaining the length of text deleted backward.| +| callback | (length: number) => string | Yes | Callback used to obtain the text of the specified length deleted backward.
In this callback, obtain the text of the specified length on the left of the cursor in the latest state of the edit box and return the text.| + +**Example** + +```js +try { + inputMethodController.on('getLeftTextOfCursor', (length) => { + console.info(`Succeeded in subscribing getLeftTextOfCursor, length: ${length}`); + let text:string = ""; + return text; + }); +} catch(err) { + console.error(`Failed to subscribe getLeftTextOfCursor. Code: ${err.code}, message: ${err.message}`); +} +``` + +### off('getLeftTextOfCursor')10+ + +off(type: 'getLeftTextOfCursor', callback?: (length: number) => string): void; + +Disables listening for the event of obtaining the length of text deleted backward. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
The value **'getLeftTextOfCursor'** indicates the event of obtaining the length of text deleted backward.| +| callback | (length: number) => string | No | Callback used to obtain the text of the specified length deleted backward. The value must be the same as that passed in by the **on** API.| + +**Example** + +```js +try { + inputMethodController.off('getLeftTextOfCursor', (length) => { + console.info(`Succeeded in unsubscribing getLeftTextOfCursor, length: ${length}`); + let text:string = ""; + return text; + }); +} catch(err) { + console.error(`Failed to unsubscribing getLeftTextOfCursor. Code: ${err.code}, message: ${err.message}`); +} +``` + +### on('getRightTextOfCursor')10+ + +on(type: 'getRightTextOfCursor', callback: (length: number) => string): void; + +Enables listening for the event of obtaining the length of text deleted forward. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----- | ---- | ------ | +| type | string | Yes | Listening type.
The value **'getRightTextOfCursor'** indicates the event of obtaining the length of text deleted forward.| +| callback | (length: number) => string | Yes | Callback used to obtain the text of the specified length deleted forward.
In this callback, obtain the text of the specified length on the right of the cursor in the latest state of the edit box and return the text.| + +**Example** + +```js +try { + inputMethodController.on('getRightTextOfCursor', (length) => { + console.info(`Succeeded in subscribing getRightTextOfCursor, length: ${length}`); + let text:string = ""; + return text; + }); +} catch(err) { + console.error(`Failed to subscribe getRightTextOfCursor. Code: ${err.code}, message: ${err.message}`); +} +``` + +### off('getRightTextOfCursor')10+ + +off(type: 'getRightTextOfCursor', callback?: (length: number) => string): void; + +Disables listening for the event of obtaining the length of text deleted forward. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
The value **'getRightTextOfCursor'** indicates the event of obtaining the length of text deleted forward.| +| callback | (length: number) => string | No | Callback used to obtain the text of the specified length deleted forward. The value must be the same as that passed in by the **on** API.| + +**Example** + +```js +try { + inputMethodController.off('getRightTextOfCursor', (length) => { + console.info(`Succeeded in unsubscribing getRightTextOfCursor, length: ${length}`); + let text:string = ""; + return text; + }); +} catch(err) { + console.error(`Failed to unsubscribing getRightTextOfCursor. Code: ${err.code}, message: ${err.message}`); +} +``` + +### on('getTextIndexAtCursor')10+ + +on(type: 'getTextIndexAtCursor', callback: () => number): void; + +Enables listening for the event of obtaining the index of text at the cursor. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----- | ---- | ------ | +| type | string | Yes | Listening type.
The value **'getTextIndexAtCursor'** indicates the event of obtaining the index of text at the cursor.| +| callback | () => number | Yes | Callback used to obtain the index of text at the cursor.
In this callback, obtain the index of text at the cursor in the latest state of the edit box and return the index.| + +**Example** + +```js +try { + inputMethodController.on('getTextIndexAtCursor', () => { + console.info(`Succeeded in subscribing getTextIndexAtCursor.`); + let index:number = 0; + return index; + }); +} catch(err) { + console.error(`Failed to subscribe getTextIndexAtCursor. Code: ${err.code}, message: ${err.message}`); +} +``` + +### off('getTextIndexAtCursor')10+ + +off(type: 'getTextIndexAtCursor', callback?: () => number): void; + +Disables listening for the event of obtaining the index of text at the cursor. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
The value **'getTextIndexAtCursor'** indicates the event of obtaining the index of text at the cursor.| +| callback | () => number | No | Callback used to obtain the index of text at the cursor. The value must be the same as that passed in by the **on** API.| + +**Example** + +```js +try { + inputMethodController.off('getTextIndexAtCursor', () => { + console.info(`Succeeded in unsubscribing getTextIndexAtCursor.`); + let index:number = 0; + return index; + }); +} catch(err) { + console.error(`Failed to unsubscribing getTextIndexAtCursor. Code: ${err.code}, message: ${err.message}`); +} +``` + ## InputMethodSetting8+ In the following API examples, you must first use [getSetting](#inputmethodgetsetting9) to obtain an **InputMethodSetting** instance, and then call the APIs using the obtained instance. @@ -2110,11 +2339,11 @@ Disables listening for the input method and subtype change event. This API uses inputMethodSetting.off('imeChange'); ``` -### on('imeShow'|'imeHide')10+ +### on('imeShow')10+ -on(type: 'imeShow'|'imeHide', callback: (info: Array\) => void): void +on(type: 'imeShow', callback: (info: Array\) => void): void -Enables listening for a soft keyboard visibility event of the input method. This API uses an asynchronous callback to return the result. +Enables listening for the show event of the soft keyboard. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -2124,7 +2353,7 @@ Enables listening for a soft keyboard visibility event of the input method. This | Name | Type| Mandatory| Description| | -------- | ---- | ---- | ---- | -| type | string | Yes| Listening type.
- The value **'imeShow'** indicates the soft keyboard display event.
- The value **'imeHide'** indicates the soft keyboard hiding event.| +| type | string | Yes| Listening type.
The value **'imeShow'** indicates the show event of the soft keyboard.| | callback | (info: Array\) => void | Yes| Callback used to return the information about the soft keyboard of the input method.| **Example** @@ -2135,11 +2364,36 @@ inputMethodSetting.on('imeShow', (info) => { }); ``` -### off('imeShow'|'imeHide')10+ +### on('imeHide')10+ + +on(type: 'imeHide', callback: (info: Array\) => void): void + +Enables listening for the hide event of the soft keyboard. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type| Mandatory| Description| +| -------- | ---- | ---- | ---- | +| type | string | Yes| Listening type.
The value **'imeHide'** indicates the hide event of the soft keyboard.| +| callback | (info: Array\) => void | Yes| Callback used to return the information about the soft keyboard of the input method.| + +**Example** + +```js +inputMethodSetting.on('imeHide', (info) => { + console.info('Succeeded in subscribing imeHide event.'); +}); +``` + +### off('imeShow')10+ -off(type: 'imeShow'|'imeHide', callback?: (info: Array\) => void): void +off(type: 'imeShow', callback?: (info: Array\) => void): void -Disables listening for a soft keyboard visibility event of the input method. +Disables listening for the show event of the soft keyboard. **System API**: This is a system API. @@ -2149,7 +2403,7 @@ Disables listening for a soft keyboard visibility event of the input method. | Name | Type| Mandatory| Description | | -------- | ---- | ---- | ------ | -| type | string | Yes| Listening type.
- The value **'imeShow'** indicates the soft keyboard display event.
- The value **'imeHide'** indicates the soft keyboard hiding event.| +| type | string | Yes| Listening type.
The value **'imeShow'** indicates the show event of the soft keyboard.| | callback | (info: Array\) => void | No| Callback used for disable listening. If this parameter is not specified, all callbacks corresponding to the set event are invoked.| **Example** @@ -2158,6 +2412,29 @@ Disables listening for a soft keyboard visibility event of the input method. inputMethodSetting.off('imeShow'); ``` +### off('imeHide')10+ + +off(type: 'imeHide', callback?: (info: Array\) => void): void + +Disables listening for the hide event of the soft keyboard. + +**System API**: This is a system API. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type| Mandatory| Description | +| -------- | ---- | ---- | ------ | +| type | string | Yes| Listening type.
The value **'imeHide'** indicates the hide event of the soft keyboard.| +| callback | (info: Array\) => void | No| Callback used for disable listening. If this parameter is not specified, all callbacks corresponding to the set event are invoked.| + +**Example** + +```js +inputMethodSetting.off('imeHide'); +``` + ### listInputMethodSubtype9+ listInputMethodSubtype(inputMethodProperty: InputMethodProperty, callback: AsyncCallback<Array<InputMethodSubtype>>): void diff --git a/en/application-dev/reference/apis/js-apis-inputmethodengine.md b/en/application-dev/reference/apis/js-apis-inputmethodengine.md index 1ab9aa0e1bae22a05750f20051029cf979db2ad1..36e504d702912c310765d0afc448ebffc9a34517 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethodengine.md +++ b/en/application-dev/reference/apis/js-apis-inputmethodengine.md @@ -504,7 +504,7 @@ This API can be called only by an input method. Only one SOFT_KEYBOARD panel and | Error Code ID | Error Message | | ---------- | ----------------------------- | -| 12800004 | not an input method extension | +| 12800004 | not an input method extension. | **Example** @@ -552,7 +552,7 @@ This API can be called only by an input method. Only one SOFT_KEYBOARD panel and | Error Code ID | Error Message | | ---------- | ----------------------------- | -| 12800004 | not an input method extension | +| 12800004 | not an input method extension. | **Example** @@ -728,6 +728,57 @@ inputMethodEngine.getKeyboardDelegate().off('keyDown', (keyEvent) => { }); ``` +### on('keyEvent')10+ + +on(type: 'keyEvent', callback: (event: InputKeyEvent) => boolean): void + +Enables listening for a keyboard event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
The value **'keyEvent'** indicates the keyboard event.| +| callback | function | Yes | Callback used to return the result.
- The input parameter, of the [InputKeyEvent](js-apis-keyevent.md#KeyEvent) type, indicates the key event information.
- If the event is consumed by the event subscriber, **true** is returned. Otherwise, **false** is returned.| + +**Example** + +```js +inputMethodEngine.getKeyboardDelegate().on('keyEvent', (keyEvent) => { + console.log('inputMethodEngine keyEvent.action:' + JSON.stringify(keyEvent.action)); + console.log('inputMethodEngine keyEvent.key.code:' + JSON.stringify(keyEvent.key.code)); + console.log('inputMethodEngine keyEvent.ctrlKey:' + JSON.stringify(keyEvent.ctrlKey)); + return true; +}); +``` + +### off('keyEvent')10+ + +off(type: 'keyEvent', callback?: (event: InputKeyEvent) => boolean): void + +Disables listening for a keyboard event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
The value **'keyEvent'** indicates the keyboard event.| +| callback | function | No | Callback to be unregistered.
- The input parameter, of the [InputKeyEvent](js-apis-keyevent.md#KeyEvent) type, indicates the key event information.
- If the event is consumed by the event subscriber, **true** is returned. Otherwise, **false** is returned.
- This parameter is optional. If this parameter is not specified, all callbacks registered for the event will be unregistered.| + +**Example** + +```js +inputMethodEngine.getKeyboardDelegate().off('keyEvent', (keyEvent) => { + console.log('This is a callback function which will be deregistered.'); + return true; +}); +inputMethodEngine.getKeyboardDelegate().off('keyEvent'); +``` + ### on('cursorContextChange') on(type: 'cursorContextChange', callback: (x: number, y:number, height:number) => void): void @@ -1147,7 +1198,7 @@ This API does not work on panels in the FLG_FIXED state. ```js try { - let promise = windowClass.moveTo(300, 300); + let promise = panel.moveTo(300, 300); promise.then(() => { console.log('Succeeded in moving the panel.'); }).catch((err) =>{ @@ -1260,11 +1311,11 @@ promise.then(() => { }); ``` -### on10+ +### on('show')10+ -on(type: 'show' | 'hide', callback: () => void): void +on(type: 'show', callback: () => void): void -Enables listening for a panel visibility event. This API uses an asynchronous callback to return the result. +Enables listening for the show event of this panel. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -1272,7 +1323,7 @@ Enables listening for a panel visibility event. This API uses an asynchronous ca | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | -------- | -| type | 'show'\|'hide' | Yes| Listening type.
- The value **'show'** indicates the panel display event.
- The value **'hide'** indicates the panel hiding event.| +| type | string | Yes| Listening type.
The value **'show'** indicates the show event.| | callback | () => void | Yes | Callback used to return the result.| **Example** @@ -1283,11 +1334,34 @@ panel.on('show', () => { }); ``` -### off10+ +### on('hide')10+ + +on(type: 'hide', callback: () => void): void + +Enables listening for the hide event of this panel. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------- | +| type | string | Yes| Listening type.
The value **'hide'** indicates the hide event.| +| callback | () => void | Yes | Callback used to return the result.| + +**Example** + +```js +panel.on('hide', () => { + console.log('Panel is hiding.'); +}); +``` + +### off('show')10+ -off(type: 'show' | 'hide', callback?: () => void): void +off(type: 'show', callback?: () => void): void -Disables listening for a panel visibility event. This API uses an asynchronous callback to return the result. +Disables listening for the show event of this panel. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -1295,7 +1369,7 @@ Disables listening for a panel visibility event. This API uses an asynchronous c | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | -------- | -| type | 'show'\|'hide' | Yes| Listening type.
- The value **'show'** indicates the panel display event.
- The value **'hide'** indicates the panel hiding event.| +| type | string | Yes| Listening type.
The value **'show'** indicates the show event.| | callback | () => void | No | Callback used to return the result.| **Example** @@ -1304,6 +1378,27 @@ Disables listening for a panel visibility event. This API uses an asynchronous c panel.off('show'); ``` +### off('hide')10+ + +off(type: 'hide', callback?: () => void): void + +Disables listening for the hide event of this panel. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------- | +| type | string | Yes| Listening type.
The value **'hide'** indicates the hide event.| +| callback | () => void | No | Callback used to return the result.| + +**Example** + +```js +panel.off('hide'); +``` + ### changeFlag10+ changeFlag(flag: PanelFlag): void @@ -2487,7 +2582,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | ------------------------------ | -| 12800003 | Input method client error. | +| 12800003 | input method client error. | | 12800006 | Input method controller error. | **Example** @@ -2523,7 +2618,7 @@ Describes the attribute of a key. | Name | Type| Readable| Writable| Description | | --------- | -------- | ---- | ---- | ------------ | -| keyCode | number | Yes | No | Key value. For detail, see [KeyCode](js-apis-keycode.md#keycode).| +| keyCode | number | Yes | No | Key value. For details, see [KeyCode](js-apis-keycode.md#keycode).| | keyAction | number | Yes | No | Key event type.
- **2**: keydown event.
- **3**: keyup event.| ## PanelFlag10+ diff --git a/en/application-dev/reference/apis/js-apis-nfcTag.md b/en/application-dev/reference/apis/js-apis-nfcTag.md index aec61516c42598051c916d9314a842ca3deac5ae..2a9f99171413030bb3374b51fb25dff3dc5cbf60 100644 --- a/en/application-dev/reference/apis/js-apis-nfcTag.md +++ b/en/application-dev/reference/apis/js-apis-nfcTag.md @@ -34,7 +34,7 @@ Before developing applications related to tag read and write, you must declare N { "name": "tag-tech", "value": "IsoDep" - }, + } // Add other technologies, // such as NfcB, NfcF, NfcV, Ndef, MifareClassic, MifareUL, and NdefFormatable. ] @@ -67,59 +67,61 @@ import tag from '@ohos.nfc.tag'; Before a card with tags is read or written, **TagInfo** must be obtained to determine the tag technologies supported by the card. In this way, the application can invoke the correct API to communicate with the card. ```js import tag from '@ohos.nfc.tag'; +import UIAbility from '@ohos.app.ability.UIAbility'; -onCreate(want, launchParam) { +export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { // Add other code here. - // want is initialized by the NFC service and contains tagInfo. - var tagInfo; - try { - tagInfo = tag.getTagInfo(want); - } catch (error) { - console.log("tag.getTagInfo caught error: " + error); - } - if (tagInfo == null || tagInfo == undefined) { - console.log("no TagInfo to be created, ignore it."); - return; - } - - // get the supported technologies for this found tag. - var isNfcATag = false; - var isIsoDepTag = false; - for (var i = 0; i < tagInfo.technology.length; i++) { - if (tagInfo.technology[i] == tag.NFC_A) { - isNfcATag = true; + // want is initialized by the NFC service and contains tagInfo. + var tagInfo; + try { + tagInfo = tag.getTagInfo(want); + } catch (error) { + console.log("tag.getTagInfo caught error: " + error); } - - if (tagInfo.technology[i] == tag.ISO_DEP) { - isIsoDepTag = true; + if (tagInfo == null || tagInfo == undefined) { + console.log("no TagInfo to be created, ignore it."); + return; } + + // get the supported technologies for this found tag. + var isNfcATag = false; + var isIsoDepTag = false; + for (var i = 0; i < tagInfo.technology.length; i++) { + if (tagInfo.technology[i] == tag.NFC_A) { + isNfcATag = true; + } + + if (tagInfo.technology[i] == tag.ISO_DEP) { + isIsoDepTag = true; + } // Also check for technology tag.NFC_B, NFC_F, NFC_V, ISO_DEP, NDEF, MIFARE_CLASSIC, MIFARE_ULTRALIGHT, and NDEF_FORMATABLE. - } + } - // use NfcA APIs to access the found tag. - if (isNfcATag) { - var nfcA; - try { - nfcA = tag.getNfcATag(tagInfo); - } catch (error) { - console.log("tag.getNfcATag caught error: " + error); + // use NfcA APIs to access the found tag. + if (isNfcATag) { + var nfcA; + try { + nfcA = tag.getNfcATag(tagInfo); + } catch (error) { + console.log("tag.getNfcATag caught error: " + error); + } + // Other code to read or write this tag. } - // Other code to read or write this tag. - } - // use getIsoDep APIs to access the found tag. - if (isIsoDepTag) { - var isoDep; - try { - isoDep = tag.getIsoDep(tagInfo); - } catch (error) { - console.log("tag.getIsoDep caught error: " + error); + // use getIsoDep APIs to access the found tag. + if (isIsoDepTag) { + var isoDep; + try { + isoDep = tag.getIsoDep(tagInfo); + } catch (error) { + console.log("tag.getIsoDep caught error: " + error); + } + // Other code to read or write this tag. } - // Other code to read or write this tag. + // Use the same code to handle "NfcA/NfcB/NfcF/NfcV/Ndef/MifareClassic/MifareUL/NdefFormatable". } - - // Use the same code to handle "NfcA/NfcB/NfcF/NfcV/Ndef/MifareClassic/MifareUL/NdefFormatable". } ``` @@ -136,14 +138,14 @@ Obtains an **NfcATag** object, which allows access to the tags that use the NFC- **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ------------------------- | ---- | ---------------------------------------- | -| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. +| Name | Type | Mandatory| Description | +| ------- | ------------------- | ---- | ------------------------------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**.| **Return value** -| **Type** | **Description** | -| ------------------------------------- | ------------- | +| **Type** | **Description** | +| ------------------------------------- | ------------------ | | [NfcATag](js-apis-nfctech.md#nfcatag) | **NfcATag** object obtained.| ## tag.getNfcA9+ @@ -156,23 +158,23 @@ Obtains an **NfcATag** object, which allows access to the tags that use the NFC- **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ------------------------- | ---- | ---------------------------------------- | -| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. +| Name | Type | Mandatory| Description | +| ------- | ------------------- | ---- | ------------------------------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**.| **Return value** -| **Type** | **Description** | -| ------------------------------------- | ------------- | +| **Type** | **Description** | +| ------------------------------------- | ------------------ | | [NfcATag](js-apis-nfctech.md#nfcatag) | **NfcATag** object obtained.| **Error codes** For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). -| ID | Error Message | -| ------- | ---------------------------------------- | -| 3100201 | Tag running state is abnormal in service. | +| ID| Error Message | +| -------- | ----------------------------------------- | +| 3100201 | Tag running state is abnormal in service. | ## tag.getNfcBTag @@ -187,14 +189,14 @@ Obtains an **NfcBTag** object, which allows access to the tags that use the NFC- **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ------------------------- | ---- | ---------------------------------------- | -| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. +| Name | Type | Mandatory| Description | +| ------- | ------------------- | ---- | ------------------------------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**.| **Return value** -| **Type** | **Description** | -| ------------------------------------- | ------------- | +| **Type** | **Description** | +| ------------------------------------- | ------------------ | | [NfcBTag](js-apis-nfctech.md#nfcbtag) | **NfcBTag** object obtained.| ## tag.getNfcB9+ @@ -207,23 +209,23 @@ Obtains an **NfcBTag** object, which allows access to the tags that use the NFC- **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ------------------------- | ---- | ---------------------------------------- | -| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. +| Name | Type | Mandatory| Description | +| ------- | ------------------- | ---- | ------------------------------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**.| **Return value** -| **Type** | **Description** | -| ------------------------------------- | ------------- | +| **Type** | **Description** | +| ------------------------------------- | ------------------ | | [NfcBTag](js-apis-nfctech.md#nfcbtag) | **NfcBTag** object obtained.| **Error codes** For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). -| ID | Error Message | -| ------- | ---------------------------------------- | -| 3100201 | Tag running state is abnormal in service. | +| ID| Error Message | +| -------- | ----------------------------------------- | +| 3100201 | Tag running state is abnormal in service. | ## tag.getNfcFTag @@ -238,14 +240,14 @@ Obtains an **NfcFTag** object, which allows access to the tags that use the NFC- **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ------------------------- | ---- | ---------------------------------------- | -| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. +| Name | Type | Mandatory| Description | +| ------- | ------------------- | ---- | ------------------------------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**.| **Return value** -| **Type** | **Description** | -| ------------------------------------- | ------------- | +| **Type** | **Description** | +| ------------------------------------- | ------------------ | | [NfcFTag](js-apis-nfctech.md#nfcftag) | **NfcFTag** object obtained.| ## tag.getNfcF9+ @@ -258,23 +260,23 @@ Obtains an **NfcFTag** object, which allows access to the tags that use the NFC- **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ------------------------- | ---- | ---------------------------------------- | -| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. +| Name | Type | Mandatory| Description | +| ------- | ------------------- | ---- | ------------------------------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**.| **Return value** -| **Type** | **Description** | -| ------------------------------------- | ------------- | +| **Type** | **Description** | +| ------------------------------------- | ------------------ | | [NfcFTag](js-apis-nfctech.md#nfcftag) | **NfcFTag** object obtained.| **Error codes** For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). -| ID | Error Message | -| ------- | ---------------------------------------- | -| 3100201 | Tag running state is abnormal in service. | +| ID| Error Message | +| -------- | ----------------------------------------- | +| 3100201 | Tag running state is abnormal in service. | ## tag.getNfcVTag @@ -289,14 +291,14 @@ Obtains an **NfcVTag** object, which allows access to the tags that use the NFC- **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ------------------------- | ---- | ---------------------------------------- | -| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. +| Name | Type | Mandatory| Description | +| ------- | ------------------- | ---- | ------------------------------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**.| **Return value** -| **Type** | **Description** | -| ------------------------------------- | ------------- | +| **Type** | **Description** | +| ------------------------------------- | ------------------ | | [NfcVTag](js-apis-nfctech.md#nfcvtag) | **NfcVTag** object obtained.| ## tag.getNfcV9+ @@ -309,23 +311,23 @@ Obtains an **NfcVTag** object, which allows access to the tags that use the NFC- **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ------------------------- | ---- | ---------------------------------------- | -| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. +| Name | Type | Mandatory| Description | +| ------- | ------------------- | ---- | ------------------------------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**.| **Return value** -| **Type** | **Description** | -| ------------------------------------- | ------------- | +| **Type** | **Description** | +| ------------------------------------- | ------------------ | | [NfcVTag](js-apis-nfctech.md#nfcvtag) | **NfcVTag** object obtained.| **Error codes** For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). -| ID | Error Message | -| ------- | ---------------------------------------- | -| 3100201 | Tag running state is abnormal in service. | +| ID| Error Message | +| -------- | ----------------------------------------- | +| 3100201 | Tag running state is abnormal in service. | ## tag.getIsoDep9+ @@ -337,23 +339,23 @@ Obtains an **IsoDepTag** object, which allows access to the tags that use the IS **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------------------- | ---- | ---------------------------------------- | -| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**.| +| Name | Type | Mandatory| Description | +| ------- | ------------------- | ---- | ------------------------------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**.| **Return value** -| **Type** | **Description** | -| ---------------------------------------- | ----------------------------------- | +| **Type** | **Description** | +| ------------------------------------------ | ------------------------------------------------------- | | [IsoDepTag](js-apis-nfctech.md#isodeptag9) | **IsoDepTag** object obtained.| **Error codes** For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). -| ID | Error Message | -| ------- | ---------------------------------------- | -| 3100201 | Tag running state is abnormal in service. | +| ID| Error Message | +| -------- | ----------------------------------------- | +| 3100201 | Tag running state is abnormal in service. | ## tag.getNdef9+ @@ -365,23 +367,23 @@ Obtains an **NdefTag** object, which allows access to the tags in the NFC Data E **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------------------- | ---- | ---------------------------------------- | -| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**.| +| Name | Type | Mandatory| Description | +| ------- | ------------------- | ---- | ------------------------------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**.| **Return value** -| **Type** | **Description** | -| -------------------------------------- | ------------------------------- | +| **Type** | **Description** | +| -------------------------------------- | --------------------------------------------------- | | [NdefTag](js-apis-nfctech.md#ndeftag9) | **NdefTag** object obtained.| **Error codes** For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). -| ID | Error Message | -| ------- | ---------------------------------------- | -| 3100201 | Tag running state is abnormal in service. | +| ID| Error Message | +| -------- | ----------------------------------------- | +| 3100201 | Tag running state is abnormal in service. | ## tag.getMifareClassic9+ @@ -393,23 +395,23 @@ Obtains a **MifareClassicTag** object, which allows access to the tags that use **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------------------- | ---- | ---------------------------------------- | -| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**.| +| Name | Type | Mandatory| Description | +| ------- | ------------------- | ---- | ------------------------------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**.| **Return value** -| **Type** | **Description** | -| ---------------------------------------- | ---------------------------------------- | +| **Type** | **Description** | +| --------------------------------------------------------- | ----------------------------------------------------------------------- | | [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) | **MifareClassicTag** object obtained.| **Error codes** For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). -| ID | Error Message | -| ------- | ---------------------------------------- | -| 3100201 | Tag running state is abnormal in service. | +| ID| Error Message | +| -------- | ----------------------------------------- | +| 3100201 | Tag running state is abnormal in service. | ## tag.getMifareUltralight9+ @@ -420,23 +422,23 @@ Obtains a **MifareUltralightTag** object, which allows access to the tags that u **System capability**: SystemCapability.Communication.NFC.Tag **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------------------- | ---- | ---------------------------------------- | -| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**.| +| Name | Type | Mandatory| Description | +| ------- | ------------------- | ---- | ------------------------------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**.| **Return value** -| **Type** | **Description** | -| ---------------------------------------- | ---------------------------------------- | +| **Type** | **Description** | +| -------------------------------------------------------------- | ----------------------------------------------------------------------------- | | [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9) | **MifareUltralightTag** object obtained.| **Error codes** For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). -| ID | Error Message | -| ------- | ---------------------------------------- | -| 3100201 | Tag running state is abnormal in service. | +| ID| Error Message | +| -------- | ----------------------------------------- | +| 3100201 | Tag running state is abnormal in service. | ## tag.getNdefFormatable9+ @@ -448,17 +450,17 @@ Obtains an **NdefFormatableTag** object, which allows access to the tags that ar **Return value** -| **Type** | **Description** | -| ---------------------------------------- | ---------------------------------------- | +| **Type** | **Description** | +| --------------------------------------------------------- | ------------------------------------------------------------------------- | | [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag) | **NdefFormatableTag** object obtained.| **Error codes** For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). -| ID | Error Message | -| ------- | ---------------------------------------- | -| 3100201 | Tag running state is abnormal in service. | +| ID| Error Message | +| -------- | ----------------------------------------- | +| 3100201 | Tag running state is abnormal in service. | ## tag.getTagInfo9+ @@ -470,14 +472,14 @@ Obtains **TagInfo** from **Want**, which is initialized by the NFC service and c **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ---------------------------------------- | ---- | --------------------------------- | -| want | [Want](js-apis-app-ability-want.md#Want) | Yes | Data obtained from the parameters of the **onCreate** entry function when an ability is dispatched.| +| Name| Type | Mandatory| Description | +| ------ | ---------------------------------------- | ---- | --------------------------------------------------- | +| want | [Want](js-apis-app-ability-want.md#Want) | Yes | Data obtained from the parameters of the **onCreate** entry function when an ability is dispatched.| **Return value** -| **Type** | **Description** | -| ------------------- | --------------------------- | +| **Type** | **Description** | +| ------------------- | -------------------------------------------- | | [TagInfo](#taginfo) | **TagInfo** object obtained.| @@ -491,14 +493,14 @@ Creates an NDEF record based on the specified URI. **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ---------------------- | -| uri | string | Yes | Data to write to the NDEF record.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | --------------------------------- | +| uri | string | Yes | Data to write to the NDEF record.| **Return value** -| **Type** | **Description** | -| -------------------------- | ---------------------------------------- | +| **Type** | **Description** | +| -------------------------- | ------------------------------------------------------------ | | [NdefRecord](#ndefrecord9) | NDEF record created. For details, see *NFCForum-TS-NDEF_1.0*.| **Example** @@ -530,15 +532,15 @@ Creates an NDEF record based on the specified text data and encoding type. **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | ------------------------ | -| text | string | Yes | Text to write to the NDEF record.| -| locale | string | Yes | Encoding mode of the text. | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------- | +| text | string | Yes | Text to write to the NDEF record.| +| locale | string | Yes | Encoding mode of the text. | **Return value** -| **Type** | **Description** | -| -------------------------- | ---------------------------------------- | +| **Type** | **Description** | +| -------------------------- | ------------------------------------------------------------ | | [NdefRecord](#ndefrecord9) | NDEF record created. For details, see *NFCForum-TS-NDEF_1.0*.| **Example** @@ -572,15 +574,15 @@ Creates an NDEF record based on the specified MIME data and type. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | ---- | ---------------------------------------- | -| mimeType | string | Yes | MIME type that complies with RFC rules, for example, **text/plain** or **image/jpeg**.| -| mimeData | number[] | Yes | MIME data, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**. | +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------------------------------------- | +| mimeType | string | Yes | MIME type that complies with RFC rules, for example, **text/plain** or **image/jpeg**.| +| mimeData | number[] | Yes | MIME data, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| **Return value** -| **Type** | **Description** | -| -------------------------- | ---------------------------------------- | +| **Type** | **Description** | +| -------------------------- | ------------------------------------------------------------ | | [NdefRecord](#ndefrecord9) | NDEF record created. For details, see *NFCForum-TS-NDEF_1.0*.| **Example** @@ -612,16 +614,16 @@ Creates an NDEF record based on application-specific data. **Parameters** -| Name | Type | Mandatory | Description | -| ------------ | -------- | ---- | ----------------------------------- | -| domainName | string | Yes | Bundle name of the application or domain name of the organization that releases the applications. | -| type | string | Yes | Type of the application data. | -| externalData | number[] | Yes | Application data, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| +| Name | Type | Mandatory| Description | +| ------------ | -------- | ---- | ------------------------------------------------------- | +| domainName | string | Yes | Bundle name of the application or domain name of the organization that releases the applications. | +| type | string | Yes | Type of the application data. | +| externalData | number[] | Yes | Application data, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| **Return value** -| **Type** | **Description** | -| -------------------------- | ---------------------------------------- | +| **Type** | **Description** | +| -------------------------- | ------------------------------------------------------------ | | [NdefRecord](#ndefrecord9) | NDEF record created. For details, see *NFCForum-TS-NDEF_1.0*.| **Example** @@ -655,14 +657,14 @@ Converts an NDEF message to bytes. **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------------- | ---- | ----------- | -| ndefMessage | [NdefMessage](js-apis-nfctech.md#ndefmessage9) | Yes | NDEF message to convert.| +| Name | Type | Mandatory| Description | +| ----------- | ---------------------------------------------- | ---- | ------------------ | +| ndefMessage | [NdefMessage](js-apis-nfctech.md#ndefmessage9) | Yes | NDEF message to convert.| **Return value** -| **Type** | **Description** | -| -------- | ---------------------------------------- | +| **Type**| **Description** | +| -------- | ------------------------------------------------------------------------------------- | | number[] | NDEF message in bytes, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| **Example** @@ -696,14 +698,14 @@ Creates an NDEF message from raw byte data. The data must comply with the NDEF r **Parameters** -| **Name**| **Type** | **Mandatory**| **Description** | -| ------- | -------- | ------ | ---------------------------------------- | -| data | number[] | Yes | Raw byte data, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**. The data must comply with the NDEF record format.| +| **Name**| **Type**| **Mandatory**| **Description** | +| ---------- | -------- | -------- | ---------------------------------------------------------------------------------- | +| data | number[] | Yes | Raw byte data, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**. The data must comply with the NDEF record format.| **Return value** -| **Type** | **Description** | -| ---------------------------------------- | ---------------------------------------- | +| **Type** | **Description** | +| ---------------------------------------------- | ------------------------------------------------------------- | | [NdefMessage](js-apis-nfctech.md#ndefmessage9) | NDEF message created. For details, see *NFCForum-TS-NDEF_1.0*.| **Example** @@ -730,14 +732,14 @@ Creates an NDEF message from the NDEF records list. **Parameters** -| **Name** | **Type** | **Mandatory**| **Description** | -| ----------- | ---------------------------------------- | ------ | ---------------------------------------- | -| ndefRecords | [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] | Yes | NDEF record list used to create the NDEF message. For details, see *NFCForum-TS-NDEF_1.0*.| +| **Name** | **Type** | **Mandatory**| **Description** | +| ----------- | --------------------------------------------- | -------- | ---------------------------------------------------------------- | +| ndefRecords | [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] | Yes | NDEF record list used to create the NDEF message. For details, see *NFCForum-TS-NDEF_1.0*.| **Return value** -| **Type** | **Description** | -| ---------------------------------------- | ---------------------------------------- | +| **Type** | **Description** | +| ---------------------------------------------- | ------------------------------------------------------------- | | [NdefMessage](js-apis-nfctech.md#ndefmessage9) | NDEF message created. For details, see *NFCForum-TS-NDEF_1.0*.| **Example** @@ -765,114 +767,113 @@ Defines the **TagInfo** object, which provides information about the tag technol **Required permissions**: ohos.permission.NFC_TAG -| **Name** | **Type** | **Readable**| **Writable**| **Description** | -| ----------------------------- | ---------------------------------------- | ------ | ------ | ---------------------------------------- | -| uid9+ | number[] | Yes | No | Tag unique identifier (UID), which consists of hexadecimal numbers ranging from **0x00** to **0xFF**. | -| technology9+ | number[] | Yes | No | Supported technologies. Each number is a constant indicating the supported technology. | -| supportedProfiles | number[] | Yes | No | Supported profiles. This parameter is not supported since API version 9. Use [tag.TagInfo#technology](#tagtaginfo) instead.| -| extrasData9+ | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap)[] | Yes | No | Extended attribute value of the tag technology.
**System API**: This is a system API. | -| tagRfDiscId9+ | number | Yes | No | ID allocated when the tag is discovered.
**System API**: This is a system API. | -| remoteTagService9+ | [rpc.RemoteObject](js-apis-rpc.md#remoteobject) | Yes | No | Remote object of the NFC service process used for interface communication between the client and the service.
**System API**: This is a system API.| +| **Name** | **Type** | **Readable**| **Writable**| **Description** | +| ----------------------------- | ------------------------------------------------------------- | -------- | -------- | -------------------------------------------------------------------------------------------- | +| uid9+ | number[] | Yes | No | Tag unique identifier (UID), which consists of hexadecimal numbers ranging from **0x00** to **0xFF**. | +| technology9+ | number[] | Yes | No | Supported technologies. Each number is a constant indicating the supported technology. | +| supportedProfiles | number[] | Yes | No | Supported profiles. This parameter is not supported since API version 9. Use [tag.TagInfo#technology](#tagtaginfo) instead. | +| extrasData9+ | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap)[] | Yes | No | Extended attribute value of the tag technology.
**System API**: This is a system API. | +| tagRfDiscId9+ | number | Yes | No | ID allocated when the tag is discovered.
**System API**: This is a system API. | +| remoteTagService9+ | [rpc.RemoteObject](js-apis-rpc.md#remoteobject) | Yes | No | Remote object of the NFC service process used for interface communication between the client and the service.
**System API**: This is a system API.| ## NdefRecord9+ Defines an NDEF record. For details, see *NFCForum-TS-NDEF_1.0*. **System capability**: SystemCapability.Communication.NFC.Tag -| **Name** | **Type** | **Readable**| **Writable**| **Description** | -| ------- | -------- | ------ | ------ | ---------------------------------------- | -| tnf | number | Yes | No | Type name field (TNF) of the NDEF record. | -| rtdType | number[] | Yes | No | Record type definition (RTD) of the NDEF record. It consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| -| id | number[] | Yes | No | NDEF record ID, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| -| payload | number[] | Yes | No | NDEF payload, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| +| **Name**| **Type**| **Readable**| **Writable**| **Description** | +| -------- | -------- | -------- | -------- | ----------------------------------------------------------------------------------------- | +| tnf | number | Yes | No | Type name field (TNF) of the NDEF record. | +| rtdType | number[] | Yes | No | Record type definition (RTD) of the NDEF record. It consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| +| id | number[] | Yes | No | NDEF record ID, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**. | +| payload | number[] | Yes | No | NDEF payload, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**. | ## Technology Type Definition Enumerates the tag technology types. **System capability**: SystemCapability.Communication.NFC.Tag -| **Name** | **Value**| **Description** | -| ---------------------------- | ----- | ------------------------ | -| NFC_A | 1 | NFC-A (ISO 14443-3A). | +| **Name** | **Value**| **Description** | +| ---------------------------- | ------ | --------------------------- | +| NFC_A | 1 | NFC-A (ISO 14443-3A). | | NFC_B | 2 | NFC-B (ISO 14443-3B).| -| ISO_DEP | 3 | ISO-DEP (ISO 14443-4).| -| NFC_F | 4 | NFC-F (JIS 6319-4). | -| NFC_V | 5 | NFC-V (ISO 15693). | -| NDEF | 6 | NDEF. | -| NDEF_FORMATABLE9+ | 7 | NDEF formattable. | -| MIFARE_CLASSIC | 8 | MIFARE Classic. | -| MIFARE_ULTRALIGHT | 9 | MIFARE Ultralight. | +| ISO_DEP | 3 | ISO-DEP (ISO 14443-4).| +| NFC_F | 4 | NFC-F (JIS 6319-4). | +| NFC_V | 5 | NFC-V (ISO 15693). | +| NDEF | 6 | NDEF. | +| NDEF_FORMATABLE9+ | 7 | NDEF formattable. | +| MIFARE_CLASSIC | 8 | MIFARE Classic. | +| MIFARE_ULTRALIGHT | 9 | MIFARE Ultralight. | ## TnfType9+ Enumerates the TNF types. For details, see *NFCForum-TS-NDEF_1.0*. **System capability**: SystemCapability.Communication.NFC.Tag -| **Name** | **Value**| **Description** | -| ---------------- | ----- | ---------------------------------------- | -| TNF_EMPTY | 0x0 | Empty. | -| TNF_WELL_KNOWN | 0x1 | NFC Forum Well Known Type [NFC RTD]. | -| TNF_MEDIA | 0x2 | Media-type as defined in RFC 2046 [RFC 2046].| -| TNF_ABSOLUTE_URI | 0x3 | Absolute URI as defined in RFC 3986 [RFC 3986].| -| TNF_EXT_APP | 0x4 | NFC Forum external type [NFC RTD]. | -| TNF_UNKNOWN | 0x5 | Unknown. | -| TNF_UNCHANGED | 0x6 | Unchanged (see section 2.3.3 in *NFCForum-TS-NDEF_1.0*). | +| **Name** | **Value**| **Description** | +| ---------------- | ------ | ------------------------------------------------ | +| TNF_EMPTY | 0x0 | Empty. | +| TNF_WELL_KNOWN | 0x1 | NFC Forum Well Known Type [NFC RTD]. | +| TNF_MEDIA | 0x2 | Media-type as defined in RFC 2046 [RFC 2046]. | +| TNF_ABSOLUTE_URI | 0x3 | Absolute URI as defined in RFC 3986 [RFC 3986].| +| TNF_EXT_APP | 0x4 | NFC Forum external type [NFC RTD]. | +| TNF_UNKNOWN | 0x5 | Unknown. | +| TNF_UNCHANGED | 0x6 | Unchanged (see section 2.3.3 in *NFCForum-TS-NDEF_1.0*). | ## NDEF Record RTD Enumerates the NDEF record types. For details about the RTD, see *NFCForum-TS-NDEF_1.0*. **System capability**: SystemCapability.Communication.NFC.Tag -| **Name** | **Value** | **Description** | -| --------------------- | ------ | ------------------ | -| RTD_TEXT9+ | [0x54] | NDEF record of the text type. | -| RTD_URI9+ | [0x55] | NDEF record of the URI type.| +| **Name** | **Value**| **Description** | +| --------------------- | ------ | ----------------------- | +| RTD_TEXT9+ | [0x54] | NDEF record of the text type.| +| RTD_URI9+ | [0x55] | NDEF record of the URI type. | ## NfcForumType9+ Enumerates the NFC Forum tag types. **System capability**: SystemCapability.Communication.NFC.Tag -| **Name** | **Value**| **Description** | -| ---------------- | ----- | ----------------- | -| NFC_FORUM_TYPE_1 | 1 | NFC Forum tag type 1. | -| NFC_FORUM_TYPE_2 | 2 | NFC Forum tag type 2. | -| NFC_FORUM_TYPE_3 | 3 | NFC Forum tag type 3. | -| NFC_FORUM_TYPE_4 | 4 | NFC Forum tag type 4. | -| MIFARE_CLASSIC | 101 | MIFARE Classic.| +| **Name** | **Value**| **Description** | +| ---------------- | ------ | -------------------- | +| NFC_FORUM_TYPE_1 | 1 | NFC Forum tag type 1. | +| NFC_FORUM_TYPE_2 | 2 | NFC Forum tag type 2. | +| NFC_FORUM_TYPE_3 | 3 | NFC Forum tag type 3. | +| NFC_FORUM_TYPE_4 | 4 | NFC Forum tag type 4. | +| MIFARE_CLASSIC | 101 | MIFARE Classic.| ## MifareClassicType9+ Enumerates the MIFARE Classic tag types. **System capability**: SystemCapability.Communication.NFC.Tag -| **Name** | **Value**| **Description** | -| ------------ | ----- | ----------------- | -| TYPE_UNKNOWN | 0 | Unknown type. | -| TYPE_CLASSIC | 1 | MIFARE Classic.| -| TYPE_PLUS | 2 | MIFARE Plus. | -| TYPE_PRO | 3 | MIFARE Pro. | +| **Name** | **Value**| **Description** | +| ------------ | ------ | -------------------- | +| TYPE_UNKNOWN | 0 | Unknown type. | +| TYPE_CLASSIC | 1 | MIFARE Classic.| +| TYPE_PLUS | 2 | MIFARE Plus. | +| TYPE_PRO | 3 | MIFARE Pro. | ## MifareClassicSize9+ Enumerates the sizes of a MIFARE Classic tag. **System capability**: SystemCapability.Communication.NFC.Tag -| **Name** | **Value**| **Description** | -| ------------ | ----- | ------------------ | -| MC_SIZE_MINI | 320 | Each tag has 5 sectors, and each sector has 4 blocks. | -| MC_SIZE_1K | 1024 | Each tag has 16 sectors, and each sector has 4 blocks.| -| MC_SIZE_2K | 2048 | Each tag has 32 sectors, and each sector has 4 blocks.| -| MC_SIZE_4K | 4096 | Each tag has 40 sectors, and each sector has 4 blocks.| +| **Name** | **Value**| **Description** | +| ------------ | ------ | --------------------------------- | +| MC_SIZE_MINI | 320 | Each tag has 5 sectors, and each sector has 4 blocks. | +| MC_SIZE_1K | 1024 | Each tag has 16 sectors, and each sector has 4 blocks.| +| MC_SIZE_2K | 2048 | Each tag has 32 sectors, and each sector has 4 blocks.| +| MC_SIZE_4K | 4096 | Each tag has 40 sectors, and each sector has 4 blocks.| ## MifareUltralightType9+ Enumerates the MIFARE Ultralight tag types. **System capability**: SystemCapability.Communication.NFC.Tag -| **Name** | **Value**| **Description** | -| ----------------- | ----- | ---------------------- | -| TYPE_UNKNOWN | 0 | Unknown type. | -| TYPE_ULTRALIGHT | 1 | MIFARE Ultralight. | -| TYPE_ULTRALIGHT_C | 2 | MIFARE Ultralight C.| - - \ No newline at end of file +| **Name** | **Value**| **Description** | +| ----------------- | ------ | ------------------------- | +| TYPE_UNKNOWN | 0 | Unknown type. | +| TYPE_ULTRALIGHT | 1 | MIFARE Ultralight. | +| TYPE_ULTRALIGHT_C | 2 | MIFARE Ultralight C.| + diff --git a/en/application-dev/reference/apis/js-apis-notificationManager.md b/en/application-dev/reference/apis/js-apis-notificationManager.md index 024b58e38329ce83b1f119d383ff697ad5df1a84..8d3bc45b1f8ab4049fa905fe4546593fc5bd52f6 100644 --- a/en/application-dev/reference/apis/js-apis-notificationManager.md +++ b/en/application-dev/reference/apis/js-apis-notificationManager.md @@ -100,7 +100,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ ```ts // NotificationRequest object let notificationRequest: notificationManager.NotificationRequest = { - notificationId: 1, + id: 1, content: { contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, normal: { @@ -217,7 +217,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ ```ts let notificationRequest: notificationManager.NotificationRequest = { - notificationId: 1, + id: 1, content: { contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, normal: { @@ -3947,11 +3947,11 @@ try{ **System API**: This is a system API and cannot be called by third-party applications. -| Name | Type | Read-only| Mandatory| Description | -| ----- | ------------------------------------- | ---- | ---- | ---------------------- | -| type | [DoNotDisturbType](#donotdisturbtype) | No | Yes | DND time type.| -| begin | Date | No | Yes | DND start time.| -| end | Date | No | Yes | DND end time.| +| Name | Type | Mandatory| Description | +| ----- | ------------------------------------- | ---- | ---------------------- | +| type | [DoNotDisturbType](#donotdisturbtype) | Yes | DND time type.| +| begin | Date | Yes | DND start time.| +| end | Date | Yes | DND end time.| ## DoNotDisturbType @@ -4041,11 +4041,11 @@ try{ **Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER, ohos.permission.NOTIFICATION_AGENT_CONTROLLER -| Name | Type | Read-only| Mandatory| Description | -| ----- | ------------------------------------- | ---- | ---- | ---------------------- | -| bundleName | string | No | Yes | Bundle name.| -| notificationId | number | No | Yes | Notification ID. | -| contentType | [ContentType](#contenttype) | No | Yes | Notification type. | +| Name | Type | Mandatory| Description | +| ----- | ------------------------------------- | --- | ---------------------- | +| bundleName | string | Yes | Bundle name.| +| notificationId | number | Yes | Notification ID. | +| contentType | [ContentType](#contenttype) | Yes | Notification type. | ## NotificationCheckResult10+ @@ -4055,7 +4055,7 @@ try{ **Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER, ohos.permission.NOTIFICATION_AGENT_CONTROLLER -| Name | Type | Read-only| Mandatory| Description | -| ----- | ------------------------------------- | ---- | ---- | ---------------------- | -| code | number | No | Yes | Result code.
**0**: display.
**1**: no display.| -| message | string | No | Yes | Result. | +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------ | ---- | ---------------------- | +| code | number | Yes | Result code.
**0**: display.
**1**: no display.| +| message | string | Yes | Result. | diff --git a/en/application-dev/reference/apis/js-apis-notificationSubscribe.md b/en/application-dev/reference/apis/js-apis-notificationSubscribe.md index 0746cb7cb1defd1691cbab96898dbb6ad47996a3..1ca3f7833aadfde7058e24f8231d0e0360d82122 100644 --- a/en/application-dev/reference/apis/js-apis-notificationSubscribe.md +++ b/en/application-dev/reference/apis/js-apis-notificationSubscribe.md @@ -665,10 +665,12 @@ notificationSubscribe.removeAll(userId, removeAllCallback); **System capability**: SystemCapability.Notification.Notification -| Name | Type | Read-only| Mandatory| Description | -| ----- | ------ | ---- | --- | -------- | -| id | number | No | Yes | Notification ID. | -| label | string | No | No | Notification label.| +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Type | Mandatory| Description | +| ----- | ------ | --- | -------- | +| id | number | Yes | Notification ID. | +| label | string | No | Notification label.| ## RemoveReason diff --git a/en/application-dev/reference/apis/js-apis-osAccount.md b/en/application-dev/reference/apis/js-apis-osAccount.md index ed266a44339d9af7e1cdb351dd305cf225a0b7d1..c5575525ae030c63abda09464bb309b70dab3f6f 100644 --- a/en/application-dev/reference/apis/js-apis-osAccount.md +++ b/en/application-dev/reference/apis/js-apis-osAccount.md @@ -2433,7 +2433,7 @@ Unsubscribes from the OS account activation states, including the states of the | -------- | -------------------------- | ---- | ------------------------------------------------------------ | | type | 'activate' \| 'activating' | Yes | Type of the event to unsubscribe from. The value **activate** means an event indicating that an OS account is activated, and **activating** means an event indicating that an OS account is being activated.| | name | string | Yes | Subscription name, which can be customized. The value cannot be empty or exceed 1024 bytes, and must be the same as the value passed by **on()**.| -| callback | Callback<number> | No | Callback for the OS account activation state events. By default, no value is passed, which unsubscribes from all the callbacks for the OS account activation state events. | +| callback | Callback<number> | No | Callback for the OS account activation state events. By default, this parameter is left empty, which unsubscribes from all the callbacks for the OS account activation state events. | **Error codes** @@ -4107,7 +4107,7 @@ Performs authentication of the current user. This API uses an asynchronous callb | ID| Error Message | | -------- | --------------------- | | 12300001 | System service exception. | -| 12300002 | Invalid challenge or authType or authTrustLevel. | +| 12300002 | Invalid challenge, authType, or authTrustLevel. | | 12300101 | Credential is incorrect. | | 12300105 | Unsupported authTrustLevel. | | 12300106 | Unsupported authType. | @@ -4166,7 +4166,7 @@ Performs authentication of the specified user. This API uses an asynchronous cal | ID| Error Message | | -------- | --------------------- | | 12300001 | System service exception. | -| 12300002 | Invalid userId or challenge or authType or authTrustLevel. | +| 12300002 | Invalid userId, challenge, authType, or authTrustLevel. | | 12300101 | Credential is incorrect. | | 12300105 | Unsupported authTrustLevel. | | 12300106 | Unsupported authType. | @@ -5649,7 +5649,7 @@ Obtains authentication information of the specified type. This API uses a promis | Name | Type | Mandatory| Description | | -------- | ----------------------------------- | ---- | -------- | -| authType | [AuthType](#authtype8) | No | Authentication type. By default, no value is passed, which means to obtain information about all authentication types.| +| authType | [AuthType](#authtype8) | No | Authentication type. By default, this parameter is left blank, which means to obtain information about all authentication types.| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-pasteboard.md b/en/application-dev/reference/apis/js-apis-pasteboard.md index fc32728b9b20dc6cb88c8b3fb6bdaaefaf871df4..eca9c534b425efc0b75bdeeec20a0f8f43693604 100644 --- a/en/application-dev/reference/apis/js-apis-pasteboard.md +++ b/en/application-dev/reference/apis/js-apis-pasteboard.md @@ -16,9 +16,9 @@ import pasteboard from '@ohos.pasteboard'; **System capability**: SystemCapability.MiscServices.Pasteboard -| Name| Type| Value| Description| -| -------- | -------- | -------- | -------- | -| MAX_RECORD_NUM7+ | number | 512 | Maximum number of records in a **PasteData** object.| +| Name| Type| Value | Description | +| -------- | -------- |--------------|-------------------------------------------------------------------------------------------------------------------------------------------| +| MAX_RECORD_NUM7+ | number | - | Maximum number of records in a **PasteData** object. In versions earlier than API version 10, the value is 512, indicating that no more records can be added once the number of records reaches 512.
Since API version 10, no limit is placed on the number of records in a **PasteData** object.| | MIMETYPE_TEXT_HTML7+ | string | 'text/html' | MIME type of the HTML content.| | MIMETYPE_TEXT_WANT7+ | string | 'text/want' | MIME type of the Want content.| | MIMETYPE_TEXT_PLAIN7+ | string | 'text/plain' | MIME type of the plain text content.| @@ -619,8 +619,6 @@ addRecord(record: PasteDataRecord): void Adds a data record to this pasteboard, and adds its type to **mimeTypes** in [PasteDataProperty](#pastedataproperty7). The parameters cannot be empty. Otherwise, the operation fails. -The pasteboard supports a maximum number of 512 data records. - **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** @@ -645,8 +643,6 @@ addRecord(mimeType: string, value: ValueType): void Adds a custom-type record to this pasteboard, and adds the custom type to **mimeTypes** in [PasteDataProperty](#pastedataproperty7). The parameters cannot be empty. Otherwise, the operation fails. -The pasteboard supports a maximum number of 512 data records. - **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** @@ -948,7 +944,6 @@ addHtmlRecord(htmlText: string): void Adds an HTML record to this pasteboard, and adds **MIMETYPE_TEXT_HTML** to **mimeTypes** in [PasteDataProperty](#pastedataproperty7). The parameters cannot be empty. Otherwise, the operation fails. -The pasteboard supports a maximum number of 512 data records. > **NOTE** > > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [addRecord](#addrecord9). @@ -975,7 +970,6 @@ addWantRecord(want: Want): void Adds a Want record to this pasteboard, and adds **MIMETYPE_TEXT_WANT** to **mimeTypes** in [PasteDataProperty](#pastedataproperty7). The parameters cannot be empty. Otherwise, the operation fails. -The pasteboard supports a maximum number of 512 data records. > **NOTE** > > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [addRecord](#addrecord9). @@ -1005,7 +999,6 @@ addTextRecord(text: string): void Adds a plain text record to this pasteboard, and adds **MIME_TEXT_PLAIN** to **mimeTypes** in [PasteDataProperty](#pastedataproperty7). The parameters cannot be empty. Otherwise, the operation fails. -The pasteboard supports a maximum number of 512 data records. > **NOTE** > > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [addRecord](#addrecord9). @@ -1031,7 +1024,6 @@ addUriRecord(uri: string): void Adds a URI record to this pasteboard, and adds **MIMETYPE_TEXT_URI** to **mimeTypes** in [PasteDataProperty](#pastedataproperty7). The parameters cannot be empty. Otherwise, the operation fails. -The pasteboard supports a maximum number of 512 data records. > **NOTE** > > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [addRecord](#addrecord9). diff --git a/en/application-dev/reference/apis/js-apis-radio.md b/en/application-dev/reference/apis/js-apis-radio.md index cd0c226e17cff6db5a3e6c51371137403adcd2a1..2050db9a62813fe6fabc01fd98cb9c0997bff43a 100644 --- a/en/application-dev/reference/apis/js-apis-radio.md +++ b/en/application-dev/reference/apis/js-apis-radio.md @@ -231,7 +231,7 @@ promise.then(data => { getNetworkSelectionMode\(slotId: number, callback: AsyncCallback\\): void -Obtains the network selection mode of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. +Obtains the network selection mode for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Telephony.CoreService @@ -268,7 +268,7 @@ radio.getNetworkSelectionMode(slotId, (err, data) => { getNetworkSelectionMode\(slotId: number\): Promise\ -Obtains the network selection mode of the SIM card in the specified slot. This API uses a promise to return the result. +Obtains the network selection mode for the SIM card in the specified slot. This API uses a promise to return the result. **System capability**: SystemCapability.Telephony.CoreService @@ -957,7 +957,7 @@ promise.then(() => { getIMEI\(callback: AsyncCallback\\): void -Obtains the IMEI of the SIM card in a card slot. This API uses an asynchronous callback to return the result. +Obtains the IMEI for the SIM card in a card slot. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -998,7 +998,7 @@ radio.getIMEI((err, data) => { getIMEI\(slotId: number, callback: AsyncCallback\\): void -Obtains the IMEI of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. +Obtains the IMEI for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -1041,7 +1041,7 @@ radio.getIMEI(slotId, (err, data) => { getIMEI\(slotId?: number\): Promise\ -Obtains the IMEI of the SIM card in the specified slot. This API uses a promise to return the result. +Obtains the IMEI for the SIM card in the specified slot. This API uses a promise to return the result. **System API**: This is a system API. @@ -1091,7 +1091,7 @@ promise.then(data => { getMEID\(callback: AsyncCallback\\): void -Obtains the MEID of the SIM card in a card slot. This API uses an asynchronous callback to return the result. +Obtains the MEID for the SIM card in a card slot. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -1132,7 +1132,7 @@ radio.getMEID((err, data) => { getMEID\(slotId: number, callback: AsyncCallback\\): void -Obtains the MEID of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. +Obtains the MEID for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -1175,7 +1175,7 @@ radio.getMEID(slotId, (err, data) => { getMEID\(slotId?: number\): Promise\ -Obtains the MEID of the SIM card in the specified slot. This API uses a promise to return the result. +Obtains the MEID for the SIM card in the specified slot. This API uses a promise to return the result. **System API**: This is a system API. @@ -1225,7 +1225,7 @@ promise.then(data => { getUniqueDeviceId\(callback: AsyncCallback\\): void -Obtains the unique device ID of the SIM card in a card slot. This API uses an asynchronous callback to return the result. +Obtains the unique device ID for the SIM card in a card slot. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -1266,7 +1266,7 @@ radio.getUniqueDeviceId((err, data) => { getUniqueDeviceId\(slotId: number, callback: AsyncCallback\\): void -Obtains the unique device ID of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. +Obtains the unique device ID for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -1309,7 +1309,7 @@ radio.getUniqueDeviceId(slotId, (err, data) => { getUniqueDeviceId\(slotId?: number\): Promise\ -Obtains the unique device ID of the SIM card in the specified slot. This API uses a promise to return the result. +Obtains the unique device ID for the SIM card in the specified slot. This API uses a promise to return the result. **System API**: This is a system API. @@ -2867,6 +2867,206 @@ promise.then(data => { ``` +## radio.getNetworkCapability10+ + +getNetworkCapability\(slotId: number, type: NetworkCapabilityType, callback: AsyncCallback\\): void + +Obtains the network capability for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -----------------------------------------------------------------------| ---- | ----------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| type | [NetworkCapabilityType](#networkcapabilitytype10) | Yes | Network capability type. | +| callback | AsyncCallback\<[NetworkCapabilityState](#networkcapabilitystate10)\> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + +**Example** + +```js +let slotId = 0; +let type = radio.NetworkCapabilityType.SERVICE_TYPE_NR; +radio.getNetworkCapability(slotId, type, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## radio.getNetworkCapability10+ + +getNetworkCapability\(slotId: number, type: NetworkCapabilityType\): Promise\ + +Obtains the network capability for the SIM card in the specified slot. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| type | [NetworkCapabilityType](#networkcapabilitytype10) | Yes | Network capability type. | + +**Return value** + +| Type | Description | +| ------------------------------------------------------------- | ----------------------- | +| Promise\<[NetworkCapabilityState](#networkcapabilitystate10)\> | Promise used to return the result.| + +**Error codes** + +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + +**Example** + +```js +let slotId = 0; +let type = radio.NetworkCapabilityType.SERVICE_TYPE_NR; +let promise = radio.getNetworkCapability(slotId, type); +promise.then(data => { + console.log(`getNetworkCapability success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`getNetworkCapability failed, promise: err->${JSON.stringify(err)}`); +}); +``` + + +## radio.setNetworkCapability10+ + +setNetworkCapability\(slotId: number, type: NetworkCapabilityType, state: NetworkCapabilityState, + callback: AsyncCallback\\): void + +Sets the network capability for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| type | [NetworkCapabilityType](#networkcapabilitytype10) | Yes | Network capability type. | +| state | [NetworkCapabilityState](#networkcapabilitystate10) | Yes | Network capability status. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Error codes** + +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + +**Example** + +```js +let slotId = 0; +let type = radio.NetworkCapabilityType.SERVICE_TYPE_NR; +let state = radio.NetworkCapabilityState.SERVICE_CAPABILITY_ON; +radio.setNetworkCapability(slotId, type, state, (err) => { + console.log(`callback: err->${JSON.stringify(err)}`); +}); +``` + +## radio.setNetworkCapability10+ + +setNetworkCapability\(slotId: number, type: NetworkCapabilityType, state: NetworkCapabilityState\): Promise\ + +Sets the network capability for the SIM card in the specified slot. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| type | [NetworkCapabilityType](#networkcapabilitytype10) | Yes | Network capability type. | +| state | [NetworkCapabilityState](#networkcapabilitystate10) | Yes | Network capability status. | + +**Return value** + +| Type | Description | +| --------------- | ----------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + +**Example** + +```js +let slotId = 0; +let type = radio.NetworkCapabilityType.SERVICE_TYPE_NR; +let state = radio.NetworkCapabilityState.SERVICE_CAPABILITY_ON; +let promise = radio.setNetworkCapability(slotId, type, state); +promise.then(data => { + console.log(`setNetworkCapability success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`setNetworkCapability failed, promise: err->${JSON.stringify(err)}`); +}); +``` + + ## RadioTechnology Enumerates radio access technologies. @@ -3290,3 +3490,29 @@ Enumerates IMS service types. | TYPE_VIDEO | 1 | Video service.| | TYPE_UT | 2 | UT service. | | TYPE_SMS | 3 | SMS service.| + +## NetworkCapabilityType10+ + +Network capability type. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Value | Description | +| -----------------| ---- | ---------- | +| SERVICE_TYPE_LTE | 0 | LTE service.| +| SERVICE_TYPE_NR | 1 | NR service.| + +## NetworkCapabilityState10+ + +Defines the network capability switch status. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Value | Description | +| -----------------------| ---- | ---------- | +| SERVICE_CAPABILITY_OFF | 0 | The network capability is disabled.| +| SERVICE_CAPABILITY_ON | 1 | The network capability is enabled.| diff --git a/en/application-dev/reference/apis/js-apis-request.md b/en/application-dev/reference/apis/js-apis-request.md index 75499d3809a14edf61ea350f5cf8c539e0408a38..675782f3822b59be27f8ff7124b7f5d4ed062530 100644 --- a/en/application-dev/reference/apis/js-apis-request.md +++ b/en/application-dev/reference/apis/js-apis-request.md @@ -94,6 +94,7 @@ Uploads files. This API uses a promise to return the result. You can use [on('co | Promise<[UploadTask](#uploadtask)> | Promise used to return the **UploadTask** object.| **Error codes** + For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). | ID| Error Message| @@ -104,6 +105,7 @@ For details about the error codes, see [Upload and Download Error Codes](../erro ```js let uploadTask; + let context; let uploadConfig = { url: 'http://patch', header: { key1: "value1", key2: "value2" }, @@ -112,16 +114,20 @@ For details about the error codes, see [Upload and Download Error Codes](../erro data: [{ name: "name123", value: "123" }], }; try { - request.uploadFile(globalThis.abilityContext, uploadConfig).then((data) => { + request.uploadFile(context, uploadConfig).then((data) => { uploadTask = data; }).catch((err) => { - console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); + console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`); }); } catch (err) { - console.error('err.code : ' + err.code + ', err.message : ' + err.message); + console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`); } ``` +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + ## request.uploadFile9+ @@ -142,6 +148,7 @@ Uploads files. This API uses an asynchronous callback to return the result. You | callback | AsyncCallback<[UploadTask](#uploadtask)> | Yes| Callback used to return the **UploadTask** object.| **Error codes** + For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). | ID| Error Message| @@ -152,6 +159,7 @@ For details about the error codes, see [Upload and Download Error Codes](../erro ```js let uploadTask; + let context; let uploadConfig = { url: 'http://patch', header: { key1: "value1", key2: "value2" }, @@ -160,18 +168,22 @@ For details about the error codes, see [Upload and Download Error Codes](../erro data: [{ name: "name123", value: "123" }], }; try { - request.uploadFile(globalThis.abilityContext, uploadConfig, (err, data) => { + request.uploadFile(context, uploadConfig, (err, data) => { if (err) { - console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); - return; + console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`); + return; } uploadTask = data; }); } catch (err) { - console.error('err.code : ' + err.code + ', err.message : ' + err.message); + console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`); } ``` +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + ## request.upload(deprecated) upload(config: UploadConfig): Promise<UploadTask> @@ -212,9 +224,9 @@ Uploads files. This API uses a promise to return the result. data: [{ name: "name123", value: "123" }], }; request.upload(uploadConfig).then((data) => { - uploadTask = data; + uploadTask = data; }).catch((err) => { - console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); + console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`); }) ``` @@ -254,11 +266,11 @@ Uploads files. This API uses an asynchronous callback to return the result. data: [{ name: "name123", value: "123" }], }; request.upload(uploadConfig, (err, data) => { - if (err) { - console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); - return; - } - uploadTask = data; + if (err) { + console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`); + return; + } + uploadTask = data; }); ``` @@ -296,7 +308,7 @@ Subscribes to upload progress events. This API uses a callback to return the res ```js let upProgressCallback = (uploadedSize, totalSize) => { - console.info("upload totalSize:" + totalSize + " uploadedSize:" + uploadedSize); + console.info("upload totalSize:" + totalSize + " uploadedSize:" + uploadedSize); }; uploadTask.on('progress', upProgressCallback); ``` @@ -329,7 +341,7 @@ Subscribes to HTTP header events for an upload task. This API uses a callback to ```js let headerCallback = (headers) => { - console.info("upOnHeader headers:" + JSON.stringify(headers)); + console.info("upOnHeader headers:" + JSON.stringify(headers)); }; uploadTask.on('headerReceive', headerCallback); ``` @@ -363,7 +375,7 @@ Subscribes to upload completion or failure events. This API uses a callback to r ```js let upCompleteCallback = (taskStates) => { for (let i = 0; i < taskStates.length; i++ ) { - console.info("upOnComplete taskState:" + JSON.stringify(taskStates[i])); + console.info("upOnComplete taskState:" + JSON.stringify(taskStates[i])); } }; uploadTask.on('complete', upCompleteCallback); @@ -392,13 +404,13 @@ Unsubscribes from upload progress events. This API uses a callback to return the | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (upload progress).| -| callback | function | No| Callback used to return the result.
**uploadedSize**: size of the uploaded files, in bytes.
**totalSize**: Total size of the files to upload, in bytes. | +| callback | function | No| Callback used to return the result.
**uploadedSize**: size of the uploaded files, in B.
**totalSize**: Total size of the files to upload, in B.| **Example** ```js let upProgressCallback = (uploadedSize, totalSize) => { - console.info('Upload delete progress notification.' + 'totalSize:' + totalSize + 'uploadedSize:' + uploadedSize); + console.info('Upload delete progress notification.' + 'totalSize:' + totalSize + 'uploadedSize:' + uploadedSize); }; uploadTask.off('progress', upProgressCallback); ``` @@ -425,7 +437,7 @@ Unsubscribes from HTTP header events for an upload task. This API uses a callbac ```js let headerCallback = (header) => { - console.info(`Upload delete headerReceive notification. header: ${JSON.stringify(header)}`); + console.info(`Upload delete headerReceive notification. header: ${JSON.stringify(header)}`); }; uploadTask.off('headerReceive', headerCallback); ``` @@ -453,7 +465,7 @@ Unsubscribes from upload completion or failure events. This API uses a callback let upCompleteCallback = (taskStates) => { console.info('Upload delete complete notification.'); for (let i = 0; i < taskStates.length; i++ ) { - console.info('taskState:' + JSON.stringify(taskStates[i])); + console.info('taskState:' + JSON.stringify(taskStates[i])); } }; uploadTask.off('complete', upCompleteCallback); @@ -486,13 +498,13 @@ Deletes this upload task. This API uses a promise to return the result. ```js uploadTask.delete().then((result) => { - if (result) { - console.info('Upload task removed successfully. '); - } else { - console.error('Failed to remove the upload task. '); - } + if (result) { + console.info('Succeeded in deleting the upload task.'); + } else { + console.error(`Failed to delete the upload task. Code: ${err.code}, message: ${err.message}`); + } }).catch((err) => { - console.error('Failed to remove the upload task. Cause: ' + JSON.stringify(err)); + console.error(`Failed to delete the upload task. Code: ${err.code}, message: ${err.message}`); }); ``` @@ -517,15 +529,15 @@ Deletes this upload task. This API uses an asynchronous callback to return the r ```js uploadTask.delete((err, result) => { - if (err) { - console.error('Failed to remove the upload task. Cause: ' + JSON.stringify(err)); - return; - } - if (result) { - console.info('Upload task removed successfully.'); - } else { - console.error('Failed to remove the upload task.'); - } + if (err) { + console.error(`Failed to delete the upload task. Code: ${err.code}, message: ${err.message}`); + return; + } + if (result) { + console.info('Succeeded in deleting the upload task.'); + } else { + console.error(`Failed to delete the upload task. Code: ${err.code}, message: ${err.message}`); + } }); ``` @@ -554,13 +566,13 @@ Removes this upload task. This API uses a promise to return the result. ```js uploadTask.remove().then((result) => { - if (result) { - console.info('Upload task removed successfully. '); - } else { - console.error('Failed to remove the upload task. '); - } + if (result) { + console.info('Succeeded in removing the upload task.'); + } else { + console.error(`Failed to remove the upload task. Code: ${err.code}, message: ${err.message}`); + } }).catch((err) => { - console.error('Failed to remove the upload task. Cause: ' + JSON.stringify(err)); + console.error(`Failed to remove the upload task. Code: ${err.code}, message: ${err.message}`); }); ``` @@ -589,15 +601,15 @@ Removes this upload task. This API uses an asynchronous callback to return the r ```js uploadTask.remove((err, result) => { - if (err) { - console.error('Failed to remove the upload task. Cause: ' + JSON.stringify(err)); - return; - } - if (result) { - console.info('Upload task removed successfully.'); - } else { - console.error('Failed to remove the upload task.'); - } + if (err) { + console.error(`Failed to remove the upload task. Code: ${err.code}, message: ${err.message}`); + return; + } + if (result) { + console.info('Succeeded in removing the upload task.'); + } else { + console.error(`Failed to remove the upload task. Code: ${err.code}, message: ${err.message}`); + } }); ``` @@ -640,7 +652,7 @@ Describes the list of files in [UploadConfig](#uploadconfig). | -------- | -------- | -------- | -------- | | filename | string | Yes| File name in the header when **multipart** is used.| | name | string | Yes| Name of a form item when **multipart** is used. The default value is **file**.| -| uri | string | Yes| Local path for storing files.
Only the **internal** protocol type is supported. In the value, **internal://cache/** is mandatory. Example:
internal://cache/path/to/file.txt | +| uri | string | Yes| Local path for storing files.
Only the **internal** protocol type is supported. In the value, **"internal://cache/"** must be included. Example:
internal://cache/path/to/file.txt | | type | string | Yes| Type of the file content. By default, the type is obtained based on the extension of the file name or URI.| @@ -681,29 +693,35 @@ Downloads files. This API uses a promise to return the result. You can use [on(' | Promise<[DownloadTask](#downloadtask)> | Promise used to return the result.| **Error codes** + For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). | ID| Error Message| | -------- | -------- | | 13400001 | file operation error. | | 13400002 | bad file path. | -| 13400003 | task manager service error. | +| 13400003 | task service ability error. | **Example** ```js let downloadTask; + let context; try { - request.downloadFile(globalThis.abilityContext, { url: 'https://xxxx/xxxx.hap' }).then((data) => { - downloadTask = data; + request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data) => { + downloadTask = data; }).catch((err) => { - console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); + console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); }) } catch (err) { - console.error('err.code : ' + err.code + ', err.message : ' + err.message); + console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); } ``` +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + ## request.downloadFile9+ @@ -725,32 +743,38 @@ Downloads files. This API uses an asynchronous callback to return the result. Yo | callback | AsyncCallback<[DownloadTask](#downloadtask)> | Yes| Callback used to return the result.| **Error codes** + For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). | ID| Error Message| | -------- | -------- | | 13400001 | file operation error. | | 13400002 | bad file path. | -| 13400003 | task manager service error. | +| 13400003 | task service ability error. | **Example** ```js let downloadTask; + let context; try { - request.downloadFile(globalThis.abilityContext, { url: 'https://xxxx/xxxxx.hap', + request.downloadFile(context, { url: 'https://xxxx/xxxxx.hap', filePath: 'xxx/xxxxx.hap'}, (err, data) => { - if (err) { - console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); - return; - } - downloadTask = data; + if (err) { + console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); + return; + } + downloadTask = data; }); } catch (err) { - console.error('err.code : ' + err.code + ', err.message : ' + err.message); + console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); } ``` +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + ## request.download(deprecated) download(config: DownloadConfig): Promise<DownloadTask> @@ -784,9 +808,9 @@ Downloads files. This API uses a promise to return the result. ```js let downloadTask; request.download({ url: 'https://xxxx/xxxx.hap' }).then((data) => { - downloadTask = data; + downloadTask = data; }).catch((err) => { - console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); + console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); }) ``` @@ -820,11 +844,11 @@ Downloads files. This API uses an asynchronous callback to return the result. let downloadTask; request.download({ url: 'https://xxxx/xxxxx.hap', filePath: 'xxx/xxxxx.hap'}, (err, data) => { - if (err) { - console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); - return; - } - downloadTask = data; + if (err) { + console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); + return; + } + downloadTask = data; }); ``` @@ -861,7 +885,7 @@ Subscribes to download progress events. This API uses a callback to return the r ```js let progresCallback = (receivedSize, totalSize) => { - console.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize); + console.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize); }; downloadTask.on('progress', progresCallback); ``` @@ -888,7 +912,7 @@ Unsubscribes from download progress events. This API uses a callback to return t ```js let progresCallback = (receivedSize, totalSize) => { - console.info('Download delete progress notification.' + 'receivedSize:' + receivedSize + 'totalSize:' + totalSize); + console.info('Download delete progress notification.' + 'receivedSize:' + receivedSize + 'totalSize:' + totalSize); }; downloadTask.off('progress', progresCallback); ``` @@ -898,7 +922,7 @@ Unsubscribes from download progress events. This API uses a callback to return t on(type: 'complete'|'pause'|'remove', callback:() => void): void -Subscribes to download events. This API uses a callback to return the result synchronously. +Subscribes to download events. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.INTERNET @@ -915,17 +939,17 @@ Subscribes to download events. This API uses a callback to return the result syn ```js let completeCallback = () => { - console.info('Download task completed.'); + console.info('Download task completed.'); }; downloadTask.on('complete', completeCallback); let pauseCallback = () => { - console.info('Download task pause.'); + console.info('Download task pause.'); }; downloadTask.on('pause', pauseCallback); let removeCallback = () => { - console.info('Download task remove.'); + console.info('Download task remove.'); }; downloadTask.on('remove', removeCallback); ``` @@ -952,17 +976,17 @@ Unsubscribes from download events. This API uses a callback to return the result ```js let completeCallback = () => { - console.info('Download delete complete notification.'); + console.info('Download delete complete notification.'); }; downloadTask.off('complete', completeCallback); let pauseCallback = () => { - console.info('Download delete pause notification.'); + console.info('Download delete pause notification.'); }; downloadTask.off('pause', pauseCallback); let removeCallback = () => { - console.info('Download delete remove notification.'); + console.info('Download delete remove notification.'); }; downloadTask.off('remove', removeCallback); ``` @@ -995,7 +1019,7 @@ Subscribes to download failure events. This API uses a callback to return the re ```js let failCallback = (err) => { - console.info('Download task failed. Cause:' + err); + console.error(`Failed to download the task. Code: ${err.code}, message: ${err.message}`); }; downloadTask.on('fail', failCallback); ``` @@ -1022,7 +1046,7 @@ Unsubscribes from download failure events. This API uses a callback to return th ```js let failCallback = (err) => { - console.info(`Download delete fail notification. err: ${err.message}`); + console.error(`Failed to download the task. Code: ${err.code}, message: ${err.message}`); }; downloadTask.off('fail', failCallback); ``` @@ -1047,13 +1071,13 @@ Removes this download task. This API uses a promise to return the result. ```js downloadTask.delete().then((result) => { - if (result) { - console.info('Download task removed.'); - } else { - console.error('Failed to remove the download task.'); - } + if (result) { + console.info('Succeeded in removing the download task.'); + } else { + console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`); + } }).catch ((err) => { - console.error('Failed to remove the download task.'); + console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`); }); ``` @@ -1078,15 +1102,15 @@ Deletes this download task. This API uses an asynchronous callback to return the ```js downloadTask.delete((err, result)=>{ - if(err) { - console.error('Failed to remove the download task.'); - return; - } - if (result) { - console.info('Download task removed.'); - } else { - console.error('Failed to remove the download task.'); - } + if(err) { + console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`); + return; + } + if (result) { + console.info('Succeeded in removing the download task.'); + } else { + console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`); + } }); ``` @@ -1111,9 +1135,9 @@ Obtains the information about this download task. This API uses a promise to ret ```js downloadTask.getTaskInfo().then((downloadInfo) => { - console.info('Download task queried. Data:' + JSON.stringify(downloadInfo)) + console.info('Succeeded in querying the download task') }) .catch((err) => { - console.error('Failed to query the download task. Cause:' + err) + console.error(`Failed to query the download task. Code: ${err.code}, message: ${err.message}`) }); ``` @@ -1138,11 +1162,11 @@ Obtains the information about this download task. This API uses an asynchronous ```js downloadTask.getTaskInfo((err, downloadInfo)=>{ - if(err) { - console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err)); - } else { - console.info('download query success. data:'+ JSON.stringify(downloadInfo)); - } + if(err) { + console.error(`Failed to query the download mimeType. Code: ${err.code}, message: ${err.message}`); + } else { + console.info('Succeeded in querying the download mimeType'); + } }); ``` @@ -1167,9 +1191,9 @@ Obtains the **MimeType** of this download task. This API uses a promise to retur ```js downloadTask.getTaskMimeType().then((data) => { - console.info('Download task queried. Data:' + JSON.stringify(data)); + console.info('Succeeded in querying the download MimeType'); }).catch((err) => { - console.error('Failed to query the download MimeType. Cause:' + JSON.stringify(err)) + console.error(`Failed to query the download MimeType. Code: ${err.code}, message: ${err.message}`) }); ``` @@ -1194,11 +1218,11 @@ Obtains the **MimeType** of this download task. This API uses an asynchronous ca ```js downloadTask.getTaskMimeType((err, data)=>{ - if(err) { - console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err)); - } else { - console.info('Download task queried. data:' + JSON.stringify(data)); - } + if(err) { + console.error(`Failed to query the download mimeType. Code: ${err.code}, message: ${err.message}`); + } else { + console.info('Succeeded in querying the download mimeType'); + } }); ``` @@ -1223,13 +1247,13 @@ Pauses this download task. This API uses a promise to return the result. ```js downloadTask.suspend().then((result) => { - if (result) { - console.info('Download task paused. '); - } else { - console.error('Failed to pause the download task. Cause:' + JSON.stringify(result)); - } + if (result) { + console.info('Succeeded in pausing the download task.'); + } else { + console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`); + } }).catch((err) => { - console.error('Failed to pause the download task. Cause:' + JSON.stringify(err)); + console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`); }); ``` @@ -1254,15 +1278,15 @@ Pauses this download task. This API uses an asynchronous callback to return the ```js downloadTask.suspend((err, result)=>{ - if(err) { - console.error('Failed to pause the download task. Cause:' + JSON.stringify(err)); - return; - } - if (result) { - console.info('Download task paused. '); - } else { - console.error('Failed to pause the download task. Cause:' + JSON.stringify(result)); - } + if(err) { + console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`); + return; + } + if (result) { + console.info('Succeeded in pausing the download task.'); + } else { + console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`); + } }); ``` @@ -1287,14 +1311,14 @@ Resumes this download task. This API uses a promise to return the result. ```js downloadTask.restore().then((result) => { - if (result) { - console.info('Download task resumed.') - } else { - console.error('Failed to resume the download task. '); - } - console.info('Download task resumed.') + if (result) { + console.info('Succeeded in resuming the download task.') + } else { + console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`); + } + console.info('Succeeded in resuming the download task.') }).catch((err) => { - console.error('Failed to resume the download task. Cause:' + err); + console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`); }); ``` @@ -1319,20 +1343,19 @@ Resumes this download task. This API uses an asynchronous callback to return the ```js downloadTask.restore((err, result)=>{ - if (err) { - console.error('Failed to resume the download task. Cause:' + err); - return; - } - if (result) { - console.info('Download task resumed.'); - } else { - console.error('Failed to resume the download task.'); - } + if (err) { + console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`); + return; + } + if (result) { + console.info('Succeeded in resuming the download task.'); + } else { + console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`); + } }); ``` - ### remove(deprecated) remove(): Promise<boolean> @@ -1357,13 +1380,13 @@ Removes this download task. This API uses a promise to return the result. ```js downloadTask.remove().then((result) => { - if (result) { - console.info('Download task removed.'); - } else { - console.error('Failed to remove the download task.'); - } + if (result) { + console.info('Succeeded in removing the download task.'); + } else { + console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`); + } }).catch ((err) => { - console.error('Failed to remove the download task.'); + console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`); }); ``` @@ -1386,21 +1409,21 @@ Removes this download task. This API uses an asynchronous callback to return the | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes| Callback used to return the task removal result. | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the task deletion result.| **Example** ```js downloadTask.remove((err, result)=>{ - if(err) { - console.error('Failed to remove the download task.'); - return; - } - if (result) { - console.info('Download task removed.'); - } else { - console.error('Failed to remove the download task.'); - } + if(err) { + console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`); + return; + } + if (result) { + console.info('Succeeded in removing the download task.'); + } else { + console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`); + } }); ``` @@ -1429,9 +1452,9 @@ Queries this download task. This API uses a promise to return the result. ```js downloadTask.query().then((downloadInfo) => { - console.info('Download task queried. Data:' + JSON.stringify(downloadInfo)) + console.info('Succeeded in querying the download task.') }) .catch((err) => { - console.error('Failed to query the download task. Cause:' + err) + console.error(`Failed to query the download task. Code: ${err.code}, message: ${err.message}`) }); ``` @@ -1460,11 +1483,11 @@ Queries this download task. This API uses an asynchronous callback to return the ```js downloadTask.query((err, downloadInfo)=>{ - if(err) { - console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err)); - } else { - console.info('download query success. data:'+ JSON.stringify(downloadInfo)); - } + if(err) { + console.error(`Failed to query the download mimeType. Code: ${err.code}, message: ${err.message}`); + } else { + console.info('Succeeded in querying the download task.'); + } }); ``` @@ -1493,9 +1516,9 @@ Queries the **MimeType** of this download task. This API uses a promise to retur ```js downloadTask.queryMimeType().then((data) => { - console.info('Download task queried. Data:' + JSON.stringify(data)); + console.info('Succeededto in querying the download MimeType.'); }).catch((err) => { - console.error('Failed to query the download MimeType. Cause:' + JSON.stringify(err)) + console.error(`Failed to query the download MimeType. Code: ${err.code}, message: ${err.message}`) }); ``` @@ -1524,11 +1547,11 @@ Queries the **MimeType** of this download task. This API uses an asynchronous ca ```js downloadTask.queryMimeType((err, data)=>{ - if(err) { - console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err)); - } else { - console.info('Download task queried. data:' + JSON.stringify(data)); - } + if(err) { + console.error(`Failed to query the download mimeType. Code: ${err.code}, message: ${err.message}`); + } else { + console.info('Succeeded in querying the download mimeType.'); + } }); ``` @@ -1557,13 +1580,13 @@ Pauses this download task. This API uses a promise to return the result. ```js downloadTask.pause().then((result) => { - if (result) { - console.info('Download task paused. '); - } else { - console.error('Failed to pause the download task. Cause:' + JSON.stringify(result)); - } + if (result) { + console.info('Succeeded in pausing the download task.'); + } else { + console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`); + } }).catch((err) => { - console.error('Failed to pause the download task. Cause:' + JSON.stringify(err)); + console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`); }); ``` @@ -1592,15 +1615,15 @@ Pauses this download task. This API uses an asynchronous callback to return the ```js downloadTask.pause((err, result)=>{ - if(err) { - console.error('Failed to pause the download task. Cause:' + JSON.stringify(err)); - return; - } - if (result) { - console.info('Download task paused. '); - } else { - console.error('Failed to pause the download task. Cause:' + JSON.stringify(result)); - } + if(err) { + console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`); + return; + } + if (result) { + console.info('Succeeded in pausing the download task.'); + } else { + console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`); + } }); ``` @@ -1629,14 +1652,14 @@ Resumes this download task. This API uses a promise to return the result. ```js downloadTask.resume().then((result) => { - if (result) { - console.info('Download task resumed.') - } else { - console.error('Failed to resume the download task. '); - } - console.info('Download task resumed.') + if (result) { + console.info('Succeeded in resuming the download task.') + } else { + console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`); + } + console.info('Succeeded in resuming the download task.') }).catch((err) => { - console.error('Failed to resume the download task. Cause:' + err); + console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`); }); ``` @@ -1665,15 +1688,15 @@ Resumes this download task. This API uses an asynchronous callback to return the ```js downloadTask.resume((err, result)=>{ - if (err) { - console.error('Failed to resume the download task. Cause:' + err); - return; - } - if (result) { - console.info('Download task resumed.'); - } else { - console.error('Failed to resume the download task.'); - } + if (err) { + console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`); + return; + } + if (result) { + console.info('Succeeded in resuming the download task.'); + } else { + console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`); + } }); ``` @@ -1693,7 +1716,7 @@ Defines the download task configuration. | enableRoaming | boolean | No| Whether download is allowed on a roaming network. The default value is **false**.
- **true**: allowed
- **false**: not allowed| | description | string | No| Description of the download session.| | filePath7+ | string | No| Path where the downloaded file is stored.
- In the FA model, use [context](js-apis-inner-app-context.md#contextgetcachedir) to obtain the cache directory of the application, for example, **\${featureAbility.getContext().getFilesDir()}/test.txt\**, and store the file in this directory.
- In the stage model, use [AbilityContext](js-apis-inner-application-context.md) to obtain the file path, for example, **\${globalThis.abilityContext.tempDir}/test.txt\**, and store the file in this path.| -| networkType | number | No| Network type allowed for download. The default value is **NETWORK_MOBILE and NETWORK_WIFI**.
- NETWORK_MOBILE: 0x00000001
- NETWORK_WIFI: 0x00010000| +| networkType | number | No| Network type allowed for the download. The default value is **NETWORK_MOBILE and NETWORK_WIFI**.
- NETWORK_MOBILE: 0x00000001
- NETWORK_WIFI: 0x00010000| | title | string | No| Download task name.| | background9+ | boolean | No| Whether to enable background task notification so that the download status is displayed in the notification panel. The default value is false.| @@ -1706,7 +1729,7 @@ Defines the download task information, which is the callback parameter of the [g **System capability**: SystemCapability.MiscServices.Download | Name| Type|Mandatory| Description| -| -------- | ------ |---------------- | +| -------- | -------- | -------- | -------- | | downloadId | number |Yes| ID of the download task.| | failedReason | number|Yes| Cause of the download failure. The value can be any constant in [Download Error Codes](#download-error-codes).| | fileName | string |Yes| Name of the downloaded file.| @@ -1718,4 +1741,1373 @@ Defines the download task information, which is the callback parameter of the [g | downloadTotalBytes | number |Yes| Total size of the files to download, in bytes.| | description | string |Yes| Description of the download task.| | downloadedBytes | number |Yes| Size of the files downloaded, in bytes.| + +## Action10+ + +Defines action options. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name| Value|Description| +| -------- | -------- |-------- | +| DOWNLOAD | 0 |Download.| +| UPLOAD | 1 |Upload.| + + +## Mode10+ +Defines mode options. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name| Value|Description| +| -------- | -------- |-------- | +| BACKGROUND | 0 |Background task.| +| FOREGROUND | 1 |Foreground task.| + +## Network10+ + +Defines network options. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name| Value|Description| +| -------- | -------- |-------- | +| ANY | 0 |Network of any type.| +| WIFI | 1 |Wi-Fi network.| +| CELLULAR | 2 |Cellular data network.| + +## FileSpec10+ +Provides the file information of a table item. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| path | string | Yes| File path. The options are as follows:
- Relative path in the cache folder of the invoker.
- URI (applicable when the application has the permission to access the URI).| +| mimeType | string | No| MIME type of the file. The default value is as follows:
- During an upload, the value is obtained from the file name or URI suffix.
- During a download, the value is **Content-Type** when there is response and **octet-stream** otherwise.| +| filename | string | No| File name. The default value is obtained from the file path.| +| extras | Object | No| Additional information of the file.| + + +## FormItem10+ +Describes the form item of a task. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Form parameter name.| +| value | string \| [FileSpec](#filespec10) \| Array<[FileSpec](#filespec10)> | Yes| Form parameter value.| + + +## Conf10+ +Provides the configuration information of an upload or download task. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| action | [Action](#action10) | Yes| Task action.
- **UPLOAD**
- **DOWNLOAD**| +| url | string | Yes| Resource URL. The value contains a maximum of 2048 characters.| +| title | string | No| Task title. The value contains a maximum of 256 characters. This parameter is left blank by default.| +| description | string | No| Task description. The value contains a maximum of 1024 characters. The default value is a null string.| +| mode | [Mode](#mode10) | No| Task mode. The default mode is background.
- For a foreground task, a callback is used for notification.
- For a background task, the system notification and network connection features (detection, recovery, and automatic retry) are provided.| +| overwrite | boolean | No| Whether to overwrite an existing file during the download. The default value is **false**.
- **true**: Overwrite the existing file.
- **false**: Do not overwrite the existing file. In this case, the download fails.| +| method | string | No| Standard HTTP method for the task. The value can be **GET**, **POST**, or **PUT**, which is case-insensitive.
- If the task is an upload, use **PUT** or **POST**. The default value is **PUT**.
- If the task is a download, use **GET** or **POST**. The default value is **GET**.| +| headers | object | No| HTTPS headers to be included in the task.
- If the task is an upload, the default **Content-Type** is **multipart/form-data**.
- If the task is a download, the default **Content-Type** is **application/json**.| +| data | string \| Array<[FormItem](#formitem10)> | No| Task data.
- If the task is a download, the value is a string, typically in JSON format (an object will be converted to a JSON string); the default value is null.
- If the task is an upload, the value is Array<[FormItem](#formitem10)>; the default value is null.| +| saveas | string | No| Path for storing downloaded files. The options are as follows:
- Relative path in the cache folder of the invoker, for example, ./xxx/yyy/zzz.html and xxx/yyy/zzz.html.
- URI (applicable when the application has the permission to access the URI), for example, **"datashare://bundle/xxx/yyy/zzz.html"**. Currently, this type is not supported.
The default value is a relative path in the cache folder of the application.| +| network | [Network](#network10) | No| Network used for the task. The default value is **ANY** (Wi-Fi or cellular).| +| metered | boolean | No| Whether the task is allowed on a metered connection. The default value is **false**.| +| roaming | boolean | No| Whether the task is allowed on a roaming network. The default value is **true**.| +| retry | boolean | No| Whether automatic retry is enabled for background tasks. The default value is **true**.| +| redirect | boolean | No| Whether redirection is allowed. The default value is **true**.| +| index | number | No| Path index of the task. It is usually used for resumable downloads. The default value is **0**.| +| begins | number | No| File start point of the task. It is usually used for resumable downloads. The default value is **0**. The value is a closed interval.
- If the task is a download, the value is obtained by sending an HTTP range request to read the start position when the server starts to download files.
- If the task is an upload, the value is obtained at the beginning of the upload.| +| ends | number | No| File end point of the task. It is usually used for resumable downloads. The default value is **-1**. The value is a closed interval.
- If the task is a download, the value is obtained by sending an HTTP range request to read the end position when the server starts to download files.
- If the task is an upload, the value is obtained at the end of the upload.| +| gauge | boolean | No| Whether to send progress notifications. This parameter applies only to background tasks. The default value is **false**.
- **false**: Progress notifications are not sent. This means that a notification is sent only to indicate the result of the total task.
- **true**: Progress notifications are sent to indicate the result of each file.| +| precise | boolean | No| - If this parameter is set to **true**, the task fails when the file size cannot be obtained.
- If this parameter is set to **false**, the task continues when the file size is set to **-1**.
The default value is **false**.| +| token | string | No| Token of the task. If the task has a token configured, this token is required for query of the task. The value contains 8 to 2048 bytes. This parameter is left empty by default.| +| extras | object | No| Additional information of the task. This parameter is left blank by default.| + +## State10+ + +Defines the current task status. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name| Value|Description| +| -------- | -------- |-------- | +| INITIALIZED | 0x00 |The task is initialized based on the configuration specified in [Conf](#conf10).| +| WAITING | 0x10 |The task lacks resources for running or the resources for retries do not match the network status.| +| RUNNING | 0x20 |The task is being executed.| +| RETRYING | 0x21 |The task has failed at least once and is being executed again.| +| PAUSED | 0x30 |The task is suspended and will be resumed later.| +| STOPPED | 0x31 |The task is stopped.| +| COMPLETED | 0x40 |The task is complete.| +| FAILED | 0x41 |The task fails.| +| REMOVED | 0x50 |The task is removed.| + + +## Progress10+ +Describes the data structure of the task progress. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| state | [State](#state10) | Yes| Current task status.| +| index | number | Yes| Index of the file that is being processed in the task.| +| processed | number | Yes| Size of processed data in the current file in the task, in bytes.| +| sizes | Array<number> | Yes| Size of files in the task, in bytes.| +| extras | object | No| Extra information of the task, for example, the header and body of the response from the server.| + + +## Broken10+ + +Defines the cause of a task failure. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name| Value|Description| +| -------- | -------- |-------- | +| OTHERS | 0xFF |Other fault.| +| DISCONNECTED | 0x00 |Network disconnection.| +| TIMEOUT | 0x10 |Timeout.| +| PROTOCOL | 0x20 |Protocol error, for example, an internal server error (500) or a data range that cannot be processed (416).| +| FSIO | 0x40 |File system I/O error, for example, an error that occurs during the open, search, read, write, or close operation.| + + +## TaskInfo10+ +Defines the data structure of the task information for query. The fields available varies depends on the query type. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| uid | string | No| UID of the application. It is only available for query by system applications.
**System API**: This is a system API.| +| bundle | string | No| Bundle name of the application. It is only available for query by system applications.
**System API**: This is a system API.| +| url | string | No| Task URL. It is only available for query by non-system applications. An empty string is returned for query by system applications.| +| data | string \| Array<[FormItem](#formitem10)> | No| Task value.| +| tid | string | Yes| Task ID.| +| title | string | Yes| Task title.| +| description | string | Yes| Task description.| +| action | [Action](#action10) | Yes| Task action.
- **UPLOAD**
- **DOWNLOAD**| +| mode | [Mode](#mode10) | Yes| Task mode.
- **FOREGROUND**
- **BACKGROUND**| +| mimeType | string | Yes| MIME type in the task configuration.| +| progress | [Progress](#progress10) | Yes| Task progress.| +| gauge | boolean | Yes| Whether to send progress notifications. This parameter applies only to background tasks.| +| ctime | string | Yes| Date and time when a task is created in UTC mode. The value is generated by the system of the current device.| +| mtime | string | Yes| Date and time when a task is modified in UTC mode. The value is generated by the system of the current device.| +| retry | boolean | Yes| Whether automatic retry is enabled for the task. This parameter applies only to background tasks.| +| tries | number | Yes| Number of retries of the task.| +| broken | [Broken](#broken10) | Yes| Failure cause of the task.
- **OTHERS**: other fault.
- **DISCONNECT**: network disconnection.
- **TIMEOUT**: timeout.
- **PROTOCOL**: protocol error.
- **FSIO**: file system I/O error.| +| reason | string | Yes| Reason why the task is waiting, failed, stopped, or paused.| +| extras | string | No| Extra information of the task| + + +## Task10+ +Implements an upload or download task. Before using this API, you must obtain a **Task** object, from a promise through [request.agent.create10+](#requestagentcreate10-1) or from a callback through [request.agent.create10+](#requestagentcreate10). + +### Attributes +Task attributes include the task ID and task configuration. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| tid | string | Yes| Task ID, which is unique in the system and is automatically generated by the system.| +| conf | [Conf](#conf10) | Yes| Task configuration.| + + +### on('progress')10+ + +on(event: 'progress', callback: (progress: Progress) => void): void + +Subscribes to task progress events. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Type of the event to subscribe to.
The value is **'progress'**, indicating the task progress.| +| callback | function | Yes| Callback used to return the data structure of the task progress.| + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 21900005 | task mode error. | + +**Example** + + ```js + let context; + let attachments = [{ + name: "taskOnTest", + value: { + filename: "taskOnTest.avi", + mimetype: "application/octet-stream", + path: "./taskOnTest.avi", + } + }]; + let conf = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', + title: 'taskOnTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.BACKGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + let createOnCallback = (progress) => { + console.info('upload task completed.'); + }; + request.agent.create(context, conf).then((task)=> { + task.on('progress', createOnCallback); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); + }).catch((err) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### on('completed')10+ + +on(event: 'completed', callback: (progress: Progress) => void): void + +Subscribes to task completion events. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Type of the event to subscribe to.
The value is **'completed'**, indicating task completion.| +| callback | function | Yes| Callback used to return the data structure of the task progress.| + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 21900005 | task mode error. | + +**Example** + + ```js + let context; + let attachments = [{ + name: "taskOnTest", + value: { + filename: "taskOnTest.avi", + mimetype: "application/octet-stream", + path: "./taskOnTest.avi", + } + }]; + let conf = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', + title: 'taskOnTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.BACKGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + let createOnCallback = (progress) => { + console.info('upload task completed.'); + }; + request.agent.create(context, conf).then((task)=> { + task.on('completed', createOnCallback); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); + }).catch((err) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### on('failed')10+ + +on(event: 'failed', callback: (progress: Progress) => void): void + +Subscribes to task failure events. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Type of the event to subscribe to.
The value is **'failed'**, indicating task failure.| +| callback | function | Yes| Callback used to return the data structure of the task progress.| + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 21900005 | task mode error. | + +**Example** + + ```js + let context; + let attachments = [{ + name: "taskOnTest", + value: { + filename: "taskOnTest.avi", + mimetype: "application/octet-stream", + path: "./taskOnTest.avi", + } + }]; + let conf = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', + title: 'taskOnTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.BACKGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + let createOnCallback = (progress) => { + console.info('upload task completed.'); + }; + request.agent.create(context, conf).then((task)=> { + task.on('failed', createOnCallback); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); + }).catch((err) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + + +### off('progress')10+ + +off(event: 'progress', callback?: (progress: Progress) => void): void + +Unsubscribes from task progress events. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Type of the event to subscribe to.
The value is **'progress'**, indicating the task progress.| +| callback | function | No| Callback used to return the data structure of the task progress.| + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 21900005 | task mode error. | + +**Example** + + ```js + let context; + let attachments = [{ + name: "taskOffTest", + value: { + filename: "taskOffTest.avi", + mimetype: "application/octet-stream", + path: "./taskOffTest.avi", + } + }]; + let conf = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', + title: 'taskOffTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.BACKGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + let createOffCallback = (progress) => { + console.info('upload task completed.'); + }; + request.agent.create(context, conf).then((task)=> { + task.on('progress', createOffCallback); + task.off('progress', createOffCallback); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); + }).catch((err) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### off('completed')10+ + +off(event: 'completed', callback?: (progress: Progress) => void): void + +Unsubscribes from task completion events. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Type of the event to subscribe to.
The value is **'completed'**, indicating task completion.| +| callback | function | No| Callback used to return the data structure of the task progress.| + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 21900005 | task mode error. | + +**Example** + + ```js + let context; + let attachments = [{ + name: "taskOffTest", + value: { + filename: "taskOffTest.avi", + mimetype: "application/octet-stream", + path: "./taskOffTest.avi", + } + }]; + let conf = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', + title: 'taskOffTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.BACKGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + let createOffCallback = (progress) => { + console.info('upload task completed.'); + }; + request.agent.create(context, conf).then((task)=> { + task.on('completed', createOffCallback); + task.off('completed', createOffCallback); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); + }).catch((err) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### off('failed')10+ + +off(event: 'failed', callback?: (progress: Progress) => void): void + +Unsubscribes from task failure events. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Type of the event to subscribe to.
The value is **'failed'**, indicating task failure.| +| callback | function | No| Callback used to return the data structure of the task progress.| + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 21900005 | task mode error. | + +**Example** + + ```js + let context; + let attachments = [{ + name: "taskOffTest", + value: { + filename: "taskOffTest.avi", + mimetype: "application/octet-stream", + path: "./taskOffTest.avi", + } + }]; + let conf = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', + title: 'taskOffTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.BACKGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + let createOffCallback = (progress) => { + console.info('upload task completed.'); + }; + request.agent.create(context, conf).then((task)=> { + task.on('failed', createOffCallback); + task.off('failed', createOffCallback); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); + }).catch((err) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### start10+ + +start(callback: AsyncCallback<void>): void + +Starts this task. This API cannot be used to start an initialized task. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | function | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400003 | task service ability error. | +| 21900007 | task state error. | + +**Example** + + ```js + let context; + let conf = { + action: request.agent.Action.DOWNLOAD, + url: 'http://127.0.0.1', + title: 'taskStartTest', + description: 'Sample code for start the download task', + mode: request.agent.Mode.BACKGROUND, + overwrite: false, + method: "GET", + data: "", + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + request.agent.create(context, conf).then((task) => { + task.start((err) => { + if (err) { + console.error(`Failed to start the download task, Code: ${err.code}, message: ${err.message}`); + return; + } + console.info(`Succeeded in starting a download task.`); + }); + console.info(`Succeeded in creating a download task. result: ${task.tid}`); + }).catch((err) => { + console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### start10+ + +start(): Promise<void> + +Starts this task. This API cannot be used to start an initialized task. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400003 | task service ability error. | +| 21900007 | task state error. | + +**Example** + + ```js + let context; + let conf = { + action: request.agent.Action.DOWNLOAD, + url: 'http://127.0.0.1', + title: 'taskStartTest', + description: 'Sample code for start the download task', + mode: request.agent.Mode.BACKGROUND, + overwrite: false, + method: "GET", + data: "", + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + request.agent.create(context, conf).then((task) => { + task.start().then(() => { + console.info(`Succeeded in starting a download task.`); + }).catch((err) => { + console.error(`Failed to start the download task, Code: ${err.code}, message: ${err.message}`); + }); + console.info(`Succeeded in creating a download task. result: ${task.tid}`); + }).catch((err) => { + console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### pause10+ + +pause(callback: AsyncCallback<void>): void + +Pauses this task. This API can be used to pause a background task that is waiting, running, or retrying. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | function | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400003 | task service ability error. | +| 21900005 | task mode error. | +| 21900007 | task state error. | + +**Example** + + ```js + let context; + let conf = { + action: request.agent.Action.DOWNLOAD, + url: 'http://127.0.0.1', + title: 'taskPauseTest', + description: 'Sample code for pause the download task', + mode: request.agent.Mode.BACKGROUND, + overwrite: false, + method: "GET", + data: "", + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + request.agent.create(context, conf).then((task) => { + task.pause((err) => { + if (err) { + console.error(`Failed to pause the download task, Code: ${err.code}, message: ${err.message}`); + return; + } + console.info(`Succeeded in pausing a download task. `); + }); + console.info(`Succeeded in creating a download task. result: ${task.tid}`); + }).catch((err) => { + console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + + +### pause10+ + +pause(): Promise<void> + +Pauses this task. This API can be used to pause a background task that is waiting, running, or retrying. This API uses a promise to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400003 | task service ability error. | +| 21900005 | task mode error. | +| 21900007 | task state error. | + +**Example** + + ```js + let context; + let conf = { + action: request.agent.Action.DOWNLOAD, + url: 'http://127.0.0.1', + title: 'taskPauseTest', + description: 'Sample code for pause the download task', + mode: request.agent.Mode.BACKGROUND, + overwrite: false, + method: "GET", + data: "", + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + request.agent.create(context, conf).then((task) => { + task.pause().then(() => { + console.info(`Succeeded in pausing a download task. `); + }).catch((err) => { + console.error(`Failed to pause the upload task, Code: ${err.code}, message: ${err.message}`); + }); + console.info(`Succeeded in creating a download task. result: ${task.tid}`); + }).catch((err) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + + +### resume10+ + +resume(callback: AsyncCallback<void>): void + +Resumes this task. This API can be used to resume a paused background task. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | function | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400003 | task service ability error. | +| 21900005 | task mode error. | +| 21900007 | task state error. | + +**Example** + + ```js + let context; + let conf = { + action: request.agent.Action.DOWNLOAD, + url: 'http://127.0.0.1', + title: 'taskResumeTest', + description: 'Sample code for resume the download task', + mode: request.agent.Mode.BACKGROUND, + overwrite: false, + method: "GET", + data: "", + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + request.agent.create(context, conf).then((task) => { + task.resume((err) => { + if (err) { + console.error(`Failed to resume the download task, Code: ${err.code}, message: ${err.message}`); + return; + } + console.info(`Succeeded in resuming a download task. `); + }); + console.info(`Succeeded in creating a download task. result: ${task.tid}`); + }).catch((err) => { + console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + + +### resume10+ + +resume(): Promise<void> + +Resumes this task. This API can be used to resume a paused background task. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400003 | task service ability error. | +| 21900005 | task mode error. | +| 21900007 | task state error. | + +**Example** + + ```js + let context; + let conf = { + action: request.agent.Action.DOWNLOAD, + url: 'http://127.0.0.1', + title: 'taskResumeTest', + description: 'Sample code for resume the download task', + mode: request.agent.Mode.BACKGROUND, + overwrite: false, + method: "GET", + data: "", + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + request.agent.create(context, conf).then((task) => { + task.resume().then(() => { + console.info(`Succeeded in resuming a download task. `); + }).catch((err) => { + console.error(`Failed to resume the download task, Code: ${err.code}, message: ${err.message}`); + }); + console.info(`Succeeded in creating a download task. result: ${task.tid}`); + }).catch((err) => { + console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + + +### stop10+ + +stop(callback: AsyncCallback<void>): void + +Stops this task. This API can be used to stop a running, waiting, or retrying task. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | function | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400003 | task service ability error. | +| 21900007 | task state error. | + +**Example** + + ```js + let context; + let conf = { + action: request.agent.Action.DOWNLOAD, + url: 'http://127.0.0.1', + title: 'taskStopTest', + description: 'Sample code for stop the download task', + mode: request.agent.Mode.BACKGROUND, + overwrite: false, + method: "GET", + data: "", + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + request.agent.create(context, conf).then((task) => { + task.stop((err) => { + if (err) { + console.error(`Failed to stop the download task, Code: ${err.code}, message: ${err.message}`); + return; + } + console.info(`Succeeded in stopping a download task. `); + }); + console.info(`Succeeded in creating a download task. result: ${task.tid}`); + }).catch((err) => { + console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + + +### stop10+ + +stop(): Promise<void> + +Stops this task. This API can be used to stop a running, waiting, or retrying task. This API uses a promise to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400003 | task service ability error. | +| 21900007 | task state error. | + +**Example** + + ```js + let context; + let conf = { + action: request.agent.Action.DOWNLOAD, + url: 'http://127.0.0.1', + title: 'taskStopTest', + description: 'Sample code for stop the download task', + mode: request.agent.Mode.BACKGROUND, + overwrite: false, + method: "GET", + data: "", + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + request.agent.create(context, conf).then((task) => { + task.stop().then(() => { + console.info(`Succeeded in stopping a download task. `); + }).catch((err) => { + console.error(`Failed to stop the download task, Code: ${err.code}, message: ${err.message}`); + }); + console.info(`Succeeded in creating a download task. result: ${task.tid}`); + }).catch((err) => { + console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +## request.agent.create10+ + +create(context: BaseContext, conf: Conf, callback: AsyncCallback<Task>): void + +Creates an upload or download task and adds it to the queue. An application can create a maximum of 10 tasks, and a maximum of 300 tasks can be carried. This API uses an asynchronous callback to return the result. + + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| conf | [Conf](#conf10) | Yes| Task configuration.| +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| +| callback | AsyncCallback<[Task](#task10)> | Yes| Callback used to return the configuration about the created task.| + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400001 | file operation error. | +| 13400003 | task service ability error. | +| 21900004 | application task queue full error. | +| 21900005 | task mode error. | + +**Example** + + ```js + let context; + let attachments = [{ + name: "reeateTest", + value: { + filename: "reeateTest.avi", + mimetype: "application/octet-stream", + path: "./reeateTest.avi", + } + }]; + let conf = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', + title: 'reeateTest', + description: 'Sample code for reeate task', + mode: request.agent.Mode.BACKGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + request.agent.create(context, conf, (err, task) => { + if (err) { + console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); + return; + } + console.info(`Succeeded in creating a download task. result: ${task.conf}`); + }); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +## request.agent.create10+ + +create(context: BaseContext, conf: Conf): Promise<Task> + +Creates an upload or download task and adds it to the queue. An application can create a maximum of 10 tasks, and a maximum of 300 tasks can be carried. This API uses a promise to return the result. + + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| +| conf | [Conf](#conf10) | Yes| Task configuration.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<[Task](#task10)> | Promise used to return the configuration about the created task.| + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400001 | file operation error. | +| 13400003 | task service ability error. | +| 21900004 | application task queue full error. | +| 21900005 | task mode error. | + +**Example** + + ```js + let context; + let attachments = [{ + name: "reeateTest", + value: { + filename: "reeateTest.avi", + mimetype: "application/octet-stream", + path: "./reeateTest.avi", + } + }]; + let conf = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', + title: 'reeateTest', + description: 'Sample code for reeate task', + mode: request.agent.Mode.BACKGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + request.agent.create(context, conf).then((task)=> { + console.info(`Succeeded in creating a download task. result: ${task.conf}`); + }).catch((err) => { + console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +## request.agent.remove10+ + +remove(id: string, callback: AsyncCallback<void>): void + +Removes a specified task of the invoker. If the task is being executed, the task is forced to stop. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| id | string | Yes| Task ID.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400003 | task service ability error. | +| 21900006 | task not found error. | + +**Example** + + ```js + request.agent.remove("id", (err) => { + if (err) { + console.error(`Failed to removing a download task, Code: ${err.code}, message: ${err.message}`); + return; + } + console.info(`Succeeded in creating a download task.`); + }); + ``` + + +## request.agent.remove10+ + +remove(id: string): Promise<void> + +Removes a specified task of the invoker. If the task is being executed, the task is forced to stop. This API uses a promise to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| id | string | Yes| Task ID.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400003 | task service ability error. | +| 21900006 | task not found error. | + +**Example** + + ```js + request.agent.remove("id").then(() => { + console.info(`Succeeded in removing a download task. `); + }).catch((err) => { + console.error(`Failed to remove a download task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + diff --git a/en/application-dev/reference/apis/js-apis-resource-manager.md b/en/application-dev/reference/apis/js-apis-resource-manager.md index a1b98717279f99d9e15c5018fcf41bb28d30c6a5..0b991202add9b4a0480f3990ccc7f1775f95f3ba 100644 --- a/en/application-dev/reference/apis/js-apis-resource-manager.md +++ b/en/application-dev/reference/apis/js-apis-resource-manager.md @@ -151,6 +151,45 @@ Obtains the **ResourceManager** object of an application based on the specified ``` +## resourceManager.getSystemResourceManager10+ + +getSystemResourceManager(): ResourceManager + +Obtains a **ResourceManager** object. + +**System capability**: SystemCapability.Global.ResourceManager + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------------------ | +| Resourcemanager | **ResourceManager** object.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001009 | If application can't access system resource. | + +**Example** + ```js +import resourceManager from '@ohos.resourceManager'; + +try { + let systemResourceManager = resourceManager.getSystemResourceManager(); + systemResourceManager.getStringValue($r('sys.string.ohos_lab_vibrate').id).then(value => { + let str = value; + }).catch(error => { + console.log("systemResourceManager getStringValue promise error is " + error); + }); +} catch (error) { + console.error(`systemResourceManager getStringValue failed, error code: ${error.code}, message: ${error.message}.`) +} + ``` + + ## Direction Enumerates the screen directions. @@ -3249,6 +3288,451 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco } ``` +### getColor10+ + +getColor(resId: number, callback: AsyncCallback<number>): void; + +Obtains the color value corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | --------------- | +| resId | number | Yes | Resource ID. | +| callback | AsyncCallback<number> | Yes | Asynchronous callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001001 | If the module resId invalid. | +| 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | + +**Example (stage)** + ```ts + try { + this.context.resourceManager.getColor($r('app.color.test').id, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let str = value; + } + }); + } catch (error) { + console.error(`callback getColor failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` + +### getColor10+ + +getColor(resId: number): Promise<number> + +Obtains the color value corresponding to the specified resource ID. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| + +**Return value** + +| Type | Description | +| --------------------- | ----------- | +| Promise<number> | Color value corresponding to the resource ID (decimal).| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | + +**Example** + ```ts + try { + this.context.resourceManager.getColor($r('app.color.test').id).then(value => { + let str = value; + }).catch(error => { + console.log("getColor promise error is " + error); + }); + } catch (error) { + console.error(`promise getColor failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` + +### getColor10+ + +getColor(resource: Resource, callback: AsyncCallback<number>): void; + +Obtains the color value corresponding to the specified resource object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | --------------- | +| resource | [Resource](#resource9) | Yes | Resource object. | +| callback | AsyncCallback<number> | Yes | Asynchronous callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | + +**Example** + ```ts + let resource = { + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.color.test').id + }; + try { + this.context.resourceManager.getColor(resource, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let str = value; + } + }); + } catch (error) { + console.error(`callback getColor failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` + +### getColor10+ + +getColor(resource: Resource): Promise<number>; + +Obtains the color value corresponding to the specified resource object. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---- | +| resource | [Resource](#resource9) | Yes | Resource object.| + +**Return value** + +| Type | Description | +| --------------------- | ---------------- | +| Promise<number> | Color value corresponding to the resource object (decimal).| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | + +**Example** + ```ts + let resource = { + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.color.test').id + }; + try { + this.context.resourceManager.getColor(resource).then(value => { + let str = value; + }).catch(error => { + console.log("getColor promise error is " + error); + }); + } catch (error) { + console.error(`callback getColor failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` + +### getColorByName10+ + +getColorByName(resName: string, callback: AsyncCallback<number>): void + +Obtains the color value corresponding to the specified resource name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | --------------- | +| resName | string | Yes | Resource name. | +| callback | AsyncCallback<number> | Yes | Asynchronous callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | +| 9001006 | If the resource re-ref too much. | + +**Example** + ```ts + try { + this.context.resourceManager.getColorByName("test", (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let string = value; + } + }); + } catch (error) { + console.error(`callback getColorByName failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` + +### getColorByName10+ + +getStringByName(resName: string): Promise<number> + +Obtains the color value corresponding to the specified resource name. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---- | +| resName | string | Yes | Resource name.| + +**Return value** + +| Type | Description | +| --------------------- | ---------- | +| Promise<number> | Color value corresponding to the resource name (decimal).| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | +| 9001006 | If the resource re-ref too much. | + +**Example** + ```ts + try { + this.context.resourceManager.getColorByName("test").then(value => { + let string = value; + }).catch(error => { + console.log("getColorByName promise error is " + error); + }); + } catch (error) { + console.error(`promise getColorByName failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` + +### getColorSync10+ + +getColorSync(resId: number) : number; + +Obtains the color value corresponding to the specified resource ID. The API returns the result synchronously. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| + +**Return value** + +| Type | Description | +| ------ | ----------- | +| number | Color value corresponding to the resource ID (decimal).| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | + +**Example** + ```ts + try { + this.context.resourceManager.getColorSync($r('app.color.test').id); + } catch (error) { + console.error(`getColorSync failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` + +### getColorSync10+ + +getColorSync(resource: Resource): number + +Obtains the color value corresponding to the specified resource object. The API returns the result synchronously. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---- | +| resource | [Resource](#resource9) | Yes | Resource object.| + +**Return value** + +| Type | Description | +| ------ | ---------------- | +| number | Color value corresponding to the resource object (decimal).| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | + +**Example** + ```ts + let resource = { + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.color.test').id + }; + try { + this.context.resourceManager.getColorSync(resource); + } catch (error) { + console.error(`getColorSync failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` + +### getColorByNameSync10+ + +getColorByNameSync(resName: string) : number; + +Obtains the color value corresponding to the specified resource name. The API returns the result synchronously. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---- | +| resName | string | Yes | Resource name.| + +**Return value** + +| Type | Description | +| ------ | ---------- | +| number | Color value corresponding to the resource name (decimal).| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | +| 9001006 | If the resource re-ref too much. | + +**Example** + ```ts + try { + this.context.resourceManager.getColorByNameSync("test"); + } catch (error) { + console.error(`getColorByNameSync failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` + +### addResource10+ + +addResource(path: string) : void; + +Loads resources from the specified path. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---- | +| path | string | Yes | Resource path.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001010 | If the overlay path is invalid. | + +**Example** + ```ts + let path = getContext().bundleCodeDir + "/library1-default-signed.hsp"; + try { + this.context.resourceManager.addResource(path); + } catch (error) { + console.error(`addResource failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` + +### removeResource10+ + +removeResource(path: string) : void; + +Removes the resources loaded from the specified path to restore the original resources. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---- | +| path | string | Yes | Resource path.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001010 | If the overlay path is invalid. | + +**Example** + ```ts + let path = getContext().bundleCodeDir + "/library1-default-signed.hsp"; + try { + this.resmgr.removeResource(path); + } catch (error) { + console.error(`removeResource failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` + ### getString(deprecated) getString(resId: number, callback: AsyncCallback<string>): void diff --git a/en/application-dev/reference/apis/js-apis-screen.md b/en/application-dev/reference/apis/js-apis-screen.md index 055787cc06b2653390f1ffe66ac7d1733ec508f4..3d9a678bdc570c864255958b7ec54fb6c54dd8eb 100644 --- a/en/application-dev/reference/apis/js-apis-screen.md +++ b/en/application-dev/reference/apis/js-apis-screen.md @@ -95,10 +95,10 @@ Subscribes to events related to the screen state. **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ---------------------- | ---- | ------------------------------------------------------------ | +| Name | Type | Mandatory| Description | +| --------- | ---------------------- | ---- | ----------------------------------------------------------- | | eventType | string | Yes | Event type.
- **connect**: an event indicating that the screen is connected.
- **disconnect**: an event indicating that the screen is disconnected.
- **change**: an event indicating that the screen state changes.| -| callback | Callback<number> | Yes | Callback used to return the screen ID. | +| callback | Callback<number> | Yes | Callback used to return the screen ID, which is an integer. | **Example** @@ -126,7 +126,7 @@ Unsubscribes from events related to the screen state. | Name | Type | Mandatory| Description | | --------- | ---------------------- | ---- | ------------------------------------------------------------ | | eventType | string | Yes | Event type.
- **connect**: an event indicating that the screen is connected.
- **disconnect**: an event indicating that the screen is disconnected.
- **change**: an event indicating that the screen state changes.| -| callback | Callback<number> | No | Callback used to return the screen ID. | +| callback | Callback<number> | No | Callback used to return the screen ID, which is an integer. | **Example** @@ -151,10 +151,10 @@ Sets the screen to the expanded mode. This API uses an asynchronous callback to **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------ | ---- | -------------------------------- | -| options | Array<[ExpandOption](#expandoption)> | Yes | Parameters for expanding the screen. | -| callback | AsyncCallback<number> | Yes | Callback used to return the group ID of the expanded screens.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------ | ---- |----------------------------| +| options | Array<[ExpandOption](#expandoption)> | Yes | Parameters for expanding the screen. | +| callback | AsyncCallback<number> | Yes | Callback used to return the group ID of the expanded screens, which is an integer.| **Error codes** @@ -198,9 +198,9 @@ Sets the screen to the expanded mode. This API uses a promise to return the resu **Return value** -| Type | Description | -| --------------------- | ----------------------------------- | -| Promise<number> | Promise used to return the group ID of the expanded screens.| +| Type | Description | +| --------------------- |---------------------------------| +| Promise<number> | Promise used to return the group ID of the expanded screens, which is an integer.| **Error codes** @@ -234,9 +234,9 @@ Stops the expanded mode. This API uses an asynchronous callback to return the re **Parameters** -| Name| Type| Mandatory| Description| -| ------------ | --------------------------- | --- | -------------------------------------------------------------- | -| expandScreen | Array<number> | Yes | IDs of the expanded screens. | +| Name| Type| Mandatory| Description | +| ------------ | --------------------------- | --- |-----------------------------------------| +| expandScreen | Array<number> | Yes | IDs of the expanded screens. Each ID must be an integer. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the expanded mode is stopped, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** @@ -274,9 +274,9 @@ Stops the expanded mode. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| ------------ | ------------------- | --- | --------------- | -| expandScreen | Array<number> | Yes | IDs of the expanded screens.| +| Name| Type| Mandatory| Description | +| ------------ | ------------------- | --- |--------------------| +| expandScreen | Array<number> | Yes | IDs of the expanded screens. Each ID must be an integer.| **Return value** @@ -317,11 +317,11 @@ Sets screen mirroring. This API uses an asynchronous callback to return the resu **Parameters** -| Name | Type | Mandatory| Description | -| ------------ | --------------------------- | ---- |-----------------| -| mainScreen | number | Yes | ID of the primary screen. | -| mirrorScreen | Array<number> | Yes | IDs of secondary screens. | -| callback | AsyncCallback<number> | Yes | Callback used to return the group ID of the secondary screens.| +| Name | Type | Mandatory| Description | +| ------------ | --------------------------- | ---- |--------------------| +| mainScreen | number | Yes | ID of the primary screen. The value must be an integer. | +| mirrorScreen | Array<number> | Yes | IDs of secondary screens. Each ID must be an integer.| +| callback | AsyncCallback<number> | Yes | Callback used to return the group ID of the secondary screens, which is an integer. | **Error codes** @@ -359,16 +359,16 @@ Sets screen mirroring. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| ------------ | ------------------- | ---- |-----------| -| mainScreen | number | Yes | ID of the primary screen. | -| mirrorScreen | Array<number> | Yes | IDs of secondary screens.| +| Name | Type | Mandatory| Description | +| ------------ | ------------------- | ---- |--------------------| +| mainScreen | number | Yes | ID of the primary screen. The value must be an integer. | +| mirrorScreen | Array<number> | Yes | IDs of secondary screens. Each ID must be an integer.| **Return value** -| Type | Description | -| --------------------- | ----------------------------------- | -| Promise<number> | Promise used to return the group ID of the secondary screens.| +| Type | Description | +| --------------------- |---------------------------------| +| Promise<number> | Promise used to return the group ID of the secondary screens, which is an integer.| **Error codes** @@ -404,10 +404,10 @@ Stops screen mirroring. This API uses an asynchronous callback to return the res **Parameters** -| Name| Type| Mandatory| Description| -| ------------ | --------------------------- | --- | -------------------------------------------------------------- | -| mirrorScreen | Array<number> | Yes | IDs of secondary screens. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. If screen mirroring is stopped, **err** is **undefined**; otherwise, **err** is an error object. | +| Name| Type| Mandatory| Description | +| ------------ | --------------------------- | --- |-----------------------------------------| +| mirrorScreen | Array<number> | Yes | IDs of secondary screens. Each ID must be an integer. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If screen mirroring is stopped, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** @@ -444,9 +444,9 @@ Stops screen mirroring. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| ------------ | ------------------- | --- | --------------- | -| mirrorScreen | Array<number> | Yes | IDs of secondary screens.| +| Name| Type| Mandatory| Description | +| ------------ | ------------------- | --- |--------------------| +| mirrorScreen | Array<number> | Yes | IDs of secondary screens. Each ID must be an integer.| **Return value** @@ -590,7 +590,7 @@ Destroys a virtual screen. This API uses an asynchronous callback to return the | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| screenId | number | Yes | Screen ID. | +| screenId | number | Yes | Screen ID. The value must be an integer. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the virtual screen is destroyed, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** @@ -630,7 +630,7 @@ Destroys a virtual screen. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ---------- | -| screenId | number | Yes | Screen ID.| +| screenId | number | Yes | Screen ID. The value must be an integer.| **Return value** @@ -675,7 +675,7 @@ Sets the surface for a virtual screen. This API uses an asynchronous callback to | Name | Type | Mandatory| Description | | --------- | ------------------------- | ---- | ------------------------------------------------------------ | -| screenId | number | Yes | Screen ID. | +| screenId | number | Yes | Screen ID. The value must be an integer. | | surfaceId | string | Yes | Surface ID. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the virtual screen surface is successfully set, **err** is **undefined**; otherwise, **err** is an error object.| @@ -719,7 +719,7 @@ Sets the surface for a virtual screen. This API uses a promise to return the res | Name | Type | Mandatory| Description | | --------- | ------ | ---- | ------------- | -| screenId | number | Yes | Screen ID. | +| screenId | number | Yes | Screen ID. The value must be an integer. | | surfaceId | string | Yes | Surface ID.| **Return value** @@ -877,9 +877,9 @@ Defines the parameters for expanding a screen. | Name | Type| Readable| Writable| Description | | -------- | -------- | ---- | ---- | ------------------- | -| screenId | number | Yes | Yes | Screen ID. | -| startX | number | Yes | Yes | Start X coordinate of the screen.| -| startY | number | Yes | Yes | Start Y coordinate of the screen.| +| screenId | number | Yes | Yes | Screen ID. The value must be an integer. | +| startX | number | Yes | Yes | Start X coordinate of the screen. The value must be an integer.| +| startY | number | Yes | Yes | Start Y coordinate of the screen. The value must be an integer.| ## VirtualScreenOption @@ -887,13 +887,13 @@ Defines virtual screen parameters. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | Type| Readable| Writable| Description | -| --------- | -------- | ---- | ---- | ------------------------- | -| name | string | Yes | Yes | Name of a virtual screen. | -| width | number | Yes | Yes | Width of the virtual screen, in pixels.| -| height | number | Yes | Yes | Height of the virtual screen, in pixels.| -| density | number | Yes | Yes | Density of the virtual screen. | -| surfaceId | string | Yes | Yes | Surface ID of the virtual screen.| +| Name | Type| Readable| Writable| Description | +| --------- | -------- | ---- | ---- |--------------------------| +| name | string | Yes | Yes | Name of a virtual screen. | +| width | number | Yes | Yes | Width of the virtual screen, in pixels. The value must be an integer.| +| height | number | Yes | Yes | Height of the virtual screen, in pixels. The value must be an integer.| +| density | number | Yes | Yes | Density of the virtual screen. The value must be a floating point number. | +| surfaceId | string | Yes | Yes | Surface ID of the virtual screen. | ## Screen @@ -905,14 +905,14 @@ Before calling any API in **Screen**, you must use **[getAllScreens()](#screenge **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | Type | Readable| Writable| Description | -| ----------------- | ---------------------------------------------- | ---- | ---- | ---------------------- | -| id | number | Yes | No | Screen ID. | -| parent | number | Yes | No | ID of the group to which a screen belongs. | -| supportedModeInfo | Array<[ScreenModeInfo](#screenmodeinfo)> | Yes | No | Mode set supported by the screen. | -| activeModeIndex | number | Yes | No | Index of the active screen mode. The current value and value range of this parameter vary according to the screen resolution, refresh rate, and device hardware.| -| orientation | [Orientation](#orientation) | Yes | No | Screen orientation. | -| sourceMode10+ | [ScreenSourceMode](#screensourcemode10) | Yes | No | Source mode of the screen. | +| Name | Type | Readable| Writable| Description | +| ----------------- | ---------------------------------------------- | ---- | ---- |-------------------------------------------------------------| +| id | number | Yes | No | Screen ID. The value must be an integer. | +| parent | number | Yes | No | ID of the group to which a screen belongs. The value must be an integer. | +| supportedModeInfo | Array<[ScreenModeInfo](#screenmodeinfo)> | Yes | No | Mode set supported by the screen. | +| activeModeIndex | number | Yes | No | Index of the active screen mode. The current value and value range of this parameter vary according to the screen resolution, refresh rate, and device hardware. The value must be an integer.| +| orientation | [Orientation](#orientation) | Yes | No | Screen orientation. | +| sourceMode10+ | [ScreenSourceMode](#screensourcemode10) | Yes | No | Source mode of the screen. | ### setOrientation @@ -1002,7 +1002,7 @@ Sets the active mode of the screen. This API uses an asynchronous callback to re | Name | Type | Mandatory| Description | | --------- | ------------------------- | ---- | ------------------------------------------------------------ | -| modeIndex | number | Yes | Index of the mode to set. The current value and value range of this parameter vary according to the screen resolution, refresh rate, and device hardware.| +| modeIndex | number | Yes | Index of the mode to set. The current value and value range of this parameter vary according to the screen resolution, refresh rate, and device hardware. The value must be an integer.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the active mode is successfully set, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** @@ -1040,7 +1040,7 @@ Sets the active mode of the screen. This API uses a promise to return the result | Name | Type | Mandatory| Description | | --------- | ------ | ---- | ---------- | -| modeIndex | number | Yes | Index of the mode to set. The current value and value range of this parameter vary according to the screen resolution, refresh rate, and device hardware.| +| modeIndex | number | Yes | Index of the mode to set. The current value and value range of this parameter vary according to the screen resolution, refresh rate, and device hardware. The value must be an integer.| **Return value** @@ -1080,9 +1080,9 @@ Sets the pixel density of the screen. This API uses an asynchronous callback to **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | Type | Mandatory| Description | -| ---------- | ------------------------- | ---- | ------------------------------------------------------------ | -| densityDpi | number | Yes | Pixel density. The value ranges from 80 to 640. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------- | ---- |------------------------------------------| +| densityDpi | number | Yes | Pixel density. The value must be an integer in the range [80, 640]. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the pixel density is successfully set, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** @@ -1118,9 +1118,9 @@ Sets the pixel density of the screen. This API uses a promise to return the resu **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | ---------------------------------- | -| densityDpi | number | Yes | Pixel density. The value ranges from 80 to 640.| +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- |------------------------------------| +| densityDpi | number | Yes | Pixel density. The value must be an integer in the range [80, 640].| **Return value** @@ -1187,7 +1187,7 @@ Defines the screen mode information. | Name | Type| Readable| Writable| Description | | ----------- | -------- | ---- | ---- | -------------------------------------------------- | -| id | number | Yes | Yes | Mode ID. The supported mode is determined by the device resolution and refresh rate.| -| width | number | Yes | Yes | Width of the screen, in pixels. | -| height | number | Yes | Yes | Height of the screen, in pixels. | -| refreshRate | number | Yes | Yes | Screen refresh rate. | +| id | number | Yes | Yes | Mode ID. The supported mode is determined by the device resolution and refresh rate. The value must be an integer.| +| width | number | Yes | Yes | Width of the screen, in pixels. The value must be an integer. | +| height | number | Yes | Yes | Height of the screen, in pixels. The value must be an integer. | +| refreshRate | number | Yes | Yes | Refresh rate of the screen. The value must be an integer. | diff --git a/en/application-dev/reference/apis/js-apis-screenshot.md b/en/application-dev/reference/apis/js-apis-screenshot.md index 8b760e7cb48b3031e728ec80cc2c178501abb677..7cb437acb05f67079800a4d181d4c5d4320fa98e 100644 --- a/en/application-dev/reference/apis/js-apis-screenshot.md +++ b/en/application-dev/reference/apis/js-apis-screenshot.md @@ -25,8 +25,8 @@ Describes screenshot options. | ---------------------- | ------------- | ---- | ------------------------------------------------------------ | | screenRect | [Rect](#rect) | No | Region of the screen to capture. If this parameter is null, the full screen will be captured. | | imageSize | [Size](#size) | No | Size of the screen region to capture. If this parameter is null, the full screen will be captured. | -| rotation | number | No | Rotation angle of the screenshot. Currently, the value can be **0** only. The default value is **0**. | -| displayId8+ | number | No | ID of the [display](js-apis-display.md#display) device on which the screen region is to be captured.| +| rotation | number | No | Rotation angle of the screenshot. Currently, the value can be **0** only. The default value is **0**. The value must be an integer. | +| displayId8+ | number | No | ID of the [display](js-apis-display.md#display) device on which the screen region is to be captured. The value must be an integer.| ## Rect @@ -37,10 +37,10 @@ Describes the region of the screen to capture. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| left | number | Yes | Left boundary of the screen region to capture, in pixels.| -| top | number | Yes | Top boundary of the screen region to capture, in pixels.| -| width | number | Yes | Width of the screen region to capture, in pixels.| -| height | number | Yes | Height of the screen region to capture, in pixels.| +| left | number | Yes | Left boundary of the screen region to capture, in pixels. The value must be an integer.| +| top | number | Yes | Top boundary of the screen region to capture, in pixels. The value must be an integer.| +| width | number | Yes | Width of the screen region to capture, in pixels. The value must be an integer.| +| height | number | Yes | Height of the screen region to capture, in pixels. The value must be an integer.| ## Size @@ -51,8 +51,8 @@ Describes the size of the screen region to capture. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| width | number | Yes | Width of the screen region to capture, in pixels.| -| height | number | Yes | Height of the screen region to capture, in pixels.| +| width | number | Yes | Width of the screen region to capture, in pixels. The value must be an integer.| +| height | number | Yes | Height of the screen region to capture, in pixels. The value must be an integer.| ## screenshot.save diff --git a/en/application-dev/reference/apis/js-apis-secureElement.md b/en/application-dev/reference/apis/js-apis-secureElement.md index 429058cec789dcb61dcec498183c4ec92161c9be..4314ea817608a8e26cdb5d0fa45aa01b64297227 100644 --- a/en/application-dev/reference/apis/js-apis-secureElement.md +++ b/en/application-dev/reference/apis/js-apis-secureElement.md @@ -43,10 +43,10 @@ The returned **SEService** object is available only when **true** is returned by **Parameters** -| **Name**| **Type** | **Description** | -| ---------- | ---------------------------------------------------- | -------------------- | -| type | string | 'serviceState' | -| callback | Callback<[ServiceState](#secureelementservicestate)> | Callback invoked to return the SE service status.| +| **Name**| **Type** | **Mandatory**| **Description** | +| ---------- | ---------------------------------------------------- | ------ | -------------------- | +| type | string | Yes | 'serviceState' | +| callback | Callback<[ServiceState](#secureelementservicestate)> | Yes | Callback invoked to return the SE service status.| **Return value** @@ -59,20 +59,18 @@ The returned **SEService** object is available only when **true** is returned by ```js import secureElement from '@ohos.secureElement'; -@State result: string = ''; -@State nfcSEService: secureElement.SEService = null; +let nfcSEService = null; -this.result = "Service state is Unkown"; try { - this.nfcSEService = secureElement.newSEService("serviceState", (state) => { + nfcSEService = secureElement.newSEService("serviceState", (state) => { if (state == secureElement.ServiceState.DISCONNECTED) { - this.result = "Service state is Disconnected"; + console.log("Service state is Disconnected"); } else { - this.result = "Service state is Connected"; + console.log.("Service state is Connected"); } }); } catch (e) { - this.result = "newSEService occurs exception:" + e.message; + console.log("newSEService occurs exception:" + e.message); } ``` @@ -95,35 +93,34 @@ Obtains the available SE readers. The returned array cannot contain duplicate ob ```js import secureElement from '@ohos.secureElement'; -@State result: string = ''; -@State nfcSEService: secureElement.SEService = null; -@State nfcServiceState: secureElement.ServiceState = null; -@State nfcOmaReader: secureElement.Reader = null; -@State nfcOmaReaderList: secureElement.Reader[] = null; +let nfcSEService = null; +let nfcServiceState = null; +let nfcOmaReader = null; +let nfcOmaReaderList = null; // get SEService try { - this.nfcSEService = secureElement.newSEService("serviceState", (state) => { + nfcSEService = secureElement.newSEService("serviceState", (state) => { if (state == secureElement.ServiceState.DISCONNECTED) { - this.result = "Service state is Disconnected"; + console.log("Service state is Disconnected"); } else { - this.result = "Service state is Connected"; + console.log("Service state is Connected"); } }); } catch (e) { - this.result = "newSEService excpetion:" + e.message; + console.log("newSEService excpetion:" + e.message); } try { - this.nfcOmaReaderList = this.nfcSEService.getReaders(); - if (this.nfcOmaReaderList != null && this.nfcOmaReaderList.length > 0) { - this.nfcOmaReader = this.nfcOmaReaderList[0]; - this.result = "get reader successfully"; + nfcOmaReaderList = nfcSEService.getReaders(); + if (nfcOmaReaderList != null && nfcOmaReaderList.length > 0) { + nfcOmaReader = this.nfcOmaReaderList[0]; + console.log("get reader successfully"); } else { - this.result = "get reader failed"; + console.log("get reader failed"); } } catch (e) { - this.result = "getReaders exception:" + e.message; + console.log("getReaders exception:" + e.message); } ``` @@ -146,20 +143,19 @@ Checks whether this SE service is connected. ```JS import secureElement from '@ohos.secureElement'; -@State result: string = '' -@State nfcSEService: secureElement.SEService = null; +let nfcSEService = null; try { let ret: boolean; // refer to newSEService for this.nfcSEService - ret = this.nfcSEService.isConnected(); + ret = nfcSEService.isConnected(); if (ret) { - this.result = 'get state: connected'; + console.log("get state: connected"); } else { - this.result = 'get state: not connected'; + console.log("get state: not connected"); } } catch (e) { - this.result = "isConnected exception: " + e.message; + console.log("isConnected exception: " + e.message); } ``` @@ -176,15 +172,15 @@ Releases all SE resources allocated to this service. After that, [isConnected](# ```js import secureElement from '@ohos.secureElement'; -@State result: string = ''; -@State nfcSEService: secureElement.SEService = null; + +let nfcSEService = null; try { // refer to newSEService for this.nfcSEService - this.nfcSEService.shutdown(); - this.result = "shutdown successfully"; + nfcSEService.shutdown(); + console.log("shutdown successfully"); } catch (e) { - this.result = "shutdown exception:" + e.message; + console.log("shutdown exception:" + e.message); } ``` @@ -207,15 +203,14 @@ Obtains the version of the Open Mobile API Specification used for the implementa ```JS import secureElement from '@ohos.secureElement'; -@State result: string = ''; -@State nfcSEService: secureElement.SEService = null; +let nfcSEService = null; this.result = "version: " try { // refer to newSEService for this.nfcSEService - this.result += this.nfcSEService.getVersion(); + console.log("version: " + nfcSEService.getVersion()); } catch (e) { - this.result = "getVersion exception:" + e.message; + console.log("getVersion exception:" + e.message); } ``` @@ -238,14 +233,13 @@ Obtains the reader name. If the card reader is a SIM reader, its name must be in ```js import secureElement from '@ohos.secureElement'; -@State result: string = ''; -@State nfcOmaReader: secureElement.Reader = null; +let nfcOmaReader = null; try { // refer to SEService.getReaders for this.nfcOmaReader - this.result = this.nfcOmaReader.getName(); + console.log(nfcOmaReader.getName()); } catch (e) { - this.result = "getName exception:" + e.message; + console.log("getName exception:" + e.message); } ``` @@ -276,18 +270,17 @@ For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.m ```js import secureElement from '@ohos.secureElement'; -@State result: string = ''; -@State nfcOmaReader: secureElement.Reader = null; +let nfcOmaReader = null; try { // refer to SEService.getReaders for this.nfcOmaReader - if (this.nfcOmaReader.isSecureElementPresent()) { - this.result = "isSecureElementPresent TRUE"; + if (nfcOmaReader.isSecureElementPresent()) { + console.log("isSecureElementPresent TRUE"); } else { - this.result = "isSecureElementPresent FALSE"; + console.log("isSecureElementPresent FALSE"); } } catch (e) { - this.result = "isSecureElementPresent exception:" + e.message; + console.log("isSecureElementPresent exception:" + e.message); } ``` @@ -319,20 +312,19 @@ For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.m ```js import secureElement from '@ohos.secureElement'; -@State result: string = ''; -@State nfcOmaReader: secureElement.Reader = null; -@State nfcOmaSession: secureElement.Session = null; +let nfcOmaReader = null; +let nfcOmaSession = null; try { // refer to SEService.getReaders for this.nfcOmaReader - this.nfcOmaSession = this.nfcOmaReader.openSession(); - if (this.nfcOmaSession) { - this.result = "get session successfully"; + nfcOmaSession = nfcOmaReader.openSession(); + if (nfcOmaSession) { + console.log("get session successfully"); } else { - this.result = "get session failed"; + console.log("get session failed"); } } catch (e) { - this.result = "OpenSession exception: " + e.message; + console.log("OpenSession exception: " + e.message); } ``` @@ -357,15 +349,14 @@ For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.m ```js import secureElement from '@ohos.secureElement'; -@State result: string = ''; -@State nfcOmaReader: secureElement.Reader = null; +nfcOmaReader = null; try { // refer to SEService.getReaders for this.nfcOmaReader - this.nfcOmaReader.closeSessions(); - this.result = "close Sessions successfully"; + nfcOmaReader.closeSessions(); + console.log("close Sessions successfully"); } catch (e) { - this.result = "closeSessions exception:" + e.message; + console.log("closeSessions exception:" + e.message); } ``` @@ -388,20 +379,19 @@ Obtains the reader that provides this session. ```js import secureElement from '@ohos.secureElement'; -@State result: string = ''; -@State nfcOmaReader: secureElement.Reader = null; -@State nfcOmaSession: secureElement.Session = null; +let nfcOmaReader = null; +let nfcOmaSession = null; try { - // refer to Reader.openSession for this.nfcOmaSession - this.nfcOmaReader = this.nfcOmaSession.getReader(); - if (this.nfcOmaReader) { - this.result = "get reader successfully"; + // See Reader.openSession for this.nfcOmaSession. + nfcOmaReader = nfcOmaSession.getReader(); + if (nfcOmaReader) { + console.log("get reader successfully"); } else { - this.result = "get reader failed"; + console.log("get reader failed"); } } catch (e) { - this.result = "getReader exception:" + e.message; + console.log("getReader exception:" + e.message); } ``` @@ -432,24 +422,25 @@ For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.m ```js import secureElement from '@ohos.secureElement'; -@State result: string = ''; -@State nfcOmaSession: secureElement.Session = null; +let nfcOmaSession = null; +let str = ""; try { - // refer to Reader.openSession for this.nfcOmaSession - let ret = this.nfcOmaSession.getATR(); + // See Reader.openSession for this.nfcOmaSession. + let ret = nfcOmaSession.getATR(); if (ret) { - this.result = "getATR result:["; + str = 'getATR result:['; for (let i = 0; i < ret.length; ++i) { - this.result += ret[i]; - this.result += ' '; + str += ret[i]; + str += ' '; } - this.result += ']'; + str += ']'; + console.log(str); } else { - this.result = "getATR result is null"; + console.log("getATR result is null"); } } catch (e) { - this.result = "getATR exception:" + e.message; + console.log("getATR exception:" + e.message); } ``` @@ -474,15 +465,14 @@ For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.m ```js import secureElement from '@ohos.secureElement'; -@State result: string = ''; -@State nfcOmaSession: secureElement.Session = null; +let nfcOmaSession = null; try { - // refer to Reader.openSession for this.nfcOmaSession - this.nfcOmaSession.close(); - this.result = "session close successfully"; + // See Reader.openSession for this.nfcOmaSession. + nfcOmaSession.close(); + console.log("session close successfully"); } catch (e) { - this.result = "session close exception:" + e.message; + console.log("session close exception:" + e.message); } ``` @@ -509,19 +499,18 @@ For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.m ```Js import secureElement from '@ohos.secureElement'; -@State result: string = ''; -@State nfcOmaSession: secureElement.Session = null; +let nfcOmaSession = null; try { - // refer to Reader.openSession for this.nfcOmaSession - let ret = this.nfcOmaSession.isClosed(); + // See Reader.openSession for this.nfcOmaSession. + let ret = nfcOmaSession.isClosed(); if (ret) { - this.result = "session state is closed"; + console.log("session state is closed"); } else { - this.result = "session state is not closed"; + console.log("session state is not closed"); } } catch (e) { - this.result = "isClosed exception:" + e.message; + console.log("isClosed exception:" + e.message); } ``` @@ -546,21 +535,20 @@ For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.m ```js import secureElement from '@ohos.secureElement'; -@State result: string = ''; -@State nfcOmaSession: secureElement.Session = null; +let nfcOmaSession = null; try { - // refer to Reader.openSession for this.nfcOmaSession - this.nfcOmaSession.closeChannels(); - this.result = "close Channels successfully"; + // See Reader.openSession for this.nfcOmaSession. + nfcOmaSession.closeChannels(); + console.log("close Channels successfully"); } catch (e) { - this.result = "closeChannels exception:" + e.message; + console.log("closeChannels exception:" + e.message); } ``` ## Session.openBasicChannel -openBasicChannel(aid: number[]): Promise +openBasicChannel(aid: number[]): Promise\ Opens a basic channel. This API uses a promise to return the result. @@ -568,15 +556,15 @@ Opens a basic channel. This API uses a promise to return the result. **Parameters** -| **Name**| **Type**| **Description** | -| ---------- | -------- | ------------------------------------------------------------ | -| aid | number[] | AIDs of the applets selected on this channel or null if no applet is selected. | +| **Name**| **Type**| **Mandatory**| **Description** | +| ---------- | -------- | ------ | ------------------------------------------------------------ | +| aid | number[] | Yes |AIDs of the applets selected on this channel or null if no applet is selected.| **Return value** | **Type**| **Description** | | -------- | --------------------- | -| Channel | Returns the **Channel** instance opened. If the SE cannot provide a new basic channel or cannot obtain the access control rule due to lack of available basic channels, null will be returned. | +| Channel | Returns the **Channel** instance opened. If the SE cannot provide a new basic channel or cannot obtain the access control rule due to lack of available basic channels, null will be returned.| **Error codes** @@ -594,27 +582,26 @@ For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.m ```js import secureElement from '@ohos.secureElement'; -@State result: string = ''; -@State nfcOmaSession: secureElement.Session = null; -@State nfcOmaChannel: secureElement.Channel = null; +let nfcOmaSession = null; +let nfcOmaChannel = null; try { // See Reader.openSession for this.nfcOmaSession. - let getPromise = this.nfcOmaSession.openBasicChannel(this.aidArray); + let getPromise = nfcOmaSession.openBasicChannel(this.aidArray); getPromise.then((channel) => { - this.nfcOmaChannel = channel; - this.result = "openBasicChannel1 get channel successfully"; + nfcOmaChannel = channel; + console.log("openBasicChannel1 get channel successfully"); }).catch ((err) => { - this.result = "openBasicChannel1 exception:" + err.message; + console.log("openBasicChannel1 exception:" + err.message); }); } catch (e) { - this.result = "OpenBasicChannel1 exception:" + e.message; + console.log("OpenBasicChannel1 exception:" + e.message); } ``` ## Session.openBasicChannel - openBasicChannel(aid: number[], callback: AsyncCallback): void + openBasicChannel(aid: number[], callback: AsyncCallback\): void Opens a basic channel. This API uses an asynchronous callback to return the result. @@ -622,10 +609,10 @@ Opens a basic channel. This API uses an asynchronous callback to return the resu **Parameters** -| **Name**| **Type** | **Description** | -| ---------- | ---------------------- | ------------------------------------------------------------ | -| aid | number[] | AIDs of the applets selected on this channel or null if no applet is selected. | -| callback | AsyncCallback | Callback invoked to return the **Channel** instance opened. If the SE cannot provide a new basic channel or cannot obtain the access control rule due to lack of available basic channels, null will be returned. | +| **Name**| **Type** | **Mandatory**| **Description** | +| ---------- | ---------------------- | ------ | ------------------------------------------------------------ | +| aid | number[] | Yes | AIDs of the applets selected on this channel or null if no applet is selected.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the **Channel** instance opened. If the SE cannot provide a new basic channel or cannot obtain the access control rule due to lack of available basic channels, null will be returned. | **Error codes** @@ -643,29 +630,28 @@ For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.m ```js import secureElement from '@ohos.secureElement'; -@State result: string = ''; -@State nfcOmaSession: secureElement.Session = null; -@State nfcOmaChannel: secureElement.Channel = null; -aidArray: number[] = [720, 1080]; +let nfcOmaSession = null; +let nfcOmaChannel = null; +let aidArray = [720, 1080]; try { // See Reader.openSession for this.nfcOmaSession. - this.nfcOmaSession.openBasicChannel(this.aidArray, (error, data) => { + nfcOmaSession.openBasicChannel(aidArray, (error, data) => { if (error) { - this.result = "openBasicChannel2 failed:" + JSON.stringify(error); + console.log("openBasicChannel2 failed:" + JSON.stringify(error)); return; } - this.nfcOmaChannel = data; - this.result = "openBasicChannel2 get channel successfully"; + nfcOmaChannel = data; + console.log("openBasicChannel2 get channel successfully"); }); } catch (e) { - this.result = "openBasicChannel2 exception:" + e.message; + console.log("openBasicChannel2 exception:" + e.message); } ``` ## Session.openBasicChannel -openBasicChannel(aid: number[], p2: number): Promise +openBasicChannel(aid: number[], p2: number): Promise\ Opens a basic channel. This API uses a promise to return the result. @@ -673,16 +659,16 @@ Opens a basic channel. This API uses a promise to return the result. **Parameters** -| **Name**| **Type**| **Description** | -| ---------- | -------- | ------------------------------------------------------------ | -| aid | number[] | AIDs of the applets selected on this channel or null if no applet is selected. | -| p2 | number | P2 parameter of the **SELECT APDU** command executed on the channel. | +| **Name**| **Type**| **Mandatory**| **Description** | +| ---------- | -------- | ------ | ------------------------------------------------------------ | +| aid | number[] | Yes | AIDs of the applets selected on this channel or null if no applet is selected.| +| p2 | number | Yes |P2 parameter of the **SELECT APDU** command executed on the channel. | **Return value** | **Type**| **Description** | | -------- | --------------------- | -| Channel | Returns the **Channel** instance opened. If the SE cannot provide a new basic channel or cannot obtain the access control rule due to lack of available basic channels, null will be returned. | +| Channel | Returns the **Channel** instance opened. If the SE cannot provide a new basic channel or cannot obtain the access control rule due to lack of available basic channels, null will be returned.| **Error codes** @@ -700,29 +686,28 @@ For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.m ```js import secureElement from '@ohos.secureElement'; -@State result: string = ''; -@State nfcOmaSession: secureElement.Session = null; -@State nfcOmaChannel: secureElement.Channel = null; -aidArray: number[] = [720, 1080]; -p2: number = 0x00; +let nfcOmaSession = null; +let nfcOmaChannel = null; +let aidArray = [720, 1080]; +let p2 = 0x00; try { // See Reader.openSession for this.nfcOmaSession. - let getPromise = this.nfcOmaSession.openBasicChannel(this.aidArray, this.p2); + let getPromise = nfcOmaSession.openBasicChannel(aidArray, p2); getPromise.then((channel) => { - this.nfcOmaChannel = channel; - this.result = "openBasicChannel3 get channel successfully"; + nfcOmaChannel = channel; + console.log("openBasicChannel3 get channel successfully"); }).catch ((err) => { - this.result = "openBasicChannel3 exception"; + console.log("openBasicChannel3 exception"); }); } catch (e) { - this.result = "openBasicChannel3 exception:" + e.message; + console.log("openBasicChannel3 exception:" + e.message); } ``` ## Session.openBasicChannel -openBasicChannel(aid: number[], p2:number, callback: AsyncCallback): void +openBasicChannel(aid: number[], p2:number, callback: AsyncCallback\): void Opens a basic channel. This API uses an asynchronous callback to return the result. @@ -730,11 +715,11 @@ Opens a basic channel. This API uses an asynchronous callback to return the resu **Parameters** -| **Name**| **Type** | **Description** | -| ---------- | ---------------------- | ------------------------------------------------------------ | -| aid | number[] | AIDs of the applets selected on this channel or null if no applet is selected. | -| p2 | number | P2 parameter of the **SELECT APDU** command executed on the channel. | -| callback | AsyncCallback | Callback invoked to return the **Channel** instance opened. If the SE cannot provide a new basic channel or cannot obtain the access control rule due to lack of available basic channels, null will be returned. | +| **Name**| **Type** | **Mandatory**| **Description** | +| ---------- | ---------------------- | ------ | ------------------------------------------------------------ | +| aid | number[] | Yes | AIDs of the applets selected on this channel or null if no applet is selected.| +| p2 | number | Yes | P2 parameter of the **SELECT APDU** command executed on the channel. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the **Channel** instance opened. If the SE cannot provide a new basic channel or cannot obtain the access control rule due to lack of available basic channels, null will be returned. | **Error codes** @@ -752,30 +737,30 @@ For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.m ```js import secureElement from '@ohos.secureElement'; -@State result: string = ''; -@State nfcOmaSession: secureElement.Session = null; -@State nfcOmaChannel: secureElement.Channel = null; -aidArray: number[] = [720, 1080]; -p2: number = 0x00; + +let nfcOmaSession = null; +let nfcOmaChannel = null; +let aidArray = [720, 1080]; +let p2 = 0x00; try { // See Reader.openSession for this.nfcOmaSession. - this.nfcOmaSession.openBasicChannel(this.aidArray, this.p2, (error, data) => { + nfcOmaSession.openBasicChannel(aidArray, p2, (error, data) => { if (error) { - this.result = "openBasicChannel4 failed:" + JSON.stringify(error); + console.log("openBasicChannel4 failed:" + JSON.stringify(error)); return; } - this.nfcOmaChannel = data; - this.result = "openBasicChannel4 get channel successfully"; + nfcOmaChannel = data; + console.log("openBasicChannel4 get channel successfully"); }); } catch (e) { - this.result = "openBasicChannel4 exception:" + e.message; + console.log("openBasicChannel4 exception:" + e.message); } ``` ## Session.openLogicalChannel -openLogicalChannel(aid: number[]): Promise +openLogicalChannel(aid: number[]): Promise\ Opens a logical channel. This API uses a promise to return the result. @@ -783,9 +768,9 @@ Opens a logical channel. This API uses a promise to return the result. **Parameters** -| **Name**| **Type**| **Description** | -| ---------- | -------- | --------------------------------------- | -| aid | number[] | AIDs of the applets selected on the **Channel** instance. | +| **Name**| **Type**| **Mandatory**| **Description** | +| ---------- | -------- | ------ | --------------------------------------- | +| aid | number[] | Yes | AIDs of the applets selected on the **Channel** instance.| **Return value** @@ -809,28 +794,27 @@ For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.m ```js import secureElement from '@ohos.secureElement'; -@State result: string = ''; -@State nfcOmaSession: secureElement.Session = null; -@State nfcOmaChannel: secureElement.Channel = null; -aidArray: number[] = [720, 1080]; +let nfcOmaSession = null; +let nfcOmaChannel = null; +let aidArray = [720, 1080]; try { // See Reader.openSession for this.nfcOmaSession. - let getPromise = this.nfcOmaSession.openLogicalChannel(this.aidArray) + let getPromise = nfcOmaSession.openLogicalChannel(aidArray) getPromise.then((channel) => { - this.nfcOmaChannel = channel; - this.result = "openLogicChannel1 get channel successfully"; + nfcOmaChannel = channel; + console.log("openLogicChannel1 get channel successfully"); }).catch ((err) => { - this.result = "openLogicChannel1 exception:" + err.message; + console.log("openLogicChannel1 exception:" + err.message); }); } catch (e) { - this.result = "openLogicChannel1 exception:" + e.message; + console.log("openLogicChannel1 exception:" + e.message); } ``` ## Session.openLogicalChannel - openLogicalChannel(aid:number[], callback: AsyncCallback): void + openLogicalChannel(aid:number[], callback: AsyncCallback\): void Opens a logical channel. This API uses an asynchronous callback to return the result. @@ -838,10 +822,10 @@ Opens a logical channel. This API uses an asynchronous callback to return the re **Parameters** -| **Name**| **Type** | **Description** | -| ---------- | ---------------------- | ------------------------------------------------------------ | -| aid | number[] | AIDs of the applets selected on the **Channel** instance. | -| callback | AsyncCallback | Callback invoked to return the **Channel** instance opened. If the SE cannot provide a new **Channel** instance or cannot obtain access control rules due to lack of available logical **Channel** instances, null will be returned.| +| **Name**| **Type** | **Mandatory**| **Description** | +| ---------- | ---------------------- | ------ | ------------------------------------------------------------ | +| aid | number[] | Yes | AIDs of the applets selected on the **Channel** instance. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the **Channel** instance opened. If the SE cannot provide a new **Channel** instance or cannot obtain access control rules due to lack of available logical **Channel** instances, null will be returned.| **Error codes** @@ -859,29 +843,28 @@ For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.m ```js import secureElement from '@ohos.secureElement'; -@State result: string = ''; -@State nfcOmaSession: secureElement.Session = null; -@State nfcOmaChannel: secureElement.Channel = null; -aidArray: number[] = [720, 1080]; +let nfcOmaSession = null; +let nfcOmaChannel = null; +let aidArray = [720, 1080]; try { // See Reader.openSession for this.nfcOmaSession. - this.nfcOmaSession.openLogicalChannel(this.aidArray, (error, data) => { + nfcOmaSession.openLogicalChannel(aidArray, (error, data) => { if (error) { - this.result = "openLogicChannel2 failed:" + JSON.stringify(error); + console.log("openLogicChannel2 failed:" + JSON.stringify(error)); return; } - this.nfcOmaChannel = data; - this.result = "openLogicChannel2 get channel successfully"; + nfcOmaChannel = data; + console.log("openLogicChannel2 get channel successfully"); }); } catch (e) { - this.result = "openLogicChannel2 exception:" + e.message; + console.log("openLogicChannel2 exception:" + e.message); } ``` ## Session.openLogicalChannel -openLogicalChannel(aid: number[], p2: number): Promise +openLogicalChannel(aid: number[], p2: number): Promise\ Opens a logical channel with the applet represented by the given AID (the AID is not null and the length is not 0). @@ -895,10 +878,10 @@ If the AID is null, this API sends the **MANAGE CHANNEL Open** only. In this cas **Parameters** -| **Name**| **Type**| **Description** | -| ---------- | -------- | ----------------------------------------- | -| aid | number[] | AIDs of the applets selected on the **Channel** instance. | -| p2 | number | P2 parameter of the **SELECT APDU** command executed on the channel. | +| **Name**| **Type**| **Mandatory**| **Description** | +| ---------- | -------- | ------ | ----------------------------------------- | +| aid | number[] | Yes | AIDs of the applets selected on the **Channel** instance.| +| p2 | number | Yes | P2 parameter of the **SELECT APDU** command executed on the channel. | **Error codes** @@ -916,30 +899,30 @@ For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.m ```js import secureElement from '@ohos.secureElement'; -@State result: string = ''; -@State nfcOmaSession: secureElement.Session = null; -@State nfcOmaChannel: secureElement.Channel = null; -aidArray: number[] = [720, 1080]; -p2: number = 0x00; -if (this.nfcOmaSession) { +let nfcOmaSession = null; +let nfcOmaChannel = null; +let aidArray = [720, 1080]; +let p2 = 0x00; + +if (nfcOmaSession) { try { // See Reader.openSession for this.nfcOmaSession. - let getPromise = this.nfcOmaSession.openLogicalChannel(this.aidArray, this.p2); + let getPromise = nfcOmaSession.openLogicalChannel(aidArray, p2); getPromise.then((channel) => { - this.nfcOmaChannel = channel; - this.result = "openLogicChannel3 get channel successfully"; + nfcOmaChannel = channel; + console.log("openLogicChannel3 get channel successfully"); }).catch ((err) => { - this.result = "openLogicChannel3 exception"; + console.log("openLogicChannel3 exception"); }) } catch (e) { - this.result = "openLogicChannel3 exception:" + e.message; + console.log("openLogicChannel3 exception:" + e.message); } ``` ## Session.openLogicalChannel -openLogicalChannel(aid: number[], p2: number, callback: AsyncCallback):void +openLogicalChannel(aid: number[], p2: number, callback: AsyncCallback\):void Opens a logical channel with the applet represented by the given AID (the AID is not null and the length is not 0). @@ -953,11 +936,11 @@ If the AID is null, this API sends the **MANAGE CHANNEL Open** only. In this cas **Parameters** -| **Name**| **Type** | **Description** | -| ---------- | ---------------------- | ------------------------------------------------------------ | -| aid | number[] | AIDs of the applets selected on the **Channel** instance. | -| p2 | number | P2 parameter of the **SELECT APDU** command executed on the channel. | -| callback | AsyncCallback | Callback invoked to return the **Channel** instance opened. If the SE cannot provide a new **Channel** instance or cannot obtain access control rules due to lack of available logical **Channel** instances, null will be returned.| +| **Name**| **Type** | **Mandatory**| **Description** | +| ---------- | ---------------------- | ------ | ------------------------------------------------------------ | +| aid | number[] | Yes | AIDs of the applets selected on the **Channel** instance. | +| p2 | number | Yes | P2 parameter of the **SELECT APDU** command executed on the channel. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the **Channel** instance opened. If the SE cannot provide a new **Channel** instance or cannot obtain access control rules due to lack of available logical **Channel** instances, null will be returned.| **Error codes** @@ -975,24 +958,23 @@ For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.m ```js import secureElement from '@ohos.secureElement'; -@State result: string = ''; -@State nfcOmaSession: secureElement.Session = null; -@State nfcOmaChannel: secureElement.Channel = null; -aidArray: number[] = [720, 1080]; -p2: number = 0x00; +let nfcOmaSession = null; +let nfcOmaChannel = null; +let aidArray = [720, 1080]; +let p2 = 0x00; try { // See Reader.openSession for this.nfcOmaSession. - this.nfcOmaSession.openLogicalChannel(this.aidArray, this.p2, (error, data) => { + nfcOmaSession.openLogicalChannel(aidArray, p2, (error, data) => { if (error) { - this.result = "openLogicChannel4 failed:" + JSON.stringify(error); + console.log("openLogicChannel4 failed:" + JSON.stringify(error)); return; } - this.nfcOmaChannel = data; - this.result = "openLogicChannel4 get channel successfully"; + nfcOmaChannel = data; + console.log("openLogicChannel4 get channel successfully"); }) } catch (e) { - this.result = "openLogicChannel4 exception:" + e.message; + console.log("openLogicChannel4 exception:" + e.message); } ``` @@ -1015,20 +997,19 @@ Obtains the session that opens this channel. ```js import secureElement from '@ohos.secureElement'; -@State result: string = ''; -@State nfcOmaSession: secureElement.Session = null; -@State nfcOmaChannel: secureElement.Channel = null; +let nfcOmaSession = null; +let nfcOmaChannel = null; try { // See Session.openBasicChannel for this.nfcOmaChannel. - let ret = this.nfcOmaChannel.getSession(); + let ret = nfcOmaChannel.getSession(); if (ret) { - this.result = "get session successfully"; + console.log("get session successfully"); } else { - this.result = "get session failed"; + console.log("get session failed"); } } catch (e) { - this.result = "getSession exception:" + e.message; + console.log("getSession exception:" + e.message); } ``` @@ -1045,16 +1026,15 @@ Closes the channel of the SE. ```js import secureElement from '@ohos.secureElement'; -@State result: string = ''; -@State nfcOmaSession: secureElement.Session = null; -@State nfcOmaChannel: secureElement.Channel = null; +let nfcOmaSession = null; +let nfcOmaChannel = null; try { // See Session.openBasicChannel for this.nfcOmaChannel. - this.nfcOmaChannel.close(); - this.result = "channel close successfully"; + nfcOmaChannel.close(); + console.log("channel close successfully"); } catch (e) { - this.result = "channel close exception:" + e.message; + console.log("channel close exception:" + e.message); } ``` @@ -1077,19 +1057,18 @@ Checks whether this channel is a basic channel. ```js import secureElement from '@ohos.secureElement'; -@State result: string = ''; -@State nfcOmaChannel: secureElement.Channel = null; +let nfcOmaChannel = null; try { // See Session.openBasicChannel for this.nfcOmaChannel. - let ret = this.nfcOmaChannel.isBasicChannel(); + let ret = nfcOmaChannel.isBasicChannel(); if (ret) { - this.result = "isBasicChannel TRUE"; + console.log("isBasicChannel TRUE"); } else { - this.result = "isBasicChannel FALSE"; + console.log("isBasicChannel FALSE"); } } catch (e) { - this.result = "isBasicChannel Exception: "+ e.message; + console.log ("isBasicChannelException: "+ e.message); } ``` @@ -1112,19 +1091,18 @@ Checks whether this channel is closed. ```js import secureElement from '@ohos.secureElement'; -@State result: string = ''; -@State nfcOmaChannel: secureElement.Channel = null; +let nfcOmaChannel = null; try { // See Session.openBasicChannel for this.nfcOmaChannel. - let ret = this.nfcOmaChannel.isClosed(); + let ret = nfcOmaChannel.isClosed(); if (ret) { - this.result = "channel isClosed TRUE"; + console.log("channel isClosed TRUE"); } else { - this.result = "channel isClosed False"; + console.log("channel isClosed False"); } } catch (e) { - this.result = "Channel isClosed exception:" + e.message; + console.log("Channel isClosed exception:" + e.message); } ``` @@ -1151,24 +1129,25 @@ For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.m ```js import secureElement from '@ohos.secureElement'; -@State result: string = ''; -@State nfcOmaChannel: secureElement.Channel = null; +let str = ''; +let nfcOmaChannel = null; try { // See Session.openBasicChannel for this.nfcOmaChannel. - let ret = this.nfcOmaChannel.getSelectResponse(); + let ret = nfcOmaChannel.getSelectResponse(); if (ret) { - this.result = "getSelectResponse result:["; + str = "getSelectResponse result:["; for (let i = 0; i < ret.length; ++i) { - this.result += ret[i]; - this.result += ' '; + str += ret[i]; + str += ' '; } - this.result += ']'; + str += ']'; + console.log(str); } else { - this.result = "getSelectResponse result is null"; + console.log("getSelectResponse result is null"); } } catch (e) { - this.result = "getSelectResponse exception:" + e.message; + console.log("getSelectResponse exception:" + e.message); } ``` @@ -1182,9 +1161,9 @@ Transmits the **APDU** command to the SE (according to ISO/IEC 7816). This API u **Parameters** -| **Name**| **Type**| **Description** | -| ---------- | -------- | ------------------------------------- | -| command | number[] | AIDs of the applets selected on the channel. | +| **Name**| **Type**| **Mandatory**| **Description** | +| ---------- | -------- | ------ | ------------------------------------- | +| command | number[] | Yes | AIDs of the applets selected on the channel.| **Return value** @@ -1207,25 +1186,25 @@ For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.m ```js import secureElement from '@ohos.secureElement'; -@State result: string = ''; -@State nfcOmaChannel: secureElement.Channel = null; - +let nfcOmaChannel = null; +let str = ""; try { let command: number[] = [100, 200]; // See Session.openBasicChannel for this.nfcOmaChannel. - let getPromise = this.nfcOmaChannel.transmit(command); + let getPromise = nfcOmaChannel.transmit(command); getPromise.then((data) => { - this.result = "transmit1 result:["; + str = "transmit1 result:["; for (let i = 0; i < data.length; ++i) { - this.result += data[i]; - this.result += " "; + str += data[i]; + str += " "; } - this.result += "]"; + str += "]"; + console.log(str); }).catch ((err) => { - this.result = "transmit1 exception:" + err.code; + console.log("transmit1 exception:" + err.code); }) } catch (e) { - this.result = "transit1 exception:" + e.message; + console.log("transit1 exception:" + e.message); } ``` @@ -1239,10 +1218,10 @@ Transmits the **APDU** command to the SE (according to ISO/IEC 7816). This API u **Parameters** -| **Name**| **Type** | **Description** | -| ---------- | ----------------------- | ------------------------------------- | -| command | number[] | AIDs of the applets selected on the channel. | -| callback | AsyncCallback | Callback invoked to return the result. | +| **Name**| **Type** | **Mandatory**| **Description** | +| ---------- | ----------------------- | ------ | ------------------------------------- | +| command | number[] | Yes | AIDs of the applets selected on the channel.| +| callback | AsyncCallback | Yes | Callback invoked to return the result. | **Error codes** @@ -1259,25 +1238,26 @@ For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.m ```js import secureElement from '@ohos.secureElement'; -@State result: string = ''; -@State nfcOmaChannel: secureElement.Channel = null; +let str = ""; +let nfcOmaChannel = null; try { let command: number[] = [100, 200]; // See Session.openBasicChannel for this.nfcOmaChannel. - this.nfcOmaChannel.transmit(command, (error, data) => { + nfcOmaChannel.transmit(command, (error, data) => { if (error) { - this.result = "transmit2 exception:" + JSON.stringify(error); + console.log("transmit2 exception:" + JSON.stringify(error)); return; } - this.result = "transmit2 result:["; + str = "transmit2 result:["; for (let i = 0; i < data.length; ++i) { - this.result += data[i]; - this.result += " "; + str += data[i]; + str += " "; } - this.result += "]"; + str += "]"; + console.log(str) }); } catch (e) { - this.result = "transit2 exception:" + e.message; + console.log("transit2 exception:" + e.message); } ``` diff --git a/en/application-dev/reference/apis/js-apis-settings.md b/en/application-dev/reference/apis/js-apis-settings.md index e888b0ef9b89fcad43556e271db6e5a6fceaeea0..2acac025ffeffe32677f5af17b1e1cabfeb6655b 100644 --- a/en/application-dev/reference/apis/js-apis-settings.md +++ b/en/application-dev/reference/apis/js-apis-settings.md @@ -249,7 +249,7 @@ Sets the value for a data item. This API uses a promise to return the result. ```js import featureAbility from '@ohos.ability.featureAbility'; -// Update the value of SCREEN_BRIGHTNESS_STATUS. (As this data item exists in the database, the setValue API will update the value of the data item.) +// Update the value of SCREEN_BRIGHTNESS_STATUS. (As this data item exists in the database, the setValue API will update its value.) let uri = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS); let helper = featureAbility.acquireDataAbilityHelper(uri); // @ts-ignore @@ -265,6 +265,8 @@ enableAirplaneMode(enable: boolean, callback: AsyncCallback\): void Enables or disables airplane mode. This API uses an asynchronous callback to return the result. +This API is not supported currently. + **System capability**: SystemCapability.Applications.settings.Core **Parameters** @@ -293,6 +295,8 @@ enableAirplaneMode(enable: boolean): Promise\ Enables or disables airplane mode. This API uses a promise to return the result. +This API is not supported currently. + **System capability**: SystemCapability.Applications.settings.Core **Parameters** diff --git a/en/application-dev/reference/apis/js-apis-system-file.md b/en/application-dev/reference/apis/js-apis-system-file.md index 8483433af3dd490b8ae640b74d2e31378c45b6d2..55120725537f9f93cfa73d37ab6b31560fabce5b 100644 --- a/en/application-dev/reference/apis/js-apis-system-file.md +++ b/en/application-dev/reference/apis/js-apis-system-file.md @@ -1,7 +1,7 @@ # @system.file (File Storage) -> **NOTE**
-> - The APIs of this module are no longer maintained since API version 6. You are advised to use [`@ohos.fileio`](js-apis-fileio.md). +> **NOTE** +> - The APIs provided by this module are no longer maintained since API Version 10. You are advised to use [@ohos.file.fs](js-apis-file-fs.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. @@ -20,7 +20,11 @@ move(Object): void Moves a specified file to a given location. -**System capability**: SystemCapability.FileManagement.File.FileIO +> **NOTE** +> +> This API is deprecated since API version 10. Use [fs.moveFile](js-apis-file-fs.md#fsmovefile) instead. + +**System Capability**: SystemCapability.FileManagement.File.FileIO.Lite **Parameters** @@ -32,7 +36,7 @@ Moves a specified file to a given location. | fail | Function | No| Called when the file fails to be moved.| | complete | Function | No| Called when the execution is complete.| -**Return value of fail()** +**Error codes** | Error Code| Description| | -------- | -------- | @@ -66,7 +70,11 @@ copy(Object): void Copies a file to the given URI. -**System capability**: SystemCapability.FileManagement.File.FileIO +> **NOTE** +> +> This API is deprecated since API version 10. Use [fs.copyFile](js-apis-file-fs.md#fscopyfile) instead. + +**System Capability**: SystemCapability.FileManagement.File.FileIO.Lite **Parameters** @@ -78,7 +86,7 @@ Copies a file to the given URI. | fail | Function | No| Called when the file fails to be copied.| | complete | Function | No| Called when the execution is complete.| -**Return value of fail()** +**Error codes** | Error Code| Description| | -------- | -------- | @@ -112,7 +120,11 @@ list(Object): void Obtains all files in the specified directory. -**System capability**: SystemCapability.FileManagement.File.FileIO +> **NOTE** +> +> This API is deprecated since API version 10. Use [fs.listFile](js-apis-file-fs.md#fslistfile) instead. + +**System Capability**: SystemCapability.FileManagement.File.FileIO.Lite **Parameters** @@ -138,7 +150,7 @@ Obtains all files in the specified directory. | length | number | File size, in bytes.| | type | string | File type. Available values are as follows:
- **dir**: directory
- **file**: file | -**Return value of fail()** +**Error codes** | Error Code| Description| | -------- | -------- | @@ -171,7 +183,11 @@ get(Object): void Obtains information about a local file. -**System capability**: SystemCapability.FileManagement.File.FileIO +> **NOTE** +> +> This API is deprecated since API version 10. Use [fs.stat](js-apis-file-fs.md#fsstat) instead. + +**System Capability**: SystemCapability.FileManagement.File.FileIO.Lite **Parameters** @@ -190,10 +206,10 @@ Obtains information about a local file. | uri | string | URI of the file.| | length | number | File size, in bytes.| | lastModifiedTime | number | Timestamp when the file is saved the last time, which is the number of milliseconds elapsed since 1970/01/01 00:00:00 GMT.| -| type | string | File type. Available values are as follows:
- **dir**: directory
- **file**: file | +| type | string | File type. Available values are as follows:
-  **dir**: directory
- **file**: file| | subFiles | Array | List of files.| -**Return value of fail()** +**Error codes** | Error Code| Description| | -------- | -------- | @@ -226,7 +242,11 @@ delete(Object): void Deletes a local file. -**System capability**: SystemCapability.FileManagement.File.FileIO +> **NOTE** +> +> This API is deprecated since API version 10. Use [fs.unlink](js-apis-file-fs.md#fsunlink) instead. + +**System Capability**: SystemCapability.FileManagement.File.FileIO.Lite **Parameters** @@ -237,7 +257,7 @@ Deletes a local file. | fail | Function | No| Called when the file fails to be deleted.| | complete | Function | No| Called when the execution is complete.| -**Return value of fail()** +**Error codes** | Error Code| Description| | -------- | -------- | @@ -270,7 +290,11 @@ writeText(Object): void Writes text into a file. Only text files can be read and written. -**System capability**: SystemCapability.FileManagement.File.FileIO +> **NOTE** +> +> This API is deprecated since API version 10. Use [fs.write](js-apis-file-fs.md#fswrite) instead. + +**System Capability**: SystemCapability.FileManagement.File.FileIO.Lite **Parameters** @@ -284,7 +308,7 @@ Writes text into a file. Only text files can be read and written. | fail | Function | No| Called when the text fails to be written into the file.| | complete | Function | No| Called when the execution is complete.| -**Return value of fail()** +**Error codes** | Error Code| Description| | -------- | -------- | @@ -317,7 +341,11 @@ writeArrayBuffer(Object): void Writes buffer data into a file. Only text files can be read and written. -**System capability**: SystemCapability.FileManagement.File.FileIO +> **NOTE** +> +> This API is deprecated since API version 10. Use [fs.write](js-apis-file-fs.md#fswrite) instead. + +**System Capability**: SystemCapability.FileManagement.File.FileIO.Lite **Parameters** @@ -331,7 +359,7 @@ Writes buffer data into a file. Only text files can be read and written. | fail | Function | No| Called when buffer data fails to be written into the file.| | complete | Function | No| Called when the execution is complete.| -**Return value of fail()** +**Error codes** | Error Code| Description| | -------- | -------- | @@ -345,7 +373,7 @@ export default { writeArrayBuffer() { file.writeArrayBuffer({ uri: 'internal://app/test', - buffer: new Uint8Array(8), // The buffer is of the Uint8Array type. + buffer: new Uint8Array(8), // The buffer is of the Uint8Array type. success: function() { console.log('call writeArrayBuffer success.'); }, @@ -364,7 +392,11 @@ readText(Object): void Reads text from a file. Only text files can be read and written. -**System capability**: SystemCapability.FileManagement.File.FileIO +> **NOTE** +> +> This API is deprecated since API version 10. Use [fs.readText](js-apis-file-fs.md#fsreadtext) instead. + +**System Capability**: SystemCapability.FileManagement.File.FileIO.Lite **Parameters** @@ -384,7 +416,7 @@ Reads text from a file. Only text files can be read and written. | -------- | -------- | -------- | | text | string | Text read from the specified file.| -**Return value of fail()** +**Error codes** | Error Code| Description| | -------- | -------- | @@ -418,7 +450,11 @@ readArrayBuffer(Object): void Reads buffer data from a file. Only text files can be read and written. -**System capability**: SystemCapability.FileManagement.File.FileIO +> **NOTE** +> +> This API is deprecated since API version 10. Use [fs.read](js-apis-file-fs.md#fsread) instead. + +**System Capability**: SystemCapability.FileManagement.File.FileIO.Lite **Parameters** @@ -437,7 +473,7 @@ Reads buffer data from a file. Only text files can be read and written. | -------- | -------- | -------- | | buffer | Uint8Array | Data read.| -**Return value of fail()** +**Error codes** | Error Code| Description| | -------- | -------- | @@ -472,7 +508,11 @@ access(Object): void Checks whether a file or directory exists. -**System capability**: SystemCapability.FileManagement.File.FileIO +> **NOTE** +> +> This API is deprecated since API version 10. Use [fs.access](js-apis-file-fs.md#fsaccess) instead. + +**System Capability**: SystemCapability.FileManagement.File.FileIO.Lite **Parameters** @@ -483,7 +523,7 @@ Checks whether a file or directory exists. | fail | Function | No| Called when the operation fails.| | complete | Function | No| Called when the execution is complete.| -**Return value of fail()** +**Error codes** | Error Code| Description| | -------- | -------- | @@ -516,7 +556,11 @@ mkdir(Object): void Creates a directory. -**System capability**: SystemCapability.FileManagement.File.FileIO +> **NOTE** +> +> This API is deprecated since API version 10. Use [fs.mkdir](js-apis-file-fs.md#fsmkdir) instead. + +**System Capability**: SystemCapability.FileManagement.File.FileIO.Lite **Parameters** @@ -528,7 +572,7 @@ Creates a directory. | fail | Function | No| Called when the directory fails to be created.| | complete | Function | No| Called when the execution is complete.| -**Return value of fail()** +**Error codes** | Error Code| Description| | -------- | -------- | @@ -560,7 +604,11 @@ rmdir(Object): void Deletes a directory. -**System capability**: SystemCapability.FileManagement.File.FileIO +> **NOTE** +> +> This API is deprecated since API version 10. Use [fs.rmdir](js-apis-file-fs.md#fsrmdir) instead. + +**System Capability**: SystemCapability.FileManagement.File.FileIO.Lite **Parameters** @@ -572,7 +620,7 @@ Deletes a directory. | fail | Function | No| Called when the directory fails to be deleted.| | complete | Function | No| Called when the execution is complete.| -**Return value of fail()** +**Error codes** | Error Code| Description| | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-system-storage.md b/en/application-dev/reference/apis/js-apis-system-storage.md index a4a3bb6b5d885308f6a6a28d994b9f27fda27536..d76f92a608d7a1bb2b7d0520ec66706011d3e991 100644 --- a/en/application-dev/reference/apis/js-apis-system-storage.md +++ b/en/application-dev/reference/apis/js-apis-system-storage.md @@ -20,7 +20,7 @@ get(options: GetStorageOptions): void Reads the value stored in the cache based on the specified key. -**System capability**: SystemCapability.DistributedDataManager.Preferences.Core +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core.Lite **Parameters** @@ -55,7 +55,7 @@ set(options: SetStorageOptions): void Sets the value in the cache based on the specified key. -**System capability**: SystemCapability.DistributedDataManager.Preferences.Core +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core.Lite **Parameters** @@ -88,7 +88,7 @@ clear(options?: ClearStorageOptions): void Clears the key-value pairs from the cache. -**System capability**: SystemCapability.DistributedDataManager.Preferences.Core +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core.Lite **Parameters** @@ -119,7 +119,7 @@ delete(options: DeleteStorageOptions): void Deletes the key-value pair based on the specified key. -**System capability**: SystemCapability.DistributedDataManager.Preferences.Core +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core.Lite **Parameters** @@ -147,20 +147,20 @@ export default { ## GetStorageOptions -**System capability**: SystemCapability.DistributedDataManager.Preferences.Core +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core.Lite | Name | Type | Mandatory| Description | | -------- | ---------------- | ---- | ------------------- | | key | string | Yes | Key of the target data. | -| default | string | No | Default value returned when the specified key does not exist. | +| default | string | No | Default value returned when the specified key does not exist. | | success | (data: any) => void | No | Called to return the result when **storage.get()** is called successfully. **data** is the value indexed by the specified key. | | fail | (data: string, code: number) => void | No | Called to return the result when **storage.get()** fails to be called. **data** is the error information, and **code** indicates the error code. | -| complete | () => void | No | Called when **storage.get()** is complete. | +| complete | () => void | No | Called when **storage.get()** is complete. | ## SetStorageOptions -**System capability**: SystemCapability.DistributedDataManager.Preferences.Core +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core.Lite | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | -------------------- | @@ -173,23 +173,22 @@ export default { ## ClearStorageOptions -**System capability**: SystemCapability.DistributedDataManager.Preferences.Core +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core.Lite | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | -------------------- | | success | () => void | No | Called when **storage.clear()** is called successfully. | | fail | (data: string, code: number) => void | No | Called to return the result when **storage.clear()** fails to be called. **data** is the error information, and **code** indicates the error code. | -| complete | () => void | No | Called when **storage.clear()** is complete. | +| complete | () => void | No | Called when **storage.clear()** is complete. | ## DeleteStorageOptions -**System capability**: SystemCapability.DistributedDataManager.Preferences.Core +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core.Lite | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------ | | key | string | Yes | Key of the data to delete. | | success | () => void | No | Called when **storage.delete()** is called successfully. | | fail | (data: string, code: number) => void | No | Called to return the result when **storage.delete()** fails to be called. **data** is the error information, and **code** indicates the error code. | -| complete | () => void | No | Called when **storage.delete()** is complete. | - +| complete | () => void | No | Called when **storage.delete()** is complete. | diff --git a/en/application-dev/reference/apis/js-apis-taskpool.md b/en/application-dev/reference/apis/js-apis-taskpool.md index 6de1a67d7af88229266bbdac7a4adb853479bb03..5e5fb1bbd6e67ef575778c601667f239b895e005 100644 --- a/en/application-dev/reference/apis/js-apis-taskpool.md +++ b/en/application-dev/reference/apis/js-apis-taskpool.md @@ -37,35 +37,32 @@ function printArgs(args) { console.log("printArgs: " + args); return args; } -async function taskpoolPriority() { - let task = new taskpool.Task(printArgs, 100); - - let highCount = 0; - let mediumCount = 0; - let lowCount = 0; - let allCount = 100; - for (let i = 0; i < allCount; i++) { - taskpool.execute(task, taskpool.Priority.LOW).then((res: number) => { - lowCount++; - console.log("taskpool lowCount is :" + lowCount); - }).catch((e) => { - console.error("low task error: " + e); - }) - taskpool.execute(task, taskpool.Priority.MEDIUM).then((res: number) => { - mediumCount++; - console.log("taskpool mediumCount is :" + mediumCount); - }).catch((e) => { - console.error("medium task error: " + e); - }) - taskpool.execute(task, taskpool.Priority.HIGH).then((res: number) => { - highCount++; - console.log("taskpool highCount is :" + highCount); - }).catch((e) => { - console.error("high task error: " + e); - }) - } + +let task = new taskpool.Task(printArgs, 100); // 100: test number +let highCount = 0; +let mediumCount = 0; +let lowCount = 0; +let allCount = 100; +for (let i = 0; i < allCount; i++) { + taskpool.execute(task, taskpool.Priority.LOW).then((res: number) => { + lowCount++; + console.log("taskpool lowCount is :" + lowCount); + }).catch((e) => { + console.error("low task error: " + e); + }) + taskpool.execute(task, taskpool.Priority.MEDIUM).then((res: number) => { + mediumCount++; + console.log("taskpool mediumCount is :" + mediumCount); + }).catch((e) => { + console.error("medium task error: " + e); + }) + taskpool.execute(task, taskpool.Priority.HIGH).then((res: number) => { + highCount++; + console.log("taskpool highCount is :" + highCount); + }).catch((e) => { + console.error("high task error: " + e); + }) } -taskpoolPriority(); ``` ## Task @@ -91,7 +88,7 @@ A constructor used to create a **Task** instance. For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). -| ID| Error Message | +| ID| Error Message | | -------- | --------------------------------------- | | 10200014 | The function is not mark as concurrent. | @@ -107,6 +104,117 @@ function printArgs(args) { let task = new taskpool.Task(printArgs, "this is my first Task"); ``` +### isCanceled10+ + +static isCanceled(): boolean + +Checks whether the running task is canceled. + +**System capability**: SystemCapability.Utils.Lang + +**Return value** + +| Type | Description | +| ------- | ------------------------------------ | +| boolean | Returns **true** if the running task is canceled; returns **false** otherwise.| + +**Example** + +```ts +@Concurrent +function inspectStatus(arg) { + // do something + if (taskpool.Task.isCanceled()) { + console.log("task has been canceled."); + // do something + return arg + 1; + } + // do something + return arg; +} +``` + +> **NOTE** +> +> **isCanceled** must be used together with **taskpool.cancel**. If **cancel** is not called, **isCanceled** returns **false** by default. + +**Example** + +```ts +@Concurrent +function inspectStatus(arg) { + // Check the cancellation status and return the result. + if (taskpool.Task.isCanceled()) { + console.log("task has been canceled before 2s sleep."); + return arg + 2; + } + // Wait for 2s. + let t = Date.now(); + while (Date.now() - t < 2000) { + continue; + } + // Check the cancellation status again and return the result. + if (taskpool.Task.isCanceled()) { + console.log("task has been canceled after 2s sleep."); + return arg + 3; + } + return arg + 1; +} + +let task = new taskpool.Task(inspectStatus, 100); // 100: test number +taskpool.execute(task).then((res)=>{ + console.log("taskpool test result: " + res); +}).catch((err) => { + console.log("taskpool test occur error: " + err); +}); +// If cancel is not called, isCanceled() returns false by default, and the task execution result is 101. +``` + +### setTransferList10+ + +setTransferList(transfer?: ArrayBuffer[]): void + +Sets the task transfer list. + +> **NOTE** +> +> This API is used to set the task transfer list in the form of **ArrayBuffer** in the task pool. The **ArrayBuffer** instance does not copy the content in the task to the worker thread during transfer. Instead, it transfers the buffer control right to the worker thread. After the transfer, the **ArrayBuffer** instance becomes invalid. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | --------------------------------------------- | +| transfer | ArrayBuffer[] | No | **ArrayBuffer** instance holding the objects to transfer. The default value is an empty array.| + +**Example** + +```ts +let buffer = new ArrayBuffer(8); +let view = new Uint8Array(buffer); +let buffer1 = new ArrayBuffer(16); +let view1 = new Uint8Array(buffer1); + +console.info("testTransfer view byteLength: " + view.byteLength); +console.info("testTransfer view1 byteLength: " + view1.byteLength); +@Concurrent +function testTransfer(arg1, arg2) { + console.info("testTransfer arg1 byteLength: " + arg1.byteLength); + console.info("testTransfer arg2 byteLength: " + arg2.byteLength); + return 100; +} +let task = new taskpool.Task(testTransfer, view, view1); +task.setTransferList([view.buffer, view1.buffer]); +taskpool.execute(task).then((res)=>{ + console.info("test result: " + res); +}).catch((e)=>{ + console.error("test catch: " + e); +}) +console.info("testTransfer view byteLength: " + view.byteLength); +console.info("testTransfer view1 byteLength: " + view1.byteLength); +``` + ### Attributes **System capability**: SystemCapability.Utils.Lang @@ -116,6 +224,96 @@ let task = new taskpool.Task(printArgs, "this is my first Task"); | function | Function | Yes | Yes | Function to be passed in during task creation. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types). | | arguments | unknown[] | Yes | Yes | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| +## TaskGroup10+ + +Implements a task group. Before using any of the following APIs, you must create a **TaskGroup** instance. + +### constructor10+ + +constructor() + +Constructor used to create a **TaskGroup** instance. + +**System capability**: SystemCapability.Utils.Lang + +**Example** + +```ts +let taskGroup = new taskpool.TaskGroup(); +``` + +### addTask10+ + +addTask(func: Function, ...args: unknown[]): void + +Adds the function to be executed to this task group. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | --------- | ---- | ---------------------------------------------------------------------- | +| func | Function | Yes | Function to be passed in for task execution. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types). | +| args | unknown[] | No | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | --------------------------------------- | +| 10200014 | The function is not mark as concurrent. | + +**Example** + +```ts +@Concurrent +function printArgs(args) { + console.log("printArgs: " + args); + return args; +} + +let taskGroup = new taskpool.TaskGroup(); +taskGroup.addTask(printArgs, 100); // 100: test number +``` + +### addTask10+ + +addTask(task: Task): void + +Adds a created task to this task group. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------------------------------------- | +| task | [Task](#task) | Yes | Task to be added to the task group. | + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | --------------------------------------- | +| 10200014 | The function is not mark as concurrent. | + +**Example** + +```ts +@Concurrent +function printArgs(args) { + console.log("printArgs: " + args); + return args; +} + +let taskGroup = new taskpool.TaskGroup(); +let task = new taskpool.Task(printArgs, 200); // 200: test number +taskGroup.addTask(task); +``` + ## taskpool.execute execute(func: Function, ...args: unknown[]): Promise\ @@ -141,11 +339,11 @@ Places the function to be executed in the internal task queue of the task pool. For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). -| ID| Error Message | -| -------- | ----------------------------------------- | -| 10200003 | Worker initialization failure. | -| 10200006 | Serializing an uncaught exception failed. | -| 10200014 | The function is not mark as concurrent. | +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200003 | Worker initialization failure. | +| 10200006 | An exception occurred during serialization. | +| 10200014 | The function is not mark as concurrent. | **Example** @@ -156,12 +354,9 @@ function printArgs(args) { return args; } -async function taskpoolExecute() { - let value = await taskpool.execute(printArgs, 100); +taskpool.execute(printArgs, 100).then((value) => { // 100: test number console.log("taskpool result: " + value); -} - -taskpoolExecute(); +}); ``` ## taskpool.execute @@ -177,23 +372,23 @@ Places a task in the internal task queue of the task pool. The task will be dist | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ---------------------------------------- | | task | [Task](#task) | Yes | Task to be executed. | -| priority | [Priority](#priority) | No | Priority of the task. The default value is **MEDIUM**.| +| priority | [Priority](#priority) | No | Priority of the task. The default value is **taskpool.Priority.MEDIUM**.| **Return value** -| Type | Description | -| ---------------- | ------------------------------ | +| Type | Description | +| ---------------- | ---------------- | | Promise\ | Promise used to return the result.| **Error codes** For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). -| ID| Error Message | -| -------- | ----------------------------------------- | -| 10200003 | Worker initialization failure. | -| 10200006 | Serializing an uncaught exception failed. | -| 10200014 | The function is not mark as concurrent. | +| ID| Error Message | +| -------- | ------------------------------------------- | +| 10200003 | Worker initialization failure. | +| 10200006 | An exception occurred during serialization. | +| 10200014 | The function is not mark as concurrent. | **Example** @@ -204,13 +399,72 @@ function printArgs(args) { return args; } -async function taskpoolExecute() { - let task = new taskpool.Task(printArgs, 100); - let value = await taskpool.execute(task); +let task = new taskpool.Task(printArgs, 100); // 100: test number +taskpool.execute(task).then((value) => { console.log("taskpool result: " + value); +}); +``` + +## taskpool.execute10+ + +execute(group: TaskGroup, priority?: Priority): Promise + +Places a task group in the internal task queue of the task pool. The task group will be distributed to the worker thread for execution. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | --------------------------- | ---- | -------------------------------------------------------------- | +| group | [TaskGroup](#taskgroup) | Yes | Task group to be executed. | +| priority | [Priority](#priority) | No | Priority of the task group. The default value is **taskpool.Priority.MEDIUM**.| + +**Return value** + +| Type | Description | +| ---------------- | ---------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ------------------------------------------- | +| 10200006 | An exception occurred during serialization. | + +**Example** + +```ts +@Concurrent +function printArgs(args) { + console.log("printArgs: " + args); + return args; } -taskpoolExecute(); +let taskGroup1 = new taskpool.TaskGroup(); +taskGroup1.addTask(printArgs, 10); // 10: test number +taskGroup1.addTask(printArgs, 20); // 20: test number +taskGroup1.addTask(printArgs, 30); // 30: test number + +let taskGroup2 = new taskpool.TaskGroup(); +let task1 = new taskpool.Task(printArgs, 100); // 100: test number +let task2 = new taskpool.Task(printArgs, 200); // 200: test number +let task3 = new taskpool.Task(printArgs, 300); // 300: test number +taskGroup2.addTask(task1); +taskGroup2.addTask(task2); +taskGroup2.addTask(task3); +taskpool.execute(taskGroup1).then((res) => { + console.info("taskpool execute res is:" + res); +}).catch((e) => { + console.error("taskpool execute error is:" + e); +}); +taskpool.execute(taskGroup2).then((res) => { + console.info("taskpool execute res is:" + res); +}).catch((e) => { + console.error("taskpool execute error is:" + e); +}); ``` ## taskpool.cancel @@ -231,91 +485,109 @@ Cancels a task in the task pool. For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). -| ID| Error Message | -| -------- | ------------------------- | -| 10200015 | If the task is not exist. | -| 10200016 | If the task is running. | +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200015 | The task does not exist when it is canceled. | +| 10200016 | The task is executing when it is canceled. | -**Example of successful task cancellation** +Since API version 10, error code 10200016 is not reported when this API is called. + +**Example of canceling an ongoing task** ```ts @Concurrent -function printArgs(args) { - console.log("printArgs: " + args); - return args; -} - -async function taskpoolCancel() { - let task = new taskpool.Task(printArgs, 100); - taskpool.execute(task); - try { - taskpool.cancel(task); - } catch (e) { - console.log("taskpool.cancel occur error:" + e); - } +function inspectStatus(arg) { + // Check the task cancellation state and return the result. + if (taskpool.Task.isCanceled()) { + console.log("task has been canceled before 2s sleep."); + return arg + 2; + } + // 2s sleep + let t = Date.now(); + while (Date.now() - t < 2000) { + continue; + } + // Check the task cancellation state again and return the result. + if (taskpool.Task.isCanceled()) { + console.log("task has been canceled after 2s sleep."); + return arg + 3; + } + return arg + 1; } -taskpoolCancel(); +let task1 = new taskpool.Task(inspectStatus, 100); // 100: test number +let task2 = new taskpool.Task(inspectStatus, 200); // 200: test number +let task3 = new taskpool.Task(inspectStatus, 300); // 300: test number +let task4 = new taskpool.Task(inspectStatus, 400); // 400: test number +let task5 = new taskpool.Task(inspectStatus, 500); // 500: test number +let task6 = new taskpool.Task(inspectStatus, 600); // 600: test number +taskpool.execute(task1).then((res)=>{ + console.log("taskpool test result: " + res); +}).catch((err) => { + console.log("taskpool test occur error: " + err); +}); +let res2 = taskpool.execute(task2); +let res3 = taskpool.execute(task3); +let res4 = taskpool.execute(task4); +let res5 = taskpool.execute(task5); +let res6 = taskpool.execute(task6); +// Cancel the task 1s later. +setTimeout(()=>{ + taskpool.cancel(task1);}, 1000); ``` -**Example of a failure to cancel a task that has been executed** +## taskpool.cancel10+ -```ts -@Concurrent -function printArgs(args) { - console.log("printArgs: " + args); - return args; -} +cancel(group: TaskGroup): void -async function taskpoolCancel() { - let task = new taskpool.Task(printArgs, 100); - let value = taskpool.execute(task); - let start = new Date().getTime(); - while (new Date().getTime() - start < 1000) {// Wait for 1s to ensure that the task has been executed. - continue; - } +Cancels a task group in the task pool. - try { - taskpool.cancel(task); // The task has been executed and fails to be canceled. - } catch (e) { - console.log("taskpool.cancel occur error:" + e); - } -} +**System capability**: SystemCapability.Utils.Lang -taskpoolCancel(); -``` +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ----------------------- | ---- | -------------------- | +| group | [TaskGroup](#taskgroup) | Yes | Task group to cancel.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). -**Example of a failure to cancel an ongoing task** +| ID| Error Message | +| -------- | ------------------------------------------------------- | +| 10200018 | The task group does not exist when it is canceled. | + +**Example** ```ts @Concurrent function printArgs(args) { + let t = Date.now(); + while (Date.now() - t < 2000) { + continue; + } console.log("printArgs: " + args); return args; } -async function taskpoolCancel() { - let task1 = new taskpool.Task(printArgs, 100); - let task2 = new taskpool.Task(printArgs, 200); - let task3 = new taskpool.Task(printArgs, 300); - let task4 = new taskpool.Task(printArgs, 400); - let task5 = new taskpool.Task(printArgs, 500); - let task6 = new taskpool.Task(printArgs, 600); - - let res1 = taskpool.execute(task1); - let res2 = taskpool.execute(task2); - let res3 = taskpool.execute(task3); - let res4 = taskpool.execute(task4); - let res5 = taskpool.execute(task5); - let res6 = taskpool.execute(task6); +let taskGroup1 = new taskpool.TaskGroup(); +taskGroup1.addTask(printArgs, 10); // 10: test number +let taskGroup2 = new taskpool.TaskGroup(); +taskGroup2.addTask(printArgs, 100); // 100: test number +taskpool.execute(taskGroup1).then((res)=>{ + console.info("taskGroup1 res is:" + res) +}); +taskpool.execute(taskGroup2).then((res)=>{ + console.info("taskGroup2 res is:" + res) +}); +setTimeout(()=>{ try { - taskpool.cancel(task1); // task1 is being executed and fails to be canceled. + taskpool.cancel(taskGroup2); } catch (e) { - console.log("taskpool.cancel occur error:" + e); + console.log("taskGroup.cancel occur error:" + e); } -} - -taskpoolCancel(); +}, 1000); ``` ## Additional Information @@ -359,7 +631,7 @@ taskpoolExecute(); ```ts // b.ets -export var c = 2000; +export let c = 2000; ``` ```ts // Reference an imported variable. @@ -420,8 +692,8 @@ function strSort(inPutArr) { export async function func1() { console.log("taskpoolTest start"); let strArray = ['c test string', 'b test string', 'a test string']; - var task = new taskpool.Task(strSort, strArray); - var result = await taskpool.execute(task); + let task = new taskpool.Task(strSort, strArray); + let result = await taskpool.execute(task); console.log("func1 result:" + result); } @@ -435,9 +707,132 @@ export async function func2() { ``` ```ts -/ / a.ets (in the same directory as c.ets) +// a.ets (in the same directory as c.ets) import { taskpoolTest1, taskpoolTest2 } from "./c"; func1(); func2(); ``` + +**Example 5** + +```ts +// Success in canceling a task +@Concurrent +function inspectStatus(arg) { + // Check the task cancellation state and return the result. + if (taskpool.Task.isCanceled()) { + console.log("task has been canceled before 2s sleep."); + return arg + 2; + } + // Wait for 2s. + let t = Date.now(); + while (Date.now() - t < 2000) { + continue; + } + // Check the task cancellation state again and return the result. + if (taskpool.Task.isCanceled()) { + console.log("task has been canceled after 2s sleep."); + return arg + 3; + } + return arg + 1; +} + +async function taskpoolCancel() { + let task = new taskpool.Task(inspectStatus, 100); // 100: test number + taskpool.execute(task).then((res)=>{ + console.log("taskpool test result: " + res); + }).catch((err) => { + console.log("taskpool test occur error: " + err); + }); + // Cancel the task 1s later. + setTimeout(()=>{ + taskpool.cancel(task);}, 1000); +} + +taskpoolCancel(); +``` + +**Example 6** + +```ts +// Failure to cancel a task that has been executed +@Concurrent +function inspectStatus(arg) { + // Check the cancellation status and return the result. + if (taskpool.Task.isCanceled()) { + return arg + 2; + } + // Wait for 2s. + let t = Date.now(); + while (Date.now() - t < 2000) { + continue; + } + // Check the cancellation status again and return the result. + if (taskpool.Task.isCanceled()) { + return arg + 3; + } + return arg + 1; +} + +async function taskpoolCancel() { + let task = new taskpool.Task(inspectStatus, 100); // 100: test number + taskpool.execute(task).then((res)=>{ + console.log("taskpool test result: " + res); + }).catch((err) => { + console.log("taskpool test occur error: " + err); + }); + setTimeout(()=>{ + try { + taskpool.cancel(task); // The task has been executed and fails to be canceled. + } catch (e) { + console.log("taskpool.cancel occur error:" + e); + } + }, 3000); // Wait for 3s to ensure that the task has been executed. +} + +taskpoolCancel(); +``` + +**Example 7** + +```ts +// Success of canceling a task group to be executed +@Concurrent +function printArgs(args) { + let t = Date.now(); + while (Date.now() - t < 1000) { + continue; + } + console.log("printArgs: " + args); + return args; +} + +async function taskpoolGroupCancelTest() { + let taskGroup1 = new taskpool.TaskGroup(); + taskGroup1.addTask(printArgs, 10); // 10: test number + taskGroup1.addTask(printArgs, 20); // 20: test number + taskGroup1.addTask(printArgs, 30); // 30: test number + let taskGroup2 = new taskpool.TaskGroup(); + let task1 = new taskpool.Task(printArgs, 100); // 100: test number + let task2 = new taskpool.Task(printArgs, 200); // 200: test number + let task3 = new taskpool.Task(printArgs, 300); // 300: test number + taskGroup2.addTask(task1); + taskGroup2.addTask(task2); + taskGroup2.addTask(task3); + taskpool.execute(taskGroup1).then((res) => { + console.info("taskpool execute res is:" + res); + }).catch((e) => { + console.error("taskpool execute error is:" + e); + }); + taskpool.execute(taskGroup2).then((res) => { + console.info("taskpool execute res is:" + res); + }).catch((e) => { + console.error("taskpool execute error is:" + e); + }); + + taskpool.cancel(taskGroup2); +} + +taskpoolGroupCancelTest() +``` diff --git a/en/application-dev/reference/apis/js-apis-uitest.md b/en/application-dev/reference/apis/js-apis-uitest.md index 673744bf89745e4b929bddf57db88f7de730c33f..f3ed68ea09339eec7f3b2901b7e3d2037bf47108 100644 --- a/en/application-dev/reference/apis/js-apis-uitest.md +++ b/en/application-dev/reference/apis/js-apis-uitest.md @@ -8,9 +8,9 @@ This module provides the following functions: - [Component9+](#component9): represents a component on the UI and provides APIs for obtaining component attributes, clicking a component, scrolling to search for a component, and text injection. - [Driver9+](#driver9): works as the entry class and provides APIs for features such as component matching/search, key injection, coordinate clicking/sliding, and screenshot. - [UiWindow9+](#uiwindow9): works as the entry class and provides APIs for obtaining window attributes, dragging windows, and adjusting window sizes. -- [By(deprecated)](#bydeprecated): provides UI component feature description APIs for component filtering and matching. This API is deprecated since API version 9. You are advised to use [On9+](#on9) instead. -- [UiComponent(deprecated)](#uicomponentdeprecated): represents a component on the UI and provides APIs for obtaining component attributes, clicking a component, scrolling to search for a component, and text injection. This API is deprecated since API version 9. You are advised to use [Component9+](#component9) instead. -- [UiDriver(deprecated)](#uidriverdeprecated): works as the entry class and provides APIs for features such as component matching/search, key injection, coordinate clicking/sliding, and screenshot. This API is deprecated since API version 9. You are advised to use [Driver9+](#driver9) instead. +- [By(deprecated)](#bydeprecated): provides UI component feature description APIs for component filtering and matching. This class is deprecated since API version 9. You are advised to use [On9+](#on9) instead. +- [UiComponent(deprecated)](#uicomponentdeprecated): represents a component on the UI and provides APIs for obtaining component attributes, clicking a component, scrolling to search for a component, and text injection. This class is deprecated since API version 9. You are advised to use [Component9+](#component9) instead. +- [UiDriver(deprecated)](#uidriverdeprecated): works as the entry class and provides APIs for features such as component matching/search, key injection, coordinate clicking/sliding, and screenshot. This class is deprecated since API version 9. You are advised to use [Driver9+](#driver9) instead. >**NOTE** > @@ -160,10 +160,8 @@ Since API version 9, the UiTest framework provides a wide range of UI component The API capabilities provided by the **On** class exhibit the following features: - Allow one or more attributes as the match conditions. For example, you can specify both the **text** and **id** attributes to find the target component. - - Provide multiple match patterns for component attributes. - -- Support absolute positioning and relative positioning for components. APIs such as [ON.isBefore](#isbefore9) and [ON.isAfter](#isafter9) can be used to specify the features of adjacent components to assist positioning. +- Support absolute positioning and relative positioning for components. APIs such as [ON.isBefore](#isbefore9) and [ON.isAfter](#isafter9) can be used to specify the features of adjacent components to assist positioning. All APIs provided in the **On** class are synchronous. You are advised to use the static constructor **ON** to create an **On** object in chain mode. @@ -1208,7 +1206,7 @@ For details about the error codes, see [UiTest Error Codes](../errorcodes/errorc ```js async function demo() { let driver = Driver.create(); - let button = await driver.findComponent(ON.type('Scroll')); + let scrollBar = await driver.findComponent(ON.type('Scroll')); let button = await scrollBar.scrollSearch(ON.text('next page')); } ``` @@ -2439,7 +2437,7 @@ For details about the error codes, see [UiTest Error Codes](../errorcodes/errorc ```js async function demo() { let driver = Driver.create(); - let obeserver = await driver.createUiEventObserve(); + let observer = await driver.createUIEventObserver() } ``` @@ -2950,7 +2948,7 @@ async function demo() { ## UIEventObserver10+ -UI event listener. +Implements a UI event listener. ### once('toastShow') @@ -2971,6 +2969,7 @@ Subscribes to events of the toast component. This API uses a callback to return ```js async function demo() { + let driver = Driver.create(); let observer = await driver.createUIEventObserver() let callback = (UIElementInfo)=>{ console.info(UIElementInfo.bundleName) @@ -3000,6 +2999,7 @@ Subscribes to events of the dialog component. This API uses a callback to return ```js async function demo() { + let driver = Driver.create(); let observer = await driver.createUIEventObserver() let callback = (UIElementInfo)=>{ console.info(UIElementInfo.bundleName) @@ -3013,15 +3013,16 @@ async function demo() { ## By(deprecated) The UiTest framework provides a wide range of UI component feature description APIs in the **By** class to filter and match components. -The API capabilities provided by the **By** class exhibit the following features: -- Allow one or more attributes as the match conditions. For example, you can specify both the **text** and **id** attributes to find the target component. +The API capabilities provided by the **By** class exhibit the following features: + +- Allow one or more attributes as the match conditions. For example, you can specify both the **text** and **id** attributes to find the target component. - Provide multiple match patterns for component attributes. - Support absolute positioning and relative positioning for components. APIs such as [By.isBefore(deprecated)](#isbeforedeprecated) and [By.isAfter(deprecated)](#isafterdeprecated) can be used to specify the features of adjacent components to assist positioning. All APIs provided in the **By** class are synchronous. You are advised to use the static constructor **BY** to create a **By** object in chain mode. -This API is deprecated since API version 9. You are advised to use [On9+](#on9) instead. +This class is deprecated since API version 9. You are advised to use [On9+](#on9) instead. ```js BY.text('123').type('button'); @@ -3347,7 +3348,7 @@ In **UiTest**, the **UiComponent** class represents a component on the UI and pr All APIs provided in this class use a promise to return the result and must be invoked using **await**. -This API is deprecated since API version 9. You are advised to use [Component9+](#component9) instead. +This class is deprecated since API version 9. You are advised to use [Component9+](#component9) instead. ### click(deprecated) @@ -3729,7 +3730,7 @@ The **UiDriver** class is the main entry to the UiTest framework. It provides AP All APIs provided by this class, except for **UiDriver.create()**, use a promise to return the result and must be invoked using **await**. -This API is deprecated since API version 9. You are advised to use [Driver9+](#driver9) instead. +This class is deprecated since API version 9. You are advised to use [Driver9+](#driver9) instead. ### create(deprecated) diff --git a/en/application-dev/reference/apis/js-apis-wallpaper.md b/en/application-dev/reference/apis/js-apis-wallpaper.md index 4e869d9d32db75389926d06212fe085f3781955b..0e76092672c8aaa5b85ada2d79a95eb003ddbd2b 100644 --- a/en/application-dev/reference/apis/js-apis-wallpaper.md +++ b/en/application-dev/reference/apis/js-apis-wallpaper.md @@ -137,9 +137,87 @@ try { } ``` +## wallpaper.setCustomWallpaper10+ + +setCustomWallpaper(source: string, wallpaperType: WallpaperType, callback: AsyncCallback<void>): void + +Sets the content from a specified URI as the wallpaper. This API works only when com.ohos.sceneboard is set. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.SET_WALLPAPER + +**System capability**: SystemCapability.MiscServices.Wallpaper + +**System API**: This is a system API. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| source | string | Yes| URI of the custom wallpaper.| +| wallpaperType | [WallpaperType](#wallpapertype7) | Yes| Wallpaper type.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the wallpaper is set, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Example** + +```js +let wallpaperPath = "/data/storage/el2/base/haps/entry/files/test.zip"; +try { + wallpaper.setCustomWallpaper(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => { + if (error) { + console.error(`failed to setCustomWallpaper because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to setCustomWallpaper.`); + }); +} catch (error) { + console.error(`failed to setCustomWallpaper because: ${JSON.stringify(error)}`); +} + +``` + +## wallpaper.setCustomWallpaper10+ + +setCustomWallpaper(source: string, wallpaperType: WallpaperType): Promise<void> + +Sets the content from a specified URI as the wallpaper. This API works only when com.ohos.sceneboard is set. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.SET_WALLPAPER + +**System capability**: SystemCapability.MiscServices.Wallpaper + +**System API**: This is a system API. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| source | string | Yes| URI of the custom wallpaper.| +| wallpaperType | [WallpaperType](#wallpapertype7) | Yes| Wallpaper type.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let wallpaperPath = "/data/storage/el2/base/haps/entry/files/test.zip"; +try { + wallpaper.setCustomWallpaper(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => { + console.log(`success to setCustomWallpaper.`); + }).catch((error) => { + console.error(`failed to setCustomWallpaper because: ${JSON.stringify(error)}`); + }); +} catch (error) { + console.error(`failed to setCustomWallpaper because: ${JSON.stringify(error)}`); +} +``` + ## wallpaper.on('wallpaperChange')10+ -on(type: 'wallpaperChange', callback: (wallpaperType: WallpaperType, resourceType: WallpaperResourceType) => void): void +on(type: 'wallpaperChange', callback: (wallpaperType: WallpaperType, resourceType: WallpaperResourceType, uri?: string) => void): void Subscribes to wallpaper change events. @@ -152,7 +230,7 @@ Subscribes to wallpaper change events. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is fixed at **'wallpaperChange'**.| -| callback | function | Yes| Callback used to return the wallpaper type and wallpaper resource type.
- wallpaperType
Wallpaper type.
- resourceType
Wallpaper resource type.| +| callback | function | Yes| Callback used to return the wallpaper type and wallpaper resource type.
- **wallpaperType**: wallpaper type.
- **resourceType**: wallpaper resource type.
- **uri**: URI of the wallpaper resource.| **Example** @@ -169,7 +247,7 @@ try { ## wallpaper.off('wallpaperChange')10+ -off(type: 'wallpaperChange', callback?: (wallpaperType: WallpaperType, resourceType: WallpaperResourceType) => void): void +off(type: 'wallpaperChange', callback?: (wallpaperType: WallpaperType, resourceType: WallpaperResourceType, uri?: string) => void): void Unsubscribes from wallpaper change events. @@ -182,7 +260,7 @@ Unsubscribes from wallpaper change events. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is fixed at **'wallpaperChange'**.| -| callback | function | No| Callback used for unsubscription. If this parameter is not set, this API unsubscribes from all callbacks of the specified event type.
- wallpaperType
Wallpaper type.
- resourceType
Wallpaper resource type.| +| callback | function | No| Callback used for unsubscription. If this parameter is not set, this API unsubscribes from all callbacks of the specified event type.
- **wallpaperType**: wallpaper type.
- **resourceType**: wallpaper resource type.
- **uri**: URI of the wallpaper resource.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-webview.md b/en/application-dev/reference/apis/js-apis-webview.md index a5334a26084d30eafb4f914ea3f7fe8d457267f7..ae261c21ebc5779e283e8e4e19d1355de9216cda 100644 --- a/en/application-dev/reference/apis/js-apis-webview.md +++ b/en/application-dev/reference/apis/js-apis-webview.md @@ -3515,7 +3515,7 @@ struct WebComponent { pageUp(top:boolean): void -Scrolls the page up by half the view port or jumps to the top of the page. +Scrolls the page up by half the viewport or jumps to the top of the page. **System capability**: SystemCapability.Web.Webview.Core @@ -3523,7 +3523,7 @@ Scrolls the page up by half the view port or jumps to the top of the page. | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------------------------------ | -| top | boolean | Yes | Whether to jump to the top of the page. The value **true** means to jump to the top of the page; and **false** means to scroll the page up by half the view port.| +| top | boolean | Yes | Whether to jump to the top of the page. The value **true** means to jump to the top of the page; and **false** means to scroll the page up by half the viewport.| **Error codes** @@ -3564,7 +3564,7 @@ struct WebComponent { pageDown(bottom:boolean): void -Scrolls the page down by half the view port or jumps to the bottom of the page. +Scrolls the page down by half the viewport or jumps to the bottom of the page. **System capability**: SystemCapability.Web.Webview.Core @@ -3572,7 +3572,7 @@ Scrolls the page down by half the view port or jumps to the bottom of the page. | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------------------------------ | -| bottom | boolean | Yes | Whether to jump to the bottom of the page. The value **true** means to jump to the bottom of the page; and **false** means to scroll the page down by half the view port.| +| bottom | boolean | Yes | Whether to jump to the bottom of the page. The value **true** means to jump to the bottom of the page; and **false** means to scroll the page down by half the viewport.| **Error codes** diff --git a/en/application-dev/reference/apis/js-apis-wifi.md b/en/application-dev/reference/apis/js-apis-wifi.md index 76f27aa775302ff5d313d17f664401b6364e25b9..e9f2fbb84b4b39521a484f2c5ffc60680223d2ac 100644 --- a/en/application-dev/reference/apis/js-apis-wifi.md +++ b/en/application-dev/reference/apis/js-apis-wifi.md @@ -244,23 +244,6 @@ Enumerates the WLAN security types. | WIFI_SEC_TYPE_SAE | 4 | Simultaneous Authentication of Equals (SAE).| -## wifi.getScanInfosSync9+ - -getScanInfosSync():  Array<[WifiScanInfo](#wifiscaninfo)> - -Obtains the scan result. This API returns the result synchronously. - -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_PEERS_MAC (or ohos.permission.LOCATION) - -**System capability**: SystemCapability.Communication.WiFi.STA - -**Return value** - - | **Type**| **Description**| - | -------- | -------- | - |  Array<[WifiScanInfo](#wifiscaninfo)> | Scan result obtained.| - - ## wifi.addDeviceConfig addDeviceConfig(config: WifiDeviceConfig): Promise<number> @@ -585,8 +568,8 @@ Connects to the specified network. **System API**: This is a system API. -**Required permissions**: ohos.permission.SET_WIFI_INFO, ohos.permission.SET_WIFI_CONFIG, and ohos.permissio.MANAGE_WIFI_CONNECTION (available only to system applications) - +**Required permissions**: ohos.permission.SET_WIFI_INFO, ohos.permission.SET_WIFI_CONFIG, and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + **System capability**: SystemCapability.Communication.WiFi.STA @@ -680,7 +663,7 @@ try { let rssi = 0; let band = 0; let level = wifi.getSignalLevel(rssi,band); - console.info("lelvel:" + JSON.stringify(lelvel)); + console.info("level:" + JSON.stringify(level)); }catch(error){ console.error("failed:" + JSON.stringify(error)); } @@ -1278,10 +1261,10 @@ Disables this hotspot. **Example** ```js -import wifi from '@ohos.wifiManager'; +import wifi from '@ohos.wifi'; try { - wifiManager.disableHotspot(); + wifi.disableHotspot(); }catch(error){ console.error("failed:" + JSON.stringify(error)); } @@ -1644,7 +1627,7 @@ Obtains the peer device list in the P2P connection. This API uses an asynchronou **Example** ```js -import wifi from '@ohos.wifiManager'; +import wifi from '@ohos.wifi'; wifi.getP2pPeerDevices((err, data) => { if (err) { @@ -2043,7 +2026,7 @@ import wifi from '@ohos.wifi'; try { let name = "****"; - wifi.setDeviceName(netId); + wifi.setDeviceName(name); }catch(error){ console.error("failed:" + JSON.stringify(error)); } diff --git a/en/application-dev/reference/apis/js-apis-wifiManager.md b/en/application-dev/reference/apis/js-apis-wifiManager.md index 6d560d345805826369d8b83cfdcbee53a47b00f5..32a9a545a4785e4de3ab0a600c74cc23bc1f8e6d 100644 --- a/en/application-dev/reference/apis/js-apis-wifiManager.md +++ b/en/application-dev/reference/apis/js-apis-wifiManager.md @@ -2,7 +2,6 @@ The **WLAN** module provides basic wireless local area network (WLAN) functions, peer-to-peer (P2P) functions, and WLAN message notification services. It allows applications to communicate with other devices over WLAN. > **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. @@ -26,22 +25,22 @@ Enables WLAN. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { wifiManager.enableWifi(); @@ -64,22 +63,22 @@ Disables WLAN. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { wifiManager.disableWifi(); @@ -100,22 +99,22 @@ Checks whether WLAN is enabled. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if WLAN is enabled; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if WLAN is enabled; returns **false** otherwise.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { let isActivate = wifiManager.isActivate(); @@ -137,22 +136,22 @@ Starts a scan for WLAN. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { wifiManager.scan(); @@ -173,27 +172,27 @@ Obtains the scan result. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| Array<[WifiScanInfo](#wifiscaninfo)> | Returns the hotspots detected.| + | **Type**| **Description**| + | -------- | -------- | + | Array<[WifiScanInfo](#wifiscaninfo)> | Returns the hotspots detected.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { let scanInfoList = wifiManager.getScanInfoList(); console.info("scanInfoList:" + JSON.stringify(scanInfoList)); - let len = Object.keys(result).length; + let len = Object.keys(scanInfoList).length; console.log("wifi received scan info: " + len); if(len > 0){ for (var i = 0; i < len; ++i) { @@ -332,14 +331,14 @@ Adds network configuration. This API uses a promise to return the result. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| **Return value** -| **Type**| **Description**| -| -------- | -------- | + | **Type**| **Description**| + | -------- | -------- | | Promise<number> | Promise used to return the ID of the added network configuration. If **-1** is returned, the network configuration fails to be added.| **Error codes** @@ -347,13 +346,13 @@ Adds network configuration. This API uses a promise to return the result. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { let config = { @@ -508,23 +507,23 @@ Adds network configuration. This API uses an asynchronous callback to return the **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| -| callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + | callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { let config = { @@ -552,27 +551,27 @@ Adds the configuration of a candidate network. This API uses a promise to return **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| Promise<number> | Promise used to return the network configuration ID.| + | **Type**| **Description**| + | -------- | -------- | + | Promise<number> | Promise used to return the network configuration ID.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| **Example** -````` - import wifi from '@ohos.wifiManager'; +`````js + import wifiManager from '@ohos.wifiManager'; try { let config = { @@ -600,22 +599,22 @@ Adds the configuration of a candidate network. This API uses an asynchronous cal **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| -| callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + | callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| **Example** -````` - import wifi from '@ohos.wifiManager'; +`````js + import wifiManager from '@ohos.wifiManager'; try { let config = { @@ -643,28 +642,28 @@ Removes the configuration of a candidate network. This API uses a promise to ret **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| networkId | number | Yes| ID of the network configuration to remove.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | networkId | number | Yes| ID of the network configuration to remove.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| + | **Type**| **Description**| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { let networkId = 0; @@ -688,9 +687,9 @@ Removes the configuration of a candidate network. This API uses an asynchronous **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| networkId | number | Yes| ID of the network configuration to remove.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | networkId | number | Yes| ID of the network configuration to remove.| | callback | AsyncCallback<void> | Yes| Callback invoked to return the result. If the operation is successful, the value of **err** is **0**. If **err** is not **0**, an error has occurred.| **Error codes** @@ -698,12 +697,12 @@ Removes the configuration of a candidate network. This API uses an asynchronous For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { let networkId = 0; @@ -727,22 +726,22 @@ Obtains candidate network configuration. **Return value** -| **Type**| **Description**| -| -------- | -------- | -|  Array<[WifiDeviceConfig](#wifideviceconfig)> | Candidate network configuration obtained.| + | **Type**| **Description**| + | -------- | -------- | + |  Array<[WifiDeviceConfig](#wifideviceconfig)> | Candidate network configuration obtained.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | -| 2501000 | Operation failed.| + | -------- | -------- | +| 2501000 | Operation failed.| **Example** -````` - import wifi from '@ohos.wifiManager'; +`````js + import wifiManager from '@ohos.wifiManager'; try { let configs = wifiManager.getCandidateConfigs(); @@ -773,22 +772,22 @@ Connects to a candidate network added by the application. If the device is alrea **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| networkId | number | Yes| ID of the candidate network configuration.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | networkId | number | Yes| ID of the candidate network configuration.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| | 2501001 | Wifi is closed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { let networkId = 0; @@ -814,23 +813,23 @@ Connects to the specified network. If the device is already connected to a hotsp **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| networkId | number | Yes| Network configuration ID.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | networkId | number | Yes| Network configuration ID.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| | 2501001 | Wifi is closed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { let networkId = 0; @@ -848,15 +847,15 @@ Connects to the specified network. If the device is already connected to a hotsp **System API**: This is a system API. -**Required permissions**: ohos.permission.SET_WIFI_INFO, ohos.permission.SET_WIFI_CONFIG, and ohos.permissio.MANAGE_WIFI_CONNECTION (available only to system applications) +**Required permissions**: ohos.permission.SET_WIFI_INFO, ohos.permission.SET_WIFI_CONFIG, and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| Configuration of the WLAN to connect. | **Error codes** @@ -864,13 +863,13 @@ Connects to the specified network. If the device is already connected to a hotsp For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| | 2501001 | Wifi is closed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { let config = { @@ -903,12 +902,12 @@ Disconnects the network. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { wifiManager.disconnect(); @@ -929,34 +928,34 @@ Obtains the WLAN signal level. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| rssi | number | Yes| RSSI of the hotspot, in dBm.| -| band | number | Yes| Frequency band of the WLAN AP.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | rssi | number | Yes| RSSI of the hotspot, in dBm.| + | band | number | Yes| Frequency band of the WLAN AP.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| number | Signal level obtained. The value range is [0, 4].| + | **Type**| **Description**| + | -------- | -------- | + | number | Signal level obtained. The value range is [0, 4].| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { let rssi = 0; let band = 0; let level = wifiManager.getSignalLevel(rssi,band); - console.info("lelvel:" + JSON.stringify(lelvel)); + console.info("level:" + JSON.stringify(level)); }catch(error){ console.error("failed:" + JSON.stringify(error)); } @@ -975,8 +974,8 @@ Obtains WLAN connection information. This API uses a promise to return the resul **Return value** -| Type| Description| -| -------- | -------- | + | Type| Description| + | -------- | -------- | | Promise<[WifiLinkedInfo](#wifilinkedinfo)> | Promise used to return the WLAN connection information obtained.| **Error codes** @@ -984,7 +983,7 @@ Obtains WLAN connection information. This API uses a promise to return the resul For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| | 2501001 | Wifi is closed.| @@ -1000,24 +999,24 @@ Obtains WLAN connection information. This API uses an asynchronous callback to r **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<[WifiLinkedInfo](#wifilinkedinfo)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the WLAN connection information obtained. If **err** is not **0**, an error has occurred.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiLinkedInfo](#wifilinkedinfo)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the WLAN connection information obtained. If **err** is not **0**, an error has occurred.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| | 2501001 | Wifi is closed.| **Example** - ```js - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; - wifi.getLinkedInfo((err, data) => { + wifiManager.getLinkedInfo((err, data) => { if (err) { console.error("get linked info error"); return; @@ -1025,12 +1024,12 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco console.info("get wifi linked info: " + JSON.stringify(data)); }); - wifi.getLinkedInfo().then(data => { + wifiManager.getLinkedInfo().then(data => { console.info("get wifi linked info: " + JSON.stringify(data)); }).catch(error => { console.info("get linked info error"); }); - ``` +``` ## WifiLinkedInfo9+ @@ -1104,24 +1103,6 @@ Enumerates the supplicant states. | UNINITIALIZED | 10 | The supplicant failed to set up the connection.| | INVALID | 11 | Invalid value.| -## SuppState10+ - -Enumerates the Wi-Fi standards. - -**System capability**: SystemCapability.Communication.WiFi.STA - -| Name| Value| Description| -| -------- | -------- | -------- | -| WIFI_STANDARD_UNDEFINED | 0 | Undefined| -| WIFI_STANDARD_11A | 1 | 802.11a| -| WIFI_STANDARD_11B | 2 | 802.11b| -| WIFI_STANDARD_11G | 3 | 802.11g| -| WIFI_STANDARD_11N | 4 | 802.11n| -| WIFI_STANDARD_11AC | 5 | 802.11ac| -| WIFI_STANDARD_11AX | 6 | 802.11ax| -| WIFI_STANDARD_11AD | 7 | 802.11ad| - - ## wifi.isConnected9+ isConnected(): boolean @@ -1134,21 +1115,21 @@ Checks whether the WLAN is connected. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the WLAN is connected; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the WLAN is connected; returns **false** otherwise.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { let ret = wifiManager.isConnected(); @@ -1173,9 +1154,9 @@ Obtains the features supported by this device. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| number | Feature value. | + | **Type**| **Description**| + | -------- | -------- | + | number | Feature value. | **Feature IDs** @@ -1197,12 +1178,12 @@ Obtains the features supported by this device. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2401000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { let ret = wifiManager.getSupportedFeatures(); @@ -1226,27 +1207,27 @@ Checks whether the device supports the specified WLAN feature. **Parameters** -| **Name**| **Type**| Mandatory| **Description**| -| -------- | -------- | -------- | -------- | -| featureId | number | Yes| Feature ID.| + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | featureId | number | Yes| Feature ID.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the feature is supported; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the feature is supported; returns **false** otherwise.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2401000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { let featureId = 0; @@ -1272,21 +1253,21 @@ Obtains the device MAC address. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| string[] | MAC address obtained.| + | **Type**| **Description**| + | -------- | -------- | + | string[] | MAC address obtained.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { let ret = wifiManager.getDeviceMacAddress(); @@ -1309,21 +1290,21 @@ Obtains IP information. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| [IpInfo](#ipinfo9) | IP information obtained.| + | **Type**| **Description**| + | -------- | -------- | + | [IpInfo](#ipinfo9) | IP information obtained.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { let info = wifiManager.getIpInfo(); @@ -1362,21 +1343,21 @@ Obtains the country code. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| string | Country code obtained.| + | **Type**| **Description**| + | -------- | -------- | + | string | Country code obtained.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2401000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { let code = wifiManager.getCountryCode(); @@ -1403,13 +1384,13 @@ Re-associates with the network. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| | 2501001 | Wifi is closed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { wifiManager.reassociate(); @@ -1435,13 +1416,13 @@ Reconnects to the network. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| | 2501001 | Wifi is closed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { wifiManager.reconnect(); @@ -1464,21 +1445,21 @@ Obtains network configuration. **Return value** -| **Type**| **Description**| -| -------- | -------- | -|  Array<[WifiDeviceConfig](#wifideviceconfig)> | Array of network configuration obtained.| + | **Type**| **Description**| + | -------- | -------- | + |  Array<[WifiDeviceConfig](#wifideviceconfig)> | Array of network configuration obtained.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { let configs = wifiManager.getDeviceConfigs(); @@ -1502,27 +1483,27 @@ Updates network configuration. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| New WLAN configuration.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| number | ID of the updated network configuration. The value **-1** indicates that the operation has failed.| + | **Type**| **Description**| + | -------- | -------- | + | number | ID of the updated network configuration. The value **-1** indicates that the operation has failed.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { let config = { @@ -1551,8 +1532,8 @@ Disables network configuration. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | | netId | number | Yes| ID of the network configuration to disable.| **Error codes** @@ -1560,12 +1541,12 @@ Disables network configuration. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { let netId = 0; @@ -1592,12 +1573,12 @@ Removes the configuration of all networks. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { wifiManager.removeAllDeviceConfigs(); @@ -1620,21 +1601,21 @@ Removes the specified network configuration. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| networkId | number | Yes| ID of the network configuration to remove.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | networkId | number | Yes| ID of the network configuration to remove.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { let id = 0; @@ -1656,51 +1637,67 @@ Checks whether the current frequency band is supported. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| bandType | WifiBandType | Yes| Wi-Fi band type.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | bandType | WifiBandType | Yes| Wi-Fi band type.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { let type = 0; - boolean isBandTypeSupported = wifiManager.isBandTypeSupported(type); + let isBandTypeSupported = wifiManager.isBandTypeSupported(type); console.info("isBandTypeSupported:" + isBandTypeSupported); }catch(error){ console.error("failed:" + JSON.stringify(error)); } ``` -## WifiBandType 10+ +## wifi.get5GChannelList10+ -Enumerates the Wi-Fi band types. +get5GChannelList(): Array<number> + +Obtains the list of 5 GHz channels supported by this device. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG **System capability**: SystemCapability.Communication.WiFi.STA -| Name| Value| Description| -| -------- | -------- | -------- | -| WIFI_BAND_NONE | 0 | Undefined| -| WIFI_BAND_2G | 1 | 2 GHz| -| WIFI_BAND_5G | 2 | 5 GHz| -| WIFI_BAND_6G | 3 | 6 GHz| -| WIFI_BAND_60G | 4 | 60 GHz| +**Error codes** +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -## wifi.get5GChannelList10+ +| **ID**| **Error Message**| + | -------- | -------- | +| 2501000 | Operation failed.| -get5GChannelList(): Array<number> +**Example** +```js + import wifiManager from '@ohos.wifiManager'; -Obtains the list of 5 GHz channels supported by this device. + try { + let channelList = wifiManager.get5GChannelList(); + console.info("channelList:" + JSON.stringify(channelList)); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` +## wifi.getDisconnectedReason10+ + +getDisconnectedReason(): DisconnectedReason + +Obtains the reason of the latest disconnection. **System API**: This is a system API. @@ -1713,21 +1710,41 @@ Obtains the list of 5 GHz channels supported by this device. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| + | -------- | -------- | +| 2601000 | Operation failed.| + +**Return value** + +| **Type**| **Description**| | -------- | -------- | -| 2501000 | Operation failed.| +| DisconnectedReason | Returns the reason of the latest disconnection obtained.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { - let channelList = wifiManager.get5GChannelList(); - console.info("channelList:" + JSON.stringify(channelList)); + let disconnectedReason = wifiManager.getDisconnectedReason(); + console.info("disconnectedReason:" + disconnectedReason); }catch(error){ console.error("failed:" + JSON.stringify(error)); } ``` +## DisconnectedReason 10+ + +Enumerates the Wi-Fi disconnection reasons. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| Name| Value| Description| +| -------- | -------- | -------- | +| DISC_REASON_DEFAULT | 0 | Default reason.| +| DISC_REASON_WRONG_PWD | 1 | Incorrect password.| +| DISC_REASON_CONNECTION_FULL | 2 | The number of connections to the router has reached the limit.| + ## wifi.enableHotspot9+ enableHotspot(): void @@ -1745,12 +1762,12 @@ Enables this hotspot. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2601000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { wifiManager.enableHotspot(); @@ -1776,12 +1793,12 @@ Disables this hotspot. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2601000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { wifiManager.disableHotspot(); @@ -1804,21 +1821,21 @@ Checks whether the hotspot supports dual band. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the hotspot supports dual band; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the hotspot supports dual band; returns **false** otherwise.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2601000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { let ret = wifiManager.isHotspotDualBandSupported(); @@ -1842,21 +1859,21 @@ Checks whether this hotspot is active. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the hotspot is active; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the hotspot is active; returns **false** otherwise.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2601000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { let ret = wifiManager.isHotspotActive(); @@ -1880,21 +1897,21 @@ Sets hotspot configuration. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| config | [HotspotConfig](#hotspotconfig9) | Yes| Hotspot configuration to set.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [HotspotConfig](#hotspotconfig9) | Yes| Hotspot configuration to set.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2601000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { let config = { @@ -1943,21 +1960,21 @@ Obtains hotspot configuration. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| [HotspotConfig](#hotspotconfig9) | Hotspot configuration obtained.| + | **Type**| **Description**| + | -------- | -------- | + | [HotspotConfig](#hotspotconfig9) | Hotspot configuration obtained.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2601000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { let config = wifiManager.getHotspotConfig(); @@ -1975,27 +1992,27 @@ Obtains information about the connected stations. **System API**: This is a system API. -**Required permissions**: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, ohos.permission.APPROXIMATELY_LOCATION, and ohos.permission.MANAGE_WIFI_HOTSPOT (available only to system applications) +**Required permissions**: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, ohos.permission.APPROXIMATELY_LOCATION, and ohos.permission.MANAGE_WIFI_HOTSPOT (available only to system applications) **System capability**: SystemCapability.Communication.WiFi.AP.Core **Return value** -| **Type**| **Description**| -| -------- | -------- | -|  Array<[StationInfo](#stationinfo9)> | Connected stations obtained.| + | **Type**| **Description**| + | -------- | -------- | + |  Array<[StationInfo](#stationinfo9)> | Connected stations obtained.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2601000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { let stations = wifiManager.getHotspotStations(); @@ -2032,8 +2049,8 @@ Obtains P2P link information. This API uses a promise to return the result. **Return value** -| Type| Description| -| -------- | -------- | + | Type| Description| + | -------- | -------- | | Promise<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | Promise used to return the P2P link information obtained.| **Error codes** @@ -2041,14 +2058,14 @@ Obtains P2P link information. This API uses a promise to return the result. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2801000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; - wifi.getP2pLinkedInfo((err, data) => { + wifiManager.getP2pLinkedInfo((err, data) => { if (err) { console.error("get p2p linked info error"); return; @@ -2056,7 +2073,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco console.info("get wifi p2p linked info: " + JSON.stringify(data)); }); - wifi.getP2pLinkedInfo().then(data => { + wifiManager.getP2pLinkedInfo().then(data => { console.info("get wifi p2p linked info: " + JSON.stringify(data)); }); ``` @@ -2099,9 +2116,9 @@ Obtains P2P link information. This API uses an asynchronous callback to return t **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the P2P link information. If **err** is not **0**, an error has occurred.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the P2P link information. If **err** is not **0**, an error has occurred.| ## wifi.getCurrentP2pGroup9+ @@ -2116,8 +2133,8 @@ Obtains the current P2P group information. This API uses a promise to return the **Return value** -| Type| Description| -| -------- | -------- | + | Type| Description| + | -------- | -------- | | Promise<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> | Promise used to return the P2P group information obtained.| **Error codes** @@ -2125,7 +2142,7 @@ Obtains the current P2P group information. This API uses a promise to return the For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2801000 | Operation failed.| ## wifi.getCurrentP2pGroup9+ @@ -2140,23 +2157,23 @@ Obtains the current P2P group information. This API uses an asynchronous callbac **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2801000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; - wifi.getCurrentP2pGroup((err, data) => { + wifiManager.getCurrentP2pGroup((err, data) => { if (err) { console.error("get current P2P group error"); return; @@ -2164,7 +2181,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco console.info("get current P2P group: " + JSON.stringify(data)); }); - wifi.getCurrentP2pGroup().then(data => { + wifiManager.getCurrentP2pGroup().then(data => { console.info("get current P2P group: " + JSON.stringify(data)); }); ``` @@ -2181,16 +2198,16 @@ Obtains the peer device list in the P2P connection. This API uses a promise to r **Return value** -| Type| Description| -| -------- | -------- | -| Promise<[WifiP2pDevice[]](#wifip2pdevice9)> | Promise used to return the peer device list.| + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pDevice[]](#wifip2pdevice9)> | Promise used to return the peer device list.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2801000 | Operation failed.| ## wifi.getP2pPeerDevices9+ @@ -2205,23 +2222,23 @@ Obtains the peer device list in the P2P connection. This API uses an asynchronou **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<[WifiP2pDevice[]](#wifip2pdevice9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the peer device list obtained. If **err** is not **0**, an error has occurred.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pDevice[]](#wifip2pdevice9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the peer device list obtained. If **err** is not **0**, an error has occurred.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2801000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; - wifi.getP2pPeerDevices((err, data) => { + wifiManager.getP2pPeerDevices((err, data) => { if (err) { console.error("get P2P peer devices error"); return; @@ -2229,7 +2246,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco console.info("get P2P peer devices: " + JSON.stringify(data)); }); - wifi.getP2pPeerDevices().then(data => { + wifiManager.getP2pPeerDevices().then(data => { console.info("get P2P peer devices: " + JSON.stringify(data)); }); ``` @@ -2276,16 +2293,16 @@ Obtains the local device information in the P2P connection. This API uses a prom **Return value** -| Type| Description| -| -------- | -------- | -| Promise<[WifiP2pDevice](#wifip2pdevice9)> | Promise used to return the local device information obtained.| + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pDevice](#wifip2pdevice9)> | Promise used to return the local device information obtained.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2801000 | Operation failed.| ## wifi.getP2pLocalDevice9+ @@ -2300,17 +2317,19 @@ Obtains the local device information in the P2P connection. This API uses an asy **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<[WifiP2pDevice](#wifip2pdevice9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the local device information obtained. If **err** is not **0**, an error has occurred.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pDevice](#wifip2pdevice9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the local device information obtained. If **err** is not **0**, an error has occurred.| + +**Error codes** | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2801000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; wifiManager.getP2pLocalDevice((err, data) => { if (err) { @@ -2320,7 +2339,7 @@ Obtains the local device information in the P2P connection. This API uses an asy console.info("get P2P local device: " + JSON.stringify(data)); }); - wifi.getP2pLocalDevice().then(data => { + wifiManager.getP2pLocalDevice().then(data => { console.info("get P2P local device: " + JSON.stringify(data)); }); ``` @@ -2337,21 +2356,21 @@ Creates a P2P group. **Parameters** -| **Name**| **Type**| Mandatory| **Description**| -| -------- | -------- | -------- | -------- | -| config | [WifiP2PConfig](#wifip2pconfig9) | Yes| Group configuration.| + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiP2PConfig](#wifip2pconfig9) | Yes| Group configuration.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2801000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { let config = { @@ -2411,12 +2430,12 @@ Removes this P2P group. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2801000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { wifiManager.removeP2pGroup(); @@ -2437,25 +2456,25 @@ Sets up a P2P connection. **Parameters** -| **Name**| **Type**| Mandatory| **Description**| -| -------- | -------- | -------- | -------- | -| config | [WifiP2PConfig](#wifip2pconfig9) | Yes| P2P group configuration.| + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiP2PConfig](#wifip2pconfig9) | Yes| P2P group configuration.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2801000 | Operation failed.| **Example** - ```js - import wifi from '@ohos.wifi'; +```js + import wifiManager from '@ohos.wifiManager'; var recvP2pConnectionChangeFunc = result => { console.info("p2p connection change receive event: " + JSON.stringify(result)); - wifi.getP2pLinkedInfo((err, data) => { + wifiManager.getP2pLinkedInfo((err, data) => { if (err) { console.error('failed to get getP2pLinkedInfo: ' + JSON.stringify(err)); return; @@ -2463,16 +2482,16 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco console.info("get getP2pLinkedInfo: " + JSON.stringify(data)); }); } - wifi.on("p2pConnectionChange", recvP2pConnectionChangeFunc); + wifiManager.on("p2pConnectionChange", recvP2pConnectionChangeFunc); var recvP2pDeviceChangeFunc = result => { console.info("p2p device change receive event: " + JSON.stringify(result)); } - wifi.on("p2pDeviceChange", recvP2pDeviceChangeFunc); + wifiManager.on("p2pDeviceChange", recvP2pDeviceChangeFunc); var recvP2pPeerDeviceChangeFunc = result => { console.info("p2p peer device change receive event: " + JSON.stringify(result)); - wifi.getP2pPeerDevices((err, data) => { + wifiManager.getP2pPeerDevices((err, data) => { if (err) { console.error('failed to get peer devices: ' + JSON.stringify(err)); return; @@ -2489,17 +2508,17 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco "groupName":"", "goBand":0, } - wifi.p2pConnect(config); + wifiManager.p2pConnect(config); } } }); } - wifi.on("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); + wifiManager.on("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); var recvP2pPersistentGroupChangeFunc = () => { console.info("p2p persistent group change receive event"); - wifi.getCurrentGroup((err, data) => { + wifiManager.getCurrentP2pGroup((err, data) => { if (err) { console.error('failed to get current group: ' + JSON.stringify(err)); return; @@ -2507,14 +2526,14 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco console.info("get current group: " + JSON.stringify(data)); }); } - wifi.on("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); + wifiManager.on("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); - setTimeout(function() {wifi.off("p2pConnectionChange", recvP2pConnectionChangeFunc);}, 125 * 1000); - setTimeout(function() {wifi.off("p2pDeviceChange", recvP2pDeviceChangeFunc);}, 125 * 1000); - setTimeout(function() {wifi.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc);}, 125 * 1000); - setTimeout(function() {wifi.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc);}, 125 * 1000); - console.info("start discover devices -> " + wifi.startP2pDiscoverDevices()); - ``` + setTimeout(function() {wifiManager.off("p2pConnectionChange", recvP2pConnectionChangeFunc);}, 125 * 1000); + setTimeout(function() {wifiManager.off("p2pDeviceChange", recvP2pDeviceChangeFunc);}, 125 * 1000); + setTimeout(function() {wifiManager.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc);}, 125 * 1000); + setTimeout(function() {wifiManager.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc);}, 125 * 1000); + console.info("start discover devices -> " + wifiManager.startDiscoverP2pDevices()); +``` ## wifi.p2pCancelConnect9+ @@ -2531,12 +2550,12 @@ Cancels this P2P connection. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2801000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { wifiManager.p2pCancelConnect(); @@ -2560,12 +2579,12 @@ Starts to discover devices. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2801000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { wifiManager.startDiscoverP2pDevices(); @@ -2589,12 +2608,12 @@ Stops discovering devices. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2801000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { wifiManager.stopDiscoverP2pDevices(); @@ -2618,21 +2637,21 @@ Deletes a persistent group. **Parameters** -| **Name**| **Type**| Mandatory| **Description**| -| -------- | -------- | -------- | -------- | -| netId | number | Yes| ID of the group to delete.| + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | netId | number | Yes| ID of the group to delete.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2801000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { let netId = 0; @@ -2656,21 +2675,21 @@ Obtains information about all P2P groups. This API uses a promise to return the **Return value** -| Type| Description| -| -------- | -------- | -| Promise< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> > | Promise used to return the group information obtained.| + | Type| Description| + | -------- | -------- | + | Promise< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> > | Promise used to return the group information obtained.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2801000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; wifiManager.getP2pGroups((err, data) => { if (err) { @@ -2680,7 +2699,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco console.info("get P2P groups: " + JSON.stringify(data)); }); - wifi.getP2pGroups().then(data => { + wifiManager.getP2pGroups().then(data => { console.info("get P2P groups: " + JSON.stringify(data)); }); @@ -2719,16 +2738,16 @@ Obtains information about all P2P groups. This API uses an asynchronous callback **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo9)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo9)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2801000 | Operation failed.| ## wifi.setP2pDeviceName9+ @@ -2745,25 +2764,25 @@ Sets the device name. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| devName | string | Yes| Device name to set.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | devName | string | Yes| Device name to set.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2801000 | Operation failed.| **Example** -``` - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; try { let name = "****"; - wifiManager.setP2pDeviceName(netId); + wifiManager.setP2pDeviceName(name); }catch(error){ console.error("failed:" + JSON.stringify(error)); } @@ -2781,17 +2800,17 @@ Registers the WLAN state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **wifiStateChange**.| -| callback | Callback<number> | Yes| Callback invoked to return the WLAN state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the WLAN state.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| **WLAN states** @@ -2816,9 +2835,9 @@ Unregisters the WLAN state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **wifiStateChange**.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiStateChange**.| | callback | Callback<number> | No| Callback for the WLAN state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Error codes** @@ -2826,23 +2845,23 @@ Unregisters the WLAN state change events. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| **Example** - ```js - import wifi from '@ohos.wifi'; +```js + import wifiManager from '@ohos.wifiManager'; var recvPowerNotifyFunc = result => { console.info("Receive power state change event: " + result); } // Register an event. - wifi.on("wifiStateChange", recvPowerNotifyFunc); + wifiManager.on("wifiStateChange", recvPowerNotifyFunc); // Unregister an event. - wifi.off("wifiStateChange", recvPowerNotifyFunc); - ``` + wifiManager.off("wifiStateChange", recvPowerNotifyFunc); +``` ## wifi.on('wifiConnectionChange')9+ @@ -2857,10 +2876,10 @@ Registers the WLAN connection state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **wifiConnectionChange**.| -| callback | Callback<number> | Yes| Callback invoked to return the WLAN connection state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiConnectionChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the WLAN connection state.| **WLAN connection states** @@ -2874,7 +2893,7 @@ Registers the WLAN connection state change events. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| ## wifi.off('wifiConnectionChange')9+ @@ -2889,9 +2908,9 @@ Unregisters the WLAN connection state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **wifiConnectionChange**.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiConnectionChange**.| | callback | Callback<number> | No| Callback for the WLAN connection state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Error codes** @@ -2899,23 +2918,23 @@ Unregisters the WLAN connection state change events. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| **Example** - ```js - import wifi from '@ohos.wifi'; +```js + import wifiManager from '@ohos.wifiManager'; var recvWifiConnectionChangeFunc = result => { console.info("Receive wifi connection change event: " + result); } // Register an event. - wifi.on("wifiConnectionChange", recvWifiConnectionChangeFunc); + wifiManager.on("wifiConnectionChange", recvWifiConnectionChangeFunc); // Unregister an event. - wifi.off("wifiConnectionChange", recvWifiConnectionChangeFunc); - ``` + wifiManager.off("wifiConnectionChange", recvWifiConnectionChangeFunc); +``` ## wifi.on('wifiScanStateChange')9+ @@ -2929,10 +2948,10 @@ Registers the WLAN scan state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **wifiScanStateChange**.| -| callback | Callback<number> | Yes| Callback invoked to return the WLAN scan state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiScanStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the WLAN scan state.| **WLAN scan states** @@ -2946,7 +2965,7 @@ Registers the WLAN scan state change events. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| ## wifi.off('wifiScanStateChange')9+ @@ -2971,23 +2990,23 @@ Unregisters the WLAN scan state change events. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| **Example** - ```js - import wifi from '@ohos.wifi'; +```js + import wifiManager from '@ohos.wifiManager'; var recvWifiScanStateChangeFunc = result => { console.info("Receive Wifi scan state change event: " + result); } // Register an event. - wifi.on("wifiScanStateChange", recvWifiScanStateChangeFunc); + wifiManager.on("wifiScanStateChange", recvWifiScanStateChangeFunc); // Unregister an event. - wifi.off("wifiScanStateChange", recvWifiScanStateChangeFunc); - ``` + wifiManager.off("wifiScanStateChange", recvWifiScanStateChangeFunc); +``` ## wifi.on('wifiRssiChange')9+ @@ -3001,17 +3020,17 @@ Registers the RSSI change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **wifiRssiChange**.| -| callback | Callback<number> | Yes| Callback invoked to return the RSSI, in dBm.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiRssiChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the RSSI, in dBm.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| ## wifi.off('wifiRssiChange')9+ @@ -3026,9 +3045,9 @@ Unregisters the RSSI change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **wifiRssiChange**.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiRssiChange**.| | callback | Callback<number> | No| Callback for the RSSI change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Error codes** @@ -3036,12 +3055,12 @@ Unregisters the RSSI change events. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2501000 | Operation failed.| **Example** - ```js - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; var recvWifiRssiChangeFunc = result => { console.info("Receive wifi rssi change event: " + result); @@ -3052,7 +3071,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco // Unregister an event. wifiManager.off("wifiRssiChange", recvWifiRssiChangeFunc); - ``` +``` ## wifi.on('hotspotStateChange')9+ @@ -3066,10 +3085,10 @@ Registers the hotspot state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **hotspotStateChange**.| -| callback | Callback<number> | Yes| Callback invoked to return the hotspot state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **hotspotStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the hotspot state.| **Hotspot states** @@ -3085,7 +3104,7 @@ Registers the hotspot state change events. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2601000 | Operation failed.| ## wifi.off('hotspotStateChange')9+ @@ -3100,9 +3119,9 @@ Unregisters the hotspot state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **hotspotStateChange**.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **hotspotStateChange**.| | callback | Callback<number> | No| Callback for the hotspot state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Error codes** @@ -3110,12 +3129,12 @@ Unregisters the hotspot state change events. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2601000 | Operation failed.| **Example** - ```js - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; var recvHotspotStateChangeFunc = result => { console.info("Receive hotspot state change event: " + result); @@ -3126,7 +3145,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco // Unregister an event. wifiManager.off("hotspotStateChange", recvHotspotStateChangeFunc); - ``` +``` ## wifi.on('p2pStateChange')9+ @@ -3140,10 +3159,10 @@ Registers the P2P state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pStateChange**.| -| callback | Callback<number> | Yes| Callback invoked to return the P2P state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the P2P state.| **P2P states** @@ -3160,7 +3179,7 @@ Registers the P2P state change events. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2801000 | Operation failed.| ## wifi.off('p2pStateChange')9+ @@ -3175,9 +3194,9 @@ Unregisters the P2P state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pStateChange**.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pStateChange**.| | callback | Callback<number> | No| Callback for the P2P state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Error codes** @@ -3185,12 +3204,12 @@ Unregisters the P2P state change events. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2801000 | Operation failed.| **Example** - ```js - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; var recvP2pStateChangeFunc = result => { console.info("Receive p2p state change event: " + result); @@ -3201,9 +3220,9 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco // Unregister an event. wifiManager.off("p2pStateChange", recvP2pStateChangeFunc); - ``` +``` - ## wifi.on('p2pConnectionChange')9+ +## wifi.on('p2pConnectionChange')9+ on(type: "p2pConnectionChange", callback: Callback<WifiP2pLinkedInfo>): void @@ -3215,9 +3234,9 @@ Registers the P2P connection state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pConnectionChange**.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pConnectionChange**.| | callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | Yes| Callback invoked to return the P2P connection state.| **Error codes** @@ -3225,7 +3244,7 @@ Registers the P2P connection state change events. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2801000 | Operation failed.| ## wifi.off('p2pConnectionChange')9+ @@ -3240,9 +3259,9 @@ Unregisters the P2P connection state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pConnectionChange**.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pConnectionChange**.| | callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | No| Callback for the P2P connection state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Error codes** @@ -3250,12 +3269,12 @@ Unregisters the P2P connection state change events. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2801000 | Operation failed.| **Example** - ```js - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; var recvP2pConnectionChangeFunc = result => { console.info("Receive p2p connection change event: " + result); @@ -3266,7 +3285,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco // Unregister an event. wifiManager.off("p2pConnectionChange", recvP2pConnectionChangeFunc); - ``` +``` ## wifi.on('p2pDeviceChange')9+ @@ -3280,9 +3299,9 @@ Registers the P2P device state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pDeviceChange**.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDeviceChange**.| | callback | Callback<[WifiP2pDevice](#wifip2pdevice9)> | Yes| Callback invoked to return the P2P device state.| **Error codes** @@ -3290,7 +3309,7 @@ Registers the P2P device state change events. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2801000 | Operation failed.| ## wifi.off('p2pDeviceChange')9+ @@ -3305,9 +3324,9 @@ Unregisters the P2P device state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pDeviceChange**.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDeviceChange**.| | callback | Callback<[WifiP2pDevice](#wifip2pdevice9)> | No| Callback for the P2P device state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Error codes** @@ -3315,12 +3334,12 @@ Unregisters the P2P device state change events. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2801000 | Operation failed.| **Example** - ```js - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; var recvP2pDeviceChangeFunc = result => { console.info("Receive recv p2p device change event: " + result); @@ -3331,7 +3350,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco // Unregister an event. wifiManager.off("p2pDeviceChange", recvP2pDeviceChangeFunc); - ``` +``` ## wifi.on('p2pPeerDeviceChange')9+ @@ -3345,9 +3364,9 @@ Registers the P2P peer device state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| | callback | Callback<[WifiP2pDevice[]](#wifip2pdevice9)> | Yes| Callback invoked to return the P2P peer device state.| **Error codes** @@ -3355,7 +3374,7 @@ Registers the P2P peer device state change events. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2801000 | Operation failed.| ## wifi.off('p2pPeerDeviceChange')9+ @@ -3370,9 +3389,9 @@ Unregisters the P2P peer device state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| | callback | Callback<[WifiP2pDevice[]](#wifip2pdevice9)> | No| Callback for the P2P peer device state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Error codes** @@ -3380,12 +3399,12 @@ Unregisters the P2P peer device state change events. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2801000 | Operation failed.| **Example** - ```js - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; var recvP2pPeerDeviceChangeFunc = result => { console.info("Receive recv p2p peer device change event: " + result); @@ -3396,7 +3415,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco // Unregister an event. wifiManager.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); - ``` +``` ## wifi.on('p2pPersistentGroupChange')9+ @@ -3410,9 +3429,9 @@ Registers the P2P persistent group state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| | callback | Callback<void> | Yes| Callback invoked to return the P2P persistent group state.| **Error codes** @@ -3420,7 +3439,7 @@ Registers the P2P persistent group state change events. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2801000 | Operation failed.| ## wifi.off('p2pPersistentGroupChange')9+ @@ -3435,9 +3454,9 @@ Unregisters the P2P persistent group state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| | callback | Callback<void> | No| Callback for the P2P persistent group state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Error codes** @@ -3445,12 +3464,12 @@ Unregisters the P2P persistent group state change events. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2801000 | Operation failed.| **Example** - ```js - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; var recvP2pPersistentGroupChangeFunc = result => { console.info("Receive recv p2p persistent group change event: " + result); @@ -3461,7 +3480,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco // Unregister an event. wifiManager.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); - ``` +``` ## wifi.on('p2pDiscoveryChange')9+ @@ -3475,10 +3494,10 @@ Registers the P2P device discovery state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| -| callback | Callback<number> | Yes| Callback invoked to return the P2P device discovery state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the P2P device discovery state.| **P2P discovered device states** @@ -3492,7 +3511,7 @@ Registers the P2P device discovery state change events. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2801000 | Operation failed.| ## wifi.off('p2pDiscoveryChange')9+ @@ -3507,9 +3526,9 @@ Unregisters the P2P device discovery state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| | callback | Callback<number> | No| Callback for the P2P device discovery state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Error codes** @@ -3517,12 +3536,12 @@ Unregisters the P2P device discovery state change events. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **ID**| **Error Message**| -| -------- | -------- | + | -------- | -------- | | 2801000 | Operation failed.| **Example** - ```js - import wifi from '@ohos.wifiManager'; +```js + import wifiManager from '@ohos.wifiManager'; var recvP2pDiscoveryChangeFunc = result => { console.info("Receive recv p2p discovery change event: " + result); @@ -3533,4 +3552,4 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco // Unregister an event. wifiManager.off("p2pDiscoveryChange", recvP2pDiscoveryChangeFunc); - ``` +``` diff --git a/en/application-dev/reference/apis/js-apis-wifiManagerExt.md b/en/application-dev/reference/apis/js-apis-wifiManagerExt.md index 4d9f1c83dd5fb5739f63520ce52c132c514d0fa7..5dc2721915e3c220beea50f52c00991834dba27e 100644 --- a/en/application-dev/reference/apis/js-apis-wifiManagerExt.md +++ b/en/application-dev/reference/apis/js-apis-wifiManagerExt.md @@ -1,4 +1,4 @@ -# @ohos.wifiManagerExt (WLAN Extension Interface) +# @ohos.wifiManagerExt (WLAN Extension) This **wifiext** module provides WLAN extension interfaces for non-universal products. > **NOTE** @@ -27,8 +27,8 @@ Enables the WLAN hotspot. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| -| -------- | -------- | +| **ID**| **Error Message**| + | -------- | -------- | | 2701000 | Operation failed.| ## wifiext.disableHotspot9+ @@ -45,8 +45,8 @@ Disables the WLAN hotspot. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| -| -------- | -------- | +| **ID**| **Error Message**| + | -------- | -------- | | 2701000 | Operation failed.| ## wifiext.getSupportedPowerMode9+ @@ -61,19 +61,19 @@ Obtains the supported power modes. This API uses a promise to return the result. **Return value** -| Type| Description| -| -------- | -------- | -| Promise<Array<[PowerMode](#powermode)>> | Promise used to return the power modes obtained.| + | Type| Description| + | -------- | -------- | + | Promise<Array<[PowerMode](#powermode)>> | Promise used to return the power modes obtained.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| -| -------- | -------- | +| **ID**| **Error Message**| + | -------- | -------- | | 2701000 | Operation failed.| -## PowerMode +## PowerMode9+ Enumerates the power modes. @@ -98,16 +98,16 @@ Obtains the supported power modes. This API uses an asynchronous callback to ret **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<Array<[PowerMode](#powermode)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the power modes obtained. If **err** is not **0**, an error has occurred.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<Array<[PowerMode](#powermode)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the power modes obtained. If **err** is not **0**, an error has occurred.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| -| -------- | -------- | +| **ID**| **Error Message**| + | -------- | -------- | | 2701000 | Operation failed.| ## wifiext.getPowerMode9+ @@ -122,16 +122,16 @@ Obtains the power mode. This API uses a promise to return the result. **Return value** -| Type| Description| -| -------- | -------- | -| Promise<[PowerMode](#powermode)> | Promise used to return the power modes obtained.| + | Type| Description| + | -------- | -------- | + | Promise<[PowerMode](#powermode)> | Promise used to return the power modes obtained.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| -| -------- | -------- | +| **ID**| **Error Message**| + | -------- | -------- | | 2701000 | Operation failed.| ## wifiext.getPowerMode9+ @@ -146,21 +146,21 @@ Obtains the power mode. This API uses an asynchronous callback to return the res **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<[PowerMode](#powermode)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the power mode obtained. If **err** is not **0**, an error has occurred.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[PowerMode](#powermode)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the power mode obtained. If **err** is not **0**, an error has occurred.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| -| -------- | -------- | +| **ID**| **Error Message**| + | -------- | -------- | | 2701000 | Operation failed.| ## wifiext.setPowerMode9+ -setPowerMode(model: PowerMode) : boolean; +setPowerMode(mode: PowerMode) : void; Sets the power mode. @@ -170,14 +170,14 @@ setPowerMode(model: PowerMode) : boolean; **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| model | [PowerMode](#powermode) | Yes| Power mode to set.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | model | [PowerMode](#powermode) | Yes| Power mode to set.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| -| -------- | -------- | +| **ID**| **Error Message**| + | -------- | -------- | | 2701000 | Operation failed.| diff --git a/en/application-dev/reference/apis/js-apis-wifiext.md b/en/application-dev/reference/apis/js-apis-wifiext.md index 51efac191d9492b2861eb3f42a58082b019b1e3a..fcdc0e4096c12f788f496b2f79dc02d51247a901 100644 --- a/en/application-dev/reference/apis/js-apis-wifiext.md +++ b/en/application-dev/reference/apis/js-apis-wifiext.md @@ -26,9 +26,9 @@ Enables the WLAN hotspot. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifiext.disableHotspot @@ -43,9 +43,9 @@ Disables the WLAN hotspot. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifiext.getSupportedPowerModel @@ -60,9 +60,9 @@ Obtains the supported power models. This API uses a promise to return the result **Return value** -| Type| Description| -| -------- | -------- | -| Promise<Array<[PowerModel](#powermodel)>> | Promise used to return the power models obtained.| + | Type| Description| + | -------- | -------- | + | Promise<Array<[PowerModel](#powermodel)>> | Promise used to return the power models obtained.| ## PowerModel @@ -90,9 +90,9 @@ Obtains the supported power models. This API uses an asynchronous callback to re **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<Array<[PowerModel](#powermodel)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is 0 and **data** is the power models obtained. If **err** is not **0**, an error has occurred.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<Array<[PowerModel](#powermodel)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is 0 and **data** is the power models obtained. If **err** is not **0**, an error has occurred.| ## wifiext.getPowerModel @@ -107,9 +107,9 @@ Obtains the power model. This API uses a promise to return the result. **Return value** -| Type| Description| -| -------- | -------- | -| Promise<[PowerModel](#powermodel)> | Promise used to return the power model obtained.| + | Type| Description| + | -------- | -------- | + | Promise<[PowerModel](#powermodel)> | Promise used to return the power model obtained.| ## wifiext.getPowerModel @@ -124,16 +124,16 @@ Obtains the power model. This API uses an asynchronous callback to return the re **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<[PowerModel](#powermodel)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the power model obtained. If **err** is not **0**, an error has occurred.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[PowerModel](#powermodel)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the power model obtained. If **err** is not **0**, an error has occurred.| ## wifiext.setPowerModel setPowerModel(model: PowerModel) : boolean; -Sets the power model. + Sets the power model. **Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT_EXT @@ -141,12 +141,12 @@ Sets the power model. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| model | [PowerModel](#powermodel) | Yes| Power model to set.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | model | [PowerModel](#powermodel) | Yes| Power model to set.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| diff --git a/en/application-dev/reference/apis/js-apis-window.md b/en/application-dev/reference/apis/js-apis-window.md index 8077e441008b42b79eee1d0ef92856db63a817ab..83ba617046bba8de2547b82015dbfee8ce9be0a7 100644 --- a/en/application-dev/reference/apis/js-apis-window.md +++ b/en/application-dev/reference/apis/js-apis-window.md @@ -54,7 +54,7 @@ Defines the parameters for creating a subwindow or system window. | ---------- | -------------------------- | -- |-----------------------------------------------------------------------------| | name | string | Yes| Name of the window. | | windowType | [WindowType](#windowtype7) | Yes| Type of the window. | -| ctx | [BaseContext](js-apis-inner-application-baseContext.md) | No| Current application context. If no value is passed, no context is used.
You do not need to set this parameter to create a subwindow in the FA model or a system window in the stage model. | +| ctx | [BaseContext](js-apis-inner-application-baseContext.md) | No| Current application context. If no value is passed, no context is used.
You do not need to set this parameter to create a subwindow in the FA model or a system window in the stage model.| | displayId | number | No| ID of the current physical screen. If no value is passed, the default value **-1** is used. The value must be an integer. | | parentId | number | No| ID of the parent window. If no value is passed, the default value **-1** is used. The value must be an integer. | @@ -228,7 +228,7 @@ Describes the window properties. | ------------------------------------- | ------------------------- | ---- | ---- |--------------------------------------------------------------------------------------------------------| | windowRect7+ | [Rect](#rect7) | Yes | Yes | Window size. | | type7+ | [WindowType](#windowtype7) | Yes | Yes | Window type. | -| isFullScreen | boolean | Yes | Yes | Whether the window is displayed in full-screen mode. The default value is **false**. The value **true** means that the window is displayed in full-screen mode, and **false** means the opposite. | +| isFullScreen | boolean | Yes | Yes | Whether the window is displayed in full-screen mode. The default value is **false**. The value **true** means that the window is displayed in full-screen mode, and **false** means the opposite. | | isLayoutFullScreen7+ | boolean | Yes | Yes | Whether the window layout is in full-screen mode (whether the window is immersive). The default value is **false**. The value **true** means that the window is immersive, and **false** means the opposite. | | focusable7+ | boolean | Yes | No | Whether the window can gain focus. The default value is **true**. The value **true** means that the window can gain focus, and **false** means the opposite. | | touchable7+ | boolean | Yes | No | Whether the window is touchable. The default value is **true**. The value **true** means that the window is touchable, and **false** means the opposite. | @@ -261,7 +261,7 @@ Describes the scale parameters. | Name | Type| Readable| Writable| Description | | ------ | -------- | ---- | ---- |--------------------------------------------| -| x | number | No | Yes | Scale factor along the x-axis. The value is a floating point number, and the default value is **1.0**. | +| x | number | No | Yes | Scale factor along the x-axis. The value is a floating point number, and the default value is **1.0**. | | y | number | No | Yes | Scale factor along the y-axis. The value is a floating point number, and the default value is **1.0**. | | pivotX | number | No | Yes | X coordinate of the scale center. The value is a floating point number in the range [0.0, 1.0], and the default value is **0.5**.| | pivotY | number | No | Yes | Y coordinate of the scale center. The value is a floating point number in the range [0.0, 1.0], and the default value is **0.5**.| @@ -276,7 +276,7 @@ Describes the rotation parameters. | Name | Type| Readable| Writable| Description | | ------ | -------- | ---- | ---- |---------------------------------------------| -| x | number | No | Yes | Rotation angle around the x-axis. The value is a floating point number, and the default value is **0.0**. | +| x | number | No | Yes | Rotation angle around the x-axis. The value is a floating point number, and the default value is **0.0**. | | y | number | No | Yes | Rotation angle around the y-axis. The value is a floating point number, and the default value is **0.0**. | | z | number | No | Yes | Rotation angle around the z-axis. The value is a floating point number, and the default value is **0.0**. | | pivotX | number | No | Yes | X coordinate of the rotation center. The value is a floating point number in the range [0.0, 1.0], and the default value is **0.5**.| @@ -790,7 +790,7 @@ try { on(type: 'systemBarTintChange', callback: Callback<SystemBarTintState>): void -Enables listening for properties changes of the status bar and navigation bar. +Subscribes to the property change event of the status bar and navigation bar. **System API**: This is a system API. @@ -819,7 +819,7 @@ try { off(type: 'systemBarTintChange', callback?: Callback<SystemBarTintState >): void -Disables listening for properties changes of the status bar and navigation bar. +Unsubscribes from the property change event of the status bar and navigation bar. **System API**: This is a system API. @@ -830,7 +830,7 @@ Disables listening for properties changes of the status bar and navigation bar. | Name | Type | Mandatory| Description | | -------- | ---------------------------------------------------------- | ---- | ------------------------------------------------------------ | | type | string | Yes | Event type. The value is fixed at **'systemBarTintChange'**, indicating the property change event of the status bar and navigation bar.| -| callback | Callback<[SystemBarTintState](#systembartintstate8)> | No | Callback used to return the properties of the status bar and navigation bar. | +| callback | Callback<[SystemBarTintState](#systembartintstate8)> | No | Callback used to return the properties of the status bar and navigation bar. If a value is passed in, the corresponding subscription is canceled. If no value is passed in, all subscriptions to the specified event are canceled. | **Example** @@ -846,7 +846,7 @@ try { on(type: 'gestureNavigationEnabledChange', callback: Callback<boolean>): void -Enables listening for gesture navigation status changes. +Subscribes to the gesture navigation status change event. **System API**: This is a system API. @@ -875,7 +875,7 @@ try { off(type: 'gestureNavigationEnabledChange', callback?: Callback<boolean>): void -Disables the listening for gesture navigation status changes. +Unsubscribes from the gesture navigation status change event. **System API**: This is a system API. @@ -886,7 +886,7 @@ Disables the listening for gesture navigation status changes. | Name | Type | Mandatory| Description | | -------- | ----------------------- | -- | ------------------------------------------------------------ | | type | string | Yes| Event type. The value is fixed at **'gestureNavigationEnabledChange'**, indicating the gesture navigation status change event.| -| callback | Callback<boolean> | No| Callback function that has been used for registering the listener. If this parameter is passed in, only the listener registered using this callback function is removed; otherwise, all gesture navigation status change listeners are removed.| +| callback | Callback<boolean> | No| Callback function that has been used for registering the listener. If a value is passed in, the corresponding subscription is canceled. If no value is passed in, all subscriptions to the specified event are canceled.| **Example** @@ -2694,7 +2694,7 @@ try { on(type: 'windowSizeChange', callback: Callback<Size>): void -Enables listening for window size changes. +Subscribes to the window size change event. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2721,7 +2721,7 @@ try { off(type: 'windowSizeChange', callback?: Callback<Size>): void -Disables listening for window size changes. +Unsubscribes from the window size change event. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2730,7 +2730,7 @@ Disables listening for window size changes. | Name | Type | Mandatory| Description | | -------- | ----------------------------- | ---- | -------------------------------------------------------- | | type | string | Yes | Event type. The value is fixed at **'windowSizeChange'**, indicating the window size change event.| -| callback | Callback<[Size](#size7)> | No | Callback used to return the window size. | +| callback | Callback<[Size](#size7)> | No | Callback used to return the window size. If a value is passed in, the corresponding subscription is canceled. If no value is passed in, all subscriptions to the specified event are canceled. | **Example** @@ -2746,7 +2746,7 @@ try { on(type: 'avoidAreaChange', callback: Callback<{AvoidAreaType, AvoidArea}>): void -Enables listening for changes to the area where the window cannot be displayed. +Subscribes to the event indicating changes to the area where the window cannot be displayed. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2774,7 +2774,7 @@ try { off(type: 'avoidAreaChange', callback?: Callback<{AvoidAreaType, AvoidArea}>): void -Disables listening for changes to the area where the window cannot be displayed. +Unsubscribes from the event indicating changes to the area where the window cannot be displayed. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2783,7 +2783,7 @@ Disables listening for changes to the area where the window cannot be displayed. | Name | Type | Mandatory | Description | | -------- |-----------------------------------------------------------------------------|-----|------------------------------------| | type | string | Yes | Event type. The value is fixed at **'avoidAreaChange'**, indicating the event of changes to the area where the window cannot be displayed.| -| callback | Callback<{[AvoidAreaType](#avoidareatype7), [AvoidArea](#avoidarea7)}> | No | Callback used to return the area and area type.| +| callback | Callback<{[AvoidAreaType](#avoidareatype7), [AvoidArea](#avoidarea7)}> | No | Callback used to return the area and area type. If a value is passed in, the corresponding subscription is canceled. If no value is passed in, all subscriptions to the specified event are canceled.| **Example** @@ -2799,7 +2799,7 @@ try { on(type: 'keyboardHeightChange', callback: Callback<number>): void -Enables listening for soft keyboard height changes in the input method panel in fixed state. Since API version 10, the input method panel can be set to the fixed or floating state. For details, see [Input Method Service](js-apis-inputmethodengine.md#changeflag10). +Subscribes to the event indicating soft keyboard height changes in the input method panel in fixed state. Since API version 10, the input method panel can be set to the fixed or floating state. For details, see [Input Method Service](js-apis-inputmethodengine.md#changeflag10). **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2826,7 +2826,7 @@ try { off(type: 'keyboardHeightChange', callback?: Callback<number>): void -Disables listening for soft keyboard height changes in the input method panel in fixed state. Since API version 10, the input method panel can be set to the fixed or floating state. For details, see [Input Method Service](js-apis-inputmethodengine.md#changeflag10). +Unsubscribes from the event indicating soft keyboard height changes in the input method panel in fixed state. Since API version 10, the input method panel can be set to the fixed or floating state. For details, see [Input Method Service](js-apis-inputmethodengine.md#changeflag10). **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2835,7 +2835,7 @@ Disables listening for soft keyboard height changes in the input method panel in | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | ------------------------------------------------------------ | | type | string | Yes | Event type. The value is fixed at **'keyboardHeightChange'**, indicating the keyboard height change event.| -| callback | Callback<number> | No | Callback used to return the current keyboard height, which is an integer. | +| callback | Callback<number> | No | Callback used to return the current keyboard height, which is an integer. If a value is passed in, the corresponding subscription is canceled. If no value is passed in, all subscriptions to the specified event are canceled. | **Example** @@ -2851,7 +2851,7 @@ try { on(type: 'touchOutside', callback: Callback<void>): void -Enables listening for click events outside this window. +Subscribes to the click event outside this window. **System API**: This is a system API. @@ -2880,7 +2880,7 @@ try { off(type: 'touchOutside', callback?: Callback<void>): void -Disables listening for click events outside this window. +Unsubscribes from the click event outside this window. **System API**: This is a system API. @@ -2891,7 +2891,7 @@ Disables listening for click events outside this window. | Name | Type | Mandatory| Description | | -------- |----------------------| ---- |--------------------------------------| | type | string | Yes | Event type. The value is fixed at **'touchOutside'**, indicating the click event outside this window.| -| callback | Callback<void> | No | Callback used to return the click event outside this window. | +| callback | Callback<void> | No | Callback used to return the click event outside this window. If a value is passed in, the corresponding subscription is canceled. If no value is passed in, all subscriptions to the specified event are canceled. | **Example** @@ -2907,7 +2907,7 @@ try { on(type: 'screenshot', callback: Callback<void>): void -Subscribes to screenshot events. +Subscribes to the screenshot event. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2934,7 +2934,7 @@ try { off(type: 'screenshot', callback?: Callback<void>): void -Unsubscribes from screenshot events. +Unsubscribes from the screenshot event. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2943,7 +2943,7 @@ Unsubscribes from screenshot events. | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | ------------------------------------------------------------ | | type | string | Yes | Event type. The value is fixed at **'screenshot'**, indicating the screenshot event.| -| callback | Callback<void> | No | Callback invoked when a screenshot event occurs.| +| callback | Callback<void> | No | Callback invoked when a screenshot event occurs. If a value is passed in, the corresponding subscription is canceled. If no value is passed in, all subscriptions to the specified event are canceled.| **Example** @@ -2969,7 +2969,7 @@ try { on(type: 'dialogTargetTouch', callback: Callback<void>): void -Subscribes to click events of the target window in the modal window mode. +Subscribes to the click event of the target window in the modal window mode. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2996,7 +2996,7 @@ try { off(type: 'dialogTargetTouch', callback?: Callback<void>): void -Unsubscribes from click events of the target window in the modal window mode. +Unsubscribes from the click event of the target window in the modal window mode. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -3005,7 +3005,7 @@ Unsubscribes from click events of the target window in the modal window mode. | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | ------------------------------------------------------------ | | type | string | Yes | Event type. The value is fixed at **'dialogTargetTouch'**, indicating the click event of the target window in the modal window mode.| -| callback | Callback<void> | No | Callback invoked when the click event occurs in the target window of the modal window mode.| +| callback | Callback<void> | No | Callback invoked when the click event occurs in the target window of the modal window mode. If a value is passed in, the corresponding subscription is canceled. If no value is passed in, all subscriptions to the specified event are canceled.| **Example** @@ -3021,7 +3021,7 @@ try { on(type: 'windowEvent', callback: Callback<WindowEventType>): void -Enables listening for window lifecycle changes. +Subscribes to the window lifecycle change event. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -3048,7 +3048,7 @@ try { off(type: 'windowEvent', callback?: Callback<WindowEventType >): void -Disables listening for window lifecycle changes. +Unsubscribes from the window lifecycle change event. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -3057,7 +3057,7 @@ Disables listening for window lifecycle changes. | Name | Type | Mandatory| Description | | -------- | ---------------------------------------------------------- | ---- | ------------------------------------------------------------ | | type | string | Yes | Event type. The value is fixed at **'windowEvent'**, indicating the window lifecycle change event.| -| callback | Callback<[WindowEventType](#windoweventtype10)> | No | Callback used to return the window lifecycle state. | +| callback | Callback<[WindowEventType](#windoweventtype10)> | No | Callback used to return the window lifecycle state. If a value is passed in, the corresponding subscription is canceled. If no value is passed in, all subscriptions to the specified event are canceled. | **Example** @@ -4430,7 +4430,7 @@ Blurs this window. | Name| Type | Mandatory| Description | | ------ | ------ | ---- |--------------------------------------------------| -| radius | number | Yes | Radius of the blur. The value is a floating point number greater than or equal to 0.0, and the value **0.0** means that the blur is disabled for the window. | +| radius | number | Yes | Radius of the blur. The value is a floating point number greater than or equal to 0.0, and the value **0.0** means that the blur is disabled for the window.| **Error codes** @@ -4465,7 +4465,7 @@ Blurs the background of this window. | Name| Type | Mandatory| Description | | ------ | ------ | ---- |-------------------------------------------------------| -| radius | number | Yes | Radius of the blur. The value is a floating point number greater than or equal to 0.0, and the value **0.0** means that the blur is disabled for the background of the window. | +| radius | number | Yes | Radius of the blur. The value is a floating point number greater than or equal to 0.0, and the value **0.0** means that the blur is disabled for the background of the window.| **Error codes** @@ -4535,7 +4535,7 @@ Sets the shadow for the window borders. | Name | Type | Mandatory| Description | | ------- | ------ | ---- |-------------------------------------------------------------| -| radius | number | Yes | Radius of the shadow. The value is a floating point number greater than or equal to 0.0, and the value **0.0** means that the shadow is disabled for the window borders. | +| radius | number | Yes | Radius of the shadow. The value is a floating point number greater than or equal to 0.0, and the value **0.0** means that the shadow is disabled for the window borders. | | color | string | No | Color of the shadow. The value is a hexadecimal RGB or ARGB color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**.| | offsetX | number | No | Offset of the shadow along the x-axis, in pixels. The value is a floating point number. | | offsetY | number | No | Offset of the shadow along the y-axis, in pixels. The value is a floating point number. | @@ -4573,7 +4573,7 @@ Sets the radius of the rounded corners for this window. | Name | Type | Mandatory| Description | | ----------- | ------- | ---- |----------------------------------------------------| -| radius | number | Yes | Radius of the rounded corners. The value is a floating point number greater than or equal to 0.0. The value **0.0** means that the window does not use rounded corners. | +| radius | number | Yes | Radius of the rounded corners. The value is a floating point number greater than or equal to 0.0. The value **0.0** means that the window does not use rounded corners.| **Error codes** @@ -4684,7 +4684,7 @@ This API is available only for the main window of the application. The aspect ra | Name | Type | Mandatory| Description | | ------------------ | ------- | ---- |-------------------------------------------| -| ratio | number | Yes | Aspect ratio of the window content layout except border decoration. The value is a floating point number greater than or equal to 0.0. | +| ratio | number | Yes | Aspect ratio of the window content layout except border decoration. The value is a floating point number greater than or equal to 0.0.| **Return value** @@ -4731,7 +4731,7 @@ This API is available only for the main window of the application. The aspect ra | Name | Type | Mandatory| Description | | ------------------ | ------- | ---- |--------------------------------------------| -| ratio | number | Yes | Aspect ratio of the window content layout except border decoration. The value is a floating point number greater than or equal to 0.0. | +| ratio | number | Yes | Aspect ratio of the window content layout except border decoration. The value is a floating point number greater than or equal to 0.0.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** @@ -5426,7 +5426,7 @@ In non-full-screen mode, the status bar and navigation bar are displayed, and th | Name | Type | Mandatory| Description | | ------------ | ------------------------- | ---- | ---------------------------------------------- | -| isFullScreen | boolean | Yes | Whether to set full-screen mode. This setting affects the display of the status bar and navigation bar. The value **true** means to set full-screen mode, and **false** means the opposite. | +| isFullScreen | boolean | Yes | Whether to set full-screen mode. This setting affects the display of the status bar and navigation bar. The value **true** means to set full-screen mode, and **false** means the opposite.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -5449,7 +5449,6 @@ setFullScreen(isFullScreen: boolean): Promise<void> Sets whether the window is in full-screen mode. This API uses a promise to return the result. In full-screen mode, the window is displayed in full screen, and the status bar and navigation bar are not displayed. - In non-full-screen mode, the status bar and navigation bar are displayed, and the window size does not overlap the positions of the status bar and navigation bar. > **NOTE** @@ -5462,7 +5461,7 @@ In non-full-screen mode, the status bar and navigation bar are displayed, and th | Name | Type | Mandatory| Description | | ------------ | ------- | ---- | ---------------------------------------------- | -| isFullScreen | boolean | Yes | Whether to set full-screen mode. This setting affects the display of the status bar and navigation bar. The value **true** means to set full-screen mode, and **false** means the opposite. | +| isFullScreen | boolean | Yes | Whether to set full-screen mode. This setting affects the display of the status bar and navigation bar. The value **true** means to set full-screen mode, and **false** means the opposite.| **Return value** @@ -5837,7 +5836,7 @@ promise.then((data)=> { on(type: 'systemAvoidAreaChange', callback: Callback<AvoidArea>): void -Enables listening for changes to the area where the window cannot be displayed. +Subscribes to the event indicating changes to the area where the window cannot be displayed. > **NOTE** > @@ -5864,7 +5863,7 @@ windowClass.on('systemAvoidAreaChange', (data) => { off(type: 'systemAvoidAreaChange', callback?: Callback<AvoidArea>): void -Disables listening for changes to the area where the window cannot be displayed. +Unsubscribes from the event indicating changes to the area where the window cannot be displayed. > **NOTE** > @@ -5877,7 +5876,7 @@ Disables listening for changes to the area where the window cannot be displayed. | Name | Type | Mandatory| Description | | -------- |------------------------------------------| ---- | ------------------------------------------------------- | | type | string | Yes | Event type. The value is fixed at **'systemAvoidAreaChange'**, indicating the event of changes to the area where the window cannot be displayed.| -| callback | Callback<[AvoidArea](#avoidarea7)> | No | Callback used to return the area. | +| callback | Callback<[AvoidArea](#avoidarea7)> | No | Callback used to return the area. If a value is passed in, the corresponding subscription is canceled. If no value is passed in, all subscriptions to the specified event are canceled. | **Example** @@ -7143,7 +7142,7 @@ export default class EntryAbility extends UIAbility { on(eventType: 'windowStageEvent', callback: Callback<WindowStageEventType>): void -Enables listening for window stage lifecycle changes. +Subscribes to the window stage lifecycle change event. **Model restriction**: This API can be used only in the stage model. @@ -7192,7 +7191,7 @@ export default class EntryAbility extends UIAbility { off(eventType: 'windowStageEvent', callback?: Callback<WindowStageEventType>): void -Disables listening for window stage lifecycle changes. +Unsubscribes from the window stage lifecycle change event. **Model restriction**: This API can be used only in the stage model. @@ -7203,7 +7202,7 @@ Disables listening for window stage lifecycle changes. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | string | Yes | Event type. The value is fixed at **'windowStageEvent'**, indicating the window stage lifecycle change event.| -| callback | Callback<[WindowStageEventType](#windowstageeventtype9)> | No | Callback used to return the window stage lifecycle state. | +| callback | Callback<[WindowStageEventType](#windowstageeventtype9)> | No | Callback used to return the window stage lifecycle state. If a value is passed in, the corresponding subscription is canceled. If no value is passed in, all subscriptions to the specified event are canceled. | **Error codes** diff --git a/en/application-dev/reference/apis/js-apis-worker.md b/en/application-dev/reference/apis/js-apis-worker.md index 7c74cdefcec7c61d2d2731ab64eae2f092a340ec..6d1bff42d490701f87940606d1ae4332b339b260 100644 --- a/en/application-dev/reference/apis/js-apis-worker.md +++ b/en/application-dev/reference/apis/js-apis-worker.md @@ -161,9 +161,9 @@ In the stage model: ### postMessage9+ -postMessage(message: Object, transfer: ArrayBuffer[]): void; +postMessage(message: Object, transfer: ArrayBuffer[]): void -Sends a message to the worker thread. The data type of the message must be sequenceable. For details about the sequenceable data types, see [More Information](#more-information). +Used by the host thread to send a message to the worker thread by transferring object ownership. **System capability**: SystemCapability.Utils.Lang @@ -171,8 +171,8 @@ Sends a message to the worker thread. The data type of the message must be seque | Name | Type | Mandatory| Description | | -------- | ------------- | ---- | ------------------------------------------------------------ | -| message | Object | Yes | Message to be sent to the worker thread. | -| transfer | ArrayBuffer[] | Yes | An **ArrayBuffer** object can be transferred. The value **null** should not be passed in the array.| +| message | Object | Yes | Data to be sent to the worker thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| +| transfer | ArrayBuffer[] | Yes | **ArrayBuffer** instance holding an array of objects for which the ownership is transferred to the worker thread. After the transfer, the objects are available only in the worker thread. The array cannot be null.| **Error codes** @@ -181,7 +181,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco | ID| Error Message | | -------- | ----------------------------------------- | | 10200004 | Worker instance is not running. | -| 10200006 | Serializing an uncaught exception failed. | +| 10200006 | An exception occurred during serialization. | **Example** @@ -196,7 +196,7 @@ workerInstance.postMessage(buffer, [buffer]); postMessage(message: Object, options?: PostMessageOptions): void -Sends a message to the worker thread. The data type of the message must be sequenceable. For details about the sequenceable data types, see [More Information](#more-information). +Used by the host thread to send a message to the worker thread by transferring object ownership or copying data. **System capability**: SystemCapability.Utils.Lang @@ -204,8 +204,8 @@ Sends a message to the worker thread. The data type of the message must be seque | Name | Type | Mandatory| Description | | ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | -| message | Object | Yes | Message to be sent to the worker thread. | -| options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The default value is **undefined**.| +| message | Object | Yes | Data to be sent to the worker thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| +| options | [PostMessageOptions](#postmessageoptions) | No | If this parameter is specified, it functions the same as **ArrayBuffer[]**. Specifically, the ownership of the objects in the array is transferred to the worker thread and becomes unavailable in the host thread. The objects are available only in the worker thread.
If this parameter is not specified, the default value **undefined** is used, and information is transferred to the worker thread by copying data.| **Error codes** @@ -214,7 +214,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco | ID| Error Message | | -------- | ----------------------------------------- | | 10200004 | Worker instance is not running. | -| 10200006 | Serializing an uncaught exception failed. | +| 10200006 | An exception occurred during serialization. | **Example** @@ -617,7 +617,7 @@ workerInstance.dispatchEvent({type:"alert_once", timeStamp:0});// timeStamp is n // The event listener created by on will not be proactively deleted. workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); -// The event listener created by addEventListener will be always valid and will not be proactively deleted. +// The event listener created by addEventListener will not be proactively deleted. workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); @@ -792,7 +792,7 @@ workerInstance.dispatchEvent({type:"alert_once", timeStamp:0});// timeStamp is n // The event listener created by on will not be proactively deleted. workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); -// The event listener created by addEventListener will be always valid and will not be proactively deleted. +// The event listener created by addEventListener will not be proactively deleted. workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); @@ -849,16 +849,16 @@ Implements communication between the worker thread and the host thread. The **po postMessage(messageObject: Object, transfer: ArrayBuffer[]): void; -Sends a message to the host thread from the worker thread. +Used by the worker thread to send a message to the host thread by transferring object ownership. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------- | ---- | ------------------------------------------------------- | -| message | Object | Yes | Message to be sent to the host thread. | -| transfer | ArrayBuffer[] | Yes | An **ArrayBuffer** object can be transferred. The value **null** should not be passed in the array.| +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ------------------------------------------------------------ | +| message | Object | Yes | Data to be sent to the host thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| +| transfer | ArrayBuffer[] | Yes | **ArrayBuffer** instance holding an array of objects for which the ownership is transferred to the host thread. After the transfer, the objects are available only in the host thread. The array cannot be null.| **Error codes** @@ -867,7 +867,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco | ID| Error Message | | -------- | ----------------------------------------- | | 10200004 | Worker instance is not running. | -| 10200006 | Serializing an uncaught exception failed. | +| 10200006 | An exception occurred during serialization. | **Example** @@ -897,7 +897,7 @@ workerPort.onmessage = function(e){ postMessage(messageObject: Object, options?: PostMessageOptions): void -Sends a message to the host thread from the worker thread. +Used by the worker thread to send a message to the host thread by transferring object ownership or copying data. **System capability**: SystemCapability.Utils.Lang @@ -905,8 +905,8 @@ Sends a message to the host thread from the worker thread. | Name | Type | Mandatory| Description | | ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | -| message | Object | Yes | Message to be sent to the host thread. | -| options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The default value is **undefined**.| +| message | Object | Yes | Data to be sent to the host thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| +| options | [PostMessageOptions](#postmessageoptions) | No | If this parameter is specified, it functions the same as **ArrayBuffer[]**. Specifically, the ownership of the objects in the array is transferred to the host thread and becomes unavailable in the worker thread. The objects are available only in the host thread.
If this parameter is not specified, the default value **undefined** is used, and information is transferred to the host thread by copying data.| **Error codes** @@ -915,7 +915,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco | ID| Error Message | | -------- | ----------------------------------------- | | 10200004 | Worker instance is not running. | -| 10200006 | Serializing an uncaught exception failed. | +| 10200006 | An exception occurred during serialization. | **Example** @@ -1256,9 +1256,9 @@ In the stage model: ### postMessage(deprecated) -postMessage(message: Object, transfer: ArrayBuffer[]): void; +postMessage(message: Object, transfer: ArrayBuffer[]): void -Sends a message to the worker thread. The data type of the message must be sequenceable. For details about the sequenceable data types, see [More Information](#more-information). +Used by the host thread to send a message to the worker thread by transferring object ownership. > **NOTE**
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.postMessage9+](#postmessage9) instead. @@ -1267,10 +1267,10 @@ Sends a message to the worker thread. The data type of the message must be seque **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------- | ---- | ----------------------------------------------- | -| message | Object | Yes | Message to be sent to the worker thread. | -| transfer | ArrayBuffer[] | Yes | **ArrayBuffer** instances that can be transferred.| +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ------------------------------------------------------------ | +| message | Object | Yes | Data to be sent to the worker thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| +| transfer | ArrayBuffer[] | Yes | **ArrayBuffer** instance holding an array of objects for which the ownership is transferred to the worker thread. After the transfer, the objects are available only in the worker thread. The array cannot be null.| **Example** @@ -1285,7 +1285,7 @@ workerInstance.postMessage(buffer, [buffer]); postMessage(message: Object, options?: PostMessageOptions): void -Sends a message to the worker thread. The data type of the message must be sequenceable. For details about the sequenceable data types, see [More Information](#more-information). +Used by the host thread to send a message to the worker thread by transferring object ownership or copying data. > **NOTE**
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.postMessage9+](#postmessage9-1) instead. @@ -1296,8 +1296,8 @@ Sends a message to the worker thread. The data type of the message must be seque | Name | Type | Mandatory| Description | | ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | -| message | Object | Yes | Message to be sent to the worker thread. | -| options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The default value is **undefined**.| +| message | Object | Yes | Data to be sent to the worker thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| +| options | [PostMessageOptions](#postmessageoptions) | No | If this parameter is specified, it functions the same as **ArrayBuffer[]**. Specifically, the ownership of the objects in the array is transferred to the worker thread and becomes unavailable in the host thread. The objects are available only in the worker thread.
If this parameter is not specified, the default value **undefined** is used, and information is transferred to the worker thread by copying data.| **Example** @@ -1696,7 +1696,7 @@ Implements communication between the worker thread and the host thread. The **po postMessage(messageObject: Object, transfer: Transferable[]): void; -Sends a message to the host thread from the worker thread. +Used by the worker thread to send a message to the host thread by transferring object ownership. > **NOTE**
> This API is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+.postMessage9+](#postmessage9-2). @@ -1707,14 +1707,14 @@ Sends a message to the host thread from the worker thread. | Name | Type | Mandatory| Description | | ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | -| messageObject | Object | Yes | Message to be sent to the host thread. | +| messageObject | Object | Yes | Data to be sent to the host thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| | transfer| Transferable[] | Yes | Currently, this parameter is not supported. | ### postMessage9+ postMessage(messageObject: Object, transfer: ArrayBuffer[]): void; -Sends a message to the host thread from the worker thread. +Used by the worker thread to send a message to the host thread by transferring object ownership. > **NOTE** > @@ -1724,10 +1724,10 @@ Sends a message to the host thread from the worker thread. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------- | ---- | ----------------------------------------------------- | -| message | Object | Yes | Message to be sent to the host thread. | -| transfer | ArrayBuffer[] | Yes | An **ArrayBuffer** object can be transferred. The value **null** should not be passed in the array.| +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ------------------------------------------------------------ | +| message | Object | Yes | Data to be sent to the host thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| +| transfer | ArrayBuffer[] | Yes | **ArrayBuffer** instance holding an array of objects for which the ownership is transferred to the host thread. After the transfer, the objects are available only in the host thread. The array cannot be null.| **Example** @@ -1756,7 +1756,7 @@ parentPort.onmessage = function(e){ postMessage(messageObject: Object, options?: PostMessageOptions): void -Sends a message to the host thread from the worker thread. +Used by the worker thread to send a message to the host thread by transferring object ownership or copying data. > **NOTE**
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+.postMessage9+](#postmessage9-3). @@ -1767,8 +1767,8 @@ Sends a message to the host thread from the worker thread. | Name | Type | Mandatory| Description | | ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | -| message | Object | Yes | Message to be sent to the host thread. | -| options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The default value is **undefined**.| +| message | Object | Yes | Data to be sent to the host thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| +| options | [PostMessageOptions](#postmessageoptions) | No | If this parameter is specified, it functions the same as **ArrayBuffer[]**. Specifically, the ownership of the objects in the array is transferred to the host thread and becomes unavailable in the worker thread. The objects are available only in the host thread.
If this parameter is not specified, the default value **undefined** is used, and information is transferred to the host thread by copying data.| **Example** @@ -1893,7 +1893,7 @@ parentPort.onmessageerror = function(e) { ## PostMessageOptions -Specifies the object whose ownership needs to be transferred during data transfer. The object must be **ArrayBuffer**. +Defines the object for which the ownership is to be transferred during data transfer. The object must be an **ArrayBuffer** instance. After the ownership is transferred, the object becomes unavailable in the sender and can be used only in the receiver. **System capability**: SystemCapability.Utils.Lang @@ -2091,19 +2091,20 @@ workerPort.onerror = function(e) { ``` ### Memory Model -The worker thread is implemented based on the actor model. In the worker interaction process, the JS main thread can create multiple worker threads, each of which are isolated and transfer data through sequentialization. They complete computing tasks and return the result to the main thread. +The worker thread is implemented based on the actor model. In the worker interaction process, the JS main thread can create multiple worker threads, each of which are isolated and transfer data through serialization. They complete computing tasks and return the result to the main thread. Each actor concurrently processes tasks of the main thread. For each actor, there is a message queue and a single-thread execution module. The message queue receives requests from the main thread and other actors; the single-thread execution module serially processes requests, sends requests to other actors, and creates new actors. These isolated actors use the asynchronous mode and can run concurrently. ### Precautions -- Currently, a maximum of seven workers can co-exist. +- Currently, a maximum of eight workers can co-exist. - In API version 8 and earlier versions, when the number of **Worker** instances exceeds the upper limit, the error "Too many workers, the number of workers exceeds the maximum." is thrown. -- Since API version 9, when the number of **Worker** instances exceeds the upper limit, the business error "Worker initialization failure, the number of workers exceeds the maximum" is thrown. +- Since API version 9, when the number of **Worker** instances exceeds the upper limit, the business error "Worker initialization failure, the number of workers exceeds the maximum." is thrown. - To proactively destroy a worker thread, you can call **terminate()** or **parentPort.close()** of the newly created **Worker** instance. - Since API version 9, if a **Worker** instance in a non-running state (such as destroyed or being destroyed) calls an API, a business error is thrown. - Creating and terminating worker threads consume performance. Therefore, you are advised to manage available workers and reuse them. - Do not use both **new worker.Worker** and **new worker.ThreadWorker** to create a **Worker** project. Otherwise, **Worker** functions abnormally. Since API version 9, you are advised to use [new worker.ThreadWorker](#constructor9). In API version 8 and earlier versions, you are advised to use [new worker.Worker](#constructordeprecated). - When creating a **Worker** project, do not import any UI construction method (such as .ets file) to the worker thread file (for example, **worker.ts** used in this document). Otherwise, the worker module becomes invalid. To check whether any UI construction method has been imported, decompress the generated HAP file, find **worker.js** in the directory where the worker thread is created, and search for the keyword **View** globally. If the keyword exists, a UI construction method has been packaged in **worker.js**. If this is your case, change the directory level of **src** in the statement **import "xxx" from src** in the worker thread file. +- A maximum of 16 MB data can be transferred during inter-thread communication. ## Sample Code > **NOTE**
diff --git a/en/application-dev/reference/apis/js-apis-zlib.md b/en/application-dev/reference/apis/js-apis-zlib.md index 17cecd628287a774ab6070bbc0d40528bb7c108d..c1cd550641f09914fe47fafba4a38b84a03513c0 100644 --- a/en/application-dev/reference/apis/js-apis-zlib.md +++ b/en/application-dev/reference/apis/js-apis-zlib.md @@ -236,7 +236,7 @@ Decompresses a file. This API uses an asynchronous callback to return the result | Name | Type | Mandatory| Description | | ----------------------- | ------------------- | ---- | ------------------------------------------------------------ | | inFile | string | Yes | Path of the file to decompress. The file name extension must be .zip. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md).| -| outFile | string | Yes | Path of the decompressed file. The path must exist in the system. Otherwise, the decompression fails. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md).| +| outFile | string | Yes | Path of the decompressed file. The path must exist in the system. Otherwise, the decompression fails. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md). If a file or folder with the same name already exists in the path, they will be overwritten.| | options | [Options](#options) | Yes | Decompression parameters. | | AsyncCallback<**void**> | callback | No | Callback used to return the result. If the operation is successful, **null** is returned; otherwise, a specific error code is returned. | @@ -259,9 +259,7 @@ import zlib from '@ohos.zlib'; let inFile = '/xx/xxx.zip'; let outFileDir = '/xxx'; let options = { - level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, - memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, - strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY + level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION }; try { @@ -288,7 +286,7 @@ Decompresses a file. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------- | ------------------- | ---- | ------------------------------------------------------------ | | inFile | string | Yes | Path of the file to decompress. The file name extension must be .zip. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md).| -| outFile | string | Yes | Path of the decompressed file. The path must exist in the system. Otherwise, the decompression fails. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md).| +| outFile | string | Yes | Path of the decompressed file. The path must exist in the system. Otherwise, the decompression fails. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md). If a file or folder with the same name already exists in the path, they will be overwritten.| | options | [Options](#options) | Yes | Decompression parameters. | **Error codes** @@ -308,9 +306,7 @@ import zlib from '@ohos.zlib'; let inFile = '/xx/xxx.zip'; let outFileDir = '/xxx'; let options = { - level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, - memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, - strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY + level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION }; try { diff --git a/en/application-dev/reference/arkui-ts/figures/size.png b/en/application-dev/reference/arkui-ts/figures/size.png index b89a721447db8981ebe3fb34bccbfd939dd1f91e..75bd2aeb4314f406b172f8d1c1df4e14b8b106fd 100644 Binary files a/en/application-dev/reference/arkui-ts/figures/size.png and b/en/application-dev/reference/arkui-ts/figures/size.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/slider_2.png b/en/application-dev/reference/arkui-ts/figures/slider_2.png new file mode 100644 index 0000000000000000000000000000000000000000..2e2ae097236ec779751fc65d9e7bf39992c09281 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/slider_2.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/swiper-digit.gif b/en/application-dev/reference/arkui-ts/figures/swiper-digit.gif new file mode 100644 index 0000000000000000000000000000000000000000..2873aa12e2e64ac904f88aef7fa8a48dd70fcd4d Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/swiper-digit.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/swiper-dot.gif b/en/application-dev/reference/arkui-ts/figures/swiper-dot.gif new file mode 100644 index 0000000000000000000000000000000000000000..159d58f9ee979616b60352da34f483010a1ea386 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/swiper-dot.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/swiper.gif b/en/application-dev/reference/arkui-ts/figures/swiper.gif index 692ac1398e1c98217a7466c66b1a3b873165a7ee..bd38d6a7e3283c15269079284432bbace9f20df5 100644 Binary files a/en/application-dev/reference/arkui-ts/figures/swiper.gif and b/en/application-dev/reference/arkui-ts/figures/swiper.gif differ diff --git a/en/application-dev/reference/arkui-ts/ts-appendix-enums.md b/en/application-dev/reference/arkui-ts/ts-appendix-enums.md index 0753b4ab4dc8028e3747f8905b1032f2a099bcfc..db5774afd9e4cda3a3e620f718619d2f2aa547cb 100644 --- a/en/application-dev/reference/arkui-ts/ts-appendix-enums.md +++ b/en/application-dev/reference/arkui-ts/ts-appendix-enums.md @@ -509,6 +509,7 @@ This API is supported in ArkTS widgets. | BACKGROUND_REGULAR | Material that creates a medium shallow depth of field effect. | | BACKGROUND_THICK | Material that creates a high shallow depth of field effect. | | BACKGROUND_ULTRA_THICK | Material that creates the maximum depth of field effect. | +| NONE10+ | No blur. | ## ThemeColorMode10+ @@ -564,3 +565,23 @@ This API is supported in ArkTS widgets. | ------- | ------------------------------------------------------------ | | DEFAULT | Default style. The caret width is fixed at 1.5 vp, and the caret height is subject to the background height and font size of the selected text.| | INLINE | Inline input style. The background height of the selected text is the same as the height of the text box. | + +## ImageSmoothingQuality8+ + +Since API version 9, this API is supported in ArkTS widgets. + +| Name | Description | +| -------- | -------------- | +| low | Low quality.| +| medium | Medium quality.| +| high | High quality.| + +## CanvasDirection8+ + +Since API version 9, this API is supported in ArkTS widgets. + +| Name | Description | +| -------- | -------------- | +| inherit | The text direction is inherited from the **\** component.| +| ltr | The text direction is from left to right.| +| rtl | The text direction is from right to left.| diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-blank.md b/en/application-dev/reference/arkui-ts/ts-basic-components-blank.md index 7ddaa3e007c8403fbd7e3e8f0df85af0ed2bc8a2..1c4ce449e689f1e3f3ec32a4f15c784e7bc26dc5 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-blank.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-blank.md @@ -16,6 +16,11 @@ Not supported Blank(min?: number | string) +Since API version 10: + - On the main axis of the parent container **\**, **\**, or **\**, if the size of the **\** component is not set, the component will be automatically stretched or shrunk; if the size is not set or the container adapts to the size of its child component, the component will not be stretched or shrunk. + - Relationship between **size** and **min** of the **\** component on the main axis: max(min, size). + - On the cross axis of the parent container, if the size of the **\** component is set, the component will not fill up the parent container; if the size is not set, the component will fill up the parent container, following the default **alignSelf** settings **ItemAlign.Stretch**. + Since API version 9, this API is supported in ArkTS widgets. **Parameters** diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md b/en/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md index 369a17a005daa7bbf1951ed25aea0ff635606df0..d2861f650f3ede62450d477ee1904b0e29e17cf2 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md @@ -24,7 +24,8 @@ Since API version 9, this API is supported in ArkTS widgets. | Name| Type| Description| | -------- | -------- | -------- | -| color | [ResourceColor](ts-types.md#resourcecolor) | Foreground color of the **\** component.
Since API version 9, this API is supported in ArkTS widgets.| +| color | [ResourceColor](ts-types.md#resourcecolor) | Foreground color of the **\** component.
Default value: **'#99666666'**
Since API version 9, this API is supported in ArkTS widgets.| +| enableLoading10+ | boolean | Whether to show the loading animation.
Default value: **true**
**NOTE**
The component still takes up space in the layout when the loading animation is not shown.
While the universal attribute **Visibility.Hidden** hides the entire component, including borders and paddings, **enableLoading=false** hides the loading animation only.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-menu.md b/en/application-dev/reference/arkui-ts/ts-basic-components-menu.md index 0136146723cecb5883d6300b006450922d7f2b00..e9667470ccce848f8e67856851b4eaef9100ca1a 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-menu.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-menu.md @@ -24,7 +24,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name | Type | Description | | -------- | ------------------------- | ---------------------------------------------------------------- | -| fontSizedeprecated | [Length](ts-types.md#length) | Font size of the menu text. When **Length** is of the number type, the unit is fp.
This API is deprecated since API version 10. You are advised to use **font** instead.| +| fontSize(deprecated) | [Length](ts-types.md#length) | Font size of the menu text. When **Length** is of the number type, the unit is fp.
This API is deprecated since API version 10. You are advised to use **font** instead.| | font10+ | [Font](ts-types.md#font) | Font style of the menu text.| | fontColor10+ | [ResourceColor](ts-types.md#resourcecolor) | Font color of the menu text.| diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md b/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md index 72b9bb67da9e44ca5298039151dbe5b929ce408d..1ba4a1e5a8798b90e59da638404cfbdcaae94e22 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md @@ -35,19 +35,21 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name | Type | Description | | ----------------------------- | ---------------------------------------- | ---------------------------------------- | | title | [ResourceStr](ts-types.md#resourcestr)10+ \| [CustomBuilder](ts-types.md#custombuilder8)8+ \| [NavigationCommonTitle](#navigationcommontitle)9+ \| [NavigationCustomTitle](#navigationcustomtitle)9+ | Page title.
**NOTE**
When the NavigationCustomTitle type is used to set the height, the **titleMode** attribute does not take effect.
When the title string is too long: (1) If no subtitle is set, the string is scaled down, wrapped in two lines, and then clipped with an ellipsis (...); (2) If a subtitle is set, the subtitle is scaled down and then clipped with an ellipsis (...).| -| subTitledeprecated | string | Subtitle of the page. If this attribute is not set, no subtitle is displayed. This attribute is deprecated since API version 9. You are advised to use **title** instead.| +| subTitle(deprecated) | string | Subtitle of the page. If this attribute is not set, no subtitle is displayed. This attribute is deprecated since API version 9. You are advised to use **title** instead.| | menus | Array<[NavigationMenuItem](#navigationmenuitem)> \| [CustomBuilder](ts-types.md#custombuilder8)8+ | Menu items in the upper right corner of the page. If this parameter is not set, no menu item is displayed. When the value type is Array\<[NavigationMenuItem](#navigationmenuitem)>, the menu shows a maximum of three icons in portrait mode and a maximum of five icons in landscape mode, plus excess icons (if any) under the automatically generated **More** icon.| | titleMode | [NavigationTitleMode](#navigationtitlemode) | Display mode of the page title bar.
Default value: **NavigationTitleMode.Free**| | toolBar | [object](#object) \| [CustomBuilder](ts-types.md#custombuilder8)8+ | Content of the toolbar. If this attribute is not set, no toolbar is displayed.
**items**: items on the toolbar.
**NOTE**
Items are evenly distributed on the toolbar at the bottom. Text and icons are evenly distributed in each content area. If the text is too long, it is scaled down level by level, wrapped in two lines, and then clipped with an ellipsis (...).| | hideToolBar | boolean | Whether to hide the toolbar.
Default value: **false**
**true**: Hide the toolbar.
**false**: Display the toolbar.| | hideTitleBar | boolean | Whether to hide the title bar.
Default value: **false**
**true**: Hide the title bar.
**false**: Display the title bar.| -| hideBackButton | boolean | Whether to hide the back button.
Default value: **false**
**true**: Hide the back button.
**false**: Display the back button.
The back button in the title bar of the **\** component cannot be hidden.
**NOTE**
The back button is available only when **titleMode** is set to **NavigationTitleMode.Mini**.| +| hideBackButton | boolean | Whether to hide the back button.
Default value: **false**
**true**: Hide the back button.
**false**: Display the back button.
The back button in the title bar of the **\** component cannot be hidden.
**NOTE**
The back button works only when **titleMode** is set to **NavigationTitleMode.Mini**.| | navBarWidth9+ | [Length](ts-types.md#length) | Width of the navigation bar.
Default value: **200**
Unit: vp
**NOTE**
This attribute is valid only when the **\** component is split.| -| navBarPosition9+ | [NavBarPosition](#navbarposition) | Position of the navigation bar.
Default value: **NavBarPosition.Start**
**NOTE**
This attribute is valid only when the **\** component is split.| -| mode9+ | [NavigationMode](#navigationmode) | Display mode of the navigation bar.
Default value: **NavigationMode.Auto**
At the default settings, the component adapts to a single column or two columns based on the component width.| +| navBarPosition9+ | [NavBarPosition](#navbarposition) | Position of the navigation bar.
Default value: **NavBarPosition.Start**
**NOTE**
This attribute is valid only when the **\** component is split.| +| mode9+ | [NavigationMode](#navigationmode) | Display mode of the navigation bar.
Default value: **NavigationMode.Auto**
At the default settings, the component adapts to a single column or two columns based on the component width.| | backButtonIcon9+ | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Back button icon on the navigation bar. The back button in the title bar of the **\** component cannot be hidden.| | hideNavBar9+ | boolean | Whether to hide the navigation bar. This attribute is valid only when **mode** is set to **NavigationMode.Split**.| -| navDestination10+ | builder: (name: string, param: unknown) => void | Creates a **\** component.
**NOTE**
The **builder** function is used, with the **name** and **param** parameters passsed in. In the builder, a layer of custom components can be included outside the **\** component. However, no attributes or events can be set for the custom components. Otherwise, only blank components are displayed.| +| navDestination10+ | builder: (name: string, param: unknown) => void | Creates a **\** component.
**NOTE**
The **builder** function is used, with the **name** and **param** parameters passed in. In the builder, a layer of custom components can be included outside the **\** component. However, no attributes or events can be set for the custom components. Otherwise, only blank components are displayed.| +| navBarWidthRange10+ | [[Dimension](ts-types.md#dimension10), [Dimension](ts-types.md#dimension10)] | Minimum and maximum widths of the navigation bar.
Default value: [240, 280]
Unit: vp | +| minContentWidth10+ | [Dimension](ts-types.md#dimension10) | Minimum width of the navigation bar content area.
Default value: **360**
Unit: vp | ## NavPathStack10+ @@ -75,7 +77,7 @@ Pushes the navigation destination page specified by **name** to the navigation s | Name | Type | Mandatory | Description | | ------ | ----------------------- | ---- | --------------- | -| name | string | Yes | Name of the navigation destination page. | +| name | string | Yes | Name of the navigation destination page. | | param | unknown | Yes | Parameter information of the navigation destination page. | ### pop10+ @@ -89,7 +91,7 @@ Pops the top element out of the navigation stack. | Type | Description | | ------ | -------- | | NavPathInfo | Returns the information about the navigation destination page at the top of the stack.| -| undefined | Returns **undefined** if the navigation stack is empty.| +| undefined | Returns **undefined** if the navigation stack is empty.| ### popTo10+ @@ -101,7 +103,7 @@ Returns the navigation stack to the first navigation destination page that match | Name | Type | Mandatory | Description | | ------ | ----------------------- | ---- | --------------- | -| name | string | Yes | Name of the navigation destination page. | +| name | string | Yes | Name of the navigation destination page. | **Return value** @@ -119,7 +121,7 @@ Returns the navigation stack to the navigation destination page that matches the | Name | Type | Mandatory | Description | | ------ | ----------------------- | ---- | --------------- | -| index | number | Yes | Index of the navigation destination page. | +| index | number | Yes | Index of the navigation destination page. | ### moveToTop10+ @@ -149,7 +151,7 @@ Moves to the top of the navigation stack the navigation destination page that ma | Name | Type | Mandatory | Description | | ------ | ----------------------- | ---- | --------------- | -| index | number | Yes | Index of the navigation destination page. | +| index | number | Yes | Index of the navigation destination page. | ### clear10+ @@ -179,13 +181,13 @@ Obtains the parameter information of the navigation destination page that matche | Name | Type | Mandatory | Description | | ------ | ----------------------- | ---- | --------------- | -| index | number | Yes | Index of the navigation destination page. | +| index | number | Yes | Index of the navigation destination page. | **Return value** | Type | Description | | ------ | -------- | -| unknown | Returns the parameter information of the matching navigation destination page.| +| unknown | Returns the parameter information of the matching navigation destination page.| | undefined | Returns **undefined** if the passed index is invalid.| ### getParamByName10+ @@ -216,7 +218,7 @@ Obtains the indexes information of all the navigation destination pages that mat | Name | Type | Mandatory | Description | | ------ | ----------------------- | ---- | --------------- | -| name | string | Yes | Name of the navigation destination page. | +| name | string | Yes | Name of the navigation destination page. | **Return value** diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-progress.md b/en/application-dev/reference/arkui-ts/ts-basic-components-progress.md index ef810a8be61e6dc14a8ccba62714a3f8bbe1b06e..c620b663ecdc67b90b59176f62639662b3bbf1a8 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-progress.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-progress.md @@ -27,7 +27,7 @@ Since API version 9, this API is supported in ArkTS widgets. | value | number | Yes | Current progress. If the value is less than 0, the value **0** is used. If the value is greater than that of **total**, the value of **total** is used.
Since API version 9, this API is supported in ArkTS widgets.| | total | number | No | Total progress.
Default value: **100**
Since API version 9, this API is supported in ArkTS widgets.| | type8+ | [ProgressType](#progresstype) | No | Style of the progress indicator.
Default value: **ProgressType.Linear**
Since API version 9, this API is supported in ArkTS widgets.| -| styledeprecated | [ProgressStyle](#progressstyle) | No | Style of the progress indicator.
This parameter is deprecated since API version 8. You are advised to use **type** instead.
Default value: **ProgressStyle.Linear**| +| style(deprecated) | [ProgressStyle](#progressstyle) | No | Style of the progress indicator.
This parameter is deprecated since API version 8. You are advised to use **type** instead.
Default value: **ProgressStyle.Linear**| ## ProgressType diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-qrcode.md b/en/application-dev/reference/arkui-ts/ts-basic-components-qrcode.md index bc6f5ef081cf9c51067f4e15c63cf2f12482ce6e..327940062946a54cb8c4a6df65fbaa0991c7e3bb 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-qrcode.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-qrcode.md @@ -33,7 +33,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Description| | -------- | -------- | -------- | | color | [ResourceColor](ts-types.md#resourcecolor) | Color of the QR code.
Default value: **Color.Black**
Since API version 9, this API is supported in ArkTS widgets.| -| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the QR code.
Default value: **Color.White**
Since API version 9, this API is supported in ArkTS widgets.| +| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the QR code.
Default value: **Color.White**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
The settings of the universal attribute [backgroundColor](./ts-universal-attributes-background.md) applies to the QR code content area instead of the entire **\** component.| ## Events diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-radio.md b/en/application-dev/reference/arkui-ts/ts-basic-components-radio.md index b76cb22dd303044b2e7456859da454cd815d957a..31136e74e7644fd2b3e30cac07b5428d0bf1106f 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-radio.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-radio.md @@ -62,6 +62,9 @@ struct RadioExample { Column() { Text('Radio1') Radio({ value: 'Radio1', group: 'radioGroup' }).checked(true) + .radioStyle({ + checkedBackgroundColor: Color.Pink + }) .height(50) .width(50) .onChange((isChecked: boolean) => { @@ -71,6 +74,9 @@ struct RadioExample { Column() { Text('Radio2') Radio({ value: 'Radio2', group: 'radioGroup' }).checked(false) + .radioStyle({ + checkedBackgroundColor: Color.Pink + }) .height(50) .width(50) .onChange((isChecked: boolean) => { @@ -80,6 +86,9 @@ struct RadioExample { Column() { Text('Radio3') Radio({ value: 'Radio3', group: 'radioGroup' }).checked(false) + .radioStyle({ + checkedBackgroundColor: Color.Pink + }) .height(50) .width(50) .onChange((isChecked: boolean) => { @@ -90,4 +99,4 @@ struct RadioExample { } } ``` -![](figures/radio.gif) +![radio](figures/radio.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-slider.md b/en/application-dev/reference/arkui-ts/ts-basic-components-slider.md index cab18d856b6dc0e86a5d49b75b7bb56afc7b7ca7..5939f8899543cdb715d6f758821af47c6ea022f7 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-slider.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-slider.md @@ -79,7 +79,7 @@ Enumerates the types of the slider in the block direction. ## Events -In addition to the **OnAppear** and **OnDisAppear** universal events, the following events are supported. +In addition to the [universal events](ts-universal-events-click.md), the following attributes are supported. | Name| Description| | -------- | -------- | @@ -96,9 +96,10 @@ Since API version 9, this API is supported in ArkTS widgets. | End | 2 | The user stops dragging the slider by lifting their finger or releasing the mouse.| | Click | 3 | The user moves the slider by touching the slider track.| - ## Example +### Example 1 + ```ts // xxx.ets @Entry @@ -253,3 +254,52 @@ struct SliderExample { ``` ![en-us_image_0000001179613854](figures/en-us_image_0000001179613854.gif) + +### Example 2 + +```ts +@Entry +@Component +struct SliderExample { + @State tipsValue: number = 40 + + build() { + Column({ space: 8 }) { + Text('block').fontSize(9).fontColor(0xCCCCCC).margin(15).width('90%') + Slider({ style: SliderStyle.OutSet, value: 40 }) + .blockSize({ width: 40, height: 40 }) + .blockBorderColor(Color.Red) + .blockBorderWidth(5) + Divider() + Text('step').fontSize(9).fontColor(0xCCCCCC).margin(15).width('90%') + Slider({ style: SliderStyle.InSet, value: 40, step: 10 }) + .showSteps(true) + .stepSize(8) + .stepColor(Color.Yellow) + Divider() + Text('track').fontSize(9).fontColor(0xCCCCCC).margin(15).width('90%') + Slider({ style: SliderStyle.InSet, value: 40 }) + .trackBorderRadius(2) + Divider() + Text('blockStyle').fontSize(9).fontColor(0xCCCCCC).margin(15).width('90%') + Slider({ style: SliderStyle.OutSet, value: 40 }) + .blockStyle({ type: SliderBlockType.DEFAULT }) + Slider({ style: SliderStyle.OutSet, value: 40 }) + .blockStyle({ type: SliderBlockType.IMAGE, image: $r('sys.media.ohos_app_icon') }) + Slider({ style: SliderStyle.OutSet, value: 40 }) + .blockSize({ width: '60px', height: '60px' }) + .blockColor(Color.Red) + .blockStyle({ type: SliderBlockType.SHAPE, shape: new Path({ commands: 'M30 30 L15 56 L45 56 Z' }) }) + Divider() + Text('tips').fontSize(9).fontColor(0xCCCCCC).margin(15).width('90%') + Slider({ style: SliderStyle.InSet, value: this.tipsValue }) + .showTips(true, 'value:' + this.tipsValue.toFixed()) + .onChange(value => { + this.tipsValue = value + }) + } + } +} +``` + +![](figures/slider_2.png) diff --git a/en/application-dev/reference/arkui-ts/ts-container-alphabet-indexer.md b/en/application-dev/reference/arkui-ts/ts-container-alphabet-indexer.md index df19454da7610c2d52acfd958c7c35e0e3073e33..e25ebce13a72fc5f7977b8dde2fded7d18f42952 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-alphabet-indexer.md +++ b/en/application-dev/reference/arkui-ts/ts-container-alphabet-indexer.md @@ -39,7 +39,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | popupFont | [Font](ts-types.md#font) | Font style of the pop-up text.
Default value:
{
size:10,
style:FontStyle.Normal,
weight:FontWeight.Normal,
family:'HarmonyOS Sans'
} | | font | [Font](ts-types.md#font) | Default font style of the alphabetic index bar.
Default value:
{
size:10,
style:FontStyle.Normal,
weight:FontWeight.Normal,
family:'HarmonyOS Sans'
} | | itemSize | string \| number | Size of an item in the alphabetic index bar. The item is a square, and the side length needs to be set. This attribute cannot be set to a percentage.
Default value: **24.0**
Unit: vp| -| alignStyle | value: [IndexerAlign](#indexeralign),
offset10+?: [Length](ts-types.md#length) | Alignment style of the alphabetic index bar.
**value**: alignment of the alphabetic index bar with the pop-up window, which can be left-aligned or right-aligned.
Default value: **IndexerAlign.Right**
**offset**: spacing between the pop-up window and the alphabetic index bar. A value greater than or equal to 0 is valid. If this attribute is set to a value less than 0 or is not set, the spacing is the same as **popupPosition.x**.| +| alignStyle | value: [IndexerAlign](#indexeralign),
offset10+?: [Length](ts-types.md#length) | Alignment style of the alphabetic index bar.
**value**: alignment of the alphabetic index bar with the pop-up window, which can be left-aligned or right-aligned.
Default value: **IndexerAlign.Right**
**offset**: spacing between the pop-up window and the alphabetic index bar. A value greater than or equal to 0 is valid. If this parameter is set to a value less than 0 or is not set, the spacing is the same as **popupPosition.x**. If this parameter and **popupPosition** are set at the same time, **offset** takes effect in the horizontal direction and **popupPosition.y** takes effect in the vertical direction.| | selected | number | Index of the selected item.
Default value: **0**
Since API version 10, this parameter supports [$$](../../quick-start/arkts-two-way-sync.md) for two-way binding of variables.| | popupPosition | [Position](ts-types.md#position8) | Position of the pop-up window relative to the center of the indexer bar's top border.
Default value: **{x:96.0, y:48.0}**| | popupSelectedColor10+ | [ResourceColor](ts-types.md#resourcecolor) | Color of the selected text excluding the initial letter in the pop-up window.
Default value: **#FF182431**| @@ -139,6 +139,10 @@ struct AlphabetIndexerSample { .popupFont({ size: 30, weight: FontWeight.Bolder}) // Font style of the pop-up text. .itemSize(28) // Size of an item in the alphabetic index bar. .alignStyle(IndexerAlign.Left) // The pop-up window is displayed on the right of the alphabetic index bar. + .popupSelectedColor(0x00FF00) + .popupUnselectedColor(0x0000FF) + .popupItemFont({ size: 30, style: FontStyle.Normal }) + .popupItemBackgroundColor(0xCCCCCC) .onSelect((index: number) => { console.info(this.value[index] + ' Selected!') }) diff --git a/en/application-dev/reference/arkui-ts/ts-container-swiper.md b/en/application-dev/reference/arkui-ts/ts-container-swiper.md index 8219faa65966b92064528a5068d5870ad757e769..366eb3e728268319bf8cdd926846b0bfc0b51ddc 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-swiper.md +++ b/en/application-dev/reference/arkui-ts/ts-container-swiper.md @@ -14,6 +14,10 @@ This component can contain child components. > **NOTE** > > Built-in components and custom components are allowed, with support for ([if/else](../../quick-start/arkts-rendering-control-ifelse.md), [ForEach](../../quick-start/arkts-rendering-control-foreach.md), and [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md)) rendering control. +> +> When the **\** component's **displayMode** attribute is set to **SwiperDisplayMode.AutoLinear** or its **displayCount** attribute is set to **'auto'**, the child component whose **visibility** attribute is set to **None** does not take up space in the viewport, but this does not affect the number of navigation dots. +> +> If the **visibility** attribute of a child component is set to **None** or **Hidden**, it takes up space in the viewport, but is not displayed. ## APIs @@ -22,42 +26,44 @@ Swiper(controller?: SwiperController) **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory | Description | | ---------- | ------------------------------------- | ---- | -------------------- | -| controller | [SwiperController](#swipercontroller) | No | Controller bound to the component to control the page switching.| +| controller | [SwiperController](#swipercontroller) | No | Controller bound to the component to control the page switching.| ## Attributes In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. [Menu control](ts-universal-attributes-menu.md) is not supported. -| Name | Type | Description | -| --------------------------- | ---------------------------------------- | ---------------------------------------- | -| index | number | Index of the child component currently displayed in the container.
Default value: **0**
**NOTE**
If the value is less than 0 or greater than or equal to the number of child components, the default value **0** is used.
Since API version 10, this attribute supports [$$](../../quick-start/arkts-two-way-sync.md) for two-way binding of variables.| -| autoPlay | boolean | Whether to enable automatic playback for child component switching.
Default value: **false**
**NOTE**
If **loop** is set to **false**, the playback stops when the last page is displayed. The playback continues when the page is not the last page after a swipe gesture.| -| interval | number | Interval for automatic playback, in ms.
Default value: **3000** | -| indicator10+ | [DotIndicator](#dotindicator) \| [DigitIndicator](#digitindicator) \| boolean | Style of the navigation point indicator.
\- **DotIndicator**: dot style.
\- **DigitIndicator**: digit style.
\- **boolean**: whether to enable the navigation point indicator.
Default value: **true**
Default type: **DotIndicator**| -| loop | boolean | Whether to enable loop playback.
The value **true** means to enable loop playback. When LazyForEach is used, it is recommended that the number of the components to load exceed 5.
Default value: **true**| -| duration | number | Duration of the animation for switching child components, in ms.
Default value: **400** | -| vertical | boolean | Whether vertical swiping is used.
Default value: **false** | -| itemSpace | number \| string | Space between child components.
Default value: **0**
**NOTE**
This parameter cannot be set in percentage.| -| displayMode | SwiperDisplayMode | Mode in which elements are displayed along the main axis. This attribute takes effect only when **displayCount** is not set.
Default value: **SwiperDisplayMode.Stretch**| -| cachedCount8+ | number | Number of child components to be cached.
Default value: **1**
**NOTE**
**cachedCount** has caching optimized. You are advised not to use it together with [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md).| -| disableSwipe8+ | boolean | Whether to disable the swipe feature.
Default value: **false** | -| curve8+ | [Curve](ts-appendix-enums.md#curve) \| string | Animation curve. The ease-in/ease-out curve is used by default. For details about common curves, see [Curve](ts-appendix-enums.md#curve). You can also create custom curves (interpolation curve objects) by using the API provided by the [interpolation calculation](../apis/js-apis-curve.md) module.
Default value: **Curve.Linear**| +| Name | Type | Description | +| ------------------------------------- | ---------------------------------------- | ---------------------------------------- | +| index | number | Index of the child component currently displayed in the container.
Default value: **0**
**NOTE**
If the value is less than 0 or greater than or equal to the number of child components, the default value **0** is used.
Since API version 10, this attribute supports [$$](../../quick-start/arkts-two-way-sync.md) for two-way binding of variables.| +| autoPlay | boolean | Whether to enable automatic playback for child component switching.
Default value: **false**
**NOTE**
If **loop** is set to **false**, the playback stops when the last page is displayed. The playback continues when the page is not the last page after a swipe gesture.| +| interval | number | Interval for automatic playback, in ms.
Default value: **3000** | +| indicator10+ | [DotIndicator](#dotindicator10) \| [DigitIndicator](#digitindicator10) \| boolean | Style of the navigation point indicator.
\- **DotIndicator**: dot style.
\- **DigitIndicator**: digit style.
\- **boolean**: whether to enable the navigation point indicator.
Default value: **true**
Default type: **DotIndicator**| +| loop | boolean | Whether to enable loop playback.
The value **true** means to enable loop playback. When LazyForEach is used, it is recommended that the number of the components to load exceed 5.
Default value: **true**| +| duration | number | Duration of the animation for switching child components, in ms.
Default value: **400** | +| vertical | boolean | Whether vertical swiping is used.
Default value: **false** | +| itemSpace | number \| string | Space between child components.
Default value: **0**
**NOTE**
This parameter cannot be set in percentage.| +| displayMode | SwiperDisplayMode | Mode in which elements are displayed along the main axis. This attribute takes effect only when **displayCount** is not set.
Default value: **SwiperDisplayMode.Stretch**| +| cachedCount8+ | number | Number of child components to be cached.
Default value: **1**
**NOTE**
This attribute applies only when the **\** component uses [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md).| +| disableSwipe8+ | boolean | Whether to disable the swipe feature.
Default value: **false** | +| curve8+ | [Curve](ts-appendix-enums.md#curve) \| string | Animation curve. The ease-in/ease-out curve is used by default. For details about common curves, see [Curve](ts-appendix-enums.md#curve). You can also create custom curves (interpolation curve objects) by using the API provided by the [interpolation calculation](../apis/js-apis-curve.md) module.
Default value: **Curve.Linear**| | indicatorStyle(deprecated) | {
left?: [Length](ts-types.md#length),
top?: [Length](ts-types.md#length),
right?: [Length](ts-types.md#length),
bottom?: [Length](ts-types.md#length),
size?: [Length](ts-types.md#length),
mask?: boolean,
color?: [ResourceColor](ts-types.md),
selectedColor?: [ResourceColor](ts-types.md)
} | Style of the navigation point indicator.
\- **left**: distance between the navigation point indicator and the left edge of the **\** component.
\- **top**: distance between the navigation point indicator and the top edge of the **\** component.
\- **right**: distance between the navigation point indicator and the right edge of the **\** component.
\- **bottom**: distance between the navigation point indicator and the bottom edge of the **\** component.
\- **size**: diameter of the navigation point indicator. The value cannot be in percentage. Default value: **6vp**
\- **mask**: whether to enable the mask for the navigation point indicator.
\- **color**: color of the navigation point indicator.
\- **selectedColor**: color of the selected navigation dot.
This API is supported since API version 8 and is deprecated since API version 9. You are advised to use [indicator](#indicator10) instead.| -| displayCount8+ | number \| string | Number of elements to display per page.
Default value: **1**
**NOTE**
If the value is of the string type, it can only be **'auto'**, whose display effect is the same as that of **SwiperDisplayMode.AutoLinear**.
If the value is of the number type, child components stretch (shrink) on the main axis after the swiper width [deducting the result of itemSpace x (displayCount – 1)] is evenly distributed among them on the main axis.| -| effectMode8+ | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Swipe effect. For details, see **EdgeEffect**.
Default value: **EdgeEffect.Spring**
**NOTE**
The spring effect does not take effect when the controller API is called.| -| displayArrow10+ | value:[ArrowStyle](#arrowstyle10) \| boolean,
isHoverShow?: boolean | Arrow style of the navigation point indicator.
Default value: **false**
**isHoverShow**: whether to show the arrow when the mouse pointer hovers over the navigation point indicator.| +| displayCount8+ | number \| string \|
[SwiperAutoFill](#swiperautofill10)10+ | Number of elements to display per page.
Default value: **1**
**NOTE**
If the value is of the string type, it can only be **'auto'**, whose display effect is the same as that of **SwiperDisplayMode.AutoLinear**.
If the value is set to a number less than or equal to 0, the default value **1** is used.
If the value is of the number type, child components stretch (shrink) on the main axis after the swiper width [deducting the result of itemSpace x (displayCount – 1)] is evenly distributed among them on the main axis.
If the value is of the SwiperAutoFill type, the system automatically calculates and changes the number of elements to display per page based on the **\** component width and the **minSize** settings for the child component. If **minSize** is left empty or set to a value less than or equal to 0, the **\** component displays one column.| +| effectMode8+ | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Swipe effect. For details, see **EdgeEffect**.
Default value: **EdgeEffect.Spring**
**NOTE**
The spring effect does not take effect when the controller API is called.| +| displayArrow10+ | value:[ArrowStyle](#arrowstyle10) \| boolean,
isHoverShow?: boolean | Arrow style of the navigation point indicator.
- **value**: arrow and background to set. In abnormal scenarios, the default values in the **ArrowStyle** object are used.
\- **isHoverShow**: whether to show the arrow only when the mouse pointer hovers over the navigation point indicator.
Default value: **false**
**NOTE**
When **isHoverShow** is set to **false**, the arrow is always displayed and can be clicked to turn pages.
When **isHoverShow** is set to **true**, the arrow is displayed only when the mouse pointer hovers over the navigation point indicator, and it can be clicked to turn pages.| +| nextMargin10+ |
[Length](ts-types.md#length)
| Next margin, used to reveal a small part of the next item.
Default value: **0**
**NOTE**
This attribute is available only when **SwiperDisplayMode** is set to **STRETCH**. | +| prevMargin10+ |
[Length](ts-types.md#length)
| Previous margin, used to reveal a small part of the previous item.
Default value: **0**
**NOTE**
This attribute is available only when **SwiperDisplayMode** is set to **STRETCH**. | ## SwiperDisplayMode -| Name| Description| -| ----------- | ------------------------------------------ | -| Stretch(deprecated) | The slide width of the **\** component is equal to the width of the component.
This API is deprecated since API version 10. You are advised to use **STRETCH** instead.| -| AutoLinear(deprecated) | The slide width of the **\** component is equal to that of the child component with the maximum width.
This API is deprecated since API version 10. You are advised to use **AUTO_LINEAR** instead.| -| STRETCH10+ | The slide width of the **\** component is equal to the width of the component.| -| AUTO_LINEAR10+ | The slide width of the **\** component is equal to that of the child component with the maximum width.| +| Name | Description | +| --------------------------------- | ---------------------------------------- | +| Stretch(deprecated) | The slide width of the **\** component is equal to the width of the component.
This API is deprecated since API version 10. You are advised to use **STRETCH** instead.| +| AutoLinear(deprecated) | The slide width of the **\** component is equal to that of the child component with the maximum width.
This API is deprecated since API version 10. You are advised to use **AUTO_LINEAR** instead.| +| STRETCH10+ | The slide width of the **\** component is equal to the width of the component. | +| AUTO_LINEAR10+ | The slide width of the **\** component is equal to the width of the leftmost child component in the viewport. | ## SwiperController @@ -83,72 +89,80 @@ Stops an animation. **Parameters** -| Name | Type | Mandatory.| Description| -| --------- | ---------- | ------ | -------- | -| callback | () => void | No | Callback invoked when the animation stops.| +| Name | Type | Mandatory. | Description | +| -------- | ---------- | ---- | -------- | +| callback | () => void | No | Callback invoked when the animation stops.| ## Indicator10+ Sets the distance between the navigation point indicator and the **\** component. -| Name| Type| Mandatory.| Description | -| ------ | -------- | ------ | ------------------------------------ | -| left | [Length](ts-types.md#length) | No | Distance between the navigation point indicator and the left edge of the **\** component.
Default value: **0**
Unit: vp| -| top | [Length](ts-types.md#length) | No | Distance between the navigation point indicator and the top edge of the **\** component.
Default value: **0**
Unit: vp| -| right | [Length](ts-types.md#length) | No | Distance between the navigation point indicator and the right edge of the **\** component.
Default value: **0**
Unit: vp| -| bottom | [Length](ts-types.md#length) | No | Distance between the navigation point indicator and the bottom edge of the **\** component.
Default value: **0**
Unit: vp| +| Name | Type | Mandatory. | Description | +| ------ | ---------------------------- | ---- | ---------------------------------------- | +| left | [Length](ts-types.md#length) | No | Distance between the navigation point indicator and the left edge of the **\** component.
Default value: **0**
Unit: vp| +| top | [Length](ts-types.md#length) | No | Distance between the navigation point indicator and the top edge of the **\** component.
Default value: **0**
Unit: vp| +| right | [Length](ts-types.md#length) | No | Distance between the navigation point indicator and the right edge of the **\** component.
Default value: **0**
Unit: vp| +| bottom | [Length](ts-types.md#length) | No | Distance between the navigation point indicator and the bottom edge of the **\** component.
Default value: **0**
Unit: vp| -### DotIndicator +## DotIndicator10+ Defines the navigation point indicator of the dot style, which inherits attributes and features from **Indicator**. -| Name | Type | Mandatory.| Description | -| ------------------ | ------------- | ------ | ------------------------------------------------------ | -| itemWidth | [Length](ts-types.md#length) | No | Width of the navigation point indicator of the dot style.
Default value: **6**
Unit: vp| -| itemHeight | [Length](ts-types.md#length) | No | Height of the navigation point indicator of the dot style.
Default value: **6**
Unit: vp| -| selectedItemWidth | [Length](ts-types.md#length) | No | Width of the selected indicator dot.
Default value: **6**
Unit: vp| -| selectedItemHeight | [Length](ts-types.md#length) | No | Height of the selected indicator dot.
Default value: **6**
Unit: vp| -| mask | boolean | No | Whether to enable the mask for the navigation point indicator of the dot style.
Default value: **false**| -| color | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the navigation point indicator of the dot style.
Default value: **'\#007DFF'**| -| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the selected indicator dot.
Default value: **'\#182431'** (10% opacity)| +| Name | Type | Mandatory. | Description | +| ------------------ | ---------------------------------------- | ---- | ---------------------------------------- | +| itemWidth | [Length](ts-types.md#length) | No | Width of the navigation point indicator of the dot style.
Default value: **6**
Unit: vp| +| itemHeight | [Length](ts-types.md#length) | No | Height of the navigation point indicator of the dot style.
Default value: **6**
Unit: vp| +| selectedItemWidth | [Length](ts-types.md#length) | No | Width of the selected indicator dot.
Default value: **6**
Unit: vp| +| selectedItemHeight | [Length](ts-types.md#length) | No | Height of the selected indicator dot.
Default value: **6**
Unit: vp| +| mask | boolean | No | Whether to enable the mask for the navigation point indicator of the dot style.
Default value: **false**| +| color | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the navigation point indicator of the dot style.
Default value: **'\#182431'** (10% opacity)| +| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the selected indicator dot.
Default value: **'\#007DFF'**| -### DigitIndicator +## DigitIndicator10+ Defines the navigation point indicator of the digit style, which inherits attributes and features from **Indicator**. -| Name | Type | Mandatory.| Description | -| ----------------- | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | -| fontColor | [ResourceColor](ts-types.md#resourcecolor) | No | Font color of the navigation point indicator of the digit style.
Default value: **'\#ff182431'**| -| selectedFontColor | [ResourceColor](ts-types.md#resourcecolor) | No | Font color of the selected indicator digit.
Default value: **'\#ff182431'**| -| digitFont | {
size?:[Length](ts-types.md#length)
weight?:number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string
} | No | Font style of the navigation point indicator of the digit style.
\- **size**: font size.
Default value: **14vp**
\- **weight**: font weight.| -| selectedDigitFont | {
size?:[Length](ts-types.md#length)
weight?:number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string
} | No | Font style of the selected indicator digit.
\- **size**: font size.
Default value: **14vp**
\- **weight**: font weight.| +| Name | Type | Mandatory. | Description | +| ----------------- | ---------------------------------------- | ---- | ---------------------------------------- | +| fontColor | [ResourceColor](ts-types.md#resourcecolor) | No | Font color of the navigation point indicator of the digit style.
Default value: **'\#ff182431'**| +| selectedFontColor | [ResourceColor](ts-types.md#resourcecolor) | No | Font color of the selected indicator digit.
Default value: **'\#ff182431'**| +| digitFont | {
size?:[Length](ts-types.md#length)
weight?:number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string
} | No | Font style of the navigation point indicator of the digit style.
\- **size**: font size.
Default value: **14vp**
\- **weight**: font weight.| +| selectedDigitFont | {
size?:[Length](ts-types.md#length)
weight?:number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string
} | No | Font style of the selected indicator digit.
\- **size**: font size.
Default value: **14vp**
\- **weight**: font weight.| -### ArrowStyle10+ +## ArrowStyle10+ Describes the left and right arrow attributes. -| Name | Type| Mandatory.| Description| -| ------------- | -------- | ------ | -------- | -| isShowBackground | boolean | No| Whether to show the background for the arrow.
Default value: **false**| -| isSidebarMiddle | boolean | No| Whether the arrow is centered on both sides of the content area.
Default value: **false** (the arrow is shown on either side of the navigation point indicator)| -| backgroundSize | [Length](ts-types.md#length) | No| Size of the background.
Default value: **24vp**| -| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | No| Color of the background.
Default value: **'\#19182431'**| -| arrowSize | [Length](ts-types.md#length) | No| Size of the arrow.
Default value: **18vp**| -| arrowColor | [ResourceColor](ts-types.md#resourcecolor) | No| Color of the arrow.
Default value: **\#182431**| +| Name | Type | Mandatory. | Description | +| ---------------- | ---------------------------------------- | ---- | ---------------------------------------- | +| isShowBackground | boolean | No | Whether to show the background for the arrow.
Default value: **false** | +| isSidebarMiddle | boolean | No | Whether the arrow is shown on either side of the navigation point indicator.
Default value: **false** (the arrow is shown on either side of the navigation point indicator) | +| backgroundSize | [Length](ts-types.md#length) | No | Size of the background.
On both sides of the navigation point indicator:
Default value: **24vp**
On both sides of the component:
Default value: **32vp**
This parameter cannot be set in percentage.| +| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the background.
On both sides of the navigation point indicator:
Default value: **'\#19182431'**
On both sides of the component:
Default value: **'\#00000000'**| +| arrowSize | [Length](ts-types.md#length) | No | Size of the arrow.
On both sides of the navigation point indicator:
Default value: **18vp**
On both sides of the component:
Default value: **24vp**
**NOTE**
If **isShowBackground** is set to **true**, the value of **arrowSize** is 3/4 of the value of **backgroundSize**.
This parameter cannot be set in percentage.| +| arrowColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the arrow.
Default value: **\#182431** | + +## SwiperAutoFill10+ +Describes the auto-fill attribute. +| Name | Type | Mandatory.| Description | +| ------- | -------------------- | ------ | ------------------------------------ | +| minSize | [VP](ts-types.md#vp10) | Yes | Minimum width of the element.
Default value: **0**| ## Events In addition to the [universal events](ts-universal-events-click.md), the following events are supported. -| Name | Description | -| ------------------------------------------------------------ | ------------------------------------------------------------ | -| onChange(event: (index: number) => void) | Triggered when the index of the currently displayed child component changes.
- **index**: index of the currently displayed element.
**NOTE**
When the **\** component is used together with **LazyForEach**, the subpage UI update cannot be triggered in the **onChange** event.| -| onAnimationStart9+(event: (index: number) => void) | Triggered when the switching animation starts.
- **index**: index of the currently displayed element.
**NOTE**
The **index** parameter indicates the index before the animation starts (not the one after). When the **\** component contains multiple columns, the index is of the leftmost element.| -| onAnimationEnd9+(event: (index: number) => void) | Triggered when the switching animation ends.
- **index**: index of the currently displayed element.
**NOTE**
This event is triggered when the animation ends regardless of whether it is due to a user gesture or invocation of **finishAnimation** through **SwiperController**. The **index** parameter indicates the index after the animation ends. When the **\** component contains multiple columns, the index is of the leftmost element.| +| Name | Description | +| ---------------------------------------- | ---------------------------------------- | +| onChange(event: (index: number) => void) | Triggered when the index of the currently displayed child component changes.
- **index**: index of the currently displayed element.
**NOTE**
When the **\** component is used together with **LazyForEach**, the subpage UI update cannot be triggered in the **onChange** event.| +| onAnimationStart9+(event: (index: number, targetIndex10+: number, extraInfo10+: [SwiperAnimationEvent](ts-types.md#swiperanimationevent10)) => void) | Triggered when the switching animation starts.
- **index**: index of the currently displayed element.
- **targetIndex**: index of the target element to switch to.
- **extraInfo**: extra information of the animation, including the offset of the currently displayed element and target element relative to the start position of the **\** along the main axis, and the hands-off velocity.
**NOTE**
The **index** parameter indicates the index before the animation starts (not the one after). When the **\** component contains multiple columns, the index is of the leftmost element.| +| onAnimationEnd9+(event: (index: number, extraInfo: [SwiperAnimationEvent](ts-types.md#swiperanimationevent10)) => void) | Triggered when the switching animation ends.
- **index**: index of the currently displayed element.
- **extraInfo**: extra information of the animation, which is the offset of the currently displayed element relative to the start position of the **\** along the main axis.
**NOTE**
This event is triggered when the switching animation of the **\** component ends, whether it is caused by gesture interruption or by calling **finishAnimation** through SwiperController. The **index** parameter indicates the index after the animation ends. When the **\** component contains multiple columns, the index is of the leftmost element.| +| onGestureSwipe10+(event: (index: number, extraInfo: [SwiperAnimationEvent](ts-types.md#swiperanimationevent10)) => void) | Triggered on a frame-by-frame basis when the page is turned by a swipe.
- **index**: index of the currently displayed element.
- **extraInfo**: extra information of the animation, which is the offset of the currently displayed element relative to the start position of the **\** along the main axis.
**NOTE**
If there are multiple columns, **index** indicates the index of the leftmost component.| ## Example +### Example 1 ```ts // xxx.ets class MyDataSource implements IDataSource { @@ -204,10 +218,32 @@ struct SwiperExample { .loop(true) .duration(1000) .itemSpace(0) + .displayArrow({ + isShowBackground:true, + isSidebarMiddle:true, + backgroundSize:24, + backgroundColor:Color.White, + arrowSize:18, + arrowColor:Color.Blue},false) .curve(Curve.Linear) .onChange((index: number) => { console.info(index.toString()) }) + .onGestureSwipe((index: number, extraInfo: SwiperAnimationEvent) => { + console.info("index: " + index) + console.info("current offset: " + extraInfo.currentOffset) + }) + .onAnimationStart((index: number, targetIndex: number, extraInfo: SwiperAnimationEvent) => { + console.info("index: " + index) + console.info("targetIndex: " + targetIndex) + console.info("current offset: " + extraInfo.currentOffset) + console.info("target offset: " + extraInfo.targetOffset) + console.info("velocity: " + extraInfo.velocity) + }) + .onAnimationEnd((index: number, extraInfo: SwiperAnimationEvent) => { + console.info("index: " + index) + console.info("current offset: " + extraInfo.currentOffset) + }) Row({ space: 12 }) { Button('showNext') @@ -226,3 +262,163 @@ struct SwiperExample { ``` ![swiper](figures/swiper.gif) + +### Example 2 +```ts +// xxx.ets +class MyDataSource implements IDataSource { + private list: number[] = [] + private listener: DataChangeListener + + constructor(list: number[]) { + this.list = list + } + + totalCount(): number { + return this.list.length + } + + getData(index: number): any { + return this.list[index] + } + + registerDataChangeListener(listener: DataChangeListener): void { + this.listener = listener + } + + unregisterDataChangeListener() { + } +} + +@Entry +@Component +struct SwiperExample { + private swiperController: SwiperController = new SwiperController() + private data: MyDataSource = new MyDataSource([]) + + aboutToAppear(): void { + let list = [] + for (var i = 1; i <= 10; i++) { + list.push(i.toString()); + } + this.data = new MyDataSource(list) + } + + build() { + Column({ space: 5 }) { + Swiper(this.swiperController) { + LazyForEach(this.data, (item: string) => { + Text(item).width('90%').height(160).backgroundColor(0xAFEEEE).textAlign(TextAlign.Center).fontSize(30) + }, item => item) + } + .cachedCount(2) + .index(1) + .autoPlay(true) + .interval(4000) + .indicator(Indicator.dot() + .itemWidth(15) + .itemHeight(15) + .selectedItemWidth(15) + .selectedItemHeight(15) + .color(Color.Gray) + .selectedColor(Color.Blue)) + .loop(true) + .duration(1000) + .itemSpace(0) + .displayArrow(true,true) + Row({ space: 12 }) { + Button('showNext') + .onClick(() => { + this.swiperController.showNext() + }) + Button('showPrevious') + .onClick(() => { + this.swiperController.showPrevious() + }) + }.margin(5) + }.width('100%') + .margin({ top: 5 }) + } +} +``` +![swiper](figures/swiper-dot.gif) + +### Example 3 +```ts +// xxx.ets +class MyDataSource implements IDataSource { + private list: number[] = [] + private listener: DataChangeListener + + constructor(list: number[]) { + this.list = list + } + + totalCount(): number { + return this.list.length + } + + getData(index: number): any { + return this.list[index] + } + + registerDataChangeListener(listener: DataChangeListener): void { + this.listener = listener + } + + unregisterDataChangeListener() { + } +} + +@Entry +@Component +struct SwiperExample { + private swiperController: SwiperController = new SwiperController() + private data: MyDataSource = new MyDataSource([]) + + aboutToAppear(): void { + let list = [] + for (var i = 1; i <= 10; i++) { + list.push(i.toString()); + } + this.data = new MyDataSource(list) + } + + build() { + Column({ space: 5 }) { + Swiper(this.swiperController) { + LazyForEach(this.data, (item: string) => { + Text(item).width('90%').height(160).backgroundColor(0xAFEEEE).textAlign(TextAlign.Center).fontSize(30) + }, item => item) + } + .cachedCount(2) + .index(1) + .autoPlay(true) + .interval(4000) + .indicator(Indicator.digit() + .right(130) + .top(200) + .fontColor(Color.Gray) + .selectedFontColor(Color.Gray) + .digitFont({size:20,weight:FontWeight.Bold}) + .selectedDigitFont({size:20,weight:FontWeight.Normal})) + .loop(true) + .duration(1000) + .itemSpace(0) + .displayArrow(true,false) + Row({ space: 12 }) { + Button('showNext') + .onClick(() => { + this.swiperController.showNext() + }) + Button('showPrevious') + .onClick(() => { + this.swiperController.showPrevious() + }) + }.margin(5) + }.width('100%') + .margin({ top: 5 }) + } +} +``` +![swiper](figures/swiper-digit.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-drawing-components-shape.md b/en/application-dev/reference/arkui-ts/ts-drawing-components-shape.md index c1d54675e22bf4d55b17ccde9727b318c028186f..e3f57037af5c78d001a79831ebe65819706bf460 100644 --- a/en/application-dev/reference/arkui-ts/ts-drawing-components-shape.md +++ b/en/application-dev/reference/arkui-ts/ts-drawing-components-shape.md @@ -36,7 +36,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Default Value| Description| | -------- | -------- | -------- | -------- | -| viewPort | {
x?: number \| string,
y?: number \| string,
width?: number \| string,
height?: number \| string
} | { x:0, y:0, width:0, height:0 } | View port of the shape.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
If of the string type, the value cannot be a percentage.| +| viewPort | {
x?: number \| string,
y?: number \| string,
width?: number \| string,
height?: number \| string
} | { x:0, y:0, width:0, height:0 } | Viewport of the shape.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
If of the string type, the value cannot be a percentage.| | fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.
Since API version 9, this API is supported in ArkTS widgets.| | fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.
Since API version 9, this API is supported in ArkTS widgets.| | stroke | [ResourceColor](ts-types.md) | - | Stroke color. If this attribute is not set, the component does not have any stroke.
Since API version 9, this API is supported in ArkTS widgets.| diff --git a/en/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md b/en/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md index 8605a29ab1e390a0e5fea2ca77f0b5d337172783..8e0313f27220c5220f4e21d3bd33d176e06c94d3 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md @@ -24,10 +24,10 @@ CustomDialogController(value:{builder: CustomDialog, cancel?: () => void, aut | alignment | [DialogAlignment](ts-methods-alert-dialog-box.md#dialogalignment) | No | Alignment mode of the dialog box in the vertical direction.
Default value: **DialogAlignment.Default**| | offset | [Offset](ts-types.md#offset) | No | Offset of the dialog box relative to the alignment position. | | customStyle | boolean | No | Whether to use a custom style for the dialog box.
Default value: **false**, which means that the dialog box automatically adapts its width to the grid system and its height to the child components; the maximum height is 90% of the container height; the rounded corner is 24 vp.| -| gridCount8+ | number | No | Number of [grid columns](../../ui/arkts-layout-development-grid-layout.md) occupied by the dialog box.
The default value is 4, and the maximum value is the maximum number of columns supported by the system. If this parameter is set to an invalid value, the default value is used.| +| gridCount8+ | number | No | Number of [grid columns](../../ui/arkts-layout-development-grid-layout.md) occupied by the dialog box.
The default value is subject to the window size, and the maximum value is the maximum number of columns supported by the system. If this parameter is set to an invalid value, the default value is used.| | maskColor10+ | [ResourceColor](ts-types.md#resourcecolor) | No | Custom mask color.
Default value: **0x33000000** | -| openAnimation10+ | [AnimateParam](ts-explicit-animation.md#animateparam) | No | Parameters for defining the open animation of the dialog box.
**NOTE**
If **iterations** is set to an odd number and **playMode** is set to **Reverse**, the dialog box will not be displayed when the animation ends.| -| closeAniamtion10+ | [AnimateParam](ts-explicit-animation.md#animateparam) | No | Parameters for defining the close animation of the dialog box. | +| openAnimation10+ | [AnimateParam](ts-explicit-animation.md#animateparam) | No | Parameters for defining the open animation of the dialog box.
**NOTE**
**iterations**: The default value is **1**, indicating that the animation is played once; any other value evaluates to the default value.
**playMode**: The default value is **PlayMode.Normal**; any other value evaluates to the default value.| +| closeAniamtion10+ | [AnimateParam](ts-explicit-animation.md#animateparam) | No | Parameters for defining the close animation of the dialog box.
**NOTE**
**iterations**: The default value is **1**, indicating that the animation is played once; any other value evaluates to the default value.
**playMode**: The default value is **PlayMode.Normal**; any other value evaluates to the default value. | | showInSubWindow10+ | boolean | No | Whether to display a dialog box in a subwindow.
Default value: **false**, indicating that the dialog box is not displayed in the subwindow
**NOTE**
A dialog box whose **showInSubWindow** attribute is **true** cannot trigger the display of another dialog box whose **showInSubWindow** attribute is also **true**.| ## CustomDialogController @@ -45,7 +45,7 @@ dialogController : CustomDialogController = new CustomDialogController(value:{bu open(): void -Opens the content of the custom dialog box. If the content has been displayed, this API does not take effect. +Opens the content of the custom dialog box. This API can be called multiple times. If the dialog box displayed in a subwindow, no new subwindow is allowed. ### close @@ -64,6 +64,7 @@ struct CustomDialogExample { @Link textValue: string @Link inputValue: string controller: CustomDialogController + // You can pass in multiple other controllers in the CustomDialog to open one or more other CustomDialogs in the CustomDialog. In this case, you must place the controller pointing to the self at the end. cancel: () => void confirm: () => void @@ -89,6 +90,7 @@ struct CustomDialogExample { }).backgroundColor(0xffffff).fontColor(Color.Red) }.margin({ bottom: 10 }) } + // The default value of borderRadius is 24vp. The border attribute must be used together with the borderRadius attribute. } } diff --git a/en/application-dev/reference/arkui-ts/ts-types.md b/en/application-dev/reference/arkui-ts/ts-types.md index df71967ffb8f97b52183d429b82ae3d7c38b8c0e..1b3f4797c639b3e566b5beccff527ab4b83c21d8 100644 --- a/en/application-dev/reference/arkui-ts/ts-types.md +++ b/en/application-dev/reference/arkui-ts/ts-types.md @@ -249,7 +249,7 @@ The **ModalTransition** type is used to set the transition type for a full-scree | ------- | ------------ | | NONE | No transition animation for the modal. | | DEFAULT | Slide-up and slide-down animation for the modal. | -| ALPHA | Opacity gradient animation for the modal. | +| ALPHA | Opacity gradient animation for the modal.| ## Dimension10+ @@ -258,7 +258,7 @@ The **Length** type is used to represent a size unit. | Type | Description | | --------------------- | -------------------------------------- | | [PX](#px10) | Physical pixel unit type. The unit px must be included, for example, **'10px'**.| -| [VP](#vp10) | Pixel unit type specific to the screen density. The unit vp must be included, for example, **'10vp'**.| +| [VP](#vp10) | Pixel unit type specific to the screen density. The unit vp can be included or omitted, for example, **10** or **'10vp'**.| | [FP](#fp10) | Font pixel unit type. The unit fp must be included, for example, **'10fp'**.| | [LPX](#lpx10) | Logical pixel unit type. The unit lpx must be included, for example, **'10lpx'**.| | [Percentage](#percentage10) | Percentage type. The unit % must be included, for example, **'10%'**.| @@ -278,7 +278,7 @@ The **VP** type is used to represent a length in vp. | Type | Description | | --------------------- | -------------------------------------- | -| {number}vp | Pixel unit type specific to the screen density. The unit vp must be included, for example, **'10vp'**.| +| {number}vp\|number | Pixel unit type specific to the screen density. The unit vp can be included or omitted, for example, **10** or **'10vp'**.| ## FP10+ @@ -311,3 +311,13 @@ The **Degree** type is used to represent a length in deg. | Type | Description | | --------------------- | -------------------------------------- | | {number}deg | Degree type. The unit deg must be included, for example, **'10deg'**.| + +## SwiperAnimationEvent10+ + +Describes the animation information of the \ component. + +| Name | Type | Description | +| ------------- | ---------------------- | ---------------------------------------- | +| currentOffset | number | Offset of the currently displayed element relative to the start position of the **\** along the main axis. Unit: vp
Default value: **0**| +| targetOffset | number | Offset of the target element relative to the start position of the **\** along the main axis. Unit: vp
Default value: **0**| +| velocity | number | Hands-off velocity at the beginning of the animation. Unit: vp/s
Default value: **0**| diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md index af2554cac67dd52793d48f5a3b0c059f70a21f2c..55e0b52c4a790fdae336c1ddb5671ee84d080a00 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md @@ -12,11 +12,11 @@ The location attributes set the alignment mode, layout direction, and position o | Name| Type| Description| | -------- | -------- | -------- | -| align | [Alignment](ts-appendix-enums.md#alignment) | Alignment mode of the component content in the drawing area.
Default value: **Alignment.Center**
Since API version 9, this API is supported in ArkTS widgets.| +| align | [Alignment](ts-appendix-enums.md#alignment) | Alignment mode of the component content in the drawing area.
This attribute is available only in the following components: **\**, **\