diff --git a/CODEOWNERS b/CODEOWNERS index 78ded76e8315733c6989c96058bc5826da9c68c0..075b95363eddc75d792d3e65f5c34f3114e666fd 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -224,8 +224,9 @@ zh-cn/application-dev/background-agent-scheduled-reminder/ @RayShih zh-cn/application-dev/background-task-management/ @ningningW @wangwenli_wolf @tangtiantian2021 @nan-xiansen zh-cn/application-dev/work-scheduler/ @ningningW zh-cn/application-dev/internationalization/ @ningningW @Buda-Liu @mengjingzhimo @yangqing3 -zh-cn/application-dev/device/usb-overview.md @ge-yafang @jasonyujia @andeszhang @liuhonggang123 -zh-cn/application-dev/device/usb-guidelines.md @ge-yafang @jasonyujia @andeszhang @liuhonggang123 +zh-cn/application-dev/device/usb-overview.md @ge-yafang @Kevin-Lau @liuhonggang123 +zh-cn/application-dev/device/usb-guidelines.md @ge-yafang @Kevin-Lau @liuhonggang123 +zh-cn/application-dev/napi/usb-ddk-guidelines.md @ge-yafang @Kevin-Lau @liuhonggang123 zh-cn/application-dev/device/device-location-overview.md @RayShih zh-cn/application-dev/device/device-location-info.md @RayShih zh-cn/application-dev/device/device-location-geocoding.md @RayShih @@ -499,9 +500,9 @@ zh-cn/application-dev/reference/apis/js-apis-uitest.md @inter515 @ningningW @int zh-cn/application-dev/reference/apis/js-apis-update.md @hughes802 @ningningW @zhangzhengxue @mamba-ting zh-cn/application-dev/reference/apis/js-apis-uri.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-url.md @gongjunsong @ge-yafang @flyingwolf @BlackStone -zh-cn/application-dev/reference/apis/js-apis-usbManager.md @jasonyujia @ge-yafang @andeszhang @liuhonggang123 -zh-cn/application-dev/reference/apis/js-apis-usb.md @jasonyujia @ge-yafang @andeszhang @liuhonggang123 -zh-cn/application-dev/reference/apis/js-apis-usb-deprecated.md @jasonyujia @ge-yafang @andeszhang @liuhonggang123 +zh-cn/application-dev/reference/apis/js-apis-usbManager.md @ge-yafang @Kevin-Lau @liuhonggang123 +zh-cn/application-dev/reference/apis/js-apis-usb.md @ge-yafang @Kevin-Lau @liuhonggang123 +zh-cn/application-dev/reference/apis/js-apis-usb-deprecated.md @ge-yafang @Kevin-Lau @liuhonggang123 zh-cn/application-dev/reference/apis/js-apis-useriam-userauth.md @gaoyong @zengyawen @niejiteng @jumozhanjiang zh-cn/application-dev/reference/apis/js-apis-util.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-vector.md @gongjunsong @ge-yafang @flyingwolf @BlackStone diff --git a/en/application-dev/application-models/js-ui-widget-development.md b/en/application-dev/application-models/js-ui-widget-development.md index 04a22731eb377f4c03a17d219549d6b230506583..178aa903a36b6a4742645cfab82a390364db0b37 100644 --- a/en/application-dev/application-models/js-ui-widget-development.md +++ b/en/application-dev/application-models/js-ui-widget-development.md @@ -80,7 +80,7 @@ The widget provider development based on the [stage model](stage-model-developme - [Creating a FormExtensionAbility Instance](#creating-a-formextensionability-instance): Develop the lifecycle callback functions of FormExtensionAbility. -- [Configuring the Widget Configuration File](#configuring-the-widget-configuration-file): Configure the application configuration file **module.json5** and profile configuration file. +- [Configuring the Widget Configuration Files](#configuring-the-widget-configuration-files): Configure the application configuration file **module.json5** and profile configuration file. - [Persistently Storing Widget Data](#persistently-storing-widget-data): Manage widget data persistence. diff --git a/en/application-dev/file-management/app-file-upload-download.md b/en/application-dev/file-management/app-file-upload-download.md index e95ba1dc8794404b4b79162356434017b57d08e4..a73fc9568cc03e791074866c20dc963b028cdb55 100644 --- a/en/application-dev/file-management/app-file-upload-download.md +++ b/en/application-dev/file-management/app-file-upload-download.md @@ -48,7 +48,7 @@ try { .then((uploadTask) => { uploadTask.on('complete', (taskStates) => { for (let i = 0; i < taskStates.length; i++) { - console.info(`upload complete taskState: ${JSON.stringify(taskStates[i])}'); + console.info(`upload complete taskState: ${JSON.stringify(taskStates[i])}`); } }); }) diff --git a/en/application-dev/file-management/figures/application-file-directory-structure.png b/en/application-dev/file-management/figures/application-file-directory-structure.png index 2ccc93278cb82842e21730194772a530324dcba7..6dd9d88ba37bd2a74a9d8a03fe8d61a378ce768e 100644 Binary files a/en/application-dev/file-management/figures/application-file-directory-structure.png and b/en/application-dev/file-management/figures/application-file-directory-structure.png differ diff --git a/en/application-dev/napi/figures/rawfile1.png b/en/application-dev/napi/figures/rawfile1.png index 9f29f7875cd983f967b7a3b27b5898bfce76c9f3..8e3ea5f2844a8124dee1bd3132b1cc86c70b8f64 100644 Binary files a/en/application-dev/napi/figures/rawfile1.png and b/en/application-dev/napi/figures/rawfile1.png differ diff --git a/en/application-dev/napi/rawfile-guidelines.md b/en/application-dev/napi/rawfile-guidelines.md index ccd517b40d77362b94b76001cf921f134a0cf237..555ef7fafdb5bf830d1f17ed7f73f50424c2edf4 100644 --- a/en/application-dev/napi/rawfile-guidelines.md +++ b/en/application-dev/napi/rawfile-guidelines.md @@ -1,313 +1,43 @@ -# Raw File Development +# RawFile Development ## When to Use -This document describes how to use the native Rawfile APIs to manage raw file directories and files in OpenHarmony. You can use Rawfile APIs to perform operations such as traversing the file list, opening, searching for, reading, and closing raw files. +This document describes how to use Native Rawfile APIs to manage the directories and files in the **rawfile** directory in OpenHarmony. You can use the APIs to perform operations, such as traversing a directory and opening, searching for, reading, and closing a file in the the **rawfile** directory. ## Available APIs -| Name | Description | -| :----------------------------------------------------------- | :--------------------------------------- | -| NativeResourceManager *OH_ResourceManager_InitNativeResourceManager(napi_env env, napi_value jsResMgr) | Initializes the native resource manager. | -| RawDir *OH_ResourceManager_OpenRawDir(const NativeResourceManager *mgr, const char *dirName) | Opens a raw file directory. | -| int OH_ResourceManager_GetRawFileCount(RawDir *rawDir) | Obtains the number of raw files in the specified directory.| -| const char *OH_ResourceManager_GetRawFileName(RawDir *rawDir, int index) | Obtains the name of a raw file. | -| RawFile *OH_ResourceManager_OpenRawFile(const NativeResourceManager *mgr, const char *fileName) | Opens a raw file. | -| long OH_ResourceManager_GetRawFileSize(RawFile *rawFile) | Obtains the size of a raw file. | -| int OH_ResourceManager_SeekRawFile(const RawFile *rawFile, long offset, int whence) | Seeks a read/write position in a raw file based on the specified offset. | -| long OH_ResourceManager_GetRawFileOffset(const RawFile *rawFile) | Obtains the offset. | -| int OH_ResourceManager_ReadRawFile(const RawFile *rawFile, void *buf, size_t length) | Reads a raw file. | -| void OH_ResourceManager_CloseRawFile(RawFile *rawFile) | Closes a raw file to release resources. | -| void OH_ResourceManager_CloseRawDir(RawDir *rawDir) | Closes a raw file directory to release resources. | -| bool OH_ResourceManager_GetRawFileDescriptor(const RawFile *rawFile, RawFileDescriptor &descriptor) | Obtains the file descriptor (FD) of a raw file. | -| bool OH_ResourceManager_ReleaseRawFileDescriptor(const RawFileDescriptor &descriptor) | Releases the FD of a raw file. | -| void OH_ResourceManager_ReleaseNativeResourceManager(NativeResourceManager *resMgr) | Releases the native resource manager. | - -## How to Develop - - The following describes how to obtain the raw file list, raw file content, and raw file descriptor on the JavaScript side as an example. - -1. Create a project. - -![Creating a C++ application](figures/rawfile1.png) - -2. Add dependencies. - -After a project is created, the **cpp** directory is created under the project. The directory contains files such as **libentry/index.d.ts**, **hello.cpp**, and **CMakeLists.txt**. - -1. Open the **src/main/cpp/CMakeLists.txt** file, and add **librawfile.z.so** and **libhilog_ndk.z.so** to **target_link_libraries**. - - ```c++ - target_link_libraries(entry PUBLIC libace_napi.z.so libhilog_ndk.z.so librawfile.z.so) - ``` - -2. Open the **src/main/cpp/types/libentry/index.d.ts** file, and declare the application functions **getFileList**, **getRawFileContent**, and **getRawFileDescriptor**. - - ```c++ - import resourceManager from '@ohos.resourceManager'; - export const getFileList: (resmgr: resourceManager.ResourceManager, path: string) => Array; - export const getRawFileContent: (resmgr: resourceManager.ResourceManager, path: string) => Uint8Array; - export const getRawFileDescriptor: (resmgr: resourceManager.ResourceManager, path: string) => resourceManager.RawFileDescriptor; - ``` - -3. Modify the source file. - -1. Open the **src/main/cpp/hello.cpp** file. During initialization, the file maps the external JavaScript APIs **getFileList**, **getRawFileContent**, and **getRawFileDescriptor** to C++ native APIs **GetFileList**, **GetRawFileContent**, and **GetRawFileDescriptor**. - - ```c++ - EXTERN_C_START - static napi_value Init(napi_env env, napi_value exports) - { - napi_property_descriptor desc[] = { - { "getFileList", nullptr, GetFileList, nullptr, nullptr, nullptr, napi_default, nullptr }, - { "getRawFileContent", nullptr, GetRawFileContent, nullptr, nullptr, nullptr, napi_default, nullptr }, - { "getRawFileDescriptor", nullptr, GetRawFileDescriptor, nullptr, nullptr, nullptr, napi_default, nullptr } - }; - - napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); - return exports; - } - EXTERN_C_END - ``` - -2. Add the three functions to the **src/main/cpp/hello.cpp** file. - - ```c++ - static napi_value GetFileList(napi_env env, napi_callback_info info) - static napi_value GetRawFileContent(napi_env env, napi_callback_info info) - static napi_value GetRawFileDescriptor(napi_env env, napi_callback_info info) - ``` - -3. Obtain JavaScript resource objects from the **hello.cpp** file, and convert them to native resource objects. Then, call the native APIs to obtain the raw file list, raw file content, and raw file descriptor {fd, offset, length}. The sample code is as follows: - - ```c++ - // Example 1: Use GetFileList to obtain the raw file list. - static napi_value GetFileList(napi_env env, napi_callback_info info) - { - OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "NDKTest Begin"); - size_t requireArgc = 3; - size_t argc = 2; - napi_value argv[2] = { nullptr }; - // Obtain arguments of the native API. - napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); - - // Obtain argv[0], which specifies conversion of the JavaScript resource object (that is, OH_ResourceManager_InitNativeResourceManager) to a native object. - NativeResourceManager *mNativeResMgr = OH_ResourceManager_InitNativeResourceManager(env, argv[0]); - - // Obtain argv[1], which specifies the relative path of the raw file. - size_t strSize; - char strBuf[256]; - napi_get_value_string_utf8(env, argv[1], strBuf, sizeof(strBuf), &strSize); - std::string dirName(strBuf, strSize); - - // Obtain the corresponding rawDir pointer object. - RawDir* rawDir = OH_ResourceManager_OpenRawDir(mNativeResMgr, dirName.c_str()); - - // Obtain the number of files and folders in rawDir. - int count = OH_ResourceManager_GetRawFileCount(rawDir); - - // Traverse rawDir to obtain the list of file names and save it. - std::vector tempArray; - for(int i = 0; i < count; i++) { - std::string filename = OH_ResourceManager_GetRawFileName(rawDir, i); - tempArray.emplace_back(filename); - } - - napi_value fileList; - napi_create_array(env, &fileList); - for (size_t i = 0; i < tempArray.size(); i++) { - napi_value jsString; - napi_create_string_utf8(env, tempArray[i].c_str(), NAPI_AUTO_LENGTH, &jsString); - napi_set_element(env, fileList, i, jsString); - } - - // Close the rawDir pointer object. - OH_ResourceManager_CloseRawDir(rawDir); - OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr); - return fileList; - } - - // Example 2: Use rawDir pointer object to obtain the content of the raw file. - napi_value CreateJsArrayValue(napi_env env, std::unique_ptr &data, long length) - { - napi_value buffer; - napi_status status = napi_create_external_arraybuffer(env, data.get(), length, - [](napi_env env, void *data, void *hint) { - delete[] static_cast(data); - }, nullptr, &buffer); - if (status != napi_ok) { - OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "Failed to create external array buffer"); - return nullptr; - } - napi_value result = nullptr; - status = napi_create_typedarray(env, napi_uint8_array, length, buffer, 0, &result); - if (status != napi_ok) { - OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "Failed to create media typed array"); - return nullptr; - } - data.release(); - return result; - } - static napi_value GetRawFileContent(napi_env env, napi_callback_info info) - { - OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "GetFileContent Begin"); - size_t requireArgc = 3; - size_t argc = 2; - napi_value argv[2] = { nullptr }; - // Obtain arguments of the native API. - napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); - - // Obtain argv[0], which specifies conversion of the JavaScript resource object (that is, OH_ResourceManager_InitNativeResourceManager) to a native object. - NativeResourceManager *mNativeResMgr = OH_ResourceManager_InitNativeResourceManager(env, argv[0]); - size_t strSize; - char strBuf[256]; - napi_get_value_string_utf8(env, argv[1], strBuf, sizeof(strBuf), &strSize); - std::string filename(strBuf, strSize); - - // Obtain the raw file pointer object. - RawFile *rawFile = OH_ResourceManager_OpenRawFile(mNativeResMgr, filename.c_str()); - if (rawFile != nullptr) { - OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "OH_ResourceManager_OpenRawFile success"); - } - // Obtain the size of the raw file and apply for memory. - long len = OH_ResourceManager_GetRawFileSize(rawFile); - std::unique_ptr data= std::make_unique(len); - // Read the raw file. - int res = OH_ResourceManager_ReadRawFile(rawFile, data.get(), len); - // Close the raw file pointer object. - OH_ResourceManager_CloseRawFile(rawFile); - OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr); - // Convert the native object to a JavaScript object. - return CreateJsArrayValue(env, data, len); - } - - // Example 3: Use GetRawFileDescriptor to obtain the FD of the raw file. - napi_value createJsFileDescriptor(napi_env env, RawFileDescriptor &descriptor) - { - napi_value result; - napi_status status = napi_create_object(env, &result); - if (status != napi_ok) { - return result; - } - - napi_value fd; - status = napi_create_int32(env, descriptor.fd, &fd); - if (status != napi_ok) { - return result; - } - status = napi_set_named_property(env, result, "fd", fd); - if (status != napi_ok) { - return result; - } - - napi_value offset; - status = napi_create_int64(env, descriptor.start, &offset); - if (status != napi_ok) { - return result; - } - status = napi_set_named_property(env, result, "offset", offset); - if (status != napi_ok) { - return result; - } - - napi_value length; - status = napi_create_int64(env, descriptor.length, &length); - if (status != napi_ok) { - return result; - } - status = napi_set_named_property(env, result, "length", length); - if (status != napi_ok) { - return result; - } - return result; - } - static napi_value GetRawFileDescriptor(napi_env env, napi_callback_info info) - { - OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "NDKTest GetRawFileDescriptor Begin"); - size_t requireArgc = 3; - size_t argc = 2; - napi_value argv[2] = { nullptr }; - // Obtain arguments of the native API. - napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); - - napi_valuetype valueType; - napi_typeof(env, argv[0], &valueType); - // Obtain the native resourceManager object. - NativeResourceManager *mNativeResMgr = OH_ResourceManager_InitNativeResourceManager(env, argv[0]); - size_t strSize; - char strBuf[256]; - napi_get_value_string_utf8(env, argv[1], strBuf, sizeof(strBuf), &strSize); - std::string filename(strBuf, strSize); - // Obtain the raw file pointer object. - RawFile *rawFile = OH_ResourceManager_OpenRawFile(mNativeResMgr, filename.c_str()); - if (rawFile != nullptr) { - OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "OH_ResourceManager_OpenRawFile success"); - } - // Obtain the FD of the raw file, that is, RawFileDescriptor {fd, offset, length}. - RawFileDescriptor descriptor; - OH_ResourceManager_GetRawFileDescriptor(rawFile, descriptor); - // Close the raw file pointer object. - OH_ResourceManager_CloseRawFile(rawFile); - OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr); - // Convert the native object to a JavaScript object. - return createJsFileDescriptor(env,descriptor); - } - ``` - -4. Call APIs on the JavaScript side. - -1. Open **src\main\ets\pages\index.ets**, and import **libentry.so**. - -2. Obtain the JavaScript resource object, that is, **resourceManager**. - -3. Call **getFileList**, that is, the native API declared in **src/main/cpp/types/libentry/index.d.ts**. When calling the API, pass the JavaScript resource object and the relative path of the raw file. The sample code is as follows: - - ```js - import hilog from '@ohos.hilog'; - import testNapi from 'libentry.so' // Import the libentry.so file. - @Entry - @Component - struct Index { - @State message: string = 'Hello World' - private resmgr = getContext().resourceManager; // Obtain the JavaScript resource object. - build() { - Row() { - Column() { - Text(this.message) - .fontSize(50) - .fontWeight(FontWeight.Bold) - .onClick(() => { - hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO); - let rawfilelist = testNapi.getFileList(this.resmgr, ""); // Pass the JavaScript resource object and the relative path of the raw file. - console.log("rawfilelist" + rawfilelist); - let rawfileContet = testNapi.getRawFileContent(this.resmgr, "rawfile1.txt"); - console.log("rawfileContet" + rawfileContet); - let rawfileDescriptor = testNapi.getRawFileDescriptor(this.resmgr, "rawfile1.txt"); - console.log("getRawFileDescriptor" + rawfileDescriptor.fd, rawfileDescriptor.offset, rawfileDescriptor.length); - }) - } - .width('100%') - } - .height('100%') - } - } - ``` - -## Using C++ Functions +| API | Description | +| :----------------------------------------------------------- | :----------------------------------------------------------- | +| NativeResourceManager *OH_ResourceManager_InitNativeResourceManager(napi_env env, napi_value jsResMgr) | Initializes a Native resource manager instance. | +| RawDir *OH_ResourceManager_OpenRawDir(const NativeResourceManager *mgr, const char *dirName) | Opens a directory in the **rawfile** directory. | +| int OH_ResourceManager_GetRawFileCount(RawDir *rawDir) | Obtains the number of files in the specified directory. | +| const char *OH_ResourceManager_GetRawFileName(RawDir *rawDir, int index) | Obtains the name of a file in the **rawfile** directory. | +| RawFile *OH_ResourceManager_OpenRawFile(const NativeResourceManager *mgr, const char *fileName) | Opens a file in the **rawfile** directory. | +| long OH_ResourceManager_GetRawFileSize(RawFile *rawFile) | Obtains the size of a file in the **rawfile** directory. | +| int OH_ResourceManager_SeekRawFile(const RawFile *rawFile, long offset, int whence) | Seeks for the read/write position in a file in the **rawfile** directory based on the specified offset. | +| long OH_ResourceManager_GetRawFileOffset(const RawFile *rawFile) | Obtains the offset of a file. | +| int OH_ResourceManager_ReadRawFile(const RawFile *rawFile, void *buf, size_t length) | Reads data from a file in the **rawfile** directory. | +| void OH_ResourceManager_CloseRawFile(RawFile *rawFile) | Closes a file in the **rawfile** directory to release resources. | +| void OH_ResourceManager_CloseRawDir(RawDir *rawDir) | Closes a directory in the **rawfile** directory to release resources. | +| bool OH_ResourceManager_GetRawFileDescriptor(const RawFile *rawFile, RawFileDescriptor &descriptor) | Obtains the file descriptor (FD) of a file in the **rawfile** directory. | +| bool OH_ResourceManager_ReleaseRawFileDescriptor(const RawFileDescriptor &descriptor) | Releases the FD of a file in the **rawfile** directory. | +| void OH_ResourceManager_ReleaseNativeResourceManager(NativeResourceManager *resMgr) | Releases a Native resource manager instance. | + +## Functions 1. Call **OH_ResourceManager_OpenRawDir** to obtain a **RawDir** instance based on the **NativeResourceManager** instance. ```c++ RawDir* rawDir = OH_ResourceManager_OpenRawDir(nativeResourceManager, path.c_str()); ``` - -2. Call **OH_ResourceManager_GetRawFileCount** to obtain the total number of raw files in the directory based on the **RawDir** instance. + +2. Call **OH_ResourceManager_GetRawFileCount** to obtain the total number of files in the directory based on the **RawDir** instance. ```c++ int count = OH_ResourceManager_GetRawFileCount(rawDir); ``` - -3. Call **OH_ResourceManager_GetRawFileName** to obtain the name of the raw file with the specified index. + +3. Call **OH_ResourceManager_GetRawFileName** to obtain the name of a file based on the specified index. ```c++ for (int index = 0; index < count; index++) { @@ -315,19 +45,19 @@ After a project is created, the **cpp** directory is created under the project. } ``` -4. Call **OH_ResourceManager_OpenRawFile** to obtain a **RawFile** instance with the specified file name. +4. Call **OH_ResourceManager_OpenRawFile** to open a **RawFile** instance with the specified file name. ```c++ RawFile* rawFile = OH_ResourceManager_OpenRawFile(nativeResourceManager, fileName.c_str()); ``` - -5. Call **OH_ResourceManager_GetRawFileSize** to obtain the size of the raw file. + +5. Call **OH_ResourceManager_GetRawFileSize** to obtain the size of the file. ```c++ long rawFileSize = OH_ResourceManager_GetRawFileSize(rawFile); ``` -6. Call **OH_ResourceManager_SeekRawFile** to seek a read/write position in the raw file based on the specified offset. +6. Call **OH_ResourceManager_SeekRawFile** to seek for the read/write position in the file based on the specified offset. ```c++ int position = OH_ResourceManager_SeekRawFile(rawFile, 10, 0); @@ -335,13 +65,13 @@ After a project is created, the **cpp** directory is created under the project. int position = OH_ResourceManager_SeekRawFile(rawFile, -10, 2); ``` -7. Call **OH_ResourceManager_GetRawFileOffset** to obtain the raw file offset. +7. Call **OH_ResourceManager_GetRawFileOffset** to obtain the file offset. ```c++ long rawFileOffset = OH_ResourceManager_GetRawFileOffset(rawFile) ``` -8. Call **OH_ResourceManager_ReadRawFile** to read the raw file. +8. Call **OH_ResourceManager_ReadRawFile** to read a file. ```c++ std::unique_ptr mediaData = std::make_unique(rawFileSize); @@ -354,27 +84,314 @@ After a project is created, the **cpp** directory is created under the project. OH_ResourceManager_CloseRawFile(rawFile); ``` -10. Call **OH_ResourceManager_CloseRawDir** to close the raw file directory. +10. Call **OH_ResourceManager_CloseRawDir** to close the file directory. ```c++ OH_ResourceManager_CloseRawDir(rawDir); ``` -11. Call **OH_ResourceManager_GetRawFileDescriptor** to obtain the FD of the raw file. +11. Call **OH_ResourceManager_GetRawFileDescriptor** to obtain the FD of the file. ```c++ RawFileDescriptor descriptor; bool result = OH_ResourceManager_GetRawFileDescriptor(rawFile, descriptor); ``` -12. Call **OH_ResourceManager_ReleaseRawFileDescriptor** to release the FD of the raw file. +12. Call **OH_ResourceManager_ReleaseRawFileDescriptor** to release the FD of the file. ```c++ OH_ResourceManager_ReleaseRawFileDescriptor(descriptor); ``` -13. Call **OH_ResourceManager_ReleaseNativeResourceManager** to release the native resource manager. +13. Call **OH_ResourceManager_ReleaseNativeResourceManager** to release the Native resource manager. ```c++ OH_ResourceManager_ReleaseNativeResourceManager(nativeResourceManager); ``` + +## How to Develop + +The following describes how to obtain the file list in the **rawfile** directory, file content, and FD {fd, offset, length} on the JavaScript side as an example. + +1. Create a project. + + ![Creating a C++ application](figures/rawfile1.png) + +2. Add dependencies. + + After the project is created, the **cpp** directory is created under the project. The directory contains files such as **libentry/index.d.ts**, **hello.cpp**, and **CMakeLists.txt**. + + 1. Open the **src/main/cpp/CMakeLists.txt** file, and add **librawfile.z.so** and **libhilog_ndk.z.so** to **target_link_libraries**. + + ``` + target_link_libraries(entry PUBLIC libace_napi.z.so libhilog_ndk.z.so librawfile.z.so) + ``` + + + + 2. Open the **src/main/cpp/types/libentry/index.d.ts** file, and declare the application functions **getFileList**, **getRawFileContent**, and **getRawFileDescriptor**. + + ```c++ + import resourceManager from '@ohos.resourceManager'; + export const getFileList: (resmgr: resourceManager.ResourceManager, path: string) => Array; + export const getRawFileContent: (resmgr: resourceManager.ResourceManager, path: string) => Uint8Array; + export const getRawFileDescriptor: (resmgr: resourceManager.ResourceManager, path: string) => resourceManager.RawFileDescriptor; + ``` + + + +3. Modify the source file. + + 1. Open the **src/main/cpp/hello.cpp** file. During initialization, the file maps the external JavaScript APIs **getFileList**, **getRawFileContent**, and **getRawFileDescriptor** to C++ native APIs **GetFileList**, **GetRawFileContent**, and **GetRawFileDescriptor**. + + ```c++ + EXTERN_C_START + static napi_value Init(napi_env env, napi_value exports) + { + napi_property_descriptor desc[] = { + { "getFileList", nullptr, GetFileList, nullptr, nullptr, nullptr, napi_default, nullptr }, + { "getRawFileContent", nullptr, GetRawFileContent, nullptr, nullptr, nullptr, napi_default, nullptr }, + { "getRawFileDescriptor", nullptr, GetRawFileDescriptor, nullptr, nullptr, nullptr, napi_default, nullptr } + }; + + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + return exports; + } + EXTERN_C_END + ``` + + + + 2. Add the three functions to the **src/main/cpp/hello.cpp** file. + + ```c++ + static napi_value GetFileList(napi_env env, napi_callback_info info) + static napi_value GetRawFileContent(napi_env env, napi_callback_info info) + static napi_value GetRawFileDescriptor(napi_env env, napi_callback_info info) + ``` + + + + 3. Obtain JavaScript resource objects from the **hello.cpp** file, and convert them to Native resource objects. Then, call the Native APIs to obtain the file list, file content, and FD {fd, offset, length}. + + The sample code is as follows: + + ```c++ + // Example 1: Use GetFileList to obtain the raw file list. + static napi_value GetFileList(napi_env env, napi_callback_info info) + { + OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "NDKTest Begin"); + size_t requireArgc = 3; + size_t argc = 2; + napi_value argv[2] = { nullptr }; + // Obtain arguments of the native API. + napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); + + // Obtain argv[0], which specifies conversion of the JavaScript resource object (that is, OH_ResourceManager_InitNativeResourceManager) to a native object. + NativeResourceManager *mNativeResMgr = OH_ResourceManager_InitNativeResourceManager(env, argv[0]); + + // Obtain argv[1], which specifies the relative path of the raw file. + size_t strSize; + char strBuf[256]; + napi_get_value_string_utf8(env, argv[1], strBuf, sizeof(strBuf), &strSize); + std::string dirName(strBuf, strSize); + + // Obtain the corresponding rawDir pointer object. + RawDir* rawDir = OH_ResourceManager_OpenRawDir(mNativeResMgr, dirName.c_str()); + + // Obtain the number of files and folders in rawDir. + int count = OH_ResourceManager_GetRawFileCount(rawDir); + + // Traverse rawDir to obtain the list of file names and save it. + std::vector tempArray; + for(int i = 0; i < count; i++) { + std::string filename = OH_ResourceManager_GetRawFileName(rawDir, i); + tempArray.emplace_back(filename); + } + + napi_value fileList; + napi_create_array(env, &fileList); + for (size_t i = 0; i < tempArray.size(); i++) { + napi_value jsString; + napi_create_string_utf8(env, tempArray[i].c_str(), NAPI_AUTO_LENGTH, &jsString); + napi_set_element(env, fileList, i, jsString); + } + + // Close the rawDir pointer object. + OH_ResourceManager_CloseRawDir(rawDir); + OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr); + return fileList; + } + + // Example 2: Use rawDir pointer object to obtain the content of the raw file. + napi_value CreateJsArrayValue(napi_env env, std::unique_ptr &data, long length) + { + napi_value buffer; + napi_status status = napi_create_external_arraybuffer(env, data.get(), length, + [](napi_env env, void *data, void *hint) { + delete[] static_cast(data); + }, nullptr, &buffer); + if (status != napi_ok) { + OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "Failed to create external array buffer"); + return nullptr; + } + napi_value result = nullptr; + status = napi_create_typedarray(env, napi_uint8_array, length, buffer, 0, &result); + if (status != napi_ok) { + OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "Failed to create media typed array"); + return nullptr; + } + data.release(); + return result; + } + static napi_value GetRawFileContent(napi_env env, napi_callback_info info) + { + OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "GetFileContent Begin"); + size_t requireArgc = 3; + size_t argc = 2; + napi_value argv[2] = { nullptr }; + // Obtain arguments of the native API. + napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); + + // Obtain argv[0], which specifies conversion of the JavaScript resource object (that is, OH_ResourceManager_InitNativeResourceManager) to a native object. + NativeResourceManager *mNativeResMgr = OH_ResourceManager_InitNativeResourceManager(env, argv[0]); + size_t strSize; + char strBuf[256]; + napi_get_value_string_utf8(env, argv[1], strBuf, sizeof(strBuf), &strSize); + std::string filename(strBuf, strSize); + + // Obtain the raw file pointer object. + RawFile *rawFile = OH_ResourceManager_OpenRawFile(mNativeResMgr, filename.c_str()); + if (rawFile != nullptr) { + OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "OH_ResourceManager_OpenRawFile success"); + } + // Obtain the size of the raw file and apply for memory. + long len = OH_ResourceManager_GetRawFileSize(rawFile); + std::unique_ptr data= std::make_unique(len); + // Read the raw file. + int res = OH_ResourceManager_ReadRawFile(rawFile, data.get(), len); + // Close the rawDir pointer object. + OH_ResourceManager_CloseRawFile(rawFile); + OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr); + // Convert the native object to a JavaScript object. + return CreateJsArrayValue(env, data, len); + } + + // Example 3: Use GetRawFileDescriptor to obtain the FD of the raw file. + napi_value createJsFileDescriptor(napi_env env, RawFileDescriptor &descriptor) + { + napi_value result; + napi_status status = napi_create_object(env, &result); + if (status != napi_ok) { + return result; + } + + napi_value fd; + status = napi_create_int32(env, descriptor.fd, &fd); + if (status != napi_ok) { + return result; + } + status = napi_set_named_property(env, result, "fd", fd); + if (status != napi_ok) { + return result; + } + + napi_value offset; + status = napi_create_int64(env, descriptor.start, &offset); + if (status != napi_ok) { + return result; + } + status = napi_set_named_property(env, result, "offset", offset); + if (status != napi_ok) { + return result; + } + + napi_value length; + status = napi_create_int64(env, descriptor.length, &length); + if (status != napi_ok) { + return result; + } + status = napi_set_named_property(env, result, "length", length); + if (status != napi_ok) { + return result; + } + return result; + } + static napi_value GetRawFileDescriptor(napi_env env, napi_callback_info info) + { + OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "NDKTest GetRawFileDescriptor Begin"); + size_t requireArgc = 3; + size_t argc = 2; + napi_value argv[2] = { nullptr }; + // Obtain arguments of the native API. + napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); + + napi_valuetype valueType; + napi_typeof(env, argv[0], &valueType); + // Obtain the native resourceManager object. + NativeResourceManager *mNativeResMgr = OH_ResourceManager_InitNativeResourceManager(env, argv[0]); + size_t strSize; + char strBuf[256]; + napi_get_value_string_utf8(env, argv[1], strBuf, sizeof(strBuf), &strSize); + std::string filename(strBuf, strSize); + // Obtain the raw file pointer object. + RawFile *rawFile = OH_ResourceManager_OpenRawFile(mNativeResMgr, filename.c_str()); + if (rawFile != nullptr) { + OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "OH_ResourceManager_OpenRawFile success"); + } + // Obtain the FD of the raw file, that is, RawFileDescriptor {fd, offset, length}. + RawFileDescriptor descriptor; + OH_ResourceManager_GetRawFileDescriptor(rawFile, descriptor); + // Close the rawDir pointer object. + OH_ResourceManager_CloseRawFile(rawFile); + OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr); + // Convert the native object to a JavaScript object. + return createJsFileDescriptor(env,descriptor); + } + ``` + + + +4. Call JavaScript APIs. + + 1. Open **src\main\ets\pages\index.ets**, and import **libentry.so**. + + 2. Obtain the JavaScript resource object, that is, **resourceManager**. + + 3. Call **getFileList**, that is, the Native API declared in **src/main/cpp/types/libentry/index.d.ts**. When calling the API, pass in the JavaScript resource object and the relative path of the file. + + The sample code is as follows: + + ```js + import hilog from '@ohos.hilog'; + import testNapi from 'libentry.so' // Import the libentry.so file. + @Entry + @Component + struct Index { + @State message: string = 'Hello World' + private resmgr = getContext().resourceManager; // Obtain the JavaScript resource object. + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + .onClick(() => { + hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO); + let rawfilelist = testNapi.getFileList(this.resmgr, ""); // Pass the JavaScript resource object and the relative path of the raw file. + console.log("rawfilelist" + rawfilelist); + let rawfileContet = testNapi.getRawFileContent(this.resmgr, "rawfile1.txt"); + console.log("rawfileContet" + rawfileContet); + let rawfileDescriptor = testNapi.getRawFileDescriptor(this.resmgr, "rawfile1.txt"); + console.log("getRawFileDescriptor" + rawfileDescriptor.fd, rawfileDescriptor.offset, rawfileDescriptor.length); + }) + } + .width('100%') + } + .height('100%') + } + } + ``` + + + diff --git a/en/application-dev/quick-start/arkts-two-way-sync.md b/en/application-dev/quick-start/arkts-two-way-sync.md index 25acb5741b55ed121950726455f9b3bfce183d29..8174856ff070faf47052f7d2dbb1c669a4e73ef8 100644 --- a/en/application-dev/quick-start/arkts-two-way-sync.md +++ b/en/application-dev/quick-start/arkts-two-way-sync.md @@ -11,7 +11,32 @@ What the internal state is depends on the component. For example, for the [bindP - $$ supports variables of simple types and variables decorated by **\@State**, **\@Link**, or **\@Prop**. -- Currently, $$ supports only the **show** parameter of the [bindPopup](../reference/arkui-ts/ts-universal-attributes-popup.md) attribute method, the **checked** attribute of the [\](../reference/arkui-ts/ts-basic-components-radio.md) component, and the **refreshing** parameter of the [\](../reference/arkui-ts/ts-container-refresh.md) component. +- $$ supports the components listed below. + + | Component | Supported Parameter/Attribute| Initial API Version| + | ------------------------------------------------------------ | --------------- | ----------- | + | [bindPopup](../reference/arkui-ts/ts-universal-attributes-popup.md) | show | 8 | + | [Checkbox](../reference/arkui-ts/ts-basic-components-checkbox.md) | select | 10 | + | [CheckboxGroup](../reference/arkui-ts/ts-basic-components-checkboxgroup.md) | selectAll | 10 | + | [DatePicker](../reference/arkui-ts/ts-basic-components-datepicker.md) | selected | 10 | + | [TimePicker](../reference/arkui-ts/ts-basic-components-timepicker.md) | selected | 10 | + | [MenuItem](../reference/arkui-ts/ts-basic-components-menuitem.md) | selected | 10 | + | [Panel](../reference/arkui-ts/ts-container-panel.md) | mode | 10 | + | [Radio](../reference/arkui-ts/ts-basic-components-radio.md) | checked | 10 | + | [Rating](../reference/arkui-ts/ts-basic-components-rating.md) | rating | 10 | + | [Refresh](../reference/arkui-ts/ts-container-refresh.md) | refreshing | 8 | + | [Search](../reference/arkui-ts/ts-basic-components-search.md) | value | 10 | + | [SideBarContainer](../reference/arkui-ts/ts-container-sidebarcontainer.md) | showSideBar | 10 | + | [Slider](../reference/arkui-ts/ts-basic-components-slider.md) | value | 10 | + | [Stepper](../reference/arkui-ts/ts-basic-components-stepper.md) | index | 10 | + | [Swiper](../reference/arkui-ts/ts-container-swiper.md) | isOn | 10 | + | [Tabs](../reference/arkui-ts/ts-container-tabs.md) | index | 10 | + | [TextArea](../reference/arkui-ts/ts-basic-components-textarea.md) | text | 10 | + | [TextInput](../reference/arkui-ts/ts-basic-components-textinput.md) | text | 10 | + | [TextPicker](../reference/arkui-ts/ts-basic-components-textpicker.md) | selected, value| 10 | + | [Toggle](../reference/arkui-ts/ts-basic-components-toggle.md) | isOn | 10 | + | [AlphabetIndexer](../reference/arkui-ts/ts-container-alphabet-indexer.md) | selected | 10 | + | [Select](../reference/arkui-ts/ts-basic-components-select.md) | selected, value| 10 | - When the variable bound to $$ changes, the UI is re-rendered synchronously. diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 6bb9b3075d7fd7787a943e44fea8a1968e413551..5d3b4b8ea4893b3784b0589e63ff12f808fc82ff 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -301,6 +301,7 @@ - [@ohos.nfc.controller (Standard NFC)](js-apis-nfcController.md) - [@ohos.nfc.tag (Standard NFC Tags)](js-apis-nfcTag.md) - [@ohos.rpc (RPC)](js-apis-rpc.md) + - [@ohos.secureElement (SE Channel Management)](js-apis-secureElement.md) - [@ohos.wifiManager (WLAN) (Recommended)](js-apis-wifiManager.md) - [@ohos.wifiManagerExt (WLAN Extension) (Recommended)](js-apis-wifiManagerExt.md) - [@ohos.wifi (WLAN) (To Be Deprecated Soon)](js-apis-wifi.md) diff --git a/en/application-dev/reference/apis/js-apis-arkui-componentSnapshot.md b/en/application-dev/reference/apis/js-apis-arkui-componentSnapshot.md index b6a2b41d6c9b9ed05603c68f94d8f53426570414..1a1972d66c2648ae0776cbd12d5dc7b769186414 100644 --- a/en/application-dev/reference/apis/js-apis-arkui-componentSnapshot.md +++ b/en/application-dev/reference/apis/js-apis-arkui-componentSnapshot.md @@ -34,6 +34,12 @@ Obtains the snapshot of a component that has been loaded. This API uses an async | id | string | Yes | [ID](../arkui-ts/ts-universal-attributes-component-id.md) of the target component.| | callback | AsyncCallback<image.PixelMap> | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 100001 | if id is not valid. | + **Example** ```js @@ -159,6 +165,12 @@ Renders a custom component in the application background and outputs its snapsho | builder | [CustomBuilder](../arkui-ts/ts-types.md#custombuilder8) | Yes | Builder of the custom component.| | callback | AsyncCallback<image.PixelMap> | Yes | Callback used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 100001 | if builder is not a valid build function. | + **Example** ```ts diff --git a/en/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md b/en/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md index cbfeab4f4142bb4cca332c0560ccd100b324acc0..25a6deb575728408b625e3c4f32aadfa05ffe960 100644 --- a/en/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md +++ b/en/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md @@ -31,6 +31,18 @@ Creates a **DrawableDescriptor** object when the passed resource ID or name belo Creates a **LayeredDrawableDescriptor** object when the passed resource ID or name belongs to a JSON file that contains foreground and background resources. +The content of the **drawble.json** file is as follows: + +```json +{ + "layered-image": + { + "background" : "$media:background", + "foreground" : "$media:foreground" + } +} +``` + **Example** ```ts // xxx.ets @@ -45,7 +57,7 @@ struct Index { Row() { Column() { Image(( (this.resManager.getDrawableDescriptor($r('app.media.icon').id)))) - Image((( (this.resManager.getDrawableDescriptor($r('app.media.icon') + Image((( (this.resManager.getDrawableDescriptor($r('app.media.drawable') .id))).getForeground()).getPixelMap()) }.height('50%') }.width('50%') @@ -68,7 +80,8 @@ Obtains this **pixelMap** object. **Example** ```ts -pixmap: PixelMap = drawable1.getPixelMap(); +pixmap: PixelMap = ( (this.resManager.getDrawableDescriptor($r('app.media.icon') + .id))).getPixelMap(); ``` ## LayeredDrawableDescriptor.getPixelMap @@ -86,7 +99,8 @@ Obtains the **pixelMap** object where the foreground, background, and mask are b **Example** ```ts -pixmap: PixelMap = layeredDrawable1.getPixelMap(); +pixmap: PixelMap = ( (this.resManager.getDrawableDescriptor($r('app.media.drawable') + .id))).getPixelMap(); ``` ## LayeredDrawableDescriptor.getForeground @@ -104,7 +118,8 @@ Obtains the **DrawableDescriptor** object of the foreground. **Example** ```ts -drawable: DrawableDescriptor = layeredDrawable1.getForeground(); +drawable: DrawableDescriptor = ( (this.resManager.getDrawableDescriptor($r('app.media.drawable') + .id))).getForeground(); ``` ## LayeredDrawableDescriptor.getBackground @@ -122,7 +137,8 @@ Obtains the **DrawableDescriptor** object of the background. **Example** ```ts -drawable: DrawableDescriptor = layeredDrawable1.getBackground(); +drawable: DrawableDescriptor = ( (this.resManager.getDrawableDescriptor($r('app.media.drawable') + .id))).getBackground(); ``` ## LayeredDrawableDescriptor.getMask @@ -140,5 +156,6 @@ Obtains the **DrawableDescriptor** object of the mask. **Example** ```ts -drawable: DrawableDescriptor = layeredDrawable1.getMask(); +drawable: DrawableDescriptor = ( (this.resManager.getDrawableDescriptor($r('app.media.drawable') + .id))).getMask(); ``` diff --git a/en/application-dev/reference/apis/js-apis-font.md b/en/application-dev/reference/apis/js-apis-font.md index 0a66ea708e32f95433061f082b3debd9911e753d..9b6d462358a52c439117f0025c440a9cb710259b 100644 --- a/en/application-dev/reference/apis/js-apis-font.md +++ b/en/application-dev/reference/apis/js-apis-font.md @@ -34,12 +34,14 @@ Registers a custom font with the font manager. ## FontOptions +**System capability**: SystemCapability.ArkUI.ArkUI.Full + | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ------------ | | familyName | string | Yes | Name of the custom font to register. | | familySrc | string | Yes | Path of the custom font to register.| -## Example +**Example** ```ts // xxx.ets @@ -68,7 +70,7 @@ struct FontExample { } } ``` -## font.getSystemFontList +## font.getSystemFontList10+ getSystemFontList(): Array\ @@ -82,7 +84,7 @@ Obtains the list of supported fonts. | -------------------- | ----------------- | | Array\ | List of supported fonts. | -## Example +**Example** ```ts // xxx.ets @@ -105,7 +107,7 @@ struct FontExample { } ``` -## font.getFontByName +## font.getFontByName10+ getFontByName(fontName: string): FontInfo; @@ -127,18 +129,22 @@ Obtains information about a system font based on the font name. ## FontInfo -| Name | Type | Description | -| -------------- | ------- | ------------------------- | -| path | string | File path of the system font. | -| postScriptName | string | PostScript name of the system font.| -| fullName | string | Name of the system font. | -| family | string | Family of the system font. | -| subfamily | string | Subfamily of the system font. | -| weight | number | Weight of the system font. | -| width | number | Width of the system font. | -| italic | boolean | Whether the system font is italic. | -| monoSpace | boolean | Whether the system font is monospaced. | -| symbolic | boolean | Whether the system font supports symbols. | +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| -------------- | ------- | ------------------------- | ------------------------- | +| path | string | Yes| File path of the system font. | +| postScriptName | string | Yes| PostScript name of the system font.| +| fullName | string | Yes| Name of the system font. | +| family | string | Yes| Family of the system font. | +| subfamily | string | Yes| Subfamily of the system font. | +| weight | number | Yes| Weight of the system font. | +| width | number | Yes| Width of the system font. | +| italic | boolean | Yes| Whether the system font is italic. | +| monoSpace | boolean | Yes| Whether the system font is monospaced. | +| symbolic | boolean | Yes| Whether the system font supports symbols. | + +**Example** ```ts // xxx.ets @@ -169,4 +175,3 @@ struct FontExample { } } ``` - diff --git a/en/application-dev/reference/apis/js-apis-huks.md b/en/application-dev/reference/apis/js-apis-huks.md index 11c2f8d4ea97dbc0149b68b6eea7b873ba8eeefb..911af6e5872df7747d837dd656ae63a259a991ad 100644 --- a/en/application-dev/reference/apis/js-apis-huks.md +++ b/en/application-dev/reference/apis/js-apis-huks.md @@ -17,7 +17,7 @@ import huks from '@ohos.security.huks' Defines the **param** in the **properties** array of **options** used in the APIs. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Core | Name| Type | Mandatory| Description | | ------ | ----------------------------------- | ---- | ------------ | @@ -28,7 +28,7 @@ Defines the **param** in the **properties** array of **options** used in the API Defines the **options** used in the APIs. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Core | Name | Type | Mandatory| Description | | ---------- | ----------------- | ---- | ------------------------ | @@ -39,7 +39,7 @@ Defines the **options** used in the APIs. Defines the HUKS handle structure. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Core | Name | Type | Mandatory| Description | | --------- | ---------- | ---- | ---------------------------------------------------- | @@ -48,9 +48,9 @@ Defines the HUKS handle structure. ## HuksReturnResult9+ -Defines the **HuksResult** structure. +Defines the **HuksResult** struct. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Core @@ -67,7 +67,7 @@ generateKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\ Generates a key. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Core **Parameters** @@ -142,7 +142,7 @@ generateKeyItem(keyAlias: string, options: HuksOptions) : Promise\ Generates a key. This API uses a promise to return the result. Because the key is always protected in an trusted environment (such as a TEE), the promise does not return the key content. It returns only the information indicating whether the API is successfully called. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension **Parameters** @@ -216,7 +216,7 @@ deleteKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\ Deletes a key. This API uses a promise to return the result. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension **Parameters** @@ -317,7 +317,7 @@ getSdkVersion(options: HuksOptions) : string Obtains the SDK version of the current system. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension **Parameters** @@ -347,7 +347,7 @@ importKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\ Imports a key in plaintext. This API uses a promise to return the result. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension **Parameters** @@ -524,7 +524,7 @@ attestKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\ Checks whether a key exists. This API uses a promise to return the result. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension **Parameters** @@ -1432,7 +1432,7 @@ let keyAlias = 'keyAlias'; let emptyOptions = { properties: [] }; -await huks.isKeyItemExist(keyAlias, emptyOptions).then((data) => { +huks.isKeyItemExist(keyAlias, emptyOptions).then((data) => { promptAction.showToast({ message: "keyAlias: " + keyAlias +"is existed! ", duration: 500, @@ -1451,7 +1451,7 @@ initSession(keyAlias: string, options: HuksOptions, callback: AsyncCallback\; Aborts a key operation. This API uses a promise to return the result. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension **Parameters** @@ -2087,7 +2087,7 @@ Enumerates the error codes. For details about the error codes, see [KUKS Error Codes](../errorcodes/errorcode-huks.md). -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Core | Name | Value| Description | | ---------------------------------------------- | -------- |--------------------------- | @@ -2114,25 +2114,25 @@ For details about the error codes, see [KUKS Error Codes](../errorcodes/errorcod Enumerates the key purposes. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Core | Name | Value | Description | | ------------------------ | ---- | -------------------------------- | -| HUKS_KEY_PURPOSE_ENCRYPT | 1 | Used to encrypt the plaintext.| -| HUKS_KEY_PURPOSE_DECRYPT | 2 | Used to decrypt the cipher text.| -| HUKS_KEY_PURPOSE_SIGN | 4 | Used for signing. | -| HUKS_KEY_PURPOSE_VERIFY | 8 | Used to verify the signature. | -| HUKS_KEY_PURPOSE_DERIVE | 16 | Used to derive a key. | -| HUKS_KEY_PURPOSE_WRAP | 32 | Used for an encrypted export. | -| HUKS_KEY_PURPOSE_UNWRAP | 64 | Used for an encrypted import. | -| HUKS_KEY_PURPOSE_MAC | 128 | Used to generate a message authentication code (MAC). | -| HUKS_KEY_PURPOSE_AGREE | 256 | Used for key agreement. | +| HUKS_KEY_PURPOSE_ENCRYPT | 1 | Used to encrypt the plaintext.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_KEY_PURPOSE_DECRYPT | 2 | Used to decrypt the cipher text.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_KEY_PURPOSE_SIGN | 4 | Used for signing.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_KEY_PURPOSE_VERIFY | 8 | Used to verify the signature.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_KEY_PURPOSE_DERIVE | 16 | Used to derive a key.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_KEY_PURPOSE_WRAP | 32 | Used for an encrypted export.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_KEY_PURPOSE_UNWRAP | 64 | Used for an encrypted import.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_KEY_PURPOSE_MAC | 128 | Used to generate a message authentication code (MAC).
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_KEY_PURPOSE_AGREE | 256 | Used for key agreement.
**System capability**: SystemCapability.Security.Huks.Extension| ## HuksKeyDigest Enumerates the digest algorithms. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension | Name | Value | Description | | ---------------------- | ---- | ---------------------------------------- | @@ -2149,89 +2149,89 @@ Enumerates the digest algorithms. Enumerates the padding algorithms. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Core | Name | Value | Description | | ---------------------- | ---- | ---------------------------------------- | -| HUKS_PADDING_NONE | 0 | No padding algorithm| -| HUKS_PADDING_OAEP | 1 | Optimal Asymmetric Encryption Padding (OAEP)| -| HUKS_PADDING_PSS | 2 | Probabilistic Signature Scheme (PSS)| -| HUKS_PADDING_PKCS1_V1_5 | 3 | Public Key Cryptography Standards (PKCS) #1 v1.5| -| HUKS_PADDING_PKCS5 | 4 | PKCS #5| -| HUKS_PADDING_PKCS7 | 5 | PKCS #7| +| HUKS_PADDING_NONE | 0 | No padding algorithm
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_PADDING_OAEP | 1 | Optimal Asymmetric Encryption Padding (OAEP)
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_PADDING_PSS | 2 | Probabilistic Signature Scheme (PSS)
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_PADDING_PKCS1_V1_5 | 3 | Public Key Cryptography Standards (PKCS) #1 v1.5
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_PADDING_PKCS5 | 4 | PKCS #5
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_PADDING_PKCS7 | 5 | PKCS #7
**System capability**: SystemCapability.Security.Huks.Core| ## HuksCipherMode Enumerates the cipher modes. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Core | Name | Value | Description | | ------------- | ---- | --------------------- | -| HUKS_MODE_ECB | 1 | Electronic Code Block (ECB) mode| -| HUKS_MODE_CBC | 2 | Cipher Block Chaining (CBC) mode| -| HUKS_MODE_CTR | 3 | Counter (CTR) mode| -| HUKS_MODE_OFB | 4 | Output Feedback (OFB) mode| -| HUKS_MODE_CCM | 31 | Counter with CBC-MAC (CCM) mode| -| HUKS_MODE_GCM | 32 | Galois/Counter (GCM) mode| +| HUKS_MODE_ECB | 1 | Electronic Code Block (ECB) mode
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_MODE_CBC | 2 | Cipher Block Chaining (CBC) mode
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_MODE_CTR | 3 | Counter (CTR) mode
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_MODE_OFB | 4 | Output Feedback (OFB) mode
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_MODE_CCM | 31 | Counter with CBC-MAC (CCM) mode
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_MODE_GCM | 32 | Galois/Counter (GCM) mode
**System capability**: SystemCapability.Security.Huks.Core| ## HuksKeySize Enumerates the key sizes. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Core | Name | Value | Description | | ---------------------------------- | ---- | ------------------------------------------ | -| HUKS_RSA_KEY_SIZE_512 | 512 | Rivest-Shamir-Adleman (RSA) key of 512 bits | -| HUKS_RSA_KEY_SIZE_768 | 768 | RSA key of 768 bits | -| HUKS_RSA_KEY_SIZE_1024 | 1024 | RSA key of 1024 bits | -| HUKS_RSA_KEY_SIZE_2048 | 2048 | RSA key of 2048 bits | -| HUKS_RSA_KEY_SIZE_3072 | 3072 | RSA key of 3072 bits | -| HUKS_RSA_KEY_SIZE_4096 | 4096 | RSA key of 4096 bits | -| HUKS_ECC_KEY_SIZE_224 | 224 | Elliptic Curve Cryptography (ECC) key of 224 bits | -| HUKS_ECC_KEY_SIZE_256 | 256 | ECC key of 256 bits | -| HUKS_ECC_KEY_SIZE_384 | 384 | ECC key of 384 bits | -| HUKS_ECC_KEY_SIZE_521 | 521 | ECC key of 521 bits | -| HUKS_AES_KEY_SIZE_128 | 128 | Advanced Encryption Standard (AES) key of 128 bits | -| HUKS_AES_KEY_SIZE_192 | 192 | AES key of 192 bits | -| HUKS_AES_KEY_SIZE_256 | 256 | AES key of 256 bits | -| HUKS_AES_KEY_SIZE_512 | 512 | AES key of 512 bits | -| HUKS_CURVE25519_KEY_SIZE_256 | 256 | Curve25519 key of 256 bits| -| HUKS_DH_KEY_SIZE_2048 | 2048 | Diffie-Hellman (DH) key of 2048 bits | -| HUKS_DH_KEY_SIZE_3072 | 3072 | DH key of 3072 bits | -| HUKS_DH_KEY_SIZE_4096 | 4096 | DH key of 4096 bits | -| HUKS_SM2_KEY_SIZE_2569+ | 256 | ShangMi2 (SM2) key of 256 bits | -| HUKS_SM4_KEY_SIZE_1289+ | 128 | ShangMi4 (SM4) key of 128 bits | +| HUKS_RSA_KEY_SIZE_512 | 512 | Rivest-Shamir-Adleman (RSA) key of 512 bits
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_RSA_KEY_SIZE_768 | 768 | RSA key of 768 bits
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_RSA_KEY_SIZE_1024 | 1024 | RSA key of 1024 bits
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_RSA_KEY_SIZE_2048 | 2048 | RSA key of 2048 bits
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_RSA_KEY_SIZE_3072 | 3072 | RSA key of 3072 bits
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_RSA_KEY_SIZE_4096 | 4096 | RSA key of 4096 bits
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_ECC_KEY_SIZE_224 | 224 | Elliptic Curve Cryptography (ECC) key of 224 bits
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_ECC_KEY_SIZE_256 | 256 | ECC key of 256 bits
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_ECC_KEY_SIZE_384 | 384 | ECC key of 384 bits
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_ECC_KEY_SIZE_521 | 521 | ECC key of 521 bits
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_AES_KEY_SIZE_128 | 128 | Advanced Encryption Standard (AES) key of 128 bits
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_AES_KEY_SIZE_192 | 192 | AES key of 192 bits
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_AES_KEY_SIZE_256 | 256 | AES key of 256 bits
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_AES_KEY_SIZE_512 | 512 | AES key of 512 bits
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_CURVE25519_KEY_SIZE_256 | 256 | Curve25519 key of 256 bits
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_DH_KEY_SIZE_2048 | 2048 | Diffie-Hellman (DH) key of 2048 bits
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_DH_KEY_SIZE_3072 | 3072 | DH key of 3072 bits
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_DH_KEY_SIZE_4096 | 4096 | DH key of 4096 bits
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_SM2_KEY_SIZE_2569+ | 256 | ShangMi2 (SM2) key of 256 bits
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_SM4_KEY_SIZE_1289+ | 128 | ShangMi4 (SM4) key of 128 bits
**System capability**: SystemCapability.Security.Huks.Extension| ## HuksKeyAlg Enumerates the key algorithms. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Core | Name | Value | Description | | ------------------------- | ---- | --------------------- | -| HUKS_ALG_RSA | 1 | RSA | -| HUKS_ALG_ECC | 2 | ECC | -| HUKS_ALG_DSA | 3 | DSA | -| HUKS_ALG_AES | 20 | AES | -| HUKS_ALG_HMAC | 50 | HMAC | -| HUKS_ALG_HKDF | 51 | HKDF | -| HUKS_ALG_PBKDF2 | 52 | PBKDF2 | -| HUKS_ALG_ECDH | 100 | ECDH | -| HUKS_ALG_X25519 | 101 | X25519 | -| HUKS_ALG_ED25519 | 102 | ED25519| -| HUKS_ALG_DH | 103 | DH | -| HUKS_ALG_SM29+ | 150 | SM2 | -| HUKS_ALG_SM39+ | 151 | SM3 | -| HUKS_ALG_SM49+ | 152 | SM4 | +| HUKS_ALG_RSA | 1 | RSA
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_ALG_ECC | 2 | ECC
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_ALG_DSA | 3 | DSA
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_ALG_AES | 20 | AES
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_ALG_HMAC | 50 | HMAC
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_ALG_HKDF | 51 | HKDF
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_ALG_PBKDF2 | 52 | PBKDF2
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_ALG_ECDH | 100 | ECDH
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_ALG_X25519 | 101 | X25519
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_ALG_ED25519 | 102 | ED25519
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_ALG_DH | 103 | DH
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_ALG_SM29+ | 150 | SM2
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_ALG_SM39+ | 151 | SM3
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_ALG_SM49+ | 152 | SM4
**System capability**: SystemCapability.Security.Huks.Extension| ## HuksKeyGenerateType Enumerates the key generation types. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension | Name | Value | Description | | ------------------------------ | ---- | ---------------- | @@ -2243,7 +2243,7 @@ Enumerates the key generation types. Enumerates the key generation modes. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Core | Name | Value | Description | | -------------------------- | ---- | ------------------------------------ | @@ -2256,20 +2256,20 @@ Enumerates the key generation modes. Enumerates the key storage modes. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Core | Name | Value | Description | | -------------------------------------------- | ---- | ------------------------------ | -| HUKS_STORAGE_TEMP | 0 | The key is managed locally. | -| HUKS_STORAGE_PERSISTENT | 1 | The key is managed by the HUKS service.| -| HUKS_STORAGE_ONLY_USED_IN_HUKS10+ | 2 | The key is stored only in the HUKS. | -| HUKS_STORAGE_KEY_EXPORT_ALLOWED10+ | 3 | The key is exported from the HUKS and is not stored.| +| HUKS_STORAGE_TEMP(deprecated) | 0 | The key is managed locally.
**NOTE**: This tag is discarded since API version 10. No substitute is provided because this tag is not used in key management. In key derivation scenarios, use **HUKS_STORAGE_ONLY_USED_IN_HUKS** or **HUKS_STORAGE_KEY_EXPORT_ALLOWED**.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_STORAGE_PERSISTENT(deprecated) | 1 | The key is managed by the HUKS service.
**NOTE**: This tag is discarded since API version 10. No substitute is provided because this tag is not used in key management. In key derivation scenarios, use **HUKS_STORAGE_ONLY_USED_IN_HUKS** or **HUKS_STORAGE_KEY_EXPORT_ALLOWED**.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_STORAGE_ONLY_USED_IN_HUKS10+ | 2 | The key derived from the master key is stored in the HUKS and managed by the HUKS.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_STORAGE_KEY_EXPORT_ALLOWED10+ | 3 | The key derived from the master key is exported to the service, and not managed by the HUKS.
**System capability**: SystemCapability.Security.Huks.Extension| ## HuksSendType Enumerates the tag transfer modes. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension | Name | Value | Description | | -------------------- | ---- | ----------------- | @@ -2280,7 +2280,7 @@ Enumerates the tag transfer modes. Enumerates the algorithm suites used for importing an encrypted key. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension | Name | Value | Description | | ---------------------------------------------- | ---- | ----------------------------------------------------- | @@ -2291,7 +2291,7 @@ Enumerates the algorithm suites used for importing an encrypted key. Enumerates the types of keys to import. By default, a public key is imported. This field is not required when a symmetric key is imported. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension | Name | Value | Description | | ------------------------- | ---- | ------------------------------ | @@ -2303,7 +2303,7 @@ Enumerates the types of keys to import. By default, a public key is imported. Th Enumerates the **salt_len** types to set when PSS padding is used in RSA signing or signature verification. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension | Name | Value | Description | | ------------------------------------------ | ---- | ---------------------------- | @@ -2314,7 +2314,7 @@ Enumerates the **salt_len** types to set when PSS padding is used in RSA signing Enumerates the user authentication types. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension | Name | Value | Description | | ------------------------------- | ---- | ------------------------- | @@ -2326,7 +2326,7 @@ Enumerates the user authentication types. Enumerates the access control types. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension | Name | Value | Description | | --------------------------------------- | ---- | ------------------------------------------------ | @@ -2337,7 +2337,7 @@ Enumerates the access control types. Enumerates the types of the challenges generated when a key is used. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension | Name | Value | Description | | ------------------------------- | ---- | ------------------------------ | @@ -2349,7 +2349,7 @@ Enumerates the types of the challenges generated when a key is used. Enumerates the positions of the 8-byte valid value in a custom challenge generated. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension | Name | Value | Description | | ------------------------------- | ---- | ------------------------------ | @@ -2362,7 +2362,7 @@ Enumerates the positions of the 8-byte valid value in a custom challenge generat Defines the signature type of the key generated or imported. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension | Name | Value | Description | | ------------------------------ | ---- | ------------------------------------------------------------ | @@ -2372,7 +2372,7 @@ Defines the signature type of the key generated or imported. Enumerates the tag data types. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Core | Name | Value | Description | | --------------------- | ------- | --------------------------------------- | @@ -2387,95 +2387,95 @@ Enumerates the tag data types. Enumerates the tags used to invoke parameters. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Core | Name | Value | Description | | -------------------------------------------- | ---------------------------------------- | -------------------------------------- | -| HUKS_TAG_INVALID | HuksTagType.HUKS_TAG_TYPE_INVALID \| 0 | Invalid tag. | -| HUKS_TAG_ALGORITHM | HuksTagType.HUKS_TAG_TYPE_UINT \| 1 | Algorithm. | -| HUKS_TAG_PURPOSE | HuksTagType.HUKS_TAG_TYPE_UINT \| 2 | Purpose of the key. | -| HUKS_TAG_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 3 | Key size. | -| HUKS_TAG_DIGEST | HuksTagType.HUKS_TAG_TYPE_UINT \| 4 | Digest algorithm. | -| HUKS_TAG_PADDING | HuksTagType.HUKS_TAG_TYPE_UINT \| 5 | Padding algorithm. | -| HUKS_TAG_BLOCK_MODE | HuksTagType.HUKS_TAG_TYPE_UINT \| 6 | Cipher mode. | -| HUKS_TAG_KEY_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 7 | Key type. | -| HUKS_TAG_ASSOCIATED_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 8 | Associated authentication data. | -| HUKS_TAG_NONCE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 9 | Field for key encryption and decryption. | -| HUKS_TAG_IV | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10 | IV. | -| HUKS_TAG_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 11 | Information generated during key derivation. | -| HUKS_TAG_SALT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 12 | Salt value used for key derivation. | -| HUKS_TAG_PWD | HuksTagType.HUKS_TAG_TYPE_BYTES \| 13 | Password used for key derivation. | -| HUKS_TAG_ITERATION | HuksTagType.HUKS_TAG_TYPE_UINT \| 14 | Number of iterations for key derivation. | -| HUKS_TAG_KEY_GENERATE_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 15 | Key generation type. | -| HUKS_TAG_DERIVE_MAIN_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 16 | Main key for key derivation. | -| HUKS_TAG_DERIVE_FACTOR | HuksTagType.HUKS_TAG_TYPE_BYTES \| 17 | Factor for key derivation. | -| HUKS_TAG_DERIVE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 18 | Type of the algorithm used for key derivation. | -| HUKS_TAG_AGREE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 19 | Type of the algorithm used for key agreement. | -| HUKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 20 | Public key alias used in key agreement. | -| HUKS_TAG_AGREE_PRIVATE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 21 | Private key alias used in key agreement. | -| HUKS_TAG_AGREE_PUBLIC_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 22 | Public key used in key agreement. | -| HUKS_TAG_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 23 | Key alias. | -| HUKS_TAG_DERIVE_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 24 | Size of the derived key. | -| HUKS_TAG_IMPORT_KEY_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 25 | Type of the imported key. | -| HUKS_TAG_UNWRAP_ALGORITHM_SUITE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 26 | Algorithm suite required for encrypted imports. | -| HUKS_TAG_DERIVED_AGREED_KEY_STORAGE_FLAG10+ | HuksTagType.HUKS_TAG_TYPE_UINT \|29 | Storage type of the derived key or agreed key.| -| HUKS_TAG_RSA_PSS_SALT_LEN_TYPE10+ | HuksTagType.HUKS_TAG_TYPE_UINT \|30 | Type of the **rsa_pss_salt_length**.| -| HUKS_TAG_ACTIVE_DATETIME(deprecated) | HuksTagType.HUKS_TAG_TYPE_ULONG \| 201 | Parameter originally reserved for certificate management. It is deprecated because certificate management is no longer implemented in this module. | -| HUKS_TAG_ORIGINATION_EXPIRE_DATETIME(deprecated) | HuksTagType.HUKS_TAG_TYPE_ULONG \| 202 | Parameter originally reserved for certificate management. It is deprecated because certificate management is no longer implemented in this module. | -| HUKS_TAG_USAGE_EXPIRE_DATETIME(deprecated) | HuksTagType.HUKS_TAG_TYPE_ULONG \| 203 | Parameter originally reserved for certificate management. It is deprecated because certificate management is no longer implemented in this module. | -| HUKS_TAG_CREATION_DATETIME(deprecated) | HuksTagType.HUKS_TAG_TYPE_ULONG \| 204 | Parameter originally reserved for certificate management. It is deprecated because certificate management is no longer implemented in this module. | -| HUKS_TAG_ALL_USERS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 301 | Reserved. | -| HUKS_TAG_USER_ID | HuksTagType.HUKS_TAG_TYPE_UINT \| 302 | ID of the user to which the key belongs. | -| HUKS_TAG_NO_AUTH_REQUIRED | HuksTagType.HUKS_TAG_TYPE_BOOL \| 303 | Reserved. | -| HUKS_TAG_USER_AUTH_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 304 | User authentication type. For details, see [HuksUserAuthType](#huksuserauthtype9). This parameter must be set together with [HuksAuthAccessType](#huksauthaccesstype9). You can set a maximum of two user authentication types at a time. For example, if **HuksAuthAccessType** is **HKS_SECURE_ACCESS_INVALID_NEW_BIO_ENROLL**, you can set two of **HKS_USER_AUTH_TYPE_FACE**, **HKS_USER_AUTH_TYPE_FINGERPRINT**, and **HKS_USER_AUTH_TYPE_FACE\**.| HKS_USER_AUTH_TYPE_FINGERPRINT | -| HUKS_TAG_AUTH_TIMEOUT | HuksTagType.HUKS_TAG_TYPE_UINT \| 305 | Timeout period of an authentication token. | -| HUKS_TAG_AUTH_TOKEN | HuksTagType.HUKS_TAG_TYPE_BYTES \| 306 | Used to pass in the authentication token. | -| HUKS_TAG_KEY_AUTH_ACCESS_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 307 | Access control type. For details, see [HuksAuthAccessType](#huksauthaccesstype9). This parameter must be set together with [HuksUserAuthType](#huksuserauthtype9).| -| HUKS_TAG_KEY_SECURE_SIGN_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 308 | Signature type of the key generated or imported.| -| HUKS_TAG_CHALLENGE_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 309 | Type of the challenge generated for a key. For details, see [HuksChallengeType](#hukschallengetype9).| -| HUKS_TAG_CHALLENGE_POS9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 310 | Position of the 8-byte valid value in a custom challenge. For details, see [HuksChallengePosition](#hukschallengeposition9).| -| HUKS_TAG_KEY_AUTH_PURPOSE10+ | HuksTagType.HUKS_TAG_TYPE_UINT \|311 | Key authentication purpose.| -| HUKS_TAG_ATTESTATION_CHALLENGE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 501 | Challenge value used in the attestation. | -| HUKS_TAG_ATTESTATION_APPLICATION_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 502 | Application ID used in the attestation. | -| HUKS_TAG_ATTESTATION_ID_BRAND | HuksTagType.HUKS_TAG_TYPE_BYTES \| 503 | Brand of the device. | -| HUKS_TAG_ATTESTATION_ID_DEVICE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 504 | ID of the device. | -| HUKS_TAG_ATTESTATION_ID_PRODUCT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 505 | Product name of the device. | -| HUKS_TAG_ATTESTATION_ID_SERIAL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 506 | SN of the device. | -| HUKS_TAG_ATTESTATION_ID_IMEI | HuksTagType.HUKS_TAG_TYPE_BYTES \| 507 | International mobile equipment identity (IMEI) of the device. | -| HUKS_TAG_ATTESTATION_ID_MEID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 508 | Mobile equipment identity (MEID) of the device. | -| HUKS_TAG_ATTESTATION_ID_MANUFACTURER | HuksTagType.HUKS_TAG_TYPE_BYTES \| 509 | Manufacturer of the device. | -| HUKS_TAG_ATTESTATION_ID_MODEL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 510 | Device model. | -| HUKS_TAG_ATTESTATION_ID_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 511 | Key alias used in the attestation. | -| HUKS_TAG_ATTESTATION_ID_SOCID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 512 | System-on-a-chip (SoCID) of the device. | -| HUKS_TAG_ATTESTATION_ID_UDID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 513 | Unique device identifier (UDID) of the device. | -| HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 514 | Security level used in the attestation. | -| HUKS_TAG_ATTESTATION_ID_VERSION_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 515 | Version information used in the attestation. | -| HUKS_TAG_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1001 | Whether to use the alias passed in during key generation.| -| HUKS_TAG_KEY_STORAGE_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1002 | Key storage mode. | -| HUKS_TAG_IS_ALLOWED_WRAP | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1003 | Reserved. | -| HUKS_TAG_KEY_WRAP_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1004 | Reserved. | -| HUKS_TAG_KEY_AUTH_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1005 | Reserved. | -| HUKS_TAG_KEY_ROLE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1006 | Reserved. | -| HUKS_TAG_KEY_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1007 | Flag of the key. | -| HUKS_TAG_IS_ASYNCHRONIZED | HuksTagType.HUKS_TAG_TYPE_UINT \| 1008 | Reserved. | -| HUKS_TAG_SECURE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1009 | Reserved. | -| HUKS_TAG_SECURE_KEY_UUID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1010 | Reserved. | -| HUKS_TAG_KEY_DOMAIN | HuksTagType.HUKS_TAG_TYPE_UINT \| 1011 | Reserved. | -| HUKS_TAG_PROCESS_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10001 | Process name. | -| HUKS_TAG_PACKAGE_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10002 | Reserved. | -| HUKS_TAG_ACCESS_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10003 | Reserved. | -| HUKS_TAG_USES_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10004 | Reserved. | -| HUKS_TAG_CRYPTO_CTX | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10005 | Reserved. | -| HUKS_TAG_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10006 | Reserved. | -| HUKS_TAG_KEY_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10007 | Key version. | -| HUKS_TAG_PAYLOAD_LEN | HuksTagType.HUKS_TAG_TYPE_UINT \| 10008 | Reserved. | -| HUKS_TAG_AE_TAG | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10009 | Used to pass in the AEAD in GCM mode. | -| HUKS_TAG_IS_KEY_HANDLE | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10010 | Reserved. | -| HUKS_TAG_OS_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10101 | OS version. | -| HUKS_TAG_OS_PATCHLEVEL | HuksTagType.HUKS_TAG_TYPE_UINT \| 10102 | OS patch level. | -| HUKS_TAG_SYMMETRIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20001 | Reserved. | -| HUKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20002 | Reserved. | -| HUKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20003 | Reserved. | +| HUKS_TAG_INVALID | HuksTagType.HUKS_TAG_TYPE_INVALID \| 0 | Invalid tag.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_TAG_ALGORITHM | HuksTagType.HUKS_TAG_TYPE_UINT \| 1 | Algorithm.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_TAG_PURPOSE | HuksTagType.HUKS_TAG_TYPE_UINT \| 2 | Purpose of the key.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_TAG_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 3 | Key size.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_TAG_DIGEST | HuksTagType.HUKS_TAG_TYPE_UINT \| 4 | Digest algorithm.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_PADDING | HuksTagType.HUKS_TAG_TYPE_UINT \| 5 | Padding algorithm.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_TAG_BLOCK_MODE | HuksTagType.HUKS_TAG_TYPE_UINT \| 6 | Cipher mode.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_TAG_KEY_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 7 | Key type.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_TAG_ASSOCIATED_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 8 | Associated authentication data.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_TAG_NONCE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 9 | Field for key encryption and decryption.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_TAG_IV | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10 | IV.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_TAG_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 11 | Information generated during key derivation.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_TAG_SALT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 12 | Salt value used for key derivation.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_PWD | HuksTagType.HUKS_TAG_TYPE_BYTES \| 13 | Password used for key derivation.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_TAG_ITERATION | HuksTagType.HUKS_TAG_TYPE_UINT \| 14 | Number of iterations for key derivation.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_KEY_GENERATE_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 15 | Key generation type.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_TAG_DERIVE_MAIN_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 16 | Main key for key derivation.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_DERIVE_FACTOR | HuksTagType.HUKS_TAG_TYPE_BYTES \| 17 | Factor for key derivation.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_DERIVE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 18 | Type of the algorithm used for key derivation.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_AGREE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 19 | Type of the algorithm used for key agreement.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 20 | Public key alias used in key agreement.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_AGREE_PRIVATE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 21 | Private key alias used in key agreement.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_AGREE_PUBLIC_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 22 | Public key used in key agreement.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 23 | Key alias.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_TAG_DERIVE_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 24 | Size of the derived key.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_IMPORT_KEY_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 25 | Type of the imported key.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_UNWRAP_ALGORITHM_SUITE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 26 | Algorithm suite required for encrypted imports.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_DERIVED_AGREED_KEY_STORAGE_FLAG10+ | HuksTagType.HUKS_TAG_TYPE_UINT \|29 | Storage type of the derived key or agreed key.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_RSA_PSS_SALT_LEN_TYPE10+ | HuksTagType.HUKS_TAG_TYPE_UINT \|30 | Type of the **rsa_pss_salt_length**.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_ACTIVE_DATETIME(deprecated) | HuksTagType.HUKS_TAG_TYPE_ULONG \| 201 | Parameter originally reserved for certificate management. It is deprecated because certificate management is no longer implemented in this module.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_ORIGINATION_EXPIRE_DATETIME(deprecated) | HuksTagType.HUKS_TAG_TYPE_ULONG \| 202 | Parameter originally reserved for certificate management. It is deprecated because certificate management is no longer implemented in this module.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_TAG_USAGE_EXPIRE_DATETIME(deprecated) | HuksTagType.HUKS_TAG_TYPE_ULONG \| 203 | Parameter originally reserved for certificate management. It is deprecated because certificate management is no longer implemented in this module.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_TAG_CREATION_DATETIME(deprecated) | HuksTagType.HUKS_TAG_TYPE_ULONG \| 204 | Parameter originally reserved for certificate management. It is deprecated because certificate management is no longer implemented in this module.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_TAG_ALL_USERS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 301 | Reserved.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_USER_ID | HuksTagType.HUKS_TAG_TYPE_UINT \| 302 | ID of the user to which the key belongs.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_NO_AUTH_REQUIRED | HuksTagType.HUKS_TAG_TYPE_BOOL \| 303 | Reserved.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_USER_AUTH_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 304 | User authentication type. For details, see [HuksUserAuthType](#huksuserauthtype9). This parameter must be set together with [HuksAuthAccessType](#huksauthaccesstype9). You can set a maximum of two user authentication types at a time. For example, if **HuksAuthAccessType** is **HKS_SECURE_ACCESS_INVALID_NEW_BIO_ENROLL**, you can set two of **HKS_USER_AUTH_TYPE_FACE**, **HKS_USER_AUTH_TYPE_FINGERPRINT**, and **HKS_USER_AUTH_TYPE_FACE\**.| HKS_USER_AUTH_TYPE_FINGERPRINT
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_AUTH_TIMEOUT | HuksTagType.HUKS_TAG_TYPE_UINT \| 305 | Timeout period of an authentication token.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_AUTH_TOKEN | HuksTagType.HUKS_TAG_TYPE_BYTES \| 306 | Used to pass in the authentication token.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_KEY_AUTH_ACCESS_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 307 | Access control type. For details, see [HuksAuthAccessType](#huksauthaccesstype9). This parameter must be set together with [HuksUserAuthType](#huksuserauthtype9).
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_KEY_SECURE_SIGN_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 308 | Signature type of the key generated or imported.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_CHALLENGE_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 309 | Type of the challenge generated for a key. For details, see [HuksChallengeType](#hukschallengetype9).
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_CHALLENGE_POS9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 310 | Position of the 8-byte valid value in a custom challenge. For details, see [HuksChallengePosition](#hukschallengeposition9).
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_KEY_AUTH_PURPOSE10+ | HuksTagType.HUKS_TAG_TYPE_UINT \|311 | Key authentication purpose.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_ATTESTATION_CHALLENGE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 501 | Challenge value used in the attestation.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_ATTESTATION_APPLICATION_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 502 | Application ID used in the attestation.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_ATTESTATION_ID_BRAND | HuksTagType.HUKS_TAG_TYPE_BYTES \| 503 | Brand of the device.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_ATTESTATION_ID_DEVICE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 504 | ID of the device.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_ATTESTATION_ID_PRODUCT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 505 | Product name of the device.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_ATTESTATION_ID_SERIAL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 506 | SN of the device.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_ATTESTATION_ID_IMEI | HuksTagType.HUKS_TAG_TYPE_BYTES \| 507 | International mobile equipment identity (IMEI) of the device.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_ATTESTATION_ID_MEID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 508 | Mobile equipment identity (MEID) of the device.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_ATTESTATION_ID_MANUFACTURER | HuksTagType.HUKS_TAG_TYPE_BYTES \| 509 | Manufacturer of the device.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_ATTESTATION_ID_MODEL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 510 | Device model.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_ATTESTATION_ID_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 511 | Key alias used in the attestation.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_ATTESTATION_ID_SOCID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 512 | System-on-a-chip (SoCID) of the device.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_ATTESTATION_ID_UDID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 513 | Unique device identifier (UDID) of the device.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 514 | Security level used in the attestation.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_ATTESTATION_ID_VERSION_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 515 | Version information used in the attestation.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1001 | Whether to use the alias passed in during key generation.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_TAG_KEY_STORAGE_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1002 | Key storage mode.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_TAG_IS_ALLOWED_WRAP | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1003 | Reserved.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_KEY_WRAP_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1004 | Reserved.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_KEY_AUTH_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1005 | Reserved.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_KEY_ROLE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1006 | Reserved.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_KEY_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1007 | Flag of the key.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_TAG_IS_ASYNCHRONIZED | HuksTagType.HUKS_TAG_TYPE_UINT \| 1008 | Reserved.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_SECURE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1009 | Reserved.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_TAG_SECURE_KEY_UUID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1010 | Reserved.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_KEY_DOMAIN | HuksTagType.HUKS_TAG_TYPE_UINT \| 1011 | Reserved.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_TAG_PROCESS_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10001 | Process name.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_TAG_PACKAGE_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10002 | Reserved.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_ACCESS_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10003 | Reserved.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_USES_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10004 | Reserved.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_CRYPTO_CTX | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10005 | Reserved.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10006 | Reserved.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_TAG_KEY_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10007 | Key version.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_PAYLOAD_LEN | HuksTagType.HUKS_TAG_TYPE_UINT \| 10008 | Reserved.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_AE_TAG | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10009 | Used to pass in the AEAD in GCM mode.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_TAG_IS_KEY_HANDLE | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10010 | Reserved.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_TAG_OS_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10101 | OS version.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_TAG_OS_PATCHLEVEL | HuksTagType.HUKS_TAG_TYPE_UINT \| 10102 | OS patch level.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_TAG_SYMMETRIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20001 | Reserved.
**System capability**: SystemCapability.Security.Huks.Core| +| HUKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20002 | Reserved.
**System capability**: SystemCapability.Security.Huks.Extension| +| HUKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20003 | Reserved.
**System capability**: SystemCapability.Security.Huks.Extension| ## huks.generateKey(deprecated) @@ -2485,7 +2485,7 @@ Generates a key. This API uses an asynchronous callback to return the result. > **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.generateKeyItem9+](#huksgeneratekeyitem9). -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension **Parameters** @@ -2537,7 +2537,7 @@ Generates a key. This API uses a promise to return the result. > **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.generateKeyItem9+](#huksgeneratekeyitem9-1). -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension **Parameters** @@ -2590,7 +2590,7 @@ Deletes a key. This API uses an asynchronous callback to return the result. > **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.deleteKeyItem9+](#huksdeletekeyitem9). -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension **Parameters** @@ -2619,7 +2619,7 @@ Deletes a key. This API uses a promise to return the result. > **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.deleteKeyItem9+](#huksdeletekeyitem9-1). -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension **Parameters** @@ -2653,7 +2653,7 @@ Imports a key in plaintext. This API uses an asynchronous callback to return the > **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.importKeyItem9+](#huksimportkeyitem9). -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension **Parameters** @@ -2713,7 +2713,7 @@ Imports a key in plaintext. This API uses a promise to return the result. > **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.importKeyItem9+](#huksimportkeyitem9-1). -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension **Parameters** @@ -2780,7 +2780,7 @@ Exports a key. This API uses an asynchronous callback to return the result. > **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.exportKeyItem9+](#huksexportkeyitem9). -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension **Parameters** @@ -2809,7 +2809,7 @@ Exports a key. This API uses a promise to return the result. > **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.exportKeyItem9+](#huksexportkeyitem9-1). -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension **Parameters** @@ -2843,7 +2843,7 @@ Obtains key properties. This API uses an asynchronous callback to return the res > **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.getKeyItemProperties9+](#huksgetkeyitemproperties9). -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension **Parameters** @@ -2872,7 +2872,7 @@ Obtains key properties. This API uses a promise to return the result. > **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.getKeyItemProperties9+](#huksgetkeyitemproperties9-1). -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension **Parameters** @@ -2906,7 +2906,7 @@ Checks whether a key exists. This API uses an asynchronous callback to return th > **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.isKeyItemExist9+](#huksiskeyitemexist9). -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension **Parameters** @@ -2935,7 +2935,7 @@ Checks whether a key exists. This API uses a promise to return the result. > **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.isKeyItemExist9+](#huksiskeyitemexist9-1). -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension **Parameters** @@ -2969,7 +2969,7 @@ Initializes the data for a key operation. This API uses an asynchronous callback > **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.initSession9+](#huksinitsession9-1). -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension **Parameters** @@ -2987,7 +2987,7 @@ Initializes the data for a key operation. This API uses a promise to return the > **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.initSession9+](#huksinitsession9-1). -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension **Parameters** @@ -3010,7 +3010,7 @@ Updates the key operation by segment. This API uses an asynchronous callback to > **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.updateSession9+](#huksupdatesession9-1). -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension **Parameters** @@ -3029,7 +3029,7 @@ Updates the key operation by segment. This API uses a promise to return the resu > **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.updateSession9+](#huksupdatesession9-2). -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension **Parameters** @@ -3053,7 +3053,7 @@ Completes the key operation and releases resources. This API uses an asynchronou > **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.finishSession9+](#huksfinishsession9). -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension **Parameters** @@ -3071,7 +3071,7 @@ Completes the key operation and releases resources. This API uses a promise to r > **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.finishSession9+](#huksfinishsession9-1). -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension **Parameters** @@ -3094,7 +3094,7 @@ Aborts the use of the key. This API uses an asynchronous callback to return the > **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.abortSession9+](#huksabortsession9). -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension **Parameters** @@ -3205,7 +3205,7 @@ Aborts the use of the key. This API uses a promise to return the result. > **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.abortSession9+](#huksabortsession9-1). -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension **Parameters** @@ -3323,7 +3323,7 @@ function huksAbort() { Defines the HUKS handle structure. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension > **NOTE**
This API is deprecated since API version 9. You are advised to use [HuksSessionHandle9+](#hukssessionhandle9). | Name | Type | Mandatory| Description | @@ -3336,7 +3336,7 @@ Defines the HUKS handle structure. Defines the **HuksResult** structure. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension > **NOTE**
This API is deprecated since API version 9. You are advised to use [HuksReturnResult9+](#huksreturnresult9). @@ -3352,7 +3352,7 @@ Defines the **HuksResult** structure. Enumerates the error codes. -**System capability**: SystemCapability.Security.Huks +**System capability**: SystemCapability.Security.Huks.Extension > **NOTE**
This API is deprecated since API version 9. You are advised to use HuksExceptionErrCode9+](#huksexceptionerrcode9). | Name | Value | Description| diff --git a/en/application-dev/reference/apis/js-apis-matrix4.md b/en/application-dev/reference/apis/js-apis-matrix4.md index 9c8c1a77c0150f8d820ec03701c3bd58ad9c8a17..e2de4ddcedf439f08598e5aa6b7eaca294fb936c 100644 --- a/en/application-dev/reference/apis/js-apis-matrix4.md +++ b/en/application-dev/reference/apis/js-apis-matrix4.md @@ -16,7 +16,7 @@ import matrix4 from '@ohos.matrix4' ## matrix4.init -init(option: [number,number,number,number,number,number,number,number,number,number,number,number,number,number,number,number]): Matrix4Transit +init(options: [number,number,number,number,number,number,number,number,number,number,number,number,number,number,number,number]): Matrix4Transit Matrix constructor, which is used to create a 4 x 4 matrix by using the input parameter. Column-major order is used. @@ -27,7 +27,7 @@ Matrix constructor, which is used to create a 4 x 4 matrix by using the input pa | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| option | [number,number,number,number,number,number,number,number,number,number,number,number,number,number,number,number] | Yes | A number array whose length is 16 (4 x 4). For details, see **Description of a 4 x 4 matrix**.
Default value:
[1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1] | +| option | [number,number,number,number,number,number,number,number,number,number,number,number,number,number,number,number] | Yes | A number array whose length is 16 (4 x 4). For details, see **Description of a 4 x 4 matrix**.
Default value:
[1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1] | **Return value** @@ -176,7 +176,7 @@ struct Test { ### combine -combine(option: Matrix4Transit): Matrix4Transit +combine(options: Matrix4Transit): Matrix4Transit Combines the effects of two matrices to generate a new matrix object. @@ -273,7 +273,7 @@ struct Tests { ### translate -translate(option: TranslateOption): Matrix4Transit +translate(options: TranslateOption): Matrix4Transit Translates this matrix object along the x, y, and z axes. @@ -317,7 +317,7 @@ struct Test { ### scale -scale(option: ScaleOption): Matrix4Transit +scale(options: ScaleOption): Matrix4Transit Scales this matrix object along the x, y, and z axes. @@ -362,7 +362,7 @@ struct Test { ### rotate -rotate(option: RotateOption): Matrix4Transit +rotate(options: RotateOption): Matrix4Transit Rotates this matrix object along the x, y, and z axes. @@ -408,7 +408,7 @@ struct Test { ### transformPoint -transformPoint(option: [number, number]): [number, number] +transformPoint(options: [number, number]): [number, number] Applies the current transformation effect to a coordinate point. @@ -466,15 +466,19 @@ struct Test { ## TranslateOption +**System capability**: SystemCapability.ArkUI.ArkUI.Full + | Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ----------------------------------------------------------- | -| x | number | No | Translation distance along the x-axis, in px.
Default value: **0**
Value range: (-∞, +∞)| -| y | number | No | Translation distance along the y-axis, in px.
Default value: **0**
Value range: (-∞, +∞)| -| z | number | No | Translation distance along the z-axis, in px.
Default value: **0**
Value range: (-∞, +∞)| +| ---- | ------ | ---- | ----------------------------------------------------------- | +| x | number | No | Translation distance along the x-axis, in px.
Default value: **0**
Value range: (-∞, +∞)| +| y | number | No | Translation distance along the y-axis, in px.
Default value: **0**
Value range: (-∞, +∞)| +| z | number | No | Translation distance along the z-axis, in px.
Default value: **0**
Value range: (-∞, +∞)| ## ScaleOption -| Name | Type | Mandatory| Description | +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Description | | ------- | ------ | ---- | ------------------------------------------------------------ | | x | number | No | Scaling multiple along the x-axis. If the value is greater than 1, the image is scaled up along the x-axis. If the value is less than 1, the image is scaled down along the x-axis.
Default value: **1**
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value.| | y | number | No | Scaling multiple along the y-axis. If the value is greater than 1, the image is scaled up along the y-axis. If the value is less than 1, the image is scaled down along the y-axis.
Default value: **1**
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value.| @@ -484,7 +488,9 @@ struct Test { ## RotateOption -| Name | Type | Mandatory| Description | +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Description | | ------- | ------ | ---- | ------------------------------------------------------- | | x | number | No | X coordinate of the rotation axis vector.
Default value: **1**
Value range: (-∞, +∞)| | y | number | No | Y coordinate of the rotation axis vector.
Default value: **1**
Value range: (-∞, +∞)| diff --git a/en/application-dev/reference/apis/js-apis-plugincomponent.md b/en/application-dev/reference/apis/js-apis-plugincomponent.md index 0ae1baf6eebdadbbdc9d43de1e9c100ac73163db..d6e63c978f5f9891858c102e161b3b9e7eddc29b 100644 --- a/en/application-dev/reference/apis/js-apis-plugincomponent.md +++ b/en/application-dev/reference/apis/js-apis-plugincomponent.md @@ -262,7 +262,7 @@ pluginComponentManager.push( name: "ets/pages/plugin2.js", data: { "js": "ets/pages/plugin.js", - "key_1": 1111, , + "key_1": 1111, }, extraData: { "extra_str": "this is push event" @@ -376,10 +376,24 @@ Listens for events of the request type and returns the requested data, or listen | eventType | string | Yes | Type of the event to listen for. The options are as follows:
**"push"**: The component provider pushes data to the component consumer.
**"request"**: The component consumer proactively requests data from the component provider.| | callback | [OnPushEventCallback](#onpusheventcallback) \| [OnRequestEventCallback](#onrequesteventcallback) | Yes | Callback used to return the result. The type is [OnPushEventCallback](#onpusheventcallback) for the push event and [OnRequestEventCallback](#onrequesteventcallback) for the request event.| - **Example** ```js +function onPushListener(source, template, data, extraData) { + console.log("onPushListener template.source=" + template.source) + console.log("onPushListener source=" + JSON.stringify(source)) + console.log("onPushListener template=" + JSON.stringify(template)) + console.log("onPushListener data=" + JSON.stringify(data)) + console.log("onPushListener extraData=" + JSON.stringify(extraData)) +} +function onRequestListener(source, name, data) { + console.error("onRequestListener"); + console.log("onRequestListener source=" + JSON.stringify(source)); + console.log("onRequestListener name=" + name); + console.log("onRequestListener data=" + JSON.stringify(data)); + + return { template: "ets/pages/plugin.js", data: data }; +} pluginComponentManager.on("push", onPushListener) pluginComponentManager.on("request", onRequestListener) ``` diff --git a/en/application-dev/reference/apis/js-apis-router.md b/en/application-dev/reference/apis/js-apis-router.md index 4319de28861f4056ca47657cf72a4af526b886f6..2d97910441aa8dc3d5fe958c5424a0b449ce0620 100644 --- a/en/application-dev/reference/apis/js-apis-router.md +++ b/en/application-dev/reference/apis/js-apis-router.md @@ -604,7 +604,7 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc | ID | Error Message| | --------- | ------- | -| 100001 | if UI execution context not found. | +| 100001 | if UI execution context not found, only throw in standard system. | | 100004 | if the named route is not exist. | **Example** @@ -645,7 +645,7 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc | ID | Error Message| | --------- | ------- | -| 100001 | if UI execution context not found. | +| 100001 | if UI execution context not found, only throw in standard system. | | 100004 | if the named route is not exist. | **Example** @@ -693,7 +693,7 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc | ID | Error Message| | --------- | ------- | -| 100001 | if can not get the delegate. | +| 100001 | if UI execution context not found, only throw in standard system. | | 100004 | if the named route is not exist. | **Example** @@ -735,7 +735,7 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc | ID | Error Message| | --------- | ------- | -| 100001 | if UI execution context not found. | +| 100001 | if UI execution context not found, only throw in standard system. | | 100004 | if the named route is not exist. | **Example** @@ -1054,7 +1054,7 @@ struct Second { Text(this.text) .fontSize(30) .onClick(() => { - this.secondData = (this.data.['array'][1]).toString() + this.secondData = (this.data['array'][1]).toString() }) .margin({ top: 20 }) Text(`This is the data passed from the first page: ${this.secondData}`) diff --git a/en/application-dev/reference/apis/js-apis-secureElement.md b/en/application-dev/reference/apis/js-apis-secureElement.md new file mode 100644 index 0000000000000000000000000000000000000000..429058cec789dcb61dcec498183c4ec92161c9be --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-secureElement.md @@ -0,0 +1,1283 @@ +# @ohos.secureElement (SE Management) + +The **secureElement** module provides APIs for operating and managing the SecureElement (SE). The SE service mentioned in this document is an **SEService** instance. For details, see [newSEService](#secureelementnewseservice). + +The instances of the following classes are involved in this document. + +| Class | Description | +| ------- | ---------------------------------------------- | +| Session | A **Session** instance represents a session for connecting to an available SE on the device.| +| Reader | A **Reader** instance represents an SE reader supported by the device. | +| Channel | A **Channel** instance represents an ISO/IEC 7816-4 channel opened to the SE. | + +> **NOTE** +> +> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## **Modules to Import** + +```js +import secureElement from '@ohos.secureElement'; +``` + +## secureElement.ServiceState + +Defines the SE service status values. + +**System capability**: SystemCapability.Communication.SecureElement + +| Name | Value | Description | +| ------------ | ---- | ------------------ | +| DISCONNECTED | 0 | The SE service is disconnected.| +| CONNECTED | 1 | The SE service is connected.| + +## secureElement.newSEService + +newSEService(type: 'serviceState', callback: Callback<[ServiceState](#secureelementservicestate)>): SEService + +Creates an **SEService** instance for connecting to all available SEs in the system. The connection is time-consuming. Therefore, this API supports only the asynchronous mode. + +The returned **SEService** object is available only when **true** is returned by the specified callback or [isConnected](#seserviceisconnected). + +**System capability**: SystemCapability.Communication.SecureElement + +**Parameters** + +| **Name**| **Type** | **Description** | +| ---------- | ---------------------------------------------------- | -------------------- | +| type | string | 'serviceState' | +| callback | Callback<[ServiceState](#secureelementservicestate)> | Callback invoked to return the SE service status.| + +**Return value** + +| **Type** | **Description** | +| :-------- | :--------- | +| SEService | Returns the **SEService** instance created.| + +**Example** + +```js +import secureElement from '@ohos.secureElement'; + +@State result: string = ''; +@State nfcSEService: secureElement.SEService = null; + +this.result = "Service state is Unkown"; +try { + this.nfcSEService = secureElement.newSEService("serviceState", (state) => { + if (state == secureElement.ServiceState.DISCONNECTED) { + this.result = "Service state is Disconnected"; + } else { + this.result = "Service state is Connected"; + } + }); +} catch (e) { + this.result = "newSEService occurs exception:" + e.message; +} +``` + +## SEService.getReaders + +getReaders(): Reader[] + +Obtains the available SE readers. The returned array cannot contain duplicate objects. Even if no card is inserted, all available readers should be listed. + +**System capability**: SystemCapability.Communication.SecureElement + +**Return value** + +| **Type**| **Description** | +| :------- | :--------------------- | +| Reader[] | Returns an array of available **Reader** objects.| + +**Example** + +```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; + +// get SEService +try { + this.nfcSEService = secureElement.newSEService("serviceState", (state) => { + if (state == secureElement.ServiceState.DISCONNECTED) { + this.result = "Service state is Disconnected"; + } else { + this.result = "Service state is Connected"; + } + }); +} catch (e) { + this.result = "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"; + } else { + this.result = "get reader failed"; + } +} catch (e) { + this.result = "getReaders exception:" + e.message; +} +``` + +## SEService.isConnected + +isConnected(): boolean + +Checks whether this SE service is connected. + +**System capability**: SystemCapability.Communication.SecureElement + +**Return value** + +| **Type**| **Description** | +| :------- | :--------------------------------------------- | +| boolean | Returns **true** if the SE service is connected; returns **false** otherwise.| + +**Example** + +```JS +import secureElement from '@ohos.secureElement'; + +@State result: string = '' +@State nfcSEService: secureElement.SEService = null; + +try { + let ret: boolean; + // refer to newSEService for this.nfcSEService + ret = this.nfcSEService.isConnected(); + if (ret) { + this.result = 'get state: connected'; + } else { + this.result = 'get state: not connected'; + } +} catch (e) { + this.result = "isConnected exception: " + e.message; +} +``` + +## SEService.shutdown + +shutdown(): void + +Releases all SE resources allocated to this service. After that, [isConnected](#seserviceisconnected) returns **false**. + +**System capability**: SystemCapability.Communication.SecureElement + +**Example** + +```js +import secureElement from '@ohos.secureElement'; + +@State result: string = ''; +@State nfcSEService: secureElement.SEService = null; + +try { + // refer to newSEService for this.nfcSEService + this.nfcSEService.shutdown(); + this.result = "shutdown successfully"; +} catch (e) { + this.result = "shutdown exception:" + e.message; +} +``` + +## SEService.getVersion + +getVersion(): string + +Obtains the version of the Open Mobile API Specification used for the implementation. + +**System capability**: SystemCapability.Communication.SecureElement + +**Return value** + +| **Type**| **Description** | +| -------- | -------------------------------------------------- | +| string | Returns the OMA version. For example, **3.3** indicates Open Mobile API Specification v3.3.| + +**Example** + +```JS +import secureElement from '@ohos.secureElement'; + +@State result: string = ''; +@State nfcSEService: secureElement.SEService = null; + +this.result = "version: " +try { + // refer to newSEService for this.nfcSEService + this.result += this.nfcSEService.getVersion(); +} catch (e) { + this.result = "getVersion exception:" + e.message; +} +``` + +## Reader.getName + +getName(): string + +Obtains the reader name. If the card reader is a SIM reader, its name must be in **SIM[Slot]** format. If the card reader is an embedded SE reader, its name must be in **eSE[slot]** format. + +**System capability**: SystemCapability.Communication.SecureElement + +**Return value** + +| **Type**| **Description** | +| -------- | ---------- | +| string | Returns the reader name obtained.| + +**Example** + +```js +import secureElement from '@ohos.secureElement'; + +@State result: string = ''; +@State nfcOmaReader: secureElement.Reader = null; + +try { + // refer to SEService.getReaders for this.nfcOmaReader + this.result = this.nfcOmaReader.getName(); +} catch (e) { + this.result = "getName exception:" + e.message; +} +``` + +## Reader.isSecureElementPresent + +isSecureElementPresent(): boolean + +Checks whether the SE corresponding to this reader is available. + +**System capability**: SystemCapability.Communication.SecureElement + +**Return value** + +| **Type**| **Description** | +| -------- | -------------------------------------------- | +| boolean | Returns **true** if the SE is available; returns **false** otherwise.| + +**Error codes** + +For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.md). + +| ID| Error Message | +| -------- | -------------------------------- | +| 3300101 | Illegal service state exception. | + +**Example** + +```js +import secureElement from '@ohos.secureElement'; + +@State result: string = ''; +@State nfcOmaReader: secureElement.Reader = null; + +try { + // refer to SEService.getReaders for this.nfcOmaReader + if (this.nfcOmaReader.isSecureElementPresent()) { + this.result = "isSecureElementPresent TRUE"; + } else { + this.result = "isSecureElementPresent FALSE"; + } +} catch (e) { + this.result = "isSecureElementPresent exception:" + e.message; +} +``` + +## Reader.openSession + + openSession(): Session + +Connects to the SE of this reader. This API initializes the SE for communication before returning the session object. Multiple sessions may be opened on a reader at the same time. + +**System capability**: SystemCapability.Communication.SecureElement + +**Return value** + +| **Type**| **Description** | +| -------- | ------------------------------ | +| Session | Returns the **Session** object used to create a channel.| + +**Error codes** + +For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.md). + +| ID| Error Message | +| -------- | -------------------------------- | +| 3300101 | Illegal service state exception. | +| 3300104 | Secure element IO exception. | + +**Example** + +```js +import secureElement from '@ohos.secureElement'; + +@State result: string = ''; +@State nfcOmaReader: secureElement.Reader = null; +@State nfcOmaSession: secureElement.Session = null; + +try { + // refer to SEService.getReaders for this.nfcOmaReader + this.nfcOmaSession = this.nfcOmaReader.openSession(); + if (this.nfcOmaSession) { + this.result = "get session successfully"; + } else { + this.result = "get session failed"; + } +} catch (e) { + this.result = "OpenSession exception: " + e.message; +} +``` + +## Reader.closeSessions + + closeSessions(): void + +Closes all sessions opened on this reader. This API closes all channels opened by these sessions. + +**System capability**: SystemCapability.Communication.SecureElement + +**Error codes** + +For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.md). + +| ID| Error Message | +| -------- | -------------------------------- | +| 3300101 | Illegal service state exception. | + +**Example** + +```js +import secureElement from '@ohos.secureElement'; + +@State result: string = ''; +@State nfcOmaReader: secureElement.Reader = null; + +try { + // refer to SEService.getReaders for this.nfcOmaReader + this.nfcOmaReader.closeSessions(); + this.result = "close Sessions successfully"; +} catch (e) { + this.result = "closeSessions exception:" + e.message; +} +``` + +## Session.getReader + +getReader(): Reader + +Obtains the reader that provides this session. + +**System capability**: SystemCapability.Communication.SecureElement + +**Return value** + +| **Type**| **Description** | +| -------- | --------------------------- | +| Reader | Returns the **Reader** object obtained.| + +**Example** + +```js +import secureElement from '@ohos.secureElement'; + +@State result: string = ''; +@State nfcOmaReader: secureElement.Reader = null; +@State nfcOmaSession: secureElement.Session = null; + +try { + // refer to Reader.openSession for this.nfcOmaSession + this.nfcOmaReader = this.nfcOmaSession.getReader(); + if (this.nfcOmaReader) { + this.result = "get reader successfully"; + } else { + this.result = "get reader failed"; + } +} catch (e) { + this.result = "getReader exception:" + e.message; +} +``` + +## Session.getATR + +getATR(): number[] + +Obtains the ATR of this SE. If the ATR of this SE is not available, an empty array will be returned. + +**System capability**: SystemCapability.Communication.SecureElement + +**Return value** + +| **Type**| **Description** | +| -------- | -------------------------------------------- | +| number[] | Returns the ATR obtained if the SE has an available ATR; returns an empty array otherwise.| + +**Error codes** + +For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.md). + +| ID| Error Message | +| -------- | -------------------------------- | +| 3300101 | Illegal service state exception. | + +**Example** + +```js +import secureElement from '@ohos.secureElement'; + +@State result: string = ''; +@State nfcOmaSession: secureElement.Session = null; + +try { + // refer to Reader.openSession for this.nfcOmaSession + let ret = this.nfcOmaSession.getATR(); + if (ret) { + this.result = "getATR result:["; + for (let i = 0; i < ret.length; ++i) { + this.result += ret[i]; + this.result += ' '; + } + this.result += ']'; + } else { + this.result = "getATR result is null"; + } +} catch (e) { + this.result = "getATR exception:" + e.message; +} +``` + +## Session.close + +close(): void + +Closes the connection with this SE. This API closes all channels opened between this application and the SE. + +**System capability**: SystemCapability.Communication.SecureElement + +**Error codes** + +For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.md). + +| ID| Error Message | +| -------- | -------------------------------- | +| 3300101 | Illegal service state exception. | + +**Example** + +```js +import secureElement from '@ohos.secureElement'; + +@State result: string = ''; +@State nfcOmaSession: secureElement.Session = null; + +try { + // refer to Reader.openSession for this.nfcOmaSession + this.nfcOmaSession.close(); + this.result = "session close successfully"; +} catch (e) { + this.result = "session close exception:" + e.message; +} +``` + +## Session. isClosed + +isClosed(): boolean + +Checks whether the session is closed. + +**System capability**: SystemCapability.Communication.SecureElement + +**Return value** + +| **Type**| **Description** | +| -------- | ------------------------------------ | +| boolean | Returns **true** if the session is closed; returns **false** otherwise.| + +**Error codes** + +For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.md). + +**Example** + +```Js +import secureElement from '@ohos.secureElement'; + +@State result: string = ''; +@State nfcOmaSession: secureElement.Session = null; + +try { + // refer to Reader.openSession for this.nfcOmaSession + let ret = this.nfcOmaSession.isClosed(); + if (ret) { + this.result = "session state is closed"; + } else { + this.result = "session state is not closed"; + } +} catch (e) { + this.result = "isClosed exception:" + e.message; +} +``` + +## Session.closeChannels + +closeChannels(): void + +Closes all channels opened in this session. + +**System capability**: SystemCapability.Communication.SecureElement + +**Error codes** + +For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.md). + +| ID| Error Message | +| -------- | -------------------------------- | +| 3300101 | Illegal service state exception. | + +**Example** + +```js +import secureElement from '@ohos.secureElement'; + +@State result: string = ''; +@State nfcOmaSession: secureElement.Session = null; + +try { + // refer to Reader.openSession for this.nfcOmaSession + this.nfcOmaSession.closeChannels(); + this.result = "close Channels successfully"; +} catch (e) { + this.result = "closeChannels exception:" + e.message; +} +``` + +## Session.openBasicChannel + +openBasicChannel(aid: number[]): Promise + +Opens a basic channel. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.SecureElement + +**Parameters** + +| **Name**| **Type**| **Description** | +| ---------- | -------- | ------------------------------------------------------------ | +| aid | number[] | 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. | + +**Error codes** + +For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.md). + +| ID| Error Message | +| -------- | -------------------------------- | +| 3300101 | Illegal service state exception. | +| 3300102 | No such element exception. | +| 3300103 | Illegal access rule exception. | +| 3300104 | Secure element IO exception. | + +**Example** + +```js +import secureElement from '@ohos.secureElement'; + +@State result: string = ''; +@State nfcOmaSession: secureElement.Session = null; +@State nfcOmaChannel: secureElement.Channel = null; + +try { + // See Reader.openSession for this.nfcOmaSession. + let getPromise = this.nfcOmaSession.openBasicChannel(this.aidArray); + getPromise.then((channel) => { + this.nfcOmaChannel = channel; + this.result = "openBasicChannel1 get channel successfully"; + }).catch ((err) => { + this.result = "openBasicChannel1 exception:" + err.message; + }); +} catch (e) { + this.result = "OpenBasicChannel1 exception:" + e.message; +} +``` + +## Session.openBasicChannel + + openBasicChannel(aid: number[], callback: AsyncCallback): void + +Opens a basic channel. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.SecureElement + +**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. | + +**Error codes** + +For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.md). + +| ID| Error Message | +| -------- | -------------------------------- | +| 3300101 | Illegal service state exception. | +| 3300102 | No such element exception. | +| 3300103 | Illegal access rule exception. | +| 3300104 | Secure element IO exception. | + +**Example** + +```js +import secureElement from '@ohos.secureElement'; + +@State result: string = ''; +@State nfcOmaSession: secureElement.Session = null; +@State nfcOmaChannel: secureElement.Channel = null; +aidArray: number[] = [720, 1080]; + +try { + // See Reader.openSession for this.nfcOmaSession. + this.nfcOmaSession.openBasicChannel(this.aidArray, (error, data) => { + if (error) { + this.result = "openBasicChannel2 failed:" + JSON.stringify(error); + return; + } + this.nfcOmaChannel = data; + this.result = "openBasicChannel2 get channel successfully"; + }); +} catch (e) { + this.result = "openBasicChannel2 exception:" + e.message; +} +``` + +## Session.openBasicChannel + +openBasicChannel(aid: number[], p2: number): Promise + +Opens a basic channel. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.SecureElement + +**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. | + +**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. | + +**Error codes** + +For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.md). + +| ID| Error Message | +| -------- | -------------------------------- | +| 3300101 | Illegal service state exception. | +| 3300102 | No such element exception. | +| 3300103 | Illegal access rule exception. | +| 3300104 | Secure element IO exception. | + +**Example** + +```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; + +try { + // See Reader.openSession for this.nfcOmaSession. + let getPromise = this.nfcOmaSession.openBasicChannel(this.aidArray, this.p2); + getPromise.then((channel) => { + this.nfcOmaChannel = channel; + this.result = "openBasicChannel3 get channel successfully"; + }).catch ((err) => { + this.result = "openBasicChannel3 exception"; + }); +} catch (e) { + this.result = "openBasicChannel3 exception:" + e.message; +} +``` + +## Session.openBasicChannel + +openBasicChannel(aid: number[], p2:number, callback: AsyncCallback): void + +Opens a basic channel. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.SecureElement + +**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. | + +**Error codes** + +For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.md). + +| ID| Error Message | +| -------- | -------------------------------- | +| 3300101 | Illegal service state exception. | +| 3300102 | No such element exception. | +| 3300103 | Illegal access rule exception. | +| 3300104 | Secure element IO exception. | + +**Example** + +```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; + +try { + // See Reader.openSession for this.nfcOmaSession. + this.nfcOmaSession.openBasicChannel(this.aidArray, this.p2, (error, data) => { + if (error) { + this.result = "openBasicChannel4 failed:" + JSON.stringify(error); + return; + } + this.nfcOmaChannel = data; + this.result = "openBasicChannel4 get channel successfully"; + }); +} catch (e) { + this.result = "openBasicChannel4 exception:" + e.message; +} +``` + +## Session.openLogicalChannel + +openLogicalChannel(aid: number[]): Promise + +Opens a logical channel. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.SecureElement + +**Parameters** + +| **Name**| **Type**| **Description** | +| ---------- | -------- | --------------------------------------- | +| aid | number[] | AIDs of the applets selected on the **Channel** instance. | + +**Return value** + +| **Type**| **Description** | +| -------- | ------------------------------------------------------------ | +| Channel | Returns 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** + +For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.md). + +| ID| Error Message | +| -------- | -------------------------------- | +| 3300101 | Illegal service state exception. | +| 3300102 | No such element exception. | +| 3300103 | Illegal access rule exception. | +| 3300104 | Secure element IO exception. | + +**Example** + +```js +import secureElement from '@ohos.secureElement'; + +@State result: string = ''; +@State nfcOmaSession: secureElement.Session = null; +@State nfcOmaChannel: secureElement.Channel = null; +aidArray: number[] = [720, 1080]; + +try { + // See Reader.openSession for this.nfcOmaSession. + let getPromise = this.nfcOmaSession.openLogicalChannel(this.aidArray) + getPromise.then((channel) => { + this.nfcOmaChannel = channel; + this.result = "openLogicChannel1 get channel successfully"; + }).catch ((err) => { + this.result = "openLogicChannel1 exception:" + err.message; + }); +} catch (e) { + this.result = "openLogicChannel1 exception:" + e.message; +} +``` + +## Session.openLogicalChannel + + openLogicalChannel(aid:number[], callback: AsyncCallback): void + +Opens a logical channel. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.SecureElement + +**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.| + +**Error codes** + +For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.md). + +| ID| Error Message | +| -------- | -------------------------------- | +| 3300101 | Illegal service state exception. | +| 3300102 | No such element exception. | +| 3300103 | Illegal access rule exception. | +| 3300104 | Secure element IO exception. | + +**Example** + +```js +import secureElement from '@ohos.secureElement'; + +@State result: string = ''; +@State nfcOmaSession: secureElement.Session = null; +@State nfcOmaChannel: secureElement.Channel = null; +aidArray: number[] = [720, 1080]; + +try { + // See Reader.openSession for this.nfcOmaSession. + this.nfcOmaSession.openLogicalChannel(this.aidArray, (error, data) => { + if (error) { + this.result = "openLogicChannel2 failed:" + JSON.stringify(error); + return; + } + this.nfcOmaChannel = data; + this.result = "openLogicChannel2 get channel successfully"; + }); +} catch (e) { + this.result = "openLogicChannel2 exception:" + e.message; +} +``` + +## Session.openLogicalChannel + +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). + +If the AID length is 0, this API sends a **select** command with the AID length of 0 (as per [GPCS]) to select the Issuer Security Domain of the SE. + +If the AID is null, this API sends the **MANAGE CHANNEL Open** only. In this case, the default applet associated with the logical channel is selected. + +**P2** is usually **0x00**. The device shall allow any value of **P2** and the following values: **0x00**, **0x04**, **0x08**, **0x0C** as defined in [ISO 7816-4](https://www.iso.org/standard/77180.html). + +**System capability**: SystemCapability.Communication.SecureElement + +**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. | + +**Error codes** + +For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.md). + +| ID| Error Message | +| -------- | -------------------------------- | +| 3300101 | Illegal service state exception. | +| 3300102 | No such element exception. | +| 3300103 | Illegal access rule exception. | +| 3300104 | Secure element IO exception. | + +**Example** + +```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) { + try { + // See Reader.openSession for this.nfcOmaSession. + let getPromise = this.nfcOmaSession.openLogicalChannel(this.aidArray, this.p2); + getPromise.then((channel) => { + this.nfcOmaChannel = channel; + this.result = "openLogicChannel3 get channel successfully"; + }).catch ((err) => { + this.result = "openLogicChannel3 exception"; + }) +} catch (e) { + this.result = "openLogicChannel3 exception:" + e.message; +} +``` + +## Session.openLogicalChannel + +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). + +If the AID length is 0, this API sends a **select** command with the AID length of 0 (as per [GPCS]) to select the Issuer Security Domain of the SE. + +If the AID is null, this API sends the **MANAGE CHANNEL Open** only. In this case, the default applet associated with the logical channel is selected. + +**P2** is usually **0x00**. The device shall allow any value of **P2** and the following values: **0x00**, **0x04**, **0x08**, **0x0C** as defined in [ISO 7816-4](https://www.iso.org/standard/77180.html). + +**System capability**: SystemCapability.Communication.SecureElement + +**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.| + +**Error codes** + +For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.md). + +| ID| Error Message | +| -------- | -------------------------------- | +| 3300101 | Illegal service state exception. | +| 3300102 | No such element exception. | +| 3300103 | Illegal access rule exception. | +| 3300104 | Secure element IO exception. | + +**Example** + +```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; + +try { + // See Reader.openSession for this.nfcOmaSession. + this.nfcOmaSession.openLogicalChannel(this.aidArray, this.p2, (error, data) => { + if (error) { + this.result = "openLogicChannel4 failed:" + JSON.stringify(error); + return; + } + this.nfcOmaChannel = data; + this.result = "openLogicChannel4 get channel successfully"; + }) +} catch (e) { + this.result = "openLogicChannel4 exception:" + e.message; +} +``` + +## Channel. getSession + + getSession(): Session + +Obtains the session that opens this channel. + +**System capability**: SystemCapability.Communication.SecureElement + +**Return value** + +| **Type**| **Description** | +| -------- | ----------------------------- | +| Session | Returns the session obtained.| + +**Example** + +```js +import secureElement from '@ohos.secureElement'; + +@State result: string = ''; +@State nfcOmaSession: secureElement.Session = null; +@State nfcOmaChannel: secureElement.Channel = null; + +try { + // See Session.openBasicChannel for this.nfcOmaChannel. + let ret = this.nfcOmaChannel.getSession(); + if (ret) { + this.result = "get session successfully"; + } else { + this.result = "get session failed"; + } +} catch (e) { + this.result = "getSession exception:" + e.message; +} +``` + +## Channel. close + +close(): void + +Closes the channel of the SE. + +**System capability**: SystemCapability.Communication.SecureElement + +**Example** + +```js +import secureElement from '@ohos.secureElement'; + +@State result: string = ''; +@State nfcOmaSession: secureElement.Session = null; +@State nfcOmaChannel: secureElement.Channel = null; + +try { + // See Session.openBasicChannel for this.nfcOmaChannel. + this.nfcOmaChannel.close(); + this.result = "channel close successfully"; +} catch (e) { + this.result = "channel close exception:" + e.message; +} +``` + +## Channel. isBasicChannel + +isBasicChannel(): boolean + +Checks whether this channel is a basic channel. + +**System capability**: SystemCapability.Communication.SecureElement + +**Return value** + +| **Type**| **Description** | +| -------- | ------------------------------------------------------------ | +| boolean | Returns **true** if the channel is a basic channel; returns **false** otherwise.| + +**Example** + +```js +import secureElement from '@ohos.secureElement'; + +@State result: string = ''; +@State nfcOmaChannel: secureElement.Channel = null; + +try { + // See Session.openBasicChannel for this.nfcOmaChannel. + let ret = this.nfcOmaChannel.isBasicChannel(); + if (ret) { + this.result = "isBasicChannel TRUE"; + } else { + this.result = "isBasicChannel FALSE"; + } +} catch (e) { + this.result = "isBasicChannel Exception: "+ e.message; +} +``` + +## Channel. isClosed + +isClosed(): boolean + +Checks whether this channel is closed. + +**System capability**: SystemCapability.Communication.SecureElement + +**Return value** + +| **Type**| **Description** | +| -------- | --------------------------------------------- | +| boolean | Returns **true** if this channel is closed; returns **false** otherwise.| + +**Example** + +```js +import secureElement from '@ohos.secureElement'; + +@State result: string = ''; +@State nfcOmaChannel: secureElement.Channel = null; + +try { + // See Session.openBasicChannel for this.nfcOmaChannel. + let ret = this.nfcOmaChannel.isClosed(); + if (ret) { + this.result = "channel isClosed TRUE"; + } else { + this.result = "channel isClosed False"; + } +} catch (e) { + this.result = "Channel isClosed exception:" + e.message; +} +``` + +## Channel. getSelectResponse + +getSelectResponse():number[] + +Obtains the data as received from the application **select** command, including the status word received when the applet is selected. + +**System capability**: SystemCapability.Communication.SecureElement + +**Return value** + +| **Type**| **Description** | +| -------- | ------------------------------------------------------------ | +| number[] | Returns the data obtained.| + +**Error codes** + +For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.md). + +**Example** + +```js +import secureElement from '@ohos.secureElement'; + +@State result: string = ''; +@State nfcOmaChannel: secureElement.Channel = null; + +try { + // See Session.openBasicChannel for this.nfcOmaChannel. + let ret = this.nfcOmaChannel.getSelectResponse(); + if (ret) { + this.result = "getSelectResponse result:["; + for (let i = 0; i < ret.length; ++i) { + this.result += ret[i]; + this.result += ' '; + } + this.result += ']'; + } else { + this.result = "getSelectResponse result is null"; + } +} catch (e) { + this.result = "getSelectResponse exception:" + e.message; +} +``` + +## Channel. transmit + +transmit(command: number[]): Promise + +Transmits the **APDU** command to the SE (according to ISO/IEC 7816). This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.SecureElement + +**Parameters** + +| **Name**| **Type**| **Description** | +| ---------- | -------- | ------------------------------------- | +| command | number[] | AIDs of the applets selected on the channel. | + +**Return value** + +| **Type**| **Description** | +| -------- | -------------- | +| number[] | Returns the response obtained.| + +**Error codes** + +For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.md). + +| ID| Error Message | +| -------- | -------------------------------- | +| 3300101 | Illegal service state exception. | +| 3300103 | Illegal access rule exception. | +| 3300104 | Secure element IO exception. | + +**Example** + +```js +import secureElement from '@ohos.secureElement'; + +@State result: string = ''; +@State nfcOmaChannel: secureElement.Channel = null; + +try { + let command: number[] = [100, 200]; + // See Session.openBasicChannel for this.nfcOmaChannel. + let getPromise = this.nfcOmaChannel.transmit(command); + getPromise.then((data) => { + this.result = "transmit1 result:["; + for (let i = 0; i < data.length; ++i) { + this.result += data[i]; + this.result += " "; + } + this.result += "]"; + }).catch ((err) => { + this.result = "transmit1 exception:" + err.code; + }) +} catch (e) { + this.result = "transit1 exception:" + e.message; +} +``` + +## Channel. transmit + +transmit(command: number[], callback: AsyncCallback): void + +Transmits the **APDU** command to the SE (according to ISO/IEC 7816). This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.SecureElement + +**Parameters** + +| **Name**| **Type** | **Description** | +| ---------- | ----------------------- | ------------------------------------- | +| command | number[] | AIDs of the applets selected on the channel. | +| callback | AsyncCallback | Callback invoked to return the result. | + +**Error codes** + +For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.md). + +| ID| Error Message | +| -------- | -------------------------------- | +| 3300101 | Illegal service state exception. | +| 3300103 | Illegal access rule exception. | +| 3300104 | Secure element IO exception. | + +**Example** + +```js +import secureElement from '@ohos.secureElement'; + +@State result: string = ''; +@State nfcOmaChannel: secureElement.Channel = null; + +try { + let command: number[] = [100, 200]; + // See Session.openBasicChannel for this.nfcOmaChannel. + this.nfcOmaChannel.transmit(command, (error, data) => { + if (error) { + this.result = "transmit2 exception:" + JSON.stringify(error); + return; + } + this.result = "transmit2 result:["; + for (let i = 0; i < data.length; ++i) { + this.result += data[i]; + this.result += " "; + } + this.result += "]"; + }); +} catch (e) { + this.result = "transit2 exception:" + e.message; +} +``` diff --git a/en/application-dev/reference/errorcodes/Readme-EN.md b/en/application-dev/reference/errorcodes/Readme-EN.md index baffeb2d779edbb96e55d77add3164bbbd2be604..8c91c3d1205b3bd853b05dfa015a3f4e06a3290f 100644 --- a/en/application-dev/reference/errorcodes/Readme-EN.md +++ b/en/application-dev/reference/errorcodes/Readme-EN.md @@ -60,6 +60,7 @@ - [Bluetooth Error Codes](errorcode-bluetoothManager.md) - [Wi-Fi Error Codes](errorcode-wifi.md) - [NFC Error Codes](errorcode-nfc.md) + - [SE Error Codes](errorcode-se.md) - [RPC Error Codes](errorcode-rpc.md) - Basic Features - [Accessibility Error Codes](errorcode-accessibility.md) diff --git a/en/application-dev/reference/errorcodes/errorcode-router.md b/en/application-dev/reference/errorcodes/errorcode-router.md index 6c805ee9853deda64bce96a325ac7175d6d9bd97..762459918ebeafed876ece076d564d6ffa2a1869 100644 --- a/en/application-dev/reference/errorcodes/errorcode-router.md +++ b/en/application-dev/reference/errorcodes/errorcode-router.md @@ -22,7 +22,7 @@ The operation for obtaining the rendering engine or parsing parameters fails. NA -## 100002 Incorrect URI +## 100002 Incorrect URI During Page Redirection **Error Message** @@ -58,7 +58,21 @@ Too many pages are pushed. Delete unnecessary or invalid pages. -## 200002 Incorrect URI +## 100004 Incorrect Route Name + +**Error Message** + +Named route error. The named route is not exist. + +**Description** + +This error code is reported when the specified route name for redirection is incorrect or does not exist. + +**Possible Causes** + +The specified route name for redirection is incorrect or does not exist. + +## 200002 Incorrect URI During Page Replacement **Error Message** diff --git a/en/application-dev/reference/errorcodes/errorcode-se.md b/en/application-dev/reference/errorcodes/errorcode-se.md new file mode 100644 index 0000000000000000000000000000000000000000..adafce2852253a434ef9f1d40ef860cea9a43832 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-se.md @@ -0,0 +1,85 @@ +# SE Error Codes + +> **NOTE** +> +> This topic describes only module-specific error codes. For details about universal error codes, see [Universal Error Codes](errorcode-universal.md). + +## 3300101 Abnormal SE Service Status + +**Error Message** + +Illegal service state exception. + +**Description** + +The SecureElement (SE) service is abnormal. + +**Possible Causes** + +1. The SE service is disconnected. + +**Solution** + +1. Close the SE service. + +2. Set up a connection with the SE service again. + +## 3300102 No Such SE + +**Error Message** + +No such element exception. + +**Description** + +The SE is unavailable. + +**Possible Causes** + +1. Communication with the SE service is abnormal. +2. Communication of the SE chip is abnormal. + +**Solution** + +1. Close the SE service and set up a connection with the SE service again. +2. Restart the device. + +## 3300103 Failed to Obtain the Access Rule + +**Error Message** + +Illegal access rule exception. + +**Description** + +The access rule cannot be obtained. + +**Possible Causes** + +1. There is no access rule for the application on the SE. + +**Solution** + +1. Write correct access rules to the SE. +2. Close the SE service and set up a connection with the SE service again. + +## 3300104 SE Chip I/O Exception + +**Error Message** + +Secure element IO exception. + +**Description** + +The I/O of the SE chip is abnormal. + +**Possible Causes** + +1. The communication with the SE chip is abnormal. +2. The SE chip is abnormal. + +**Solution** + +1. Close the SE service and set up a connection with the SE service again. + +2. Restart the device. diff --git a/en/application-dev/reference/native-api-intro.md b/en/application-dev/reference/native-api-intro.md new file mode 100644 index 0000000000000000000000000000000000000000..75e18a70d7ca16751be7c6ed7979401919303d4a --- /dev/null +++ b/en/application-dev/reference/native-api-intro.md @@ -0,0 +1,77 @@ +# Native API Introduction + +Native APIs, also called Native Develop Kit (NDK), are a set of native interfaces and tools provided by the OpenHarmony SDK for implementing key application features by using C or C++. Different from JS APIs, the Native APIs provide only part of underlying capabilities of OpenHarmony, such as the libc, graphics library, window system, multimedia, and compression library. The Native APIs will be build as a dynamic library before being packaged into an application. + +## Concepts + +|Term|Description| +|--|--| +|Native API|Native interfaces, build scripts, and compiler toolchains provided by the **native** package in the OpenHarmony SDK for third-party application development. Native APIs include the C runtime libc, 3D graphics library **OpenGL**, and Node-APIs for cross-language programming between JS and C.| +|NDK|Native Develop Kit (NDK) that provides the Native APIs in OpenHarmony. NDK is the equivalent of Native API. Native API is the official name.| +|SDK CAPI|C interfaces and toolchains in OpenHarmony Native APIs.
Currently, OpenHarmony Native APIs contain only C interfaces. Therefore, Native API is CAPI. However, you are advised to use CAPI.| +|Node-API|Native interfaces that implement cross-language invocation between C and JS. Node-API is formerly called napi. Although OpenHarmony Node-APIs are extension of the Node-APIs provided by **Node.js**, they are not fully compatible with the Node-APIs in **Node.js**.| +|napi|Former name of Node-API. It is not used because it may be interpreted as Native API or Node-API by mistake. Currently, the interfaces in the Node-API header files still start with **napi_**.| + +## Native API Composition + +### Native API Directory Structure + +Native APIs are stored in the **$(SDK_ROOT)/native** directory of the SDK. + +|Directory|Description| +|--|--| +|build|Provides the toolchain cmake script used to build the dynamic library of an application. The **ohos.toolchain.cmake** file in this directory defines OpenHarmony cross-compilation options.| +|build-tools|Provides build tools, such as CMake.| +|docs|Provides Native API reference documents, which are extracted from the header files using Doxgen.| +|llvm|Provides the LLVM, a cross compiler that supports the OpenHarmony Application Binary Interface (ABI).| +|sysroot|Provides dependencies of links, including header files and dynamic libraries.| + +### Native APIs + +|Category|Description|Introduced Since Version| +|--|--|--| +|[C standard library](native-lib/third_party_libc/musl.md)|Provides more than 1500 libc interfaces based on musl.|8| +|[C++ standard library](native-lib/third_party_libc/cpp.md)|Provides the libc++_shared library for C++ runtime. This library must be packed or statically linked to the application during packing.|8| +|Log|Provides HiLog interfaces for printing logs to the system.|8| +|Node-API|Provides APIs like Node-APIs (also called napis) for accessing the JS application environment. Node-APIs are provided by ArkUI and are part of Native APIs.|8| +|XComponent|Provides Surface and touchscreen event interfaces for developing high-performance graphics applications on ArkUI.|8| +|libuv|Provides a third-party asynchronous I/O library integrated by ArkUI.|8| +|libz|Provides basic compression and decompression interfaces.|8| +|Drawing|Provides a 2D graphics library for drawing on Surface.|8| +|OpenGL|Provides OpenGL 3.0 interfaces.|8| +|Rawfile|Provides application resource access interfaces for reading various resources packed in applications.|8| +|OpenSLES|Provides interfaces for 2D and 3D audio acceleration.|8| +|Mindspore|Provides AI model interfaces.|9| +|Bundle management|Provides bundle service interfaces for querying bundle information of applications.|8| + +### Native API Documents + +* [Native API Reference](native-apis/_o_h___native_x_component.md): provides reference for Native APIs. +* [Standard Libraries Supported by Native APIs](../reference/native-lib/third_party_libc/musl.md): describes the open-source standard libraries supported by Native APIs. +* [Native API Development](../napi/napi-guidelines.md): describes how to use Native APIs. +* [Using NDK to Build a CMake C/C++ Project](../faqs/how-to-migrate-cmake-with-ohosndk.md): describes how to use Native APIs to develop a CMake project. +* [Using Node-APIs in Application Projects](../napi/napi-guidelines.md): describes how to use Node-APIs. + +## How to Use + +### Recommended Use of Native APIs + +Use Native APIs when you want to: + +1. Develop performance-sensitive code in computing-intensive scenarios, such as gaming and physical simulation. +2. Reuse the existing C or C++ library. +3. Customize libraries related to CPU features, such as neon acceleration. + +### Use of Native APIs Not Recommended + +Do not use Native APIs when you want to: + +1. Develop a pure OpenHarmony application. +2. Develop an application that is compatible on as many OpenHarmony devices as possible. + +## Debugging Capabilities + +1. OpenHarmony provides remote code debugging by using the low-level Debugger (LLDB). For details, see [LLDB](https://gitee.com/openharmony/third_party_llvm-project/blob/master/lldb/README_en.md). +2. OpenHarmony provides the log debugging for the musl library. For details, see "Debugging Capabilities" in [libc](./native-lib/third_party_libc/musl.md). + + \ No newline at end of file diff --git a/en/application-dev/reference/native-apis/_huks_type_api.md b/en/application-dev/reference/native-apis/_huks_type_api.md index 398b5df7b89d78913171fe0aa5d06a41e5ed81e2..fd8b7e2ee7038277dd517a32cf9ebe40298b9430 100644 --- a/en/application-dev/reference/native-apis/_huks_type_api.md +++ b/en/application-dev/reference/native-apis/_huks_type_api.md @@ -3,11 +3,11 @@ ## Overview -Defines the macros, enumerated values, data structures, and error codes used by OpenHarmony Universal KeyStore (HUKS) APIs. +Defines the macros, enums, structs, and error codes used by OpenHarmony Universal KeyStore (HUKS) APIs. \@syscap SystemCapability.Security.Huks -**Since:** +**Since**: 9 @@ -16,74 +16,75 @@ Defines the macros, enumerated values, data structures, and error codes used by ### Files -| Name | Description | +| Name| Description| | -------- | -------- | -| [native_huks_type.h](native__huks__type_8h.md) | Defines the enumerated variables, structures, and macros used in the HUKS APIs.
File to Include: | +| [native_huks_type.h](native__huks__type_8h.md) | Defines the enumerated variables, structs, and macros used in the HUKS APIs.
**File to include**:
**Library**: libhuks_ndk.z.so| ### Structs -| Name | Description | +| Name| Description| | -------- | -------- | -| [OH_Huks_Result](_o_h___huks___result.md) | Defines the return data, including the result code and message. | -| [OH_Huks_Blob](_o_h___huks___blob.md) | Defines the structure for storing data. | -| [OH_Huks_Param](_o_h___huks___param.md) | Defines the parameter structure in a parameter set. | -| [OH_Huks_ParamSet](_o_h___huks___param_set.md) | Defines the structure of the parameter set. | -| [OH_Huks_CertChain](_o_h___huks___cert_chain.md) | Defines the structure of the certificate chain. | -| [OH_Huks_KeyInfo](_o_h___huks___key_info.md) | Defines the key information structure. | -| [OH_Huks_PubKeyInfo](_o_h___huks___pub_key_info.md) | Defines the structure of a public key. | -| [OH_Huks_KeyMaterialRsa](_o_h___huks___key_material_rsa.md) | Defines the structure of an RSA key. | -| [OH_Huks_KeyMaterialEcc](_o_h___huks___key_material_ecc.md) | Defines the structure of an ECC key. | -| [OH_Huks_KeyMaterialDsa](_o_h___huks___key_material_dsa.md) | Defines the structure of a DSA key. | -| [OH_Huks_KeyMaterialDh](_o_h___huks___key_material_dh.md) | Defines the structure of a DH key. | -| [OH_Huks_KeyMaterial25519](_o_h___huks___key_material25519.md) | Defines the structure of a 25519 key. | +| [OH_Huks_Result](_o_h___huks___result.md) | Defines the returned status data, including the return code and message. | +| [OH_Huks_Blob](_o_h___huks___blob.md) | Defines the structure of the binary large object (BLOB) that stores data. | +| [OH_Huks_Param](_o_h___huks___param.md) | Defines the structure of the parameters in a parameter set. | +| [OH_Huks_ParamSet](_o_h___huks___param_set.md) | Defines the parameter set structure. | +| [OH_Huks_CertChain](_o_h___huks___cert_chain.md) | Defines the certificate chain structure. | +| [OH_Huks_KeyInfo](_o_h___huks___key_info.md) | Defines the key information structure. | +| [OH_Huks_PubKeyInfo](_o_h___huks___pub_key_info.md) | Defines the structure of a public key. | +| [OH_Huks_KeyMaterialRsa](_o_h___huks___key_material_rsa.md) | Defines the structure of an RSA key. | +| [OH_Huks_KeyMaterialEcc](_o_h___huks___key_material_ecc.md) | Defines the structure of an Elliptic Curve Cryptography (ECC) key. | +| [OH_Huks_KeyMaterialDsa](_o_h___huks___key_material_dsa.md) | Defines the structure of a DSA key. | +| [OH_Huks_KeyMaterialDh](_o_h___huks___key_material_dh.md) | Defines the structure of a Diffie-Hellman (DH) key. | +| [OH_Huks_KeyMaterial25519](_o_h___huks___key_material25519.md) | Defines the structure of a 25519 key. | ### Macros -| Name | Value | +| Name| Value| | -------- | -------- | -| **OH_HUKS_AE_TAG_LEN** | 16 | -| **OH_HUKS_BITS_PER_BYTE** | 8 | -| **OH_HUKS_MAX_KEY_SIZE** | 2048 | -| **OH_HUKS_AE_NONCE_LEN** | 12| -| **OH_HUKS_MAX_KEY_ALIAS_LEN** | 64 | -| **OH_HUKS_MAX_PROCESS_NAME_LEN** | 50 | -| **OH_HUKS_MAX_RANDOM_LEN** | 1024 | -| **OH_HUKS_SIGNATURE_MIN_SIZE** | 64 | -| **OH_HUKS_MAX_OUT_BLOB_SIZE** | (5 \* 1024 \* 1024) | -| **OH_HUKS_WRAPPED_FORMAT_MAX_SIZE** | (1024 \* 1024) | -| **OH_HUKS_IMPORT_WRAPPED_KEY_TOTAL_BLOBS** | 10 | -| **TOKEN_CHALLENGE_LEN** | 32 | -| **SHA256_SIGN_LEN** | 32 | -| **TOKEN_SIZE** | 32| -| **MAX_AUTH_TIMEOUT_SECOND** | 60 | -| **SECURE_SIGN_VERSION** | 0x01000001 | +| **OH_HUKS_AE_TAG_LEN** | 16 | +| **OH_HUKS_BITS_PER_BYTE** | 8| +| **OH_HUKS_MAX_KEY_SIZE** | 2048 | +| **OH_HUKS_AE_NONCE_LEN** | 12 | +| **OH_HUKS_MAX_KEY_ALIAS_LEN** | 64 | +| **OH_HUKS_MAX_PROCESS_NAME_LEN** | 50 | +| **OH_HUKS_MAX_RANDOM_LEN** | 1024 | +| **OH_HUKS_SIGNATURE_MIN_SIZE** | 64 | +| **OH_HUKS_MAX_OUT_BLOB_SIZE** | (5 \* 1024 \* 1024) | +| **OH_HUKS_WRAPPED_FORMAT_MAX_SIZE** | (1024 \* 1024) | +| **OH_HUKS_IMPORT_WRAPPED_KEY_TOTAL_BLOBS** | 10 | +| **TOKEN_CHALLENGE_LEN** |32 | +| **SHA256_SIGN_LEN** | 32 | +| **TOKEN_SIZE** |32 | +| **MAX_AUTH_TIMEOUT_SECOND** | 60 | +| **SECURE_SIGN_VERSION** | 0x01000001 | ### Enums -| Name | Description | +| Name| Description| | -------- | -------- | -| [OH_Huks_KeyPurpose](#oh_huks_keypurpose) {
OH_HUKS_KEY_PURPOSE_ENCRYPT = 1, OH_HUKS_KEY_PURPOSE_DECRYPT = 2, OH_HUKS_KEY_PURPOSE_SIGN = 4, OH_HUKS_KEY_PURPOSE_VERIFY = 8,
OH_HUKS_KEY_PURPOSE_DERIVE = 16, OH_HUKS_KEY_PURPOSE_WRAP = 32, OH_HUKS_KEY_PURPOSE_UNWRAP = 64, OH_HUKS_KEY_PURPOSE_MAC = 128,
OH_HUKS_KEY_PURPOSE_AGREE = 256
} | Enumerates the key purposes. | -| [OH_Huks_KeyDigest](#oh_huks_keydigest) {
OH_HUKS_DIGEST_NONE = 0, OH_HUKS_DIGEST_MD5 = 1, OH_HUKS_DIGEST_SM3 = 2, OH_HUKS_DIGEST_SHA1 = 10,
OH_HUKS_DIGEST_SHA224 = 11, OH_HUKS_DIGEST_SHA256 = 12, OH_HUKS_DIGEST_SHA384 = 13, OH_HUKS_DIGEST_SHA512 = 14
} | Enumerates the digest algorithms. | -| [OH_Huks_KeyPadding](#oh_huks_keypadding) {
OH_HUKS_PADDING_NONE = 0, OH_HUKS_PADDING_OAEP = 1, OH_HUKS_PADDING_PSS = 2, OH_HUKS_PADDING_PKCS1_V1_5 = 3,
OH_HUKS_PADDING_PKCS5 = 4, OH_HUKS_PADDING_PKCS7 = 5
} | Enumerates the padding algorithms. | -| [OH_Huks_CipherMode](#oh_huks_ciphermode) {
OH_HUKS_MODE_ECB = 1, OH_HUKS_MODE_CBC = 2, OH_HUKS_MODE_CTR = 3, OH_HUKS_MODE_OFB = 4,
OH_HUKS_MODE_CCM = 31, OH_HUKS_MODE_GCM = 32
} | Enumerates the cipher modes. | -| [OH_Huks_KeySize](#oh_huks_keysize) {
OH_HUKS_RSA_KEY_SIZE_512 = 512, OH_HUKS_RSA_KEY_SIZE_768 = 768, OH_HUKS_RSA_KEY_SIZE_1024 = 1024, OH_HUKS_RSA_KEY_SIZE_2048 = 2048,
OH_HUKS_RSA_KEY_SIZE_3072 = 3072, OH_HUKS_RSA_KEY_SIZE_4096 = 4096, OH_HUKS_ECC_KEY_SIZE_224 = 224, OH_HUKS_ECC_KEY_SIZE_256 = 256,
OH_HUKS_ECC_KEY_SIZE_384 = 384, OH_HUKS_ECC_KEY_SIZE_521 = 521, OH_HUKS_AES_KEY_SIZE_128 = 128, OH_HUKS_AES_KEY_SIZE_192 = 192,
OH_HUKS_AES_KEY_SIZE_256 = 256, OH_HUKS_AES_KEY_SIZE_512 = 512, OH_HUKS_CURVE25519_KEY_SIZE_256 = 256, OH_HUKS_DH_KEY_SIZE_2048 = 2048,
OH_HUKS_DH_KEY_SIZE_3072 = 3072, OH_HUKS_DH_KEY_SIZE_4096 = 4096, OH_HUKS_SM2_KEY_SIZE_256 = 256, OH_HUKS_SM4_KEY_SIZE_128 = 128
} | Enumerates the key sizes. | -| [OH_Huks_KeyAlg](#oh_huks_keyalg) {
OH_HUKS_ALG_RSA = 1, OH_HUKS_ALG_ECC = 2, OH_HUKS_ALG_DSA = 3, OH_HUKS_ALG_AES = 20,
OH_HUKS_ALG_HMAC = 50, OH_HUKS_ALG_HKDF = 51, OH_HUKS_ALG_PBKDF2 = 52, OH_HUKS_ALG_ECDH = 100,
OH_HUKS_ALG_X25519 = 101, OH_HUKS_ALG_ED25519 = 102, OH_HUKS_ALG_DH = 103, OH_HUKS_ALG_SM2 = 150,
OH_HUKS_ALG_SM3 = 151, OH_HUKS_ALG_SM4 = 152
} | Enumerates the key algorithms. | -| [OH_Huks_AlgSuite](#oh_huks_algsuite) { OH_HUKS_UNWRAP_SUITE_X25519_AES_256_GCM_NOPADDING = 1, OH_HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING = 2 } | Enumerates the algorithm suites required for ciphertext imports. | -| [OH_Huks_KeyGenerateType](#oh_huks_keygeneratetype) { OH_HUKS_KEY_GENERATE_TYPE_DEFAULT = 0, OH_HUKS_KEY_GENERATE_TYPE_DERIVE = 1, OH_HUKS_KEY_GENERATE_TYPE_AGREE = 2 } | Enumerates the key generation types. | -| [OH_Huks_KeyFlag](#oh_huks_keyflag) { OH_HUKS_KEY_FLAG_IMPORT_KEY = 1, OH_HUKS_KEY_FLAG_GENERATE_KEY = 2, OH_HUKS_KEY_FLAG_AGREE_KEY = 3, OH_HUKS_KEY_FLAG_DERIVE_KEY = 4 } | Enumerates the key generation modes. | -| [OH_Huks_KeyStorageType](#oh_huks_keystoragetype) { OH_HUKS_STORAGE_TEMP = 0, OH_HUKS_STORAGE_PERSISTENT = 1 } | Enumerates the key storage modes. | -| [OH_Huks_ImportKeyType](#oh_huks_importkeytype) { OH_HUKS_KEY_TYPE_PUBLIC_KEY = 0, OH_HUKS_KEY_TYPE_PRIVATE_KEY = 1, OH_HUKS_KEY_TYPE_KEY_PAIR = 2 } | Enumerates the types of keys to import. By default, a public key is imported. This field is not required when a symmetric key is imported. | -| [OH_Huks_ErrCode](#oh_huks_errcode) {
OH_HUKS_SUCCESS = 0, OH_HUKS_ERR_CODE_PERMISSION_FAIL = 201, OH_HUKS_ERR_CODE_ILLEGAL_ARGUMENT = 401, OH_HUKS_ERR_CODE_NOT_SUPPORTED_API = 801,
OH_HUKS_ERR_CODE_FEATURE_NOT_SUPPORTED = 12000001, OH_HUKS_ERR_CODE_MISSING_CRYPTO_ALG_ARGUMENT = 12000002, OH_HUKS_ERR_CODE_INVALID_CRYPTO_ALG_ARGUMENT = 12000003, OH_HUKS_ERR_CODE_FILE_OPERATION_FAIL = 12000004,
OH_HUKS_ERR_CODE_COMMUNICATION_FAIL = 12000005, OH_HUKS_ERR_CODE_CRYPTO_FAIL = 12000006, OH_HUKS_ERR_CODE_KEY_AUTH_PERMANENTLY_INVALIDATED = 12000007, OH_HUKS_ERR_CODE_KEY_AUTH_VERIFY_FAILED = 12000008,
OH_HUKS_ERR_CODE_KEY_AUTH_TIME_OUT = 12000009, OH_HUKS_ERR_CODE_SESSION_LIMIT = 12000010, OH_HUKS_ERR_CODE_ITEM_NOT_EXIST = 12000011, OH_HUKS_ERR_CODE_INTERNAL_ERROR = 12000012,
OH_HUKS_ERR_CODE_CREDENTIAL_NOT_EXIST = 12000013
} | Enumerates the error codes. | -| [OH_Huks_TagType](#oh_huks_tagtype) {
OH_HUKS_TAG_TYPE_INVALID = 0 << 28, OH_HUKS_TAG_TYPE_INT = 1 << 28, OH_HUKS_TAG_TYPE_UINT = 2 << 28, OH_HUKS_TAG_TYPE_ULONG = 3 << 28,
OH_HUKS_TAG_TYPE_BOOL = 4 << 28, OH_HUKS_TAG_TYPE_BYTES = 5 << 28
} | Enumerates the tag types. | -| [OH_Huks_UserAuthType](#oh_huks_userauthtype) { OH_HUKS_USER_AUTH_TYPE_FINGERPRINT = 1 << 0, OH_HUKS_USER_AUTH_TYPE_FACE = 1 << 1, OH_HUKS_USER_AUTH_TYPE_PIN = 1 << 2 } | Enumerates the user authentication types. | -| [OH_Huks_AuthAccessType](#oh_huks_authaccesstype) { OH_HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD = 1 << 0, OH_HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL = 1 << 1 } | Enumerates the access control types. | -| [OH_Huks_ChallengeType](#oh_huks_challengetype) { OH_HUKS_CHALLENGE_TYPE_NORMAL = 0, OH_HUKS_CHALLENGE_TYPE_CUSTOM = 1, OH_HUKS_CHALLENGE_TYPE_NONE = 2 } | Enumerates the types of the challenges generated when a key is used. | -| [OH_Huks_ChallengePosition](#oh_huks_challengeposition) { OH_HUKS_CHALLENGE_POS_0 = 0, OH_HUKS_CHALLENGE_POS_1, OH_HUKS_CHALLENGE_POS_2, OH_HUKS_CHALLENGE_POS_3 } | Enumerates the positions of the 8-byte valid value in a custom challenge generated. | -| [OH_Huks_SecureSignType](#oh_huks_securesigntype) { OH_HUKS_SECURE_SIGN_WITH_AUTHINFO = 1 } | Enumerates the signature types of the keys generated or imported. | -| [OH_Huks_Tag](#oh_huks_tag) {
OH_HUKS_TAG_ALGORITHM = OH_HUKS_TAG_TYPE_UINT \| 1, OH_HUKS_TAG_PURPOSE = OH_HUKS_TAG_TYPE_UINT \| 2, OH_HUKS_TAG_KEY_SIZE = OH_HUKS_TAG_TYPE_UINT \| 3,
OH_HUKS_TAG_DIGEST = OH_HUKS_TAG_TYPE_UINT \| 4, OH_HUKS_TAG_PADDING = OH_HUKS_TAG_TYPE_UINT \| 5, OH_HUKS_TAG_BLOCK_MODE = OH_HUKS_TAG_TYPE_UINT \| 6, OH_HUKS_TAG_KEY_TYPE = OH_HUKS_TAG_TYPE_UINT \| 7,
OH_HUKS_TAG_ASSOCIATED_DATA = OH_HUKS_TAG_TYPE_BYTES \| 8, OH_HUKS_TAG_NONCE = OH_HUKS_TAG_TYPE_BYTES \| 9, OH_HUKS_TAG_IV = OH_HUKS_TAG_TYPE_BYTES \| 10, OH_HUKS_TAG_INFO = OH_HUKS_TAG_TYPE_BYTES \| 11,
OH_HUKS_TAG_SALT = OH_HUKS_TAG_TYPE_BYTES \| 12, OH_HUKS_TAG_ITERATION = OH_HUKS_TAG_TYPE_UINT \| 14, OH_HUKS_TAG_KEY_GENERATE_TYPE = OH_HUKS_TAG_TYPE_UINT \| 15,
OH_HUKS_TAG_AGREE_ALG = OH_HUKS_TAG_TYPE_UINT \| 19,
OH_HUKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS = OH_HUKS_TAG_TYPE_BOOL \| 20, OH_HUKS_TAG_AGREE_PRIVATE_KEY_ALIAS = OH_HUKS_TAG_TYPE_BYTES \| 21, OH_HUKS_TAG_AGREE_PUBLIC_KEY = OH_HUKS_TAG_TYPE_BYTES \| 22, OH_HUKS_TAG_KEY_ALIAS = OH_HUKS_TAG_TYPE_BYTES \| 23,
OH_HUKS_TAG_DERIVE_KEY_SIZE = OH_HUKS_TAG_TYPE_UINT \| 24, OH_HUKS_TAG_IMPORT_KEY_TYPE = OH_HUKS_TAG_TYPE_UINT \| 25, OH_HUKS_TAG_UNWRAP_ALGORITHM_SUITE = OH_HUKS_TAG_TYPE_UINT \| 26, OH_HUKS_TAG_ALL_USERS = OH_HUKS_TAG_TYPE_BOOL \| 301,
OH_HUKS_TAG_USER_ID = OH_HUKS_TAG_TYPE_UINT \| 302, OH_HUKS_TAG_NO_AUTH_REQUIRED = OH_HUKS_TAG_TYPE_BOOL \| 303, OH_HUKS_TAG_USER_AUTH_TYPE = OH_HUKS_TAG_TYPE_UINT \| 304, OH_HUKS_TAG_AUTH_TIMEOUT = OH_HUKS_TAG_TYPE_UINT \| 305,
OH_HUKS_TAG_AUTH_TOKEN = OH_HUKS_TAG_TYPE_BYTES \| 306, OH_HUKS_TAG_KEY_AUTH_ACCESS_TYPE = OH_HUKS_TAG_TYPE_UINT \| 307, OH_HUKS_TAG_KEY_SECURE_SIGN_TYPE = OH_HUKS_TAG_TYPE_UINT \| 308, OH_HUKS_TAG_CHALLENGE_TYPE = OH_HUKS_TAG_TYPE_UINT \| 309,
OH_HUKS_TAG_CHALLENGE_POS = OH_HUKS_TAG_TYPE_UINT \| 310, OH_HUKS_TAG_ATTESTATION_CHALLENGE = OH_HUKS_TAG_TYPE_BYTES \| 501, OH_HUKS_TAG_ATTESTATION_APPLICATION_ID = OH_HUKS_TAG_TYPE_BYTES \| 502,
OH_HUKS_TAG_ATTESTATION_ID_ALIAS = OH_HUKS_TAG_TYPE_BYTES \| 511,
OH_HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO = OH_HUKS_TAG_TYPE_BYTES \| 514, OH_HUKS_TAG_ATTESTATION_ID_VERSION_INFO = OH_HUKS_TAG_TYPE_BYTES \| 515,
OH_HUKS_TAG_IS_KEY_ALIAS = OH_HUKS_TAG_TYPE_BOOL \| 1001, OH_HUKS_TAG_KEY_STORAGE_FLAG = OH_HUKS_TAG_TYPE_UINT \| 1002, OH_HUKS_TAG_IS_ALLOWED_WRAP = OH_HUKS_TAG_TYPE_BOOL \| 1003, OH_HUKS_TAG_KEY_WRAP_TYPE = OH_HUKS_TAG_TYPE_UINT \| 1004,
OH_HUKS_TAG_KEY_AUTH_ID = OH_HUKS_TAG_TYPE_BYTES \| 1005, OH_HUKS_TAG_KEY_ROLE = OH_HUKS_TAG_TYPE_UINT \| 1006, OH_HUKS_TAG_KEY_FLAG = OH_HUKS_TAG_TYPE_UINT \| 1007, OH_HUKS_TAG_IS_ASYNCHRONIZED = OH_HUKS_TAG_TYPE_UINT \| 1008,
OH_HUKS_TAG_KEY_DOMAIN = OH_HUKS_TAG_TYPE_UINT \| 1011, OH_HUKS_TAG_SYMMETRIC_KEY_DATA = OH_HUKS_TAG_TYPE_BYTES \| 20001,
OH_HUKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATA = OH_HUKS_TAG_TYPE_BYTES \| 20002, OH_HUKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATA = OH_HUKS_TAG_TYPE_BYTES \| 20003
} | Enumerates the tag values used in parameter sets. | +| [OH_Huks_KeyPurpose](#oh_huks_keypurpose) {
OH_HUKS_KEY_PURPOSE_ENCRYPT = 1,
OH_HUKS_KEY_PURPOSE_DECRYPT = 2,
OH_HUKS_KEY_PURPOSE_SIGN = 4,
OH_HUKS_KEY_PURPOSE_VERIFY = 8,
OH_HUKS_KEY_PURPOSE_DERIVE = 16,
OH_HUKS_KEY_PURPOSE_WRAP = 32,
OH_HUKS_KEY_PURPOSE_UNWRAP = 64,
OH_HUKS_KEY_PURPOSE_MAC = 128,
OH_HUKS_KEY_PURPOSE_AGREE = 256
} | Enumerates the key purposes. | +| [OH_Huks_KeyDigest](#oh_huks_keydigest) {
OH_HUKS_DIGEST_NONE = 0,
OH_HUKS_DIGEST_MD5 = 1,
OH_HUKS_DIGEST_SM3 = 2,
OH_HUKS_DIGEST_SHA1 = 10,
OH_HUKS_DIGEST_SHA224 = 11,
OH_HUKS_DIGEST_SHA256 = 12,
OH_HUKS_DIGEST_SHA384 = 13,
OH_HUKS_DIGEST_SHA512 = 14
} | Enumerates the digest algorithms. | +| [OH_Huks_KeyPadding](#oh_huks_keypadding) {
OH_HUKS_PADDING_NONE = 0,
OH_HUKS_PADDING_OAEP = 1,
OH_HUKS_PADDING_PSS = 2,
OH_HUKS_PADDING_PKCS1_V1_5 = 3,
OH_HUKS_PADDING_PKCS5 = 4,
OH_HUKS_PADDING_PKCS7 = 5
} | Enumerates the padding algorithms. | +| [OH_Huks_CipherMode](#oh_huks_ciphermode) {
OH_HUKS_MODE_ECB = 1,
OH_HUKS_MODE_CBC = 2,
OH_HUKS_MODE_CTR = 3,
OH_HUKS_MODE_OFB = 4,
OH_HUKS_MODE_CCM = 31,
OH_HUKS_MODE_GCM = 32
} | Enumerates the cipher modes. | +| [OH_Huks_KeySize](#oh_huks_keysize) {
OH_HUKS_RSA_KEY_SIZE_512 = 512,
OH_HUKS_RSA_KEY_SIZE_768 = 768,
OH_HUKS_RSA_KEY_SIZE_1024 = 1024,
OH_HUKS_RSA_KEY_SIZE_2048 = 2048,
OH_HUKS_RSA_KEY_SIZE_3072 = 3072,
OH_HUKS_RSA_KEY_SIZE_4096 = 4096,
OH_HUKS_ECC_KEY_SIZE_224 = 224,
OH_HUKS_ECC_KEY_SIZE_256 = 256,
OH_HUKS_ECC_KEY_SIZE_384 = 384,
OH_HUKS_ECC_KEY_SIZE_521 = 521,
OH_HUKS_AES_KEY_SIZE_128 = 128,
OH_HUKS_AES_KEY_SIZE_192 = 192,
OH_HUKS_AES_KEY_SIZE_256 = 256,
OH_HUKS_AES_KEY_SIZE_512 = 512,
OH_HUKS_CURVE25519_KEY_SIZE_256 = 256,
OH_HUKS_DH_KEY_SIZE_2048 = 2048,
OH_HUKS_DH_KEY_SIZE_3072 = 3072,
OH_HUKS_DH_KEY_SIZE_4096 = 4096,
OH_HUKS_SM2_KEY_SIZE_256 = 256,
OH_HUKS_SM4_KEY_SIZE_128 = 128
} | Enumerates key sizes of different algorithms. | +| [OH_Huks_KeyAlg](#oh_huks_keyalg) {
OH_HUKS_ALG_RSA = 1,
OH_HUKS_ALG_ECC = 2,
OH_HUKS_ALG_DSA = 3,
OH_HUKS_ALG_AES = 20,
OH_HUKS_ALG_HMAC = 50,
OH_HUKS_ALG_HKDF = 51,
OH_HUKS_ALG_PBKDF2 = 52,
OH_HUKS_ALG_ECDH = 100,
OH_HUKS_ALG_X25519 = 101,
OH_HUKS_ALG_ED25519 = 102,
OH_HUKS_ALG_DH = 103,
OH_HUKS_ALG_SM2 = 150,
OH_HUKS_ALG_SM3 = 151,
OH_HUKS_ALG_SM4 = 152
} | Enumerates the algorithms for keys. | +| [OH_Huks_AlgSuite](#oh_huks_algsuite) {
OH_HUKS_UNWRAP_SUITE_X25519_AES_256_GCM_NOPADDING = 1,
OH_HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING = 2
} | Enumerates the algorithm suites for the import of a wrapped key. | +| [OH_Huks_KeyGenerateType](#oh_huks_keygeneratetype) {
OH_HUKS_KEY_GENERATE_TYPE_DEFAULT = 0,
OH_HUKS_KEY_GENERATE_TYPE_DERIVE = 1,
OH_HUKS_KEY_GENERATE_TYPE_AGREE = 2
} | Enumerates the types of the key generated. | +| [OH_Huks_KeyFlag](#oh_huks_keyflag) {
OH_HUKS_KEY_FLAG_IMPORT_KEY = 1,
OH_HUKS_KEY_FLAG_GENERATE_KEY = 2,
OH_HUKS_KEY_FLAG_AGREE_KEY = 3,
OH_HUKS_KEY_FLAG_DERIVE_KEY = 4
} | Enumerates the key generation types. | +| [OH_Huks_KeyStorageType](#oh_huks_keystoragetype) {
OH_HUKS_STORAGE_TEMP = 0,
OH_HUKS_STORAGE_PERSISTENT = 1,
OH_HUKS_STORAGE_ONLY_USED_IN_HUKS = 2,
OH_HUKS_STORAGE_KEY_EXPORT_ALLOWED = 3
} | Enumerates the key storage types. | +| [OH_Huks_ImportKeyType](#oh_huks_importkeytype) {
OH_HUKS_KEY_TYPE_PUBLIC_KEY = 0,
OH_HUKS_KEY_TYPE_PRIVATE_KEY = 1,
OH_HUKS_KEY_TYPE_KEY_PAIR = 2
} | Enumerates the types of the key to import. By default, a public key is imported. This field is not required when a symmetric key is imported. | +| [OH_Huks_RsaPssSaltLenType](#oh_huks_rsapsssaltlentype) {
OH_HUKS_RSA_PSS_SALT_LEN_DIGEST = 0, OH_HUKS_RSA_PSS_SALT_LEN_MAX = 1
} | Enumerates the salt length types when the PSS padding mode is used in RSA signing or signature verification.| +| [OH_Huks_ErrCode](#oh_huks_errcode) {
OH_HUKS_SUCCESS = 0,
OH_HUKS_ERR_CODE_PERMISSION_FAIL = 201,
OH_HUKS_ERR_CODE_ILLEGAL_ARGUMENT = 401,
OH_HUKS_ERR_CODE_NOT_SUPPORTED_API = 801,
OH_HUKS_ERR_CODE_FEATURE_NOT_SUPPORTED = 12000001,
OH_HUKS_ERR_CODE_MISSING_CRYPTO_ALG_ARGUMENT = 12000002,
OH_HUKS_ERR_CODE_INVALID_CRYPTO_ALG_ARGUMENT = 12000003,
OH_HUKS_ERR_CODE_FILE_OPERATION_FAIL = 12000004,
OH_HUKS_ERR_CODE_COMMUNICATION_FAIL = 12000005,
OH_HUKS_ERR_CODE_CRYPTO_FAIL = 12000006,
OH_HUKS_ERR_CODE_KEY_AUTH_PERMANENTLY_INVALIDATED = 12000007,
OH_HUKS_ERR_CODE_KEY_AUTH_VERIFY_FAILED = 12000008,
OH_HUKS_ERR_CODE_KEY_AUTH_TIME_OUT = 12000009,
OH_HUKS_ERR_CODE_SESSION_LIMIT = 12000010,
OH_HUKS_ERR_CODE_ITEM_NOT_EXIST = 12000011,
OH_HUKS_ERR_CODE_INTERNAL_ERROR = 12000012,
OH_HUKS_ERR_CODE_CREDENTIAL_NOT_EXIST = 12000013
} | Enumerates the error codes. | +| [OH_Huks_TagType](#oh_huks_tagtype) {
OH_HUKS_TAG_TYPE_INVALID = 0 << 28,
OH_HUKS_TAG_TYPE_INT = 1 << 28,
OH_HUKS_TAG_TYPE_UINT = 2 << 28,
OH_HUKS_TAG_TYPE_ULONG = 3 << 28,
OH_HUKS_TAG_TYPE_BOOL = 4 << 28,
OH_HUKS_TAG_TYPE_BYTES = 5 << 28
} | Enumerates the mask values of the parameter type in the parameter set. | +| [OH_Huks_UserAuthType](#oh_huks_userauthtype) {
OH_HUKS_USER_AUTH_TYPE_FINGERPRINT = 1 << 0,
OH_HUKS_USER_AUTH_TYPE_FACE = 1 << 1,
OH_HUKS_USER_AUTH_TYPE_PIN = 1 << 2
} | Enumerates the user authentication types in key access control. | +| [OH_Huks_AuthAccessType](#oh_huks_authaccesstype) {
OH_HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD = 1 << 0,
OH_HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL = 1 << 1
} | Enumerates the rules for invalidating a key. | +| [OH_Huks_ChallengeType](#oh_huks_challengetype) {
OH_HUKS_CHALLENGE_TYPE_NORMAL = 0,
OH_HUKS_CHALLENGE_TYPE_CUSTOM = 1,
OH_HUKS_CHALLENGE_TYPE_NONE = 2
} | Enumerates the types of the challenge generated when a key is used. | +| [OH_Huks_ChallengePosition](#oh_huks_challengeposition) {
OH_HUKS_CHALLENGE_POS_0 = 0,
OH_HUKS_CHALLENGE_POS_1,
OH_HUKS_CHALLENGE_POS_2,
OH_HUKS_CHALLENGE_POS_3
} | Enumerates the positions of the 8-byte valid value in a custom challenge generated. | +| [OH_Huks_SecureSignType](#oh_huks_securesigntype) { OH_HUKS_SECURE_SIGN_WITH_AUTHINFO = 1 } | Enumerates the signature types of the key generated or imported. | +| [OH_Huks_Tag](#oh_huks_tag) {
OH_HUKS_TAG_ALGORITHM = OH_HUKS_TAG_TYPE_UINT \| 1, OH_HUKS_TAG_PURPOSE = OH_HUKS_TAG_TYPE_UINT \| 2, OH_HUKS_TAG_KEY_SIZE = OH_HUKS_TAG_TYPE_UINT \| 3,
OH_HUKS_TAG_DIGEST = OH_HUKS_TAG_TYPE_UINT \| 4, OH_HUKS_TAG_PADDING = OH_HUKS_TAG_TYPE_UINT \| 5, OH_HUKS_TAG_BLOCK_MODE = OH_HUKS_TAG_TYPE_UINT \| 6, OH_HUKS_TAG_KEY_TYPE = OH_HUKS_TAG_TYPE_UINT \| 7,
OH_HUKS_TAG_ASSOCIATED_DATA = OH_HUKS_TAG_TYPE_BYTES \| 8, OH_HUKS_TAG_NONCE = OH_HUKS_TAG_TYPE_BYTES \| 9, OH_HUKS_TAG_IV = OH_HUKS_TAG_TYPE_BYTES \| 10, OH_HUKS_TAG_INFO = OH_HUKS_TAG_TYPE_BYTES \| 11,
OH_HUKS_TAG_SALT = OH_HUKS_TAG_TYPE_BYTES \| 12, OH_HUKS_TAG_ITERATION = OH_HUKS_TAG_TYPE_UINT \| 14, OH_HUKS_TAG_KEY_GENERATE_TYPE = OH_HUKS_TAG_TYPE_UINT \| 15, OH_HUKS_TAG_AGREE_ALG = OH_HUKS_TAG_TYPE_UINT \| 19,
OH_HUKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS = OH_HUKS_TAG_TYPE_BOOL \| 20, OH_HUKS_TAG_AGREE_PRIVATE_KEY_ALIAS = OH_HUKS_TAG_TYPE_BYTES \| 21, OH_HUKS_TAG_AGREE_PUBLIC_KEY = OH_HUKS_TAG_TYPE_BYTES \| 22, OH_HUKS_TAG_KEY_ALIAS = OH_HUKS_TAG_TYPE_BYTES \| 23,
OH_HUKS_TAG_DERIVE_KEY_SIZE = OH_HUKS_TAG_TYPE_UINT \| 24, OH_HUKS_TAG_IMPORT_KEY_TYPE = OH_HUKS_TAG_TYPE_UINT \| 25, OH_HUKS_TAG_UNWRAP_ALGORITHM_SUITE = OH_HUKS_TAG_TYPE_UINT \| 26, OH_HUKS_TAG_DERIVED_AGREED_KEY_STORAGE_FLAG = OH_HUKS_TAG_TYPE_UINT \| 29, OH_HUKS_TAG_RSA_PSS_SALT_LEN_TYPE = OH_HUKS_TAG_TYPE_UINT \| 30, OH_HUKS_TAG_ALL_USERS = OH_HUKS_TAG_TYPE_BOOL \| 301,
OH_HUKS_TAG_USER_ID = OH_HUKS_TAG_TYPE_UINT \| 302, OH_HUKS_TAG_NO_AUTH_REQUIRED = OH_HUKS_TAG_TYPE_BOOL \| 303, OH_HUKS_TAG_USER_AUTH_TYPE = OH_HUKS_TAG_TYPE_UINT \| 304, OH_HUKS_TAG_AUTH_TIMEOUT = OH_HUKS_TAG_TYPE_UINT \| 305,
OH_HUKS_TAG_AUTH_TOKEN = OH_HUKS_TAG_TYPE_BYTES \| 306, OH_HUKS_TAG_KEY_AUTH_ACCESS_TYPE = OH_HUKS_TAG_TYPE_UINT \| 307, OH_HUKS_TAG_KEY_SECURE_SIGN_TYPE = OH_HUKS_TAG_TYPE_UINT \| 308, OH_HUKS_TAG_CHALLENGE_TYPE = OH_HUKS_TAG_TYPE_UINT \| 309,
OH_HUKS_TAG_CHALLENGE_POS = OH_HUKS_TAG_TYPE_UINT \| 310, OH_HUKS_TAG_KEY_AUTH_PURPOSE = OH_HUKS_TAG_TYPE_UINT \| 311, OH_HUKS_TAG_ATTESTATION_CHALLENGE = OH_HUKS_TAG_TYPE_BYTES \| 501, OH_HUKS_TAG_ATTESTATION_APPLICATION_ID = OH_HUKS_TAG_TYPE_BYTES \| 502, OH_HUKS_TAG_ATTESTATION_ID_ALIAS = OH_HUKS_TAG_TYPE_BYTES \| 511,
OH_HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO = OH_HUKS_TAG_TYPE_BYTES \| 514, OH_HUKS_TAG_ATTESTATION_ID_VERSION_INFO = OH_HUKS_TAG_TYPE_BYTES \| 515,
OH_HUKS_TAG_IS_KEY_ALIAS = OH_HUKS_TAG_TYPE_BOOL \| 1001, OH_HUKS_TAG_KEY_STORAGE_FLAG = OH_HUKS_TAG_TYPE_UINT \| 1002, OH_HUKS_TAG_IS_ALLOWED_WRAP = OH_HUKS_TAG_TYPE_BOOL \| 1003, OH_HUKS_TAG_KEY_WRAP_TYPE = OH_HUKS_TAG_TYPE_UINT \| 1004,
OH_HUKS_TAG_KEY_AUTH_ID = OH_HUKS_TAG_TYPE_BYTES \| 1005, OH_HUKS_TAG_KEY_ROLE = OH_HUKS_TAG_TYPE_UINT \| 1006, OH_HUKS_TAG_KEY_FLAG = OH_HUKS_TAG_TYPE_UINT \| 1007, OH_HUKS_TAG_IS_ASYNCHRONIZED = OH_HUKS_TAG_TYPE_UINT \| 1008,
OH_HUKS_TAG_KEY_DOMAIN = OH_HUKS_TAG_TYPE_UINT \| 1011, OH_HUKS_TAG_SYMMETRIC_KEY_DATA = OH_HUKS_TAG_TYPE_BYTES \| 20001,
OH_HUKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATA = OH_HUKS_TAG_TYPE_BYTES \| 20002, OH_HUKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATA = OH_HUKS_TAG_TYPE_BYTES \| 20003
} | Enumerates the tag values used in the parameter set. | ## Enum Description @@ -91,416 +92,463 @@ Defines the macros, enumerated values, data structures, and error codes used by ### OH_Huks_AlgSuite - + ``` enum OH_Huks_AlgSuite ``` -**Description**
-Enumerates the algorithm suites required for ciphertext imports. +**Description** + +Enumerates the algorithm suites for the import of a wrapped key. -| Name | Description | +| Value| Description| | -------- | -------- | -| OH_HUKS_UNWRAP_SUITE_X25519_AES_256_GCM_NOPADDING | Key material format (Length-Value format), X25519 key agreement, and AES-256-GCM encryption and decryption. \| x25519_plain_pubkey_length (4 Byte) \| x25519_plain_pubkey \| agreekey_aad_length (4 Byte) \| agreekey_aad \| agreekey_nonce_length (4 Byte) \| agreekey_nonce \| agreekey_aead_tag_len(4 Byte) \| agreekey_aead_tag \| kek_enc_data_length (4 Byte) \| kek_enc_data \| kek_aad_length (4 Byte) \| kek_aad \| kek_nonce_length (4 Byte) \| kek_nonce \| kek_aead_tag_len (4 Byte) \| kek_aead_tag \| key_material_size_len (4 Byte) \| key_material_size \| key_mat_enc_length (4 Byte) \| key_mat_enc_data | -| OH_HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING | Key material format (Length-Value format), ECDH-p256 key agreement, and AES-256-GCM encryption and decryption. \| ECC_plain_pubkey_length (4 Byte) \| ECC_plain_pubkey \| agreekey_aad_length (4 Byte) \| agreekey_aad \| agreekey_nonce_length (4 Byte) \| agreekey_nonce \| agreekey_aead_tag_len(4 Byte) \| agreekey_aead_tag \| kek_enc_data_length (4 Byte) \| kek_enc_data \| kek_aad_length (4 Byte) \| kek_aad \| kek_nonce_length (4 Byte) \| kek_nonce \| kek_aead_tag_len (4 Byte) \| kek_aead_tag \| key_material_size_len (4 Byte) \| key_material_size \| key_mat_enc_length (4 Byte) \| key_mat_enc_data | +| OH_HUKS_UNWRAP_SUITE_X25519_AES_256_GCM_NOPADDING | Key material format (Length-Value format), use X25519 for key agreement, and use AES-256-GCM for encryption and decryption: \| x25519_plain_pubkey_length (4 Byte) \| x25519_plain_pubkey \| agreekey_aad_length (4 Byte) \| agreekey_aad \| agreekey_nonce_length (4 Byte) \| agreekey_nonce \| agreekey_aead_tag_len(4 Byte) \| agreekey_aead_tag \| kek_enc_data_length (4 Byte) \| kek_enc_data \| kek_aad_length (4 Byte) \| kek_aad \| kek_nonce_length (4 Byte) \| kek_nonce \| kek_aead_tag_len (4 Byte) \| kek_aead_tag \| key_material_size_len (4 Byte) \| key_material_size \| key_mat_enc_length (4 Byte) \| key_mat_enc_data | +| OH_HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING | Key material format (Length-Value format), use ECDH-p256 for key agreement, and use AES-256-GCM for encryption and decryption: \| ECC_plain_pubkey_length (4 Byte) \| ECC_plain_pubkey \| agreekey_aad_length (4 Byte) \| agreekey_aad \| agreekey_nonce_length (4 Byte) \| agreekey_nonce \| agreekey_aead_tag_len(4 Byte) \| agreekey_aead_tag \| kek_enc_data_length (4 Byte) \| kek_enc_data \| kek_aad_length (4 Byte) \| kek_aad \| kek_nonce_length (4 Byte) \| kek_nonce \| kek_aead_tag_len (4 Byte) \| kek_aead_tag \| key_material_size_len (4 Byte) \| key_material_size \| key_mat_enc_length (4 Byte) \| key_mat_enc_data | ### OH_Huks_AuthAccessType - + ``` enum OH_Huks_AuthAccessType ``` -**Description**
-Enumerates the access control types. +**Description** + +Enumerates the rules for invalidating a key. -| Name | Description | +| Name | Description| | -------- | -------- | -| OH_HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | The key is invalid after the password is cleared. | -| OH_HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | The key is invalid after a new biometric feature is enrolled. | +| OH_HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | The key becomes invalid after the password is cleared.| +| OH_HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | The key becomes invalid after a new biometric feature is enrolled.| ### OH_Huks_ChallengePosition - + ``` enum OH_Huks_ChallengePosition ``` -**Description**
+**Description** + Enumerates the positions of the 8-byte valid value in a custom challenge generated. -| Name | Description | +| Name | Description| | -------- | -------- | -| OH_HUKS_CHALLENGE_POS_0 | Bytes 0 to 7. | -| OH_HUKS_CHALLENGE_POS_1 | Bytes 8 to 15. | -| OH_HUKS_CHALLENGE_POS_2 | Bytes 16 to 23. | -| OH_HUKS_CHALLENGE_POS_3 | Bytes 24 to 31. | +| OH_HUKS_CHALLENGE_POS_0 | Bytes 0 to 7.| +| OH_HUKS_CHALLENGE_POS_1 | Bytes 8 to 15.| +| OH_HUKS_CHALLENGE_POS_2 | Bytes 16 to 23.| +| OH_HUKS_CHALLENGE_POS_3 | Bytes 24 to 31.| ### OH_Huks_ChallengeType - + ``` enum OH_Huks_ChallengeType ``` -**Description**
-Enumerates the types of the challenges generated when a key is used. +**Description** - **See** +Enumerates the types of the challenge generated when a key is used. + +**See** [OH_Huks_ChallengePosition](#oh_huks_challengeposition) -| Name | Description | +| Name | Description| | -------- | -------- | -| OH_HUKS_CHALLENGE_TYPE_NORMAL | Normal challenge, which is of 32 bytes by default. | -| OH_HUKS_CHALLENGE_TYPE_CUSTOM | Custom challenge, which supports only one authentication for multiple keys. The valid value of a custom challenge is of 8 bytes. | -| OH_HUKS_CHALLENGE_TYPE_NONE | Challenge is not required. | +| OH_HUKS_CHALLENGE_TYPE_NORMAL | Normal challenge, which is of 32 bytes by default.| +| OH_HUKS_CHALLENGE_TYPE_CUSTOM | Custom challenge, which supports only one authentication for multiple keys. The valid value of a custom challenge is of 8 bytes.| +| OH_HUKS_CHALLENGE_TYPE_NONE | Challenge is not required.| ### OH_Huks_CipherMode - + ``` enum OH_Huks_CipherMode ``` -**Description**
+**Description** + Enumerates the cipher modes. -| Name | Description | +| Name | Description| | -------- | -------- | -| OH_HUKS_MODE_ECB | Electronic Code Block (ECB) mode. | -| OH_HUKS_MODE_CBC | Cipher Block Chaining (CBC) mode. | -| OH_HUKS_MODE_CTR | Counter (CTR) mode. | -| OH_HUKS_MODE_OFB | Output Feedback (OFB) mode. | -| OH_HUKS_MODE_CCM | Counter with CBC-MAC (CCM) mode. | -| OH_HUKS_MODE_GCM | Galois/Counter (GCM) mode. | +| OH_HUKS_MODE_ECB | Electronic Code Block (ECB) mode.| +| OH_HUKS_MODE_CBC | Cipher Block Chaining (CBC) mode.| +| OH_HUKS_MODE_CTR | Counter (CTR) mode.| +| OH_HUKS_MODE_OFB | Output Feedback (OFB) mode.| +| OH_HUKS_MODE_CCM | Counter with CBC-MAC (CCM) mode.| +| OH_HUKS_MODE_GCM | Galois/Counter (GCM) mode.| + + +### OH_Huks_RsaPssSaltLenType + +``` +enum OH_Huks_RsaPssSaltLenType +``` +**Description** + +Enumerates the types of the salt length when the PSS padding mode is used in RSA signing or signature verification. + +**Since**: +10 + +| Name | Description| +| -------- | -------- | +| OH_HUKS_RSA_PSS_SALT_LEN_DIGEST | The salt length is set to the digest length.| +| OH_HUKS_RSA_PSS_SALT_LEN_MAX | The salt length is set to the maximum length.| ### OH_Huks_ErrCode - + ``` enum OH_Huks_ErrCode ``` -**Description**
+**Description** + Enumerates the error codes. -| Name | Description | +| Name | Description| | -------- | -------- | -| OH_HUKS_SUCCESS | The operation is successful. | -| OH_HUKS_ERR_CODE_PERMISSION_FAIL | Permission verification failed. | -| OH_HUKS_ERR_CODE_ILLEGAL_ARGUMENT | Invalid parameters are detected. | -| OH_HUKS_ERR_CODE_NOT_SUPPORTED_API | The API is not supported. | -| OH_HUKS_ERR_CODE_FEATURE_NOT_SUPPORTED | The feature is not supported. | -| OH_HUKS_ERR_CODE_MISSING_CRYPTO_ALG_ARGUMENT | Key algorithm parameters are missing. | -| OH_HUKS_ERR_CODE_INVALID_CRYPTO_ALG_ARGUMENT | Invalid key algorithm parameters are detected. | -| OH_HUKS_ERR_CODE_FILE_OPERATION_FAIL | Failed to operate the file. | -| OH_HUKS_ERR_CODE_COMMUNICATION_FAIL | The process communication failed. | -| OH_HUKS_ERR_CODE_CRYPTO_FAIL | Failed to operate the algorithm library. | -| OH_HUKS_ERR_CODE_KEY_AUTH_PERMANENTLY_INVALIDATED | Failed to access the key because the key has expired. | -| OH_HUKS_ERR_CODE_KEY_AUTH_VERIFY_FAILED | Failed to access the key because the authentication has failed. | -| OH_HUKS_ERR_CODE_KEY_AUTH_TIME_OUT | Key access timed out. | -| OH_HUKS_ERR_CODE_SESSION_LIMIT | The number of key operation sessions has reached the limit. | -| OH_HUKS_ERR_CODE_ITEM_NOT_EXIST | The entity does not exist. | -| OH_HUKS_ERR_CODE_INTERNAL_ERROR | Internal error. | -| OH_HUKS_ERR_CODE_CREDENTIAL_NOT_EXIST | The authentication credential does not exist. | +| OH_HUKS_SUCCESS | Success.| +| OH_HUKS_ERR_CODE_PERMISSION_FAIL | Permission verification failed.| +| OH_HUKS_ERR_CODE_ILLEGAL_ARGUMENT | Invalid parameter (universal).| +| OH_HUKS_ERR_CODE_NOT_SUPPORTED_API | The API is not supported.| +| OH_HUKS_ERR_CODE_FEATURE_NOT_SUPPORTED | The feature is not supported.| +| OH_HUKS_ERR_CODE_MISSING_CRYPTO_ALG_ARGUMENT | Key algorithm parameters are missing.| +| OH_HUKS_ERR_CODE_INVALID_CRYPTO_ALG_ARGUMENT | Invalid key algorithm parameter.| +| OH_HUKS_ERR_CODE_FILE_OPERATION_FAIL | File operation failed.| +| OH_HUKS_ERR_CODE_COMMUNICATION_FAIL | The process communication failed.| +| OH_HUKS_ERR_CODE_CRYPTO_FAIL | Failed to operate the crypto algorithm library.| +| OH_HUKS_ERR_CODE_KEY_AUTH_PERMANENTLY_INVALIDATED | Failed to access the key because the key has expired.| +| OH_HUKS_ERR_CODE_KEY_AUTH_VERIFY_FAILED | Failed to access the key because the authentication has failed.| +| OH_HUKS_ERR_CODE_KEY_AUTH_TIME_OUT | Key access timed out.| +| OH_HUKS_ERR_CODE_SESSION_LIMIT | The number of key operation sessions has reached the limit.| +| OH_HUKS_ERR_CODE_ITEM_NOT_EXIST | The entity does not exist.| +| OH_HUKS_ERR_CODE_INTERNAL_ERROR | Internal error.| +| OH_HUKS_ERR_CODE_CREDENTIAL_NOT_EXIST | The authentication credential does not exist.| ### OH_Huks_ImportKeyType - + ``` enum OH_Huks_ImportKeyType ``` -**Description**
-Enumerates the types of keys to import. By default, a public key is imported. This field is not required when a symmetric key is imported. +**Description** -| Name | Description | +Enumerates the types of the key to import. By default, a public key is imported. This field is not required when a symmetric key is imported. + +| Name | Description| | -------- | -------- | -| OH_HUKS_KEY_TYPE_PUBLIC_KEY | Public key. | -| OH_HUKS_KEY_TYPE_PRIVATE_KEY | Private key. | -| OH_HUKS_KEY_TYPE_KEY_PAIR | Public and private key pair. | +| OH_HUKS_KEY_TYPE_PUBLIC_KEY | Public key.| +| OH_HUKS_KEY_TYPE_PRIVATE_KEY | Private key.| +| OH_HUKS_KEY_TYPE_KEY_PAIR | Public and private key pair.| ### OH_Huks_KeyAlg - + ``` enum OH_Huks_KeyAlg ``` -**Description**
-Enumerates the key algorithms. +**Description** + +Enumerates the algorithms for keys. -| Name | Description | +| Name | Description| | -------- | -------- | -| OH_HUKS_ALG_RSA | RSA. | -| OH_HUKS_ALG_ECC | ECC. | -| OH_HUKS_ALG_DSA | DSA. | -| OH_HUKS_ALG_AES | AES. | -| OH_HUKS_ALG_HMAC | HMAC. | -| OH_HUKS_ALG_HKDF | HKDF. | -| OH_HUKS_ALG_PBKDF2 | PBKDF2. | -| OH_HUKS_ALG_ECDH | ECDH. | -| OH_HUKS_ALG_X25519 | X25519. | -| OH_HUKS_ALG_ED25519 | Ed25519. | -| OH_HUKS_ALG_DH | DH. | -| OH_HUKS_ALG_SM2 | SM2. | -| OH_HUKS_ALG_SM3 | SM3. | -| OH_HUKS_ALG_SM4 | SM4. | +| OH_HUKS_ALG_RSA | RSA.| +| OH_HUKS_ALG_ECC | ECC.| +| OH_HUKS_ALG_DSA | DSA.| +| OH_HUKS_ALG_AES | Advanced Encryption Standard (AES).| +| OH_HUKS_ALG_HMAC | HMAC algorithm.| +| OH_HUKS_ALG_HKDF | HKDF.| +| OH_HUKS_ALG_PBKDF2 | PBKDF2.| +| OH_HUKS_ALG_ECDH | ECDH.| +| OH_HUKS_ALG_X25519 | X25519.| +| OH_HUKS_ALG_ED25519 | Ed25519.| +| OH_HUKS_ALG_DH | DH.| +| OH_HUKS_ALG_SM2 | ShangMi2 (SM2).| +| OH_HUKS_ALG_SM3 | SM3.| +| OH_HUKS_ALG_SM4 | ShangMi4 (SM4).| ### OH_Huks_KeyDigest - + ``` enum OH_Huks_KeyDigest ``` -**Description**
+**Description** + Enumerates the digest algorithms. -| Name | Description | +| Name | Description| | -------- | -------- | -| OH_HUKS_DIGEST_NONE | No digest algorithm. | -| OH_HUKS_DIGEST_MD5 | MD5. | -| OH_HUKS_DIGEST_SM3 | SM3. | -| OH_HUKS_DIGEST_SHA1 | SHA-1. | -| OH_HUKS_DIGEST_SHA224 | SHA-224. | -| OH_HUKS_DIGEST_SHA256 | SHA-256. | -| OH_HUKS_DIGEST_SHA384 | SHA-384. | -| OH_HUKS_DIGEST_SHA512 | SHA-512. | +| OH_HUKS_DIGEST_NONE | No digest algorithm.| +| OH_HUKS_DIGEST_MD5 | MD5.| +| OH_HUKS_DIGEST_SM3 | SM3.| +| OH_HUKS_DIGEST_SHA1 | SHA-1.| +| OH_HUKS_DIGEST_SHA224 | SHA-224.| +| OH_HUKS_DIGEST_SHA256 | SHA-256.| +| OH_HUKS_DIGEST_SHA384 | SHA-384.| +| OH_HUKS_DIGEST_SHA512 | SHA-512.| ### OH_Huks_KeyFlag - + ``` enum OH_Huks_KeyFlag ``` -**Description**
-Enumerates the key generation modes. +**Description** -| Name | Description | +Enumerates the key generation types. + +| Name | Description| | -------- | -------- | -| OH_HUKS_KEY_FLAG_IMPORT_KEY | Import a public key using an API. | -| OH_HUKS_KEY_FLAG_GENERATE_KEY | Generate a key by using an API. | -| OH_HUKS_KEY_FLAG_AGREE_KEY | Generate a key by using a key agreement API. | -| OH_HUKS_KEY_FLAG_DERIVE_KEY | Derive a key by using an API. | +| OH_HUKS_KEY_FLAG_IMPORT_KEY | Import a public key using an API.| +| OH_HUKS_KEY_FLAG_GENERATE_KEY | Generate a key by using an API.| +| OH_HUKS_KEY_FLAG_AGREE_KEY | Generate a key by using a key agreement API.| +| OH_HUKS_KEY_FLAG_DERIVE_KEY | Derive a key by using an API.| ### OH_Huks_KeyGenerateType - + ``` enum OH_Huks_KeyGenerateType ``` -**Description**
-Enumerates the key generation types. +**Description** -| Name | Description | +Enumerates the types of the key generated. + +| Name | Description| | -------- | -------- | -| OH_HUKS_KEY_GENERATE_TYPE_DEFAULT | Key generated by default. | -| OH_HUKS_KEY_GENERATE_TYPE_DERIVE | Derived key. | -| OH_HUKS_KEY_GENERATE_TYPE_AGREE | Key obtained by key agreement. | +| OH_HUKS_KEY_GENERATE_TYPE_DEFAULT | Key generated by default.| +| OH_HUKS_KEY_GENERATE_TYPE_DERIVE | Derived key.| +| OH_HUKS_KEY_GENERATE_TYPE_AGREE | Key generated by key agreement.| ### OH_Huks_KeyPadding - + ``` enum OH_Huks_KeyPadding ``` -**Description**
+**Description** + Enumerates the padding algorithms. -| Name | Description | +| Name | Description| | -------- | -------- | -| OH_HUKS_PADDING_NONE | No padding algorithm. | -| OH_HUKS_PADDING_OAEP | Optimal Asymmetric Encryption Padding (OAEP). | -| OH_HUKS_PADDING_PSS | Probabilistic Signature Scheme (PSS). | -| OH_HUKS_PADDING_PKCS1_V1_5 | Public Key Cryptography Standards (PKCS) \#1 v1.5. | -| OH_HUKS_PADDING_PKCS5 | PKCS \#5. | -| OH_HUKS_PADDING_PKCS7 | PKCS \#7. | +| OH_HUKS_PADDING_NONE | No padding algorithm.| +| OH_HUKS_PADDING_OAEP | Optimal Asymmetric Encryption Padding (OAEP).| +| OH_HUKS_PADDING_PSS | Probabilistic Signature Scheme (PSS).| +| OH_HUKS_PADDING_PKCS1_V1_5 | Public Key Cryptography Standards (PKCS) #1 v1.5.| +| OH_HUKS_PADDING_PKCS5 | PKCS #5.| +| OH_HUKS_PADDING_PKCS7 | PKCS #7.| ### OH_Huks_KeyPurpose - + ``` enum OH_Huks_KeyPurpose ``` -**Description**
+**Description** + Enumerates the key purposes. -| Name | Description | +| Name | Description| | -------- | -------- | -| OH_HUKS_KEY_PURPOSE_ENCRYPT | Used to encrypt the plaintext. | -| OH_HUKS_KEY_PURPOSE_DECRYPT | Used to decrypt the cipher text. | -| OH_HUKS_KEY_PURPOSE_SIGN | Used to sign data. | -| OH_HUKS_KEY_PURPOSE_VERIFY | Used to verify the signature. | -| OH_HUKS_KEY_PURPOSE_DERIVE | Used to derive a key. | -| OH_HUKS_KEY_PURPOSE_WRAP | Used for an encrypted export. | -| OH_HUKS_KEY_PURPOSE_UNWRAP | Used for an encrypted import. | -| OH_HUKS_KEY_PURPOSE_MAC | Used to generate a message authentication code (MAC). | -| OH_HUKS_KEY_PURPOSE_AGREE | Used for key agreement. | +| OH_HUKS_KEY_PURPOSE_ENCRYPT | Used to encrypt the plaintext.| +| OH_HUKS_KEY_PURPOSE_DECRYPT | Used to decrypt the cipher text.| +| OH_HUKS_KEY_PURPOSE_SIGN | Used for signing.| +| OH_HUKS_KEY_PURPOSE_VERIFY | Used to verify the signature.| +| OH_HUKS_KEY_PURPOSE_DERIVE | Used to derive a key.| +| OH_HUKS_KEY_PURPOSE_WRAP | Used for an encrypted export.| +| OH_HUKS_KEY_PURPOSE_UNWRAP | Used for an encrypted import.| +| OH_HUKS_KEY_PURPOSE_MAC | Used to generate a message authentication code (MAC).| +| OH_HUKS_KEY_PURPOSE_AGREE | Used for key agreement.| ### OH_Huks_KeySize - + ``` enum OH_Huks_KeySize ``` -**Description**
-Enumerates the key sizes. +**Description** -| Name | Description | +Enumerates key sizes of different algorithms. + +| Name | Description| | -------- | -------- | -| OH_HUKS_RSA_KEY_SIZE_512 | Rivest-Shamir-Adleman (RSA) key of 512 bits. | -| OH_HUKS_RSA_KEY_SIZE_768 | RSA key of 768 bits. | -| OH_HUKS_RSA_KEY_SIZE_1024 | RSA key of 1024 bits. | -| OH_HUKS_RSA_KEY_SIZE_2048 | RSA key of 2048 bits. | -| OH_HUKS_RSA_KEY_SIZE_3072 | RSA key of 3072 bits. | -| OH_HUKS_RSA_KEY_SIZE_4096 | RSA key of 4096 bits. | -| OH_HUKS_ECC_KEY_SIZE_224 | Elliptic Curve Cryptography (ECC) key of 224 bits. | -| OH_HUKS_ECC_KEY_SIZE_256 | ECC key of 256 bits. | -| OH_HUKS_ECC_KEY_SIZE_384 | ECC key of 384 bits. | -| OH_HUKS_ECC_KEY_SIZE_521 | ECC key of 521 bits. | -| OH_HUKS_AES_KEY_SIZE_128 | Advanced Encryption Standard (AES) key of 128 bits. | -| OH_HUKS_AES_KEY_SIZE_192 | AES key of 192 bits. | -| OH_HUKS_AES_KEY_SIZE_256 | AES key of 256 bits. | -| OH_HUKS_AES_KEY_SIZE_512 | AES key of 512 bits. | -| OH_HUKS_CURVE25519_KEY_SIZE_256 | Curve25519 key of 256 bits. | -| OH_HUKS_DH_KEY_SIZE_2048 | Diffie-Hellman (DH) key of 2048 bits. | -| OH_HUKS_DH_KEY_SIZE_3072 | DH key of 3072 bits. | -| OH_HUKS_DH_KEY_SIZE_4096 | DH key of 4096 bits. | -| OH_HUKS_SM2_KEY_SIZE_256 | ShangMi2 (SM2) key of 256 bits. | -| OH_HUKS_SM4_KEY_SIZE_128 | ShangMi4 (SM4) key of 128 bits. | +| OH_HUKS_RSA_KEY_SIZE_512 | Rivest-Shamir-Adleman (RSA) key of 512 bits.| +| OH_HUKS_RSA_KEY_SIZE_768 | RSA key of 768 bits.| +| OH_HUKS_RSA_KEY_SIZE_1024 | RSA key of 1024 bits.| +| OH_HUKS_RSA_KEY_SIZE_2048 | RSA key of 2048 bits.| +| OH_HUKS_RSA_KEY_SIZE_3072 | RSA key of 3072 bits.| +| OH_HUKS_RSA_KEY_SIZE_4096 | RSA key of 4096 bits.| +| OH_HUKS_ECC_KEY_SIZE_224 | ECC key of 224 bits.| +| OH_HUKS_ECC_KEY_SIZE_256 | ECC key of 256 bits.| +| OH_HUKS_ECC_KEY_SIZE_384 | ECC key of 384 bits.| +| OH_HUKS_ECC_KEY_SIZE_521 | ECC key of 521 bits.| +| OH_HUKS_AES_KEY_SIZE_128 | AES key of 128 bits.| +| OH_HUKS_AES_KEY_SIZE_192 | AES key of 192 bits.| +| OH_HUKS_AES_KEY_SIZE_256 | AES key of 256 bits.| +| OH_HUKS_AES_KEY_SIZE_512 | AES key of 512 bits.| +| OH_HUKS_CURVE25519_KEY_SIZE_256 | Curve25519 key of 256 bits.| +| OH_HUKS_DH_KEY_SIZE_2048 | DH key of 2048 bits.| +| OH_HUKS_DH_KEY_SIZE_3072 | DH key of 3072 bits.| +| OH_HUKS_DH_KEY_SIZE_4096 | DH key of 4096 bits.| +| OH_HUKS_SM2_KEY_SIZE_256 | SM2 key of 256 bits.| +| OH_HUKS_SM4_KEY_SIZE_128 | SM4 key of 128 bits.| ### OH_Huks_KeyStorageType - + ``` enum OH_Huks_KeyStorageType ``` -**Description**
-Enumerates the key storage modes. +**Description** + +Enumerates the key storage types. -| Name | Description | +| Name | Description| | -------- | -------- | -| OH_HUKS_STORAGE_TEMP | The key is managed locally. | -| OH_HUKS_STORAGE_PERSISTENT | The key is managed by the HUKS service. | +| OH_HUKS_STORAGE_TEMP | The key is managed locally.| +| OH_HUKS_STORAGE_PERSISTENT | The key is managed by the HUKS service.| +| OH_HUKS_STORAGE_ONLY_USED_IN_HUKS | The key is stored only in the HUKS.| +| OH_HUKS_STORAGE_KEY_EXPORT_ALLOWED | The key is exported from the HUKS and is not stored.| ### OH_Huks_SecureSignType - + ``` enum OH_Huks_SecureSignType ``` -**Description**
-Enumerates the signature types of the keys generated or imported. +**Description** + +Enumerates the signature types of the key generated or imported. -| Name | Description | +| Name | Description| | -------- | -------- | -| OH_HUKS_SECURE_SIGN_WITH_AUTHINFO | The signature carries authentication information. This field is specified when a key is generated or imported. When the key is used to sign data, the data will be added with the authentication information and then be signed. | +| OH_HUKS_SECURE_SIGN_WITH_AUTHINFO | The signature carries authentication information. This field is specified when a key is generated or imported. When the key is used for signing, the data will be added with the authentication information and then be signed.| ### OH_Huks_Tag - + ``` enum OH_Huks_Tag ``` -**Description**
-Enumerates the tag values used in parameter sets. - -| Name | Description | -| -------- | -------- | -| OH_HUKS_TAG_ALGORITHM | Tags for key parameters. The value range is 1 to 200. Algorithm. | -| OH_HUKS_TAG_PURPOSE | Key purpose. | -| OH_HUKS_TAG_KEY_SIZE | Key size. | -| OH_HUKS_TAG_DIGEST | Digest algorithm. | -| OH_HUKS_TAG_PADDING | Padding algorithm. | -| OH_HUKS_TAG_BLOCK_MODE | Cipher mode. | -| OH_HUKS_TAG_KEY_TYPE | Key type. | -| OH_HUKS_TAG_ASSOCIATED_DATA | Associated authentication data. | -| OH_HUKS_TAG_NONCE | Field for key encryption and decryption. | -| OH_HUKS_TAG_IV | Initialized vector (IV). | -| OH_HUKS_TAG_INFO | Information generated during key derivation. | -| OH_HUKS_TAG_SALT | Salt value used for key derivation. | -| OH_HUKS_TAG_ITERATION | Number of iterations for key derivation. | -| OH_HUKS_TAG_KEY_GENERATE_TYPE | Type of the generated key. For details, see [OH_Huks_KeyGenerateType](#oh_huks_keygeneratetype). | -| OH_HUKS_TAG_AGREE_ALG | Algorithm used in key agreement. | -| OH_HUKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS | Alias of the public key used for key agreement. | -| OH_HUKS_TAG_AGREE_PRIVATE_KEY_ALIAS | Alias of the private key used for key agreement. | -| OH_HUKS_TAG_AGREE_PUBLIC_KEY | Public key used for key agreement. | -| OH_HUKS_TAG_KEY_ALIAS | Alias of the key. | -| OH_HUKS_TAG_DERIVE_KEY_SIZE | Size of the derived key. | -| OH_HUKS_TAG_IMPORT_KEY_TYPE | Type of the key to import. For details, see [OH_Huks_ImportKeyType](#oh_huks_importkeytype). | -| OH_HUKS_TAG_UNWRAP_ALGORITHM_SUITE | Algorithm suite required for encrypted imports. | -| OH_HUKS_TAG_ALL_USERS | Tags for access control and user authentication. The value range is 301 to 500. All users in the multi-user scenario. | -| OH_HUKS_TAG_USER_ID | Multi-user ID. | -| OH_HUKS_TAG_NO_AUTH_REQUIRED | Specifies whether key access control is required. | -| OH_HUKS_TAG_USER_AUTH_TYPE | User authentication type in key access control. | -| OH_HUKS_TAG_AUTH_TIMEOUT | Timeout duration for key access. | -| OH_HUKS_TAG_AUTH_TOKEN | Authentication token for the key. | -| OH_HUKS_TAG_KEY_AUTH_ACCESS_TYPE | Access control type. For details, see [OH_Huks_AuthAccessType](#oh_huks_authaccesstype). This parameter must be set together with the user authentication type. | -| OH_HUKS_TAG_KEY_SECURE_SIGN_TYPE | Signature type for the key to be generated or imported. | -| OH_HUKS_TAG_CHALLENGE_TYPE | Challenge type. For details, see [OH_Huks_ChallengeType](#oh_huks_challengetype). | -| OH_HUKS_TAG_CHALLENGE_POS | Position of the 8-byte valid value in a custom challenge. For details, see [OH_Huks_ChallengePosition](#oh_huks_challengeposition). | -| OH_HUKS_TAG_ATTESTATION_CHALLENGE | Tags for key attestation. The value range is 501 to 600. Challenge value used in the attestation. | -| OH_HUKS_TAG_ATTESTATION_APPLICATION_ID | Application ID used in the attestation. | -| OH_HUKS_TAG_ATTESTATION_ID_ALIAS | Alias of the key. | -| OH_HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO | Security level used in the attestation. | -| OH_HUKS_TAG_ATTESTATION_ID_VERSION_INFO | Version information used in the attestation. | -| OH_HUKS_TAG_IS_KEY_ALIAS | 601 to 1000 are reserved for other tags.
Extended tags. The value range is 1001 to 9999. Specifies whether it is a key alias. | -| OH_HUKS_TAG_KEY_STORAGE_FLAG | Key storage mode. For details, see [OH_Huks_KeyStorageType](#oh_huks_keystoragetype). | -| OH_HUKS_TAG_IS_ALLOWED_WRAP | Specifies whether to allow the key to be wrapped. | -| OH_HUKS_TAG_KEY_WRAP_TYPE | Key wrap type. | -| OH_HUKS_TAG_KEY_AUTH_ID | Authentication ID. | -| OH_HUKS_TAG_KEY_ROLE | Role of the key. | -| OH_HUKS_TAG_KEY_FLAG | Key flag. For details, see [OH_Huks_KeyFlag](#oh_huks_keyflag). | -| OH_HUKS_TAG_IS_ASYNCHRONIZED | Specifies whether this API is asynchronous. | -| OH_HUKS_TAG_KEY_DOMAIN | Key domain. | -| OH_HUKS_TAG_SYMMETRIC_KEY_DATA | 11000 to 12000 are reserved.
20001 to N are reserved for other tags. Symmetric key data. | -| OH_HUKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATA | Public key data of the asymmetric key pair. | -| OH_HUKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATA | Private key data of the asymmetric key pair. | +**Description** + +Enumerates the tag values used in the parameter set. + +| Name | Description| +| :------- | -------- | +| Tags for key parameters: 1 to 200 | | +| OH_HUKS_TAG_ALGORITHM | Algorithm type. | +| OH_HUKS_TAG_PURPOSE | Key purpose.| +| OH_HUKS_TAG_KEY_SIZE | Key length.| +| OH_HUKS_TAG_DIGEST | Digest algorithm.| +| OH_HUKS_TAG_PADDING | Padding algorithm.| +| OH_HUKS_TAG_BLOCK_MODE | Cipher mode.| +| OH_HUKS_TAG_KEY_TYPE | Key type.| +| OH_HUKS_TAG_ASSOCIATED_DATA | Associated authentication data.| +| OH_HUKS_TAG_NONCE | Field for key encryption and decryption.| +| OH_HUKS_TAG_IV | Initialized vector (IV).| +| OH_HUKS_TAG_INFO | Information generated during key derivation.| +| OH_HUKS_TAG_SALT | Salt value used for key derivation.| +| OH_HUKS_TAG_ITERATION | Number of iterations for key derivation.| +| OH_HUKS_TAG_KEY_GENERATE_TYPE | Type of the generated key. For details, see [OH_Huks_KeyGenerateType](#oh_huks_keygeneratetype).| +| OH_HUKS_TAG_AGREE_ALG | Algorithm used in key agreement.| +| OH_HUKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS | Alias of the public key used for key agreement.| +| OH_HUKS_TAG_AGREE_PRIVATE_KEY_ALIAS | Alias of the private key used for key agreement.| +| OH_HUKS_TAG_AGREE_PUBLIC_KEY | Public key used for key agreement.| +| OH_HUKS_TAG_KEY_ALIAS | Key alias.| +| OH_HUKS_TAG_DERIVE_KEY_SIZE | Size of the derived key.| +| OH_HUKS_TAG_IMPORT_KEY_TYPE | Type of the key to import. For details, see {@link OH_Huks_ImportKeyType}.| +| OH_HUKS_TAG_UNWRAP_ALGORITHM_SUITE | Algorithm suite required for encrypted imports.| +| OH_HUKS_TAG_DERIVED_AGREED_KEY_STORAGE_FLAG | Storage type of the derived/agreed key.| +| OH_HUKS_TAG_RSA_PSS_SALT_LEN_TYPE | Salt length type when the PSS padding mode is used for the RSA algorithm.| +| Tags for key access control and authentication: 300 to 500 | | +| OH_HUKS_TAG_ALL_USERS | All users in multi-user scenarios. | +| OH_HUKS_TAG_USER_ID | Multi-user ID.| +| OH_HUKS_TAG_NO_AUTH_REQUIRED | Whether key access control is required.| +| OH_HUKS_TAG_USER_AUTH_TYPE | User authentication type in key access control.| +| OH_HUKS_TAG_AUTH_TIMEOUT | Timeout duration for key access.| +| OH_HUKS_TAG_AUTH_TOKEN | Authentication token for the key.| +| OH_HUKS_TAG_KEY_AUTH_ACCESS_TYPE | Access control type. For details, see {@link OH_Huks_AuthAccessType}. This parameter must be set together with the user authentication type.| +| OH_HUKS_TAG_KEY_SECURE_SIGN_TYPE | Signature type of the key generated or imported.| +| OH_HUKS_TAG_CHALLENGE_TYPE | Type of the challenge generated for a key. For details, see {@link OH_Huks_ChallengeType}.| +| OH_HUKS_TAG_CHALLENGE_POS | Position of the 8-byte valid value in a custom challenge. For details, see {@link OH_Huks_ChallengePosition}.| +| H_HUKS_TAG_KEY_AUTH_PURPOSE | Type of the key authentication purpose.| +| Tags for key attestation: 501 to 600 | | +| OH_HUKS_TAG_ATTESTATION_CHALLENGE | Challenge value used for key attestation. | +| OH_HUKS_TAG_ATTESTATION_APPLICATION_ID | ID of the application, to which the key belongs, in key attestation.| +| OH_HUKS_TAG_ATTESTATION_ID_ALIAS | Key alias.| +| OH_HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO | Security level used in key attestation.| +| OH_HUKS_TAG_ATTESTATION_ID_VERSION_INFO | Version information used in key attestation.| +| 601 to 1000 are reserved. Extended tags: 1001 to 9999 | | +| OH_HUKS_TAG_IS_KEY_ALIAS | Whether the key alias is used. | +| OH_HUKS_TAG_KEY_STORAGE_FLAG | Key storage mode. For details, see [OH_Huks_KeyStorageType](#oh_huks_keystoragetype).| +| OH_HUKS_TAG_IS_ALLOWED_WRAP | Whether to allow the key to be wrapped.| +| OH_HUKS_TAG_KEY_WRAP_TYPE | Key wrap type.| +| OH_HUKS_TAG_KEY_AUTH_ID | Authentication ID.| +| OH_HUKS_TAG_KEY_ROLE | Role of the key.| +| OH_HUKS_TAG_KEY_FLAG | Key flag. For details, see [OH_Huks_KeyFlag](#oh_huks_keyflag).| +| OH_HUKS_TAG_IS_ASYNCHRONIZED | Whether the invocation is asynchronous.| +| OH_HUKS_TAG_KEY_DOMAIN | Key domain.| +| 11000 to 12000 are reserved. Reserved values for other tags: 20001 - N | | +| OH_HUKS_TAG_SYMMETRIC_KEY_DATA | Symmetric key data. | +| OH_HUKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATA | Public key data of the asymmetric key pair.| +| OH_HUKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATA | Private key data of the asymmetric key pair.| ### OH_Huks_TagType - + ``` enum OH_Huks_TagType ``` -**Description**
-Enumerates the tag types. +**Description** - **See** +Enumerates the mask values of the parameter type in the parameter set. + +**See** [OH_Huks_Param](_o_h___huks___param.md) -| Name | Description | +| Name | Description| | -------- | -------- | -| OH_HUKS_TAG_TYPE_INVALID | Invalid tag type. | -| OH_HUKS_TAG_TYPE_INT | int32_t. | -| OH_HUKS_TAG_TYPE_UINT | uin32_t. | -| OH_HUKS_TAG_TYPE_ULONG | uin64_t. | -| OH_HUKS_TAG_TYPE_BOOL | Boolean. | -| OH_HUKS_TAG_TYPE_BYTES | [OH_Huks_Blob](_o_h___huks___blob.md). | +| OH_HUKS_TAG_TYPE_INVALID | Invalid tag type.| +| OH_HUKS_TAG_TYPE_INT | int32_t.| +| OH_HUKS_TAG_TYPE_UINT | uin32_t.| +| OH_HUKS_TAG_TYPE_ULONG | uin64_t.| +| OH_HUKS_TAG_TYPE_BOOL | Boolean.| +| OH_HUKS_TAG_TYPE_BYTES | OH_Huks_Blob.| ### OH_Huks_UserAuthType - + ``` enum OH_Huks_UserAuthType ``` -**Description**
-Enumerates the user authentication types. +**Description** + +Enumerates the user authentication types in key access control. -| Name | Description | +| Name | Description| | -------- | -------- | -| OH_HUKS_USER_AUTH_TYPE_FINGERPRINT | Fingerprint authentication. | -| OH_HUKS_USER_AUTH_TYPE_FACE | Facial authentication. | -| OH_HUKS_USER_AUTH_TYPE_PIN | PIN authentication. | +| OH_HUKS_USER_AUTH_TYPE_FINGERPRINT | Fingerprint authentication.| +| OH_HUKS_USER_AUTH_TYPE_FACE | Facial authentication.| +| OH_HUKS_USER_AUTH_TYPE_PIN | PIN authentication.| diff --git a/en/application-dev/reference/native-apis/native__huks__type_8h.md b/en/application-dev/reference/native-apis/native__huks__type_8h.md index caa129bf8f4d97fdf18e2e333998e536b84bbbba..6b5368fefeb2f9647ca419446891d0f7d8adbc95 100644 --- a/en/application-dev/reference/native-apis/native__huks__type_8h.md +++ b/en/application-dev/reference/native-apis/native__huks__type_8h.md @@ -3,12 +3,12 @@ ## Overview -Defines the enumerated variables, structures, and macros used in the HUKS APIs. +Defines the enumerated variables, structs, and macros used in the HUKS APIs. -**Since:** + **Since** 9 -**Related Modules:** +**Related Modules** [HuksTypeApi](_huks_type_api.md) @@ -18,64 +18,65 @@ Defines the enumerated variables, structures, and macros used in the HUKS APIs. ### Structs -| Name | Description | +| Name| Description| | -------- | -------- | -| [OH_Huks_Result](_o_h___huks___result.md) | Defines the return data, including the result code and message. | -| [OH_Huks_Blob](_o_h___huks___blob.md) | Defines the structure for storing data. | -| [OH_Huks_Param](_o_h___huks___param.md) | Defines the parameter structure in a parameter set. | -| [OH_Huks_ParamSet](_o_h___huks___param_set.md) | Defines the structure of the parameter set. | -| [OH_Huks_CertChain](_o_h___huks___cert_chain.md) | Defines the structure of the certificate chain. | -| [OH_Huks_KeyInfo](_o_h___huks___key_info.md) | Defines the key information structure. | -| [OH_Huks_PubKeyInfo](_o_h___huks___pub_key_info.md) | Defines the structure of a public key. | -| [OH_Huks_KeyMaterialRsa](_o_h___huks___key_material_rsa.md) | Defines the structure of an RSA key. | -| [OH_Huks_KeyMaterialEcc](_o_h___huks___key_material_ecc.md) | Defines the structure of an ECC key. | -| [OH_Huks_KeyMaterialDsa](_o_h___huks___key_material_dsa.md) | Defines the structure of a DSA key. | -| [OH_Huks_KeyMaterialDh](_o_h___huks___key_material_dh.md) | Defines the structure of a DH key. | -| [OH_Huks_KeyMaterial25519](_o_h___huks___key_material25519.md) | Defines the structure of a 25519 key. | +| [OH_Huks_Result](_o_h___huks___result.md) | Defines the returned status data, including the return code and message. | +| [OH_Huks_Blob](_o_h___huks___blob.md) | Defines the binary large object (BLOB) that stores data. | +| [OH_Huks_Param](_o_h___huks___param.md) | Defines the structure of the parameters in a parameter set. | +| [OH_Huks_ParamSet](_o_h___huks___param_set.md) | Defines the parameter set information. | +| [OH_Huks_CertChain](_o_h___huks___cert_chain.md) | Defines the certificate chain information. | +| [OH_Huks_KeyInfo](_o_h___huks___key_info.md) | Defines the key information. | +| [OH_Huks_PubKeyInfo](_o_h___huks___pub_key_info.md) | Defines the information of a public key. | +| [OH_Huks_KeyMaterialRsa](_o_h___huks___key_material_rsa.md) | Defines the information of an RSA key. | +| [OH_Huks_KeyMaterialEcc](_o_h___huks___key_material_ecc.md) | Defines the information of an ECC key. | +| [OH_Huks_KeyMaterialDsa](_o_h___huks___key_material_dsa.md) | Defines the information of a DSA key. | +| [OH_Huks_KeyMaterialDh](_o_h___huks___key_material_dh.md) | Defines the information of a DH key. | +| [OH_Huks_KeyMaterial25519](_o_h___huks___key_material25519.md) | Defines the information of a 25519 key. | ### Macros -| Name | Value | +| Name| Value| | -------- | -------- | -| **OH_HUKS_AE_TAG_LEN** | 16 | -| **OH_HUKS_BITS_PER_BYTE** | 8| +| **OH_HUKS_AE_TAG_LEN** | 16| +| **OH_HUKS_BITS_PER_BYTE** |8 | | **OH_HUKS_MAX_KEY_SIZE** | 2048 | | **OH_HUKS_AE_NONCE_LEN** | 12 | | **OH_HUKS_MAX_KEY_ALIAS_LEN** | 64 | -| **OH_HUKS_MAX_PROCESS_NAME_LEN** | 50| -| **OH_HUKS_MAX_RANDOM_LEN** | 1024 | +| **OH_HUKS_MAX_PROCESS_NAME_LEN** | 50 | +| **OH_HUKS_MAX_RANDOM_LEN** | 1024 | | **OH_HUKS_SIGNATURE_MIN_SIZE** | 64 | -| **OH_HUKS_MAX_OUT_BLOB_SIZE** | (5 \* 1024 \* 1024) | +| **OH_HUKS_MAX_OUT_BLOB_SIZE** | (5 \* 1024 \* 1024) | | **OH_HUKS_WRAPPED_FORMAT_MAX_SIZE** | (1024 \* 1024) | | **OH_HUKS_IMPORT_WRAPPED_KEY_TOTAL_BLOBS** | 10 | | **TOKEN_CHALLENGE_LEN** | 32 | | **SHA256_SIGN_LEN** | 32 | -| **TOKEN_SIZE** | 32 | -| **MAX_AUTH_TIMEOUT_SECOND** | 60 | -| **SECURE_SIGN_VERSION** | 0x01000001 | +| **TOKEN_SIZE** | 32 | +| **MAX_AUTH_TIMEOUT_SECOND** | 60 | +| **SECURE_SIGN_VERSION** | 0x01000001| ### Enums -| Name | Description | +| Name| Description| | -------- | -------- | -| [OH_Huks_KeyPurpose](_huks_type_api.md#oh_huks_keypurpose) {
OH_HUKS_KEY_PURPOSE_ENCRYPT = 1, OH_HUKS_KEY_PURPOSE_DECRYPT = 2, OH_HUKS_KEY_PURPOSE_SIGN = 4, OH_HUKS_KEY_PURPOSE_VERIFY = 8,
OH_HUKS_KEY_PURPOSE_DERIVE = 16, OH_HUKS_KEY_PURPOSE_WRAP = 32, OH_HUKS_KEY_PURPOSE_UNWRAP = 64, OH_HUKS_KEY_PURPOSE_MAC = 128,
OH_HUKS_KEY_PURPOSE_AGREE = 256
} | Enumerates the key purposes. | -| [OH_Huks_KeyDigest](_huks_type_api.md#oh_huks_keydigest) {
OH_HUKS_DIGEST_NONE = 0, OH_HUKS_DIGEST_MD5 = 1, OH_HUKS_DIGEST_SM3 = 2, OH_HUKS_DIGEST_SHA1 = 10,
OH_HUKS_DIGEST_SHA224 = 11, OH_HUKS_DIGEST_SHA256 = 12, OH_HUKS_DIGEST_SHA384 = 13, OH_HUKS_DIGEST_SHA512 = 14
} | Enumerates the digest algorithms. | -| [OH_Huks_KeyPadding](_huks_type_api.md#oh_huks_keypadding) {
OH_HUKS_PADDING_NONE = 0, OH_HUKS_PADDING_OAEP = 1, OH_HUKS_PADDING_PSS = 2, OH_HUKS_PADDING_PKCS1_V1_5 = 3,
OH_HUKS_PADDING_PKCS5 = 4, OH_HUKS_PADDING_PKCS7 = 5
} | Enumerates the padding algorithms. | -| [OH_Huks_CipherMode](_huks_type_api.md#oh_huks_ciphermode) {
OH_HUKS_MODE_ECB = 1, OH_HUKS_MODE_CBC = 2, OH_HUKS_MODE_CTR = 3, OH_HUKS_MODE_OFB = 4,
OH_HUKS_MODE_CCM = 31, OH_HUKS_MODE_GCM = 32
} | Enumerates the cipher modes. | -| [OH_Huks_KeySize](_huks_type_api.md#oh_huks_keysize) {
OH_HUKS_RSA_KEY_SIZE_512 = 512, OH_HUKS_RSA_KEY_SIZE_768 = 768, OH_HUKS_RSA_KEY_SIZE_1024 = 1024, OH_HUKS_RSA_KEY_SIZE_2048 = 2048,
OH_HUKS_RSA_KEY_SIZE_3072 = 3072, OH_HUKS_RSA_KEY_SIZE_4096 = 4096, OH_HUKS_ECC_KEY_SIZE_224 = 224, OH_HUKS_ECC_KEY_SIZE_256 = 256,
OH_HUKS_ECC_KEY_SIZE_384 = 384, OH_HUKS_ECC_KEY_SIZE_521 = 521, OH_HUKS_AES_KEY_SIZE_128 = 128, OH_HUKS_AES_KEY_SIZE_192 = 192,
OH_HUKS_AES_KEY_SIZE_256 = 256, OH_HUKS_AES_KEY_SIZE_512 = 512, OH_HUKS_CURVE25519_KEY_SIZE_256 = 256, OH_HUKS_DH_KEY_SIZE_2048 = 2048,
OH_HUKS_DH_KEY_SIZE_3072 = 3072, OH_HUKS_DH_KEY_SIZE_4096 = 4096, OH_HUKS_SM2_KEY_SIZE_256 = 256, OH_HUKS_SM4_KEY_SIZE_128 = 128
} | Enumerates the key sizes. | -| [OH_Huks_KeyAlg](_huks_type_api.md#oh_huks_keyalg) {
OH_HUKS_ALG_RSA = 1, OH_HUKS_ALG_ECC = 2, OH_HUKS_ALG_DSA = 3, OH_HUKS_ALG_AES = 20,
OH_HUKS_ALG_HMAC = 50, OH_HUKS_ALG_HKDF = 51, OH_HUKS_ALG_PBKDF2 = 52, OH_HUKS_ALG_ECDH = 100,
OH_HUKS_ALG_X25519 = 101, OH_HUKS_ALG_ED25519 = 102, OH_HUKS_ALG_DH = 103, OH_HUKS_ALG_SM2 = 150,
OH_HUKS_ALG_SM3 = 151, OH_HUKS_ALG_SM4 = 152
} | Enumerates the key algorithms. | -| [OH_Huks_AlgSuite](_huks_type_api.md#oh_huks_algsuite) { OH_HUKS_UNWRAP_SUITE_X25519_AES_256_GCM_NOPADDING = 1, OH_HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING = 2 } | Enumerates the algorithm suites required for ciphertext imports. | -| [OH_Huks_KeyGenerateType](_huks_type_api.md#oh_huks_keygeneratetype) { OH_HUKS_KEY_GENERATE_TYPE_DEFAULT = 0, OH_HUKS_KEY_GENERATE_TYPE_DERIVE = 1, OH_HUKS_KEY_GENERATE_TYPE_AGREE = 2 } | Enumerates the key generation types. | -| [OH_Huks_KeyFlag](_huks_type_api.md#oh_huks_keyflag) { OH_HUKS_KEY_FLAG_IMPORT_KEY = 1, OH_HUKS_KEY_FLAG_GENERATE_KEY = 2, OH_HUKS_KEY_FLAG_AGREE_KEY = 3, OH_HUKS_KEY_FLAG_DERIVE_KEY = 4 } | Enumerates the key generation modes. | -| [OH_Huks_KeyStorageType](_huks_type_api.md#oh_huks_keystoragetype) { OH_HUKS_STORAGE_TEMP = 0, OH_HUKS_STORAGE_PERSISTENT = 1 } | Enumerates the key storage modes. | -| [OH_Huks_ImportKeyType](_huks_type_api.md#oh_huks_importkeytype) { OH_HUKS_KEY_TYPE_PUBLIC_KEY = 0, OH_HUKS_KEY_TYPE_PRIVATE_KEY = 1, OH_HUKS_KEY_TYPE_KEY_PAIR = 2 } | Enumerates the types of keys to import. By default, a public key is imported. This field is not required when a symmetric key is imported. | -| [OH_Huks_ErrCode](_huks_type_api.md#oh_huks_errcode) {
OH_HUKS_SUCCESS = 0, OH_HUKS_ERR_CODE_PERMISSION_FAIL = 201, OH_HUKS_ERR_CODE_ILLEGAL_ARGUMENT = 401, OH_HUKS_ERR_CODE_NOT_SUPPORTED_API = 801,
OH_HUKS_ERR_CODE_FEATURE_NOT_SUPPORTED = 12000001, OH_HUKS_ERR_CODE_MISSING_CRYPTO_ALG_ARGUMENT = 12000002, OH_HUKS_ERR_CODE_INVALID_CRYPTO_ALG_ARGUMENT = 12000003, OH_HUKS_ERR_CODE_FILE_OPERATION_FAIL = 12000004,
OH_HUKS_ERR_CODE_COMMUNICATION_FAIL = 12000005, OH_HUKS_ERR_CODE_CRYPTO_FAIL = 12000006, OH_HUKS_ERR_CODE_KEY_AUTH_PERMANENTLY_INVALIDATED = 12000007, OH_HUKS_ERR_CODE_KEY_AUTH_VERIFY_FAILED = 12000008,
OH_HUKS_ERR_CODE_KEY_AUTH_TIME_OUT = 12000009, OH_HUKS_ERR_CODE_SESSION_LIMIT = 12000010, OH_HUKS_ERR_CODE_ITEM_NOT_EXIST = 12000011, OH_HUKS_ERR_CODE_INTERNAL_ERROR = 12000012,
OH_HUKS_ERR_CODE_CREDENTIAL_NOT_EXIST = 12000013
} | Enumerates the error codes. | -| [OH_Huks_TagType](_huks_type_api.md#oh_huks_tagtype) {
OH_HUKS_TAG_TYPE_INVALID = 0 << 28, OH_HUKS_TAG_TYPE_INT = 1 << 28, OH_HUKS_TAG_TYPE_UINT = 2 << 28, OH_HUKS_TAG_TYPE_ULONG = 3 << 28,
OH_HUKS_TAG_TYPE_BOOL = 4 << 28, OH_HUKS_TAG_TYPE_BYTES = 5 << 28
} | Enumerates the tag types. | -| [OH_Huks_UserAuthType](_huks_type_api.md#oh_huks_userauthtype) { OH_HUKS_USER_AUTH_TYPE_FINGERPRINT = 1 << 0, OH_HUKS_USER_AUTH_TYPE_FACE = 1 << 1, OH_HUKS_USER_AUTH_TYPE_PIN = 1 << 2 } | Enumerates the user authentication types. | -| [OH_Huks_AuthAccessType](_huks_type_api.md#oh_huks_authaccesstype) { OH_HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD = 1 << 0, OH_HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL = 1 << 1 } | Enumerates the access control types. | -| [OH_Huks_ChallengeType](_huks_type_api.md#oh_huks_challengetype) { OH_HUKS_CHALLENGE_TYPE_NORMAL = 0, OH_HUKS_CHALLENGE_TYPE_CUSTOM = 1, OH_HUKS_CHALLENGE_TYPE_NONE = 2 } | Enumerates the types of the challenges generated when a key is used. | -| [OH_Huks_ChallengePosition](_huks_type_api.md#oh_huks_challengeposition) { OH_HUKS_CHALLENGE_POS_0 = 0, OH_HUKS_CHALLENGE_POS_1, OH_HUKS_CHALLENGE_POS_2, OH_HUKS_CHALLENGE_POS_3 } | Enumerates the positions of the 8-byte valid value in a custom challenge generated. | -| [OH_Huks_SecureSignType](_huks_type_api.md#oh_huks_securesigntype) { OH_HUKS_SECURE_SIGN_WITH_AUTHINFO = 1 } | Enumerates the signature types of the keys generated or imported. | -| [OH_Huks_Tag](_huks_type_api.md#oh_huks_tag) {
OH_HUKS_TAG_ALGORITHM = OH_HUKS_TAG_TYPE_UINT \| 1, OH_HUKS_TAG_PURPOSE = OH_HUKS_TAG_TYPE_UINT \| 2, OH_HUKS_TAG_KEY_SIZE = OH_HUKS_TAG_TYPE_UINT \| 3,
OH_HUKS_TAG_DIGEST = OH_HUKS_TAG_TYPE_UINT \| 4, OH_HUKS_TAG_PADDING = OH_HUKS_TAG_TYPE_UINT \| 5, OH_HUKS_TAG_BLOCK_MODE = OH_HUKS_TAG_TYPE_UINT \| 6, OH_HUKS_TAG_KEY_TYPE = OH_HUKS_TAG_TYPE_UINT \| 7,
OH_HUKS_TAG_ASSOCIATED_DATA = OH_HUKS_TAG_TYPE_BYTES \| 8, OH_HUKS_TAG_NONCE = OH_HUKS_TAG_TYPE_BYTES \| 9, OH_HUKS_TAG_IV = OH_HUKS_TAG_TYPE_BYTES \| 10, OH_HUKS_TAG_INFO = OH_HUKS_TAG_TYPE_BYTES \| 11,
OH_HUKS_TAG_SALT = OH_HUKS_TAG_TYPE_BYTES \| 12, OH_HUKS_TAG_ITERATION = OH_HUKS_TAG_TYPE_UINT \| 14, OH_HUKS_TAG_KEY_GENERATE_TYPE = OH_HUKS_TAG_TYPE_UINT \| 15,
OH_HUKS_TAG_AGREE_ALG = OH_HUKS_TAG_TYPE_UINT \| 19,
OH_HUKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS = OH_HUKS_TAG_TYPE_BOOL \| 20, OH_HUKS_TAG_AGREE_PRIVATE_KEY_ALIAS = OH_HUKS_TAG_TYPE_BYTES \| 21, OH_HUKS_TAG_AGREE_PUBLIC_KEY = OH_HUKS_TAG_TYPE_BYTES \| 22, OH_HUKS_TAG_KEY_ALIAS = OH_HUKS_TAG_TYPE_BYTES \| 23,
OH_HUKS_TAG_DERIVE_KEY_SIZE = OH_HUKS_TAG_TYPE_UINT \| 24, OH_HUKS_TAG_IMPORT_KEY_TYPE = OH_HUKS_TAG_TYPE_UINT \| 25, OH_HUKS_TAG_UNWRAP_ALGORITHM_SUITE = OH_HUKS_TAG_TYPE_UINT \| 26, OH_HUKS_TAG_ALL_USERS = OH_HUKS_TAG_TYPE_BOOL \| 301,
OH_HUKS_TAG_USER_ID = OH_HUKS_TAG_TYPE_UINT \| 302, OH_HUKS_TAG_NO_AUTH_REQUIRED = OH_HUKS_TAG_TYPE_BOOL \| 303, OH_HUKS_TAG_USER_AUTH_TYPE = OH_HUKS_TAG_TYPE_UINT \| 304, OH_HUKS_TAG_AUTH_TIMEOUT = OH_HUKS_TAG_TYPE_UINT \| 305,
OH_HUKS_TAG_AUTH_TOKEN = OH_HUKS_TAG_TYPE_BYTES \| 306, OH_HUKS_TAG_KEY_AUTH_ACCESS_TYPE = OH_HUKS_TAG_TYPE_UINT \| 307, OH_HUKS_TAG_KEY_SECURE_SIGN_TYPE = OH_HUKS_TAG_TYPE_UINT \| 308, OH_HUKS_TAG_CHALLENGE_TYPE = OH_HUKS_TAG_TYPE_UINT \| 309,
OH_HUKS_TAG_CHALLENGE_POS = OH_HUKS_TAG_TYPE_UINT \| 310, OH_HUKS_TAG_ATTESTATION_CHALLENGE = OH_HUKS_TAG_TYPE_BYTES \| 501, OH_HUKS_TAG_ATTESTATION_APPLICATION_ID = OH_HUKS_TAG_TYPE_BYTES \| 502,
OH_HUKS_TAG_ATTESTATION_ID_ALIAS = OH_HUKS_TAG_TYPE_BYTES \| 511,
OH_HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO = OH_HUKS_TAG_TYPE_BYTES \| 514, OH_HUKS_TAG_ATTESTATION_ID_VERSION_INFO = OH_HUKS_TAG_TYPE_BYTES \| 515,
OH_HUKS_TAG_IS_KEY_ALIAS = OH_HUKS_TAG_TYPE_BOOL \| 1001, OH_HUKS_TAG_KEY_STORAGE_FLAG = OH_HUKS_TAG_TYPE_UINT \| 1002, OH_HUKS_TAG_IS_ALLOWED_WRAP = OH_HUKS_TAG_TYPE_BOOL \| 1003, OH_HUKS_TAG_KEY_WRAP_TYPE = OH_HUKS_TAG_TYPE_UINT \| 1004,
OH_HUKS_TAG_KEY_AUTH_ID = OH_HUKS_TAG_TYPE_BYTES \| 1005, OH_HUKS_TAG_KEY_ROLE = OH_HUKS_TAG_TYPE_UINT \| 1006, OH_HUKS_TAG_KEY_FLAG = OH_HUKS_TAG_TYPE_UINT \| 1007, OH_HUKS_TAG_IS_ASYNCHRONIZED = OH_HUKS_TAG_TYPE_UINT \| 1008,
OH_HUKS_TAG_KEY_DOMAIN = OH_HUKS_TAG_TYPE_UINT \| 1011, OH_HUKS_TAG_SYMMETRIC_KEY_DATA = OH_HUKS_TAG_TYPE_BYTES \| 20001,
OH_HUKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATA = OH_HUKS_TAG_TYPE_BYTES \| 20002, OH_HUKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATA = OH_HUKS_TAG_TYPE_BYTES \| 20003
} | Enumerates the tag values used in parameter sets. | +| [OH_Huks_KeyPurpose](_huks_type_api.md#oh_huks_keypurpose) {
OH_HUKS_KEY_PURPOSE_ENCRYPT = 1,
OH_HUKS_KEY_PURPOSE_DECRYPT = 2,
OH_HUKS_KEY_PURPOSE_SIGN = 4,
OH_HUKS_KEY_PURPOSE_VERIFY = 8,
OH_HUKS_KEY_PURPOSE_DERIVE = 16,
OH_HUKS_KEY_PURPOSE_WRAP = 32,
OH_HUKS_KEY_PURPOSE_UNWRAP = 64,
OH_HUKS_KEY_PURPOSE_MAC = 128,
OH_HUKS_KEY_PURPOSE_AGREE = 256
} | Enumerates the key purposes. | +| [OH_Huks_KeyDigest](_huks_type_api.md#oh_huks_keydigest) {
OH_HUKS_DIGEST_NONE = 0,
OH_HUKS_DIGEST_MD5 = 1,
OH_HUKS_DIGEST_SM3 = 2,
OH_HUKS_DIGEST_SHA1 = 10,
OH_HUKS_DIGEST_SHA224 = 11,
OH_HUKS_DIGEST_SHA256 = 12,
OH_HUKS_DIGEST_SHA384 = 13,
OH_HUKS_DIGEST_SHA512 = 14
} | Enumerates the digest algorithms. | +| [OH_Huks_KeyPadding](_huks_type_api.md#oh_huks_keypadding) {
OH_HUKS_PADDING_NONE = 0,
OH_HUKS_PADDING_OAEP = 1,
OH_HUKS_PADDING_PSS = 2,
OH_HUKS_PADDING_PKCS1_V1_5 = 3,
OH_HUKS_PADDING_PKCS5 = 4,
OH_HUKS_PADDING_PKCS7 = 5
} | Enumerates the padding algorithms. | +| [OH_Huks_CipherMode](_huks_type_api.md#oh_huks_ciphermode) {
OH_HUKS_MODE_ECB = 1,
OH_HUKS_MODE_CBC = 2,
OH_HUKS_MODE_CTR = 3,
OH_HUKS_MODE_OFB = 4,
OH_HUKS_MODE_CCM = 31,
OH_HUKS_MODE_GCM = 32
} | Enumerates the cipher modes. | +| [OH_Huks_KeySize](_huks_type_api.md#oh_huks_keysize) {
OH_HUKS_RSA_KEY_SIZE_512 = 512,
OH_HUKS_RSA_KEY_SIZE_768 = 768,
OH_HUKS_RSA_KEY_SIZE_1024 = 1024,
OH_HUKS_RSA_KEY_SIZE_2048 = 2048,
OH_HUKS_RSA_KEY_SIZE_3072 = 3072,
OH_HUKS_RSA_KEY_SIZE_4096 = 4096,
OH_HUKS_ECC_KEY_SIZE_224 = 224,
OH_HUKS_ECC_KEY_SIZE_256 = 256,
OH_HUKS_ECC_KEY_SIZE_384 = 384,
OH_HUKS_ECC_KEY_SIZE_521 = 521,
OH_HUKS_AES_KEY_SIZE_128 = 128,
OH_HUKS_AES_KEY_SIZE_192 = 192,
OH_HUKS_AES_KEY_SIZE_256 = 256,
OH_HUKS_AES_KEY_SIZE_512 = 512,
OH_HUKS_CURVE25519_KEY_SIZE_256 = 256,
OH_HUKS_DH_KEY_SIZE_2048 = 2048,
OH_HUKS_DH_KEY_SIZE_3072 = 3072,
OH_HUKS_DH_KEY_SIZE_4096 = 4096,
OH_HUKS_SM2_KEY_SIZE_256 = 256,
OH_HUKS_SM4_KEY_SIZE_128 = 128
} | Enumerates key sizes of different algorithms. | +| [OH_Huks_KeyAlg](_huks_type_api.md#oh_huks_keyalg) {
OH_HUKS_ALG_RSA = 1,
OH_HUKS_ALG_ECC = 2,
OH_HUKS_ALG_DSA = 3,
OH_HUKS_ALG_AES = 20,
OH_HUKS_ALG_HMAC = 50,
OH_HUKS_ALG_HKDF = 51,
OH_HUKS_ALG_PBKDF2 = 52,
OH_HUKS_ALG_ECDH = 100,
OH_HUKS_ALG_X25519 = 101,
OH_HUKS_ALG_ED25519 = 102,
OH_HUKS_ALG_DH = 103,
OH_HUKS_ALG_SM2 = 150,
OH_HUKS_ALG_SM3 = 151,
OH_HUKS_ALG_SM4 = 152
} | Enumerates the algorithms for keys. | +| [OH_Huks_AlgSuite](_huks_type_api.md#oh_huks_algsuite) {
OH_HUKS_UNWRAP_SUITE_X25519_AES_256_GCM_NOPADDING = 1,
OH_HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING = 2
} | Enumerates the algorithm suites for the import of a wrapped key. | +| [OH_Huks_KeyGenerateType](_huks_type_api.md#oh_huks_keygeneratetype) {
OH_HUKS_KEY_GENERATE_TYPE_DEFAULT = 0,
OH_HUKS_KEY_GENERATE_TYPE_DERIVE = 1,
OH_HUKS_KEY_GENERATE_TYPE_AGREE = 2
} | Enumerates the types of the key generated. | +| [OH_Huks_KeyFlag](_huks_type_api.md#oh_huks_keyflag) {
OH_HUKS_KEY_FLAG_IMPORT_KEY = 1,
OH_HUKS_KEY_FLAG_GENERATE_KEY = 2,
OH_HUKS_KEY_FLAG_AGREE_KEY = 3,
OH_HUKS_KEY_FLAG_DERIVE_KEY = 4
} | Enumerates the key generation types. | +| [OH_Huks_KeyStorageType](_huks_type_api.md#oh_huks_keystoragetype) {
OH_HUKS_STORAGE_TEMP = 0,
OH_HUKS_STORAGE_PERSISTENT = 1,
OH_HUKS_STORAGE_ONLY_USED_IN_HUKS = 2,
OH_HUKS_STORAGE_KEY_EXPORT_ALLOWED = 3
} | Enumerates the key storage types. | +| [OH_Huks_ImportKeyType](_huks_type_api.md#oh_huks_importkeytype) {
OH_HUKS_KEY_TYPE_PUBLIC_KEY = 0,
OH_HUKS_KEY_TYPE_PRIVATE_KEY = 1,
OH_HUKS_KEY_TYPE_KEY_PAIR = 2
}| Enumerates the types of the key to import. By default, a public key is imported. This field is not required when a symmetric key is imported. | +| [OH_Huks_RsaPssSaltLenType](_huks_type_api.md#oh_huks_rsapsssaltlentype) {
OH_HUKS_RSA_PSS_SALT_LEN_DIGEST = 0, OH_HUKS_RSA_PSS_SALT_LEN_MAX = 1
} | Enumerates the salt length types when the PSS padding mode is used in RSA signing or signature verification.| +| [OH_Huks_ErrCode](_huks_type_api.md#oh_huks_errcode) {
OH_HUKS_SUCCESS = 0,
OH_HUKS_ERR_CODE_PERMISSION_FAIL = 201,
OH_HUKS_ERR_CODE_ILLEGAL_ARGUMENT = 401,
OH_HUKS_ERR_CODE_NOT_SUPPORTED_API = 801,
OH_HUKS_ERR_CODE_FEATURE_NOT_SUPPORTED = 12000001,
OH_HUKS_ERR_CODE_MISSING_CRYPTO_ALG_ARGUMENT = 12000002,
OH_HUKS_ERR_CODE_INVALID_CRYPTO_ALG_ARGUMENT = 12000003,
OH_HUKS_ERR_CODE_FILE_OPERATION_FAIL = 12000004,
OH_HUKS_ERR_CODE_COMMUNICATION_FAIL = 12000005,
OH_HUKS_ERR_CODE_CRYPTO_FAIL = 12000006,
OH_HUKS_ERR_CODE_KEY_AUTH_PERMANENTLY_INVALIDATED = 12000007,
OH_HUKS_ERR_CODE_KEY_AUTH_VERIFY_FAILED = 12000008,
OH_HUKS_ERR_CODE_KEY_AUTH_TIME_OUT = 12000009,
OH_HUKS_ERR_CODE_SESSION_LIMIT = 12000010,
OH_HUKS_ERR_CODE_ITEM_NOT_EXIST = 12000011,
OH_HUKS_ERR_CODE_INTERNAL_ERROR = 12000012,
OH_HUKS_ERR_CODE_CREDENTIAL_NOT_EXIST = 12000013
} | Enumerates the error codes. | +| [OH_Huks_TagType](_huks_type_api.md#oh_huks_tagtype) {
OH_HUKS_TAG_TYPE_INVALID = 0 << 28,
OH_HUKS_TAG_TYPE_INT = 1 << 28,
OH_HUKS_TAG_TYPE_UINT = 2 << 28,
OH_HUKS_TAG_TYPE_ULONG = 3 << 28,
OH_HUKS_TAG_TYPE_BOOL = 4 << 28,
OH_HUKS_TAG_TYPE_BYTES = 5 << 28
} | Enumerates the mask values of the parameter type in the parameter set. | +| [OH_Huks_UserAuthType](_huks_type_api.md#oh_huks_userauthtype) {
OH_HUKS_USER_AUTH_TYPE_FINGERPRINT = 1 << 0,
OH_HUKS_USER_AUTH_TYPE_FACE = 1 << 1,
OH_HUKS_USER_AUTH_TYPE_PIN = 1 << 2
} | Enumerates the user authentication types in key access control. | +| [OH_Huks_AuthAccessType](_huks_type_api.md#oh_huks_authaccesstype) {
OH_HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD = 1 << 0,
OH_HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL = 1 << 1
} | Enumerates the rules for invalidating a key. | +| [OH_Huks_ChallengeType](_huks_type_api.md#oh_huks_challengetype) {
OH_HUKS_CHALLENGE_TYPE_NORMAL = 0,
OH_HUKS_CHALLENGE_TYPE_CUSTOM = 1,
OH_HUKS_CHALLENGE_TYPE_NONE = 2
} | Enumerates the types of the challenge generated when a key is used. | +| [OH_Huks_ChallengePosition](_huks_type_api.md#oh_huks_challengeposition) {
OH_HUKS_CHALLENGE_POS_0 = 0,
OH_HUKS_CHALLENGE_POS_1,
OH_HUKS_CHALLENGE_POS_2,
OH_HUKS_CHALLENGE_POS_3
} | Enumerates the positions of the 8-byte valid value in a custom challenge generated. | +| [OH_Huks_SecureSignType](_huks_type_api.md#oh_huks_securesigntype) { OH_HUKS_SECURE_SIGN_WITH_AUTHINFO = 1 } | Enumerates the signature types of the key generated or imported. | +| [OH_Huks_Tag](_huks_type_api.md#oh_huks_tag) {
OH_HUKS_TAG_ALGORITHM = OH_HUKS_TAG_TYPE_UINT \| 1, OH_HUKS_TAG_PURPOSE = OH_HUKS_TAG_TYPE_UINT \| 2, OH_HUKS_TAG_KEY_SIZE = OH_HUKS_TAG_TYPE_UINT \| 3,
OH_HUKS_TAG_DIGEST = OH_HUKS_TAG_TYPE_UINT \| 4, OH_HUKS_TAG_PADDING = OH_HUKS_TAG_TYPE_UINT \| 5, OH_HUKS_TAG_BLOCK_MODE = OH_HUKS_TAG_TYPE_UINT \| 6, OH_HUKS_TAG_KEY_TYPE = OH_HUKS_TAG_TYPE_UINT \| 7,
OH_HUKS_TAG_ASSOCIATED_DATA = OH_HUKS_TAG_TYPE_BYTES \| 8, OH_HUKS_TAG_NONCE = OH_HUKS_TAG_TYPE_BYTES \| 9, OH_HUKS_TAG_IV = OH_HUKS_TAG_TYPE_BYTES \| 10, OH_HUKS_TAG_INFO = OH_HUKS_TAG_TYPE_BYTES \| 11,
OH_HUKS_TAG_SALT = OH_HUKS_TAG_TYPE_BYTES \| 12, OH_HUKS_TAG_ITERATION = OH_HUKS_TAG_TYPE_UINT \| 14, OH_HUKS_TAG_KEY_GENERATE_TYPE = OH_HUKS_TAG_TYPE_UINT \| 15, OH_HUKS_TAG_AGREE_ALG = OH_HUKS_TAG_TYPE_UINT \| 19,
OH_HUKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS = OH_HUKS_TAG_TYPE_BOOL \| 20, OH_HUKS_TAG_AGREE_PRIVATE_KEY_ALIAS = OH_HUKS_TAG_TYPE_BYTES \| 21, OH_HUKS_TAG_AGREE_PUBLIC_KEY = OH_HUKS_TAG_TYPE_BYTES \| 22, OH_HUKS_TAG_KEY_ALIAS = OH_HUKS_TAG_TYPE_BYTES \| 23,
OH_HUKS_TAG_DERIVE_KEY_SIZE = OH_HUKS_TAG_TYPE_UINT \| 24, OH_HUKS_TAG_IMPORT_KEY_TYPE = OH_HUKS_TAG_TYPE_UINT \| 25, OH_HUKS_TAG_UNWRAP_ALGORITHM_SUITE = OH_HUKS_TAG_TYPE_UINT \| 26,
OH_HUKS_TAG_DERIVED_AGREED_KEY_STORAGE_FLAG = OH_HUKS_TAG_TYPE_UINT \| 29,
OH_HUKS_TAG_RSA_PSS_SALT_LEN_TYPE = OH_HUKS_TAG_TYPE_UINT \| 30, OH_HUKS_TAG_ALL_USERS = OH_HUKS_TAG_TYPE_BOOL \| 301,
OH_HUKS_TAG_USER_ID = OH_HUKS_TAG_TYPE_UINT \| 302, OH_HUKS_TAG_NO_AUTH_REQUIRED = OH_HUKS_TAG_TYPE_BOOL \| 303, OH_HUKS_TAG_USER_AUTH_TYPE = OH_HUKS_TAG_TYPE_UINT \| 304, OH_HUKS_TAG_AUTH_TIMEOUT = OH_HUKS_TAG_TYPE_UINT \| 305,
OH_HUKS_TAG_AUTH_TOKEN = OH_HUKS_TAG_TYPE_BYTES \| 306, OH_HUKS_TAG_KEY_AUTH_ACCESS_TYPE = OH_HUKS_TAG_TYPE_UINT \| 307, OH_HUKS_TAG_KEY_SECURE_SIGN_TYPE = OH_HUKS_TAG_TYPE_UINT \| 308, OH_HUKS_TAG_CHALLENGE_TYPE = OH_HUKS_TAG_TYPE_UINT \| 309,
OH_HUKS_TAG_CHALLENGE_POS = OH_HUKS_TAG_TYPE_UINT \| 310, OH_HUKS_TAG_KEY_AUTH_PURPOSE = OH_HUKS_TAG_TYPE_UINT \| 311, OH_HUKS_TAG_ATTESTATION_CHALLENGE = OH_HUKS_TAG_TYPE_BYTES \| 501, OH_HUKS_TAG_ATTESTATION_APPLICATION_ID = OH_HUKS_TAG_TYPE_BYTES \| 502, OH_HUKS_TAG_ATTESTATION_ID_ALIAS = OH_HUKS_TAG_TYPE_BYTES \| 511,
OH_HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO = OH_HUKS_TAG_TYPE_BYTES \| 514, OH_HUKS_TAG_ATTESTATION_ID_VERSION_INFO = OH_HUKS_TAG_TYPE_BYTES \| 515,
OH_HUKS_TAG_IS_KEY_ALIAS = OH_HUKS_TAG_TYPE_BOOL \| 1001, OH_HUKS_TAG_KEY_STORAGE_FLAG = OH_HUKS_TAG_TYPE_UINT \| 1002, OH_HUKS_TAG_IS_ALLOWED_WRAP = OH_HUKS_TAG_TYPE_BOOL \| 1003, OH_HUKS_TAG_KEY_WRAP_TYPE = OH_HUKS_TAG_TYPE_UINT \| 1004,
OH_HUKS_TAG_KEY_AUTH_ID = OH_HUKS_TAG_TYPE_BYTES \| 1005, OH_HUKS_TAG_KEY_ROLE = OH_HUKS_TAG_TYPE_UINT \| 1006, OH_HUKS_TAG_KEY_FLAG = OH_HUKS_TAG_TYPE_UINT \| 1007, OH_HUKS_TAG_IS_ASYNCHRONIZED = OH_HUKS_TAG_TYPE_UINT \| 1008,
OH_HUKS_TAG_KEY_DOMAIN = OH_HUKS_TAG_TYPE_UINT \| 1011, OH_HUKS_TAG_SYMMETRIC_KEY_DATA = OH_HUKS_TAG_TYPE_BYTES \| 20001,
OH_HUKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATA = OH_HUKS_TAG_TYPE_BYTES \| 20002, OH_HUKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATA = OH_HUKS_TAG_TYPE_BYTES \| 20003
} | Enumerates the tag values used in the parameter set. | diff --git a/en/application-dev/reference/native-apis/rawfile.md b/en/application-dev/reference/native-apis/rawfile.md index 7314b4b36ea9eac50bf23972ef35833f5a828537..d77f9e4fb1c94336eed7aee74e8d21f7ee5c62f1 100644 --- a/en/application-dev/reference/native-apis/rawfile.md +++ b/en/application-dev/reference/native-apis/rawfile.md @@ -1,13 +1,11 @@ # Rawfile -## Overview +Provides APIs for operating the **rawfile** directory and its files, including traversing the **rawfile** directory and opening, searching for, reading, and closing a file in it. -Provides the function of operating rawfile directories and rawfiles. +**Since** -These functions include traversing, opening, searching, reading, and closing rawfiles. -**Since:** 8 @@ -16,399 +14,506 @@ These functions include traversing, opening, searching, reading, and closing raw ### Files -| Name | Description | -| -------- | -------- | -| [raw_dir.h](raw__dir_8h.md) | Provides functions for operating rawfile directories.
File to Include: | -| [raw_file.h](raw__file_8h.md) | Provides functions for operating rawfiles.
File to Include: | -| [raw_file_manager.h](raw__file__manager_8h.md) | Provides functions for managing rawfile resources.
File to Include: | +| Name | Description | +| ---------------------------------------- | ------------------ | +| [raw_dir.h](raw__dir_8h.md) | Provides functions related to the **rawfile** directory.
File to include: \ | +| [raw_file.h](raw__file_8h.md) | Provides functions related to the files in the **rawfile** directory.
File to include: \ | +| [raw_file_manager.h](raw__file__manager_8h.md) | Provides file management functions for the **rawfile** directory.
File to import: \| ### Structs -| Name | Description | -| -------- | -------- | -| [RawFileDescriptor](_raw_file_descriptor.md) | Provides rawfile descriptor information. | +| Name | Description | +| ---------------------------------------- | ----------------- | +| [RawFileDescriptor](_raw_file_descriptor.md) | Defines the file descriptor (FD) information of a file in the **rawfile** directory. | ### Types -| Name | Description | -| -------- | -------- | -| [RawDir](#rawdir) | Provides the function of accessing rawfile directories. | -| [RawFile](#rawfile) | Provides the function of accessing rawfiles. | -| [NativeResourceManager](#nativeresourcemanager) | Implements the resource manager. | +| Name | Description | +| ---------------------------------------- | ------------------- | +| [RawDir](#rawdir) | Provides access to the **rawfile** directory. | +| [RawFile](#rawfile) | Provides access to the files in **rawfile**. | +| [NativeResourceManager](#nativeresourcemanager) | Represents the resource manager.| ### Functions -| Name | Description | -| -------- | -------- | -| [OH_ResourceManager_GetRawFileName](#oh_resourcemanager_getrawfilename) ([RawDir](#rawdir) \*rawDir, int index) | Obtains the rawfile name via an index. | -| [OH_ResourceManager_GetRawFileCount](#oh_resourcemanager_getrawfilecount) ([RawDir](#rawdir) \*rawDir) |Obtains the number of rawfiles in [RawDir](#rawdir). | -| [OH_ResourceManager_CloseRawDir](#oh_resourcemanager_closerawdir) ([RawDir](#rawdir) \*rawDir) | Closes an opened [RawDir](#rawdir) and releases all associated resources. | -| [OH_ResourceManager_ReadRawFile](#oh_resourcemanager_readrawfile) (const [RawFile](#rawfile) \*rawFile, void \*buf, size_t length) |Reads a rawfile. | -| [OH_ResourceManager_SeekRawFile](#oh_resourcemanager_seekrawfile) (const [RawFile](#rawfile) \*rawFile, long offset, int whence) |Seeks for the data read/write position in the rawfile based on the specified offset. | -| [OH_ResourceManager_GetRawFileSize](#oh_resourcemanager_getrawfilesize) ([RawFile](#rawfile) \*rawFile) | Obtains the length of a rawfile in int32_t. | -| [OH_ResourceManager_CloseRawFile](#oh_resourcemanager_closerawfile) ([RawFile](#rawfile) \*rawFile) | Closes an opened [RawFile](#rawfile) and releases all associated resources. | -| [OH_ResourceManager_GetRawFileOffset](#oh_resourcemanager_getrawfileoffset) (const [RawFile](#rawfile) \*rawFile) | Obtains the current offset of the rawfile in int32_t. | -| [OH_ResourceManager_GetRawFileDescriptor](#oh_resourcemanager_getrawfiledescriptor) (const [RawFile](#rawfile) \*rawFile, [RawFileDescriptor](_raw_file_descriptor.md) &descriptor) | Opens a rawfile descriptor. | -| [OH_ResourceManager_ReleaseRawFileDescriptor](#oh_resourcemanager_releaserawfiledescriptor) (const [RawFileDescriptor](_raw_file_descriptor.md) &descriptor) | Closes a rawfile descriptor. | -| [OH_ResourceManager_InitNativeResourceManager](#oh_resourcemanager_initnativeresourcemanager) (napi_env env, napi_value jsResMgr) | Obtains the native resource manager based on JavaScipt resource manager. | -| [OH_ResourceManager_ReleaseNativeResourceManager](#oh_resourcemanager_releasenativeresourcemanager) ([NativeResourceManager](#nativeresourcemanager) \*resMgr) | Releases a native resource manager. | -| [OH_ResourceManager_OpenRawDir](#oh_resourcemanager_openrawdir) (const [NativeResourceManager](#nativeresourcemanager) \*mgr, const char \*dirName) | Opens a rawfile directory. | -| [OH_ResourceManager_OpenRawFile](#oh_resourcemanager_openrawfile) (const [NativeResourceManager](#nativeresourcemanager) \*mgr, const char \*fileName) | Opens a rawfile. | +| Name | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| [OH_ResourceManager_GetRawFileName](#oh_resourcemanager_getrawfilename) ([RawDir](#rawdir) \*rawDir, int index) | Obtains the name of a file in **rawfile** based on the index. | +| [OH_ResourceManager_GetRawFileCount](#oh_resourcemanager_getrawfilecount) ([RawDir](#rawdir) \*rawDir) | Obtains the number of files in a [RawDir](#rawdir). | +| [OH_ResourceManager_CloseRawDir](#oh_resourcemanager_closerawdir) ([RawDir](#rawdir) \*rawDir) | Closes a [RawDir](#rawdir) and releases all associated resources. | +| [OH_ResourceManager_ReadRawFile](#oh_resourcemanager_readrawfile) (const [RawFile](#rawfile) \*rawFile, void \*buf, size_t length) | Reads data from a file in **rawfile**. | +| [OH_ResourceManager_SeekRawFile](#oh_resourcemanager_seekrawfile) (const [RawFile](#rawfile) \*rawFile, long offset, int whence) | Seeks for the data read/write position in a file in **rawfile** based on the specified offset. | +| [OH_ResourceManager_GetRawFileSize](#oh_resourcemanager_getrawfilesize) ([RawFile](#rawfile) \*rawFile) | Obtains the size of a file in **rawfile**. | +| [OH_ResourceManager_CloseRawFile](#oh_resourcemanager_closerawfile) ([RawFile](#rawfile) \*rawFile) | Closes a [RawFile](#rawfile) and releases all associated resources. | +| [OH_ResourceManager_GetRawFileOffset](#oh_resourcemanager_getrawfileoffset) (const [RawFile](#rawfile) \*rawFile) | Obtains the current offset of a file in **rawfile**. | +| [OH_ResourceManager_GetRawFileDescriptor](#oh_resourcemanager_getrawfiledescriptor) (const [RawFile](#rawfile) \*rawFile, [RawFileDescriptor](_raw_file_descriptor.md) &descriptor) | Opens a file in **rawfile** based on the offset and file length and obtains the FD. | +| [OH_ResourceManager_ReleaseRawFileDescriptor](#oh_resourcemanager_releaserawfiledescriptor) (const [RawFileDescriptor](_raw_file_descriptor.md) &descriptor) | Releases an FD. | +| [OH_ResourceManager_InitNativeResourceManager](#oh_resourcemanager_initnativeresourcemanager) (napi_env env, napi_value jsResMgr) | Initializes a Native resource manager using the JavaScript resource manager. You can use the Native resource manager obtained to implement operations related to **rawfile**. | +| [OH_ResourceManager_ReleaseNativeResourceManager](#oh_resourcemanager_releasenativeresourcemanager) ([NativeResourceManager](#nativeresourcemanager) \*resMgr) | Releases a Native resource manager instance. | +| [OH_ResourceManager_OpenRawDir](#oh_resourcemanager_openrawdir) (const [NativeResourceManager](#nativeresourcemanager) \*mgr, const char \*dirName) | Opens a directory in the **rawfile** directory. | +| [OH_ResourceManager_OpenRawFile](#oh_resourcemanager_openrawfile) (const [NativeResourceManager](#nativeresourcemanager) \*mgr, const char \*fileName) | Opens a file in the **rawfile** directory. | -## Type Description +## Description -### NativeResourceManager +### Type Description + + +#### NativeResourceManager + - ``` -typedef struct NativeResourceManagerNativeResourceManager +typedef struct NativeResourceManager NativeResourceManager ``` -**Description**
-Implements the resource manager. -This class encapsulates the native implementation of the JavaScript resource manager. You can obtain the pointer to **ResourceManager** by calling [OH_ResourceManager_InitNativeResourceManager](#oh_resourcemanager_initnativeresourcemanager). +**Description** + +Represents the resource manager. + +This class encapsulates the native implementation of the JavaScript resource manager. The **ResourceManager** pointer can be obtained by using [OH_ResourceManager_InitNativeResourceManager](#oh_resourcemanager_initnativeresourcemanager). + +**Since** + +8 + +#### RawDir -### RawDir - ``` -typedef struct RawDirRawDir +typedef struct RawDir RawDir ``` -**Description**
-Provides the function of accessing rawfile directories. + +**Description** + +Provides access to the **rawfile** directory. + +**Since** + +8 -### RawFile +#### RawFile + - ``` -typedef struct RawFileRawFile +typedef struct RawFile RawFile ``` -**Description**
-Provides the function of accessing rawfiles. +**Description** + +Provides access to the files in **rawfile**. + +**Since** + +8 + + +### Function Description -## Function Description +#### OH_ResourceManager_CloseRawDir() -### OH_ResourceManager_CloseRawDir() - ``` void OH_ResourceManager_CloseRawDir (RawDir * rawDir) ``` -**Description**
-Closes an opened [RawDir](#rawdir) and releases all associated resources. - **Parameters** +**Description** -| Name | Description | -| -------- | -------- | -| rawDir | Indicates the pointer to [RawDir](#rawdir). | +Closes a [RawDir](#rawdir) opened and releases all associated resources. - **See** +**Parameters** + +| Name | Description | +| ------ | ------------------------- | +| rawDir | Pointer to the [RawDir](#rawdir) to close.| + +**See** [OH_ResourceManager_OpenRawDir](#oh_resourcemanager_openrawdir) +**Since** + +8 + + +#### OH_ResourceManager_CloseRawFile() -### OH_ResourceManager_CloseRawFile() - ``` void OH_ResourceManager_CloseRawFile (RawFile * rawFile) ``` -**Description**
-Closes an opened [RawFile](#rawfile) and releases all associated resources. - **Parameters** +**Description** -| Name | Description | -| -------- | -------- | -| rawFile | Indicates the pointer to [RawFile](#rawfile). | +Closes a [RawFile](#rawfile) and releases all associated resources. - **See** +**Parameters** + +| Name | Description | +| ------- | --------------------------- | +| rawFile | Pointer to the [RawFile](#rawfile) to close.| + +**See** [OH_ResourceManager_OpenRawFile](#oh_resourcemanager_openrawfile) +**Since** + +8 + + +#### OH_ResourceManager_GetRawFileCount() -### OH_ResourceManager_GetRawFileCount() - ``` int OH_ResourceManager_GetRawFileCount (RawDir * rawDir) ``` -**Description**
-Obtains the number of rawfiles in [RawDir](#rawdir). + +**Description** + +Obtains the number of files in a [RawDir](#rawdir). You can use this function to obtain available indexes in [OH_ResourceManager_GetRawFileName](#oh_resourcemanager_getrawfilename). - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| rawDir | Indicates the pointer to [RawDir](#rawdir). | +| Name | Description | +| ------ | ------------------------- | +| rawDir | Pointer to the target [RawDir](#rawdir).| - **See** +**See** [OH_ResourceManager_GetRawFileName](#oh_resourcemanager_getrawfilename) +**Since** + +8 + + +#### OH_ResourceManager_GetRawFileDescriptor() -### OH_ResourceManager_GetRawFileDescriptor() - ``` bool OH_ResourceManager_GetRawFileDescriptor (const RawFile * rawFile, RawFileDescriptor & descriptor ) ``` -**Description**
-Opens a rawfile descriptor. -After the descriptor is opened, you can use it to read the rawfile based on the offset (in int32_t) and file length. +**Description** + +Opens a file in the **rawfile** directory based on the offset and file length and obtains the FD. - **Parameters** +The FD obtained can be used to read the file. -| Name | Description | -| -------- | -------- | -| rawFile | Indicates the pointer to [RawFile](#rawfile). | -| descriptor | Indicates the rawfile descriptor, and the start position and length of the rawfile file in the HAP package. | +**Parameters** + +| Name | Description | +| ---------- | ---------------------------------------------------- | +| rawFile | Pointer to the [RawFile](#rawfile). | +| descriptor | File descriptor of the file, start position of the file in the hAP, and length of the file.| **Returns** -Returns **true** if the rawfile descriptor is opened successfully; returns **false** if the rawfile cannot be accessed. +Returns true if the file is opened; returns false if the access to the file is rejected. + +**Since** + +8 -### OH_ResourceManager_GetRawFileName() +#### OH_ResourceManager_GetRawFileName() + - ``` const char* OH_ResourceManager_GetRawFileName (RawDir * rawDir, int index ) ``` -**Description**
-Obtains the rawfile name via an index. -You can use this function to traverse a rawfile directory. +**Description** + +Obtains the name of a file in **rawfile** based on the index. + +You can use this function to traverse the **rawfile** directory. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| rawDir | Indicates the pointer to [RawDir](#rawdir). | -| index | Indicates the index of the file in [RawDir](#rawdir). | +| Name | Description | +| ------ | ----------------------------- | +| rawDir | Pointer to the [RawDir](#rawdir). | +| index | Index of the file in the [RawDir](#rawdir).| **Returns** -Returns the rawfile name via an index. The return value can be used as the input parameter of [OH_ResourceManager_OpenRawFile](#oh_resourcemanager_openrawfile). If no rawfile is found after all rawfiles are traversed, **NULL** will be returned. +Returns the file name obtained if the file exists in the directory; returns **null** otherwise. The file name returned can be used as the input parameter of [OH_ResourceManager_OpenRawFile](#oh_resourcemanager_openrawfile). - **See** +**See** [OH_ResourceManager_OpenRawFile](#oh_resourcemanager_openrawfile) +**Since** + +8 + + +#### OH_ResourceManager_GetRawFileOffset() -### OH_ResourceManager_GetRawFileOffset() - ``` long OH_ResourceManager_GetRawFileOffset (const RawFile * rawFile) ``` -**Description**
-Obtains the current offset of the rawfile in int32_t. - **Parameters** +**Description** + +Obtains the current offset of a file in **rawfile**. + +The offset indicates the position of the file in the HAP. -| Name | Description | -| -------- | -------- | -| rawFile | Indicates the pointer to [RawFile](#rawfile). | +**Parameters** + +| Name | Description | +| ------- | --------------------------- | +| rawFile | Pointer to the target [RawFile](#rawfile).| **Returns** -Returns the current offset of the rawfile. +Returns the file offset obtained. + +**Since** + +8 -### OH_ResourceManager_GetRawFileSize() +#### OH_ResourceManager_GetRawFileSize() + - ``` long OH_ResourceManager_GetRawFileSize (RawFile * rawFile) ``` -**Description**
-Obtains the length of a rawfile in int32_t. - **Parameters** +**Description** + +Obtains the size of a file in **rawfile**. + +**Parameters** -| Name | Description | -| -------- | -------- | -| rawFile | Indicates the pointer to [RawFile](#rawfile). | +| Name | Description | +| ------- | --------------------------- | +| rawFile | Pointer to the target [RawFile](#rawfile).| **Returns** -Returns the total length of the rawfile. +Returns the file size obtained. +**Since** + +8 + + +#### OH_ResourceManager_InitNativeResourceManager() -### OH_ResourceManager_InitNativeResourceManager() - ``` NativeResourceManager* OH_ResourceManager_InitNativeResourceManager (napi_env env, napi_value jsResMgr ) ``` -**Description**
-Obtains the native resource manager based on JavaScipt resource manager. -After obtaining a resource manager, you can use it complete various rawfile operations. +**Description** + +Initializes a Native resource manager using the JavaScript resource manager. + +You can use the resource manager obtained to implement **rawfile** operations. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| env | Indicates the pointer to the JavaScipt Native Interface (napi) environment. | -| jsResMgr | Indicates the JavaScipt resource manager. | +| Name | Description | +| -------- | ---------------------------------------- | +| env | Pointer to the JavaScript Native API (napi) environment.| +| jsResMgr | JavaScript resource manager. | **Returns** -Returns the pointer to [NativeResourceManager](#nativeresourcemanager). +Returns the pointer to the [NativeResourceManager](#nativeresourcemanager) obtained. +**Since** + +8 + + +#### OH_ResourceManager_OpenRawDir() -### OH_ResourceManager_OpenRawDir() - ``` RawDir* OH_ResourceManager_OpenRawDir (const NativeResourceManager * mgr, const char * dirName ) ``` -**Description**
-Opens a rawfile directory. -After opening a rawfile directory, you can traverse all the rawfile files in it. +**Description** - **Parameters** +Opens a directory in **rawfile**. -| Name | Description | -| -------- | -------- | -| mgr | Indicates the pointer to [NativeResourceManager](#nativeresourcemanager). You can obtain this pointer by calling [OH_ResourceManager_InitNativeResourceManager](#oh_resourcemanager_initnativeresourcemanager). | -| dirName | Indicates the name of the rawfile directory to open. If this field is left empty, the root directory of rawfile will be opened. | +After opening the directory, you can traverse all files in it. + +**Parameters** + +| Name | Description | +| ------- | ---------------------------------------- | +| mgr | Pointer to the [NativeResourceManager](#nativeresourcemanager), which is obtained by using [OH_ResourceManager_InitNativeResourceManager](#oh_resourcemanager_initnativeresourcemanager).| +| dirName | Pointer to the name of the directory to open. If this field is left empty, the root directory will be opened.| **Returns** -Returns the pointer to [RawDir](#rawdir). If this pointer is no longer needed after use, call [OH_ResourceManager_CloseRawDir](#oh_resourcemanager_closerawdir) to release it. +Returns the pointer to the [RawDir](#rawdir) opened. You can use [OH_ResourceManager_CloseRawDir](#oh_resourcemanager_closerawdir) to close the directory and release resources. - **See** +**See** [OH_ResourceManager_InitNativeResourceManager](#oh_resourcemanager_initnativeresourcemanager) [OH_ResourceManager_CloseRawDir](#oh_resourcemanager_closerawdir) +**Since** + +8 + + +#### OH_ResourceManager_OpenRawFile() -### OH_ResourceManager_OpenRawFile() - ``` RawFile* OH_ResourceManager_OpenRawFile (const NativeResourceManager * mgr, const char * fileName ) ``` -**Description**
-Opens a rawfile. -After a rawfile is opened, you can read the data in it. +**Description** - **Parameters** +Opens a file in **rawfile**. -| Name | Description | -| -------- | -------- | -| mgr | Indicates the pointer to [NativeResourceManager](#nativeresourcemanager). You can obtain this pointer by calling [OH_ResourceManager_InitNativeResourceManager](#oh_resourcemanager_initnativeresourcemanager). | -| fileName | Indicates the file name in the relative path of the rawfile root directory. | +After the file is opened, you can read data in it. + +**Parameters** + +| Name | Description | +| -------- | ---------------------------------------- | +| mgr | Pointer to the [NativeResourceManager](#nativeresourcemanager), which is obtained by using [OH_ResourceManager_InitNativeResourceManager](#oh_resourcemanager_initnativeresourcemanager).| +| fileName | Pointer to the name of the file in the relative path of the **rawfile** root directory. | **Returns** -Returns the pointer to [RawFile](#rawfile). If this pointer is no longer needed after use, call [OH_ResourceManager_CloseRawFile](#oh_resourcemanager_closerawfile) to release it. +Returns the pointer to the [RawFile](#rawfile) opened. You can use [OH_ResourceManager_CloseRawFile](#oh_resourcemanager_closerawfile) to close the file and release resources. - **See** +**See** [OH_ResourceManager_InitNativeResourceManager](#oh_resourcemanager_initnativeresourcemanager) [OH_ResourceManager_CloseRawFile](#oh_resourcemanager_closerawfile) +**Since** + +8 + + +#### OH_ResourceManager_ReadRawFile() -### OH_ResourceManager_ReadRawFile() - ``` int OH_ResourceManager_ReadRawFile (const RawFile * rawFile, void * buf, size_t length ) ``` -**Description**
-Reads a rawfile. + +**Description** + +Reads a file in **rawfile**. You can use this function to read data of the specified length from the current position. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| rawFile | Indicates the pointer to [RawFile](#rawfile). | -| buf | Indicates the pointer to the buffer for storing the read data. | -| length | Indicates the length of the read data, in bytes. | +| Name | Description | +| ------- | --------------------------- | +| rawFile | Pointer to the [RawFile](#rawfile) to read.| +| buf | Pointer to the buffer for receiving the read data. | +| length | Length of the data to read. | **Returns** -Returns the length of the read data in bytes. If the length is beyond the end of the rawfile, **0** will be returned. +Returns the number of bytes read. If the read length exceeds the length of the file end, **0** will be returned. + +**Since** +8 + + +#### OH_ResourceManager_ReleaseNativeResourceManager() -### OH_ResourceManager_ReleaseNativeResourceManager() - ``` void OH_ResourceManager_ReleaseNativeResourceManager (NativeResourceManager * resMgr) ``` -**Description**
-Releases a native resource manager. - **Parameters** +**Description** + +Releases a Native resource manager instance. + +**Parameters** + +| Name | Description | +| ------ | ---------------------------------------- | +| resMgr | Pointer to the [NativeResourceManager](#nativeresourcemanager) instance to release.| + +**Since** + +8 -| Name | Description | -| -------- | -------- | -| resMgr | Indicates the pointer to [NativeResourceManager](#nativeresourcemanager). | +#### OH_ResourceManager_ReleaseRawFileDescriptor() -### OH_ResourceManager_ReleaseRawFileDescriptor() - ``` bool OH_ResourceManager_ReleaseRawFileDescriptor (const RawFileDescriptor & descriptor) ``` -**Description**
-Closes a rawfile descriptor. -To prevent file descriptor leakage, you are advised to release a rawfile descriptor after use. +**Description** + +Releases the FD of a file in **rawfile**. + +To prevent FD leakage, you are advised to release an FD immediately after use. - **Parameters** +**Parameters** -| Name | Description | -| -------- | -------- | -| descriptor | Indicates the rawfile descriptor, and the start position and length of the rawfile file in the HAP package. | +| Name | Description | +| ---------- | ------------------------------------------------------------ | +| descriptor | File descriptor to close. It contains the FD, start position in the HAP, and file length. | **Returns** -Returns **true** if the rawfile descriptor is closed successfully; returns **false** otherwise. +Returns true if the FD is released; returns false otherwise. + +**Since** + +8 -### OH_ResourceManager_SeekRawFile() +#### OH_ResourceManager_SeekRawFile() + - ``` int OH_ResourceManager_SeekRawFile (const RawFile * rawFile, long offset, int whence ) ``` -**Description**
-Seeks for the data read/write position in the rawfile based on the specified offset. - **Parameters** +**Description** + +Seeks for the data read/write position in a file in **rawfile** based on the specified offset. + +**Parameters** -| Name | Description | -| -------- | -------- | -| rawFile | Indicates the pointer to [RawFile](#rawfile). | -| offset | Indicates the specified offset. | -| whence | Indicates the data read/write position. The options are as follows:
**0**: The read/write position is **offset**.
**1**: The read/write position is the current position plus **offset**.
**2**: The read/write position is the end of the file (EOF) plus **offset**. | +| Name | Description | +| ------- | ---------------------------------------- | +| rawFile | Pointer to the target [RawFile](#rawfile). | +| offset | Offset. | +| whence | Read/Write position. The options are as follows:
**0**: The read/write position is the offset.
**1**: The read/write position is the current position plus the offset.
**2**: The read/write position is the end of the file (EOF) plus the offset.| **Returns** -Returns the new data read/write position if the operation is successful; returns **(long) -1** otherwise. +Returns the read/write position if the operation is successful; returns **(long) -1** otherwise. + +**Since** + +8 diff --git a/en/application-dev/reference/native-lib/Readme-EN.md b/en/application-dev/reference/native-lib/Readme-EN.md index 9b0fbca08e15c7b7e0e5e500d3532019bb56eb87..35aae001da731ad020290e3f35ee0f3693221018 100644 --- a/en/application-dev/reference/native-lib/Readme-EN.md +++ b/en/application-dev/reference/native-lib/Readme-EN.md @@ -1,8 +1,12 @@ -# Standard Libraries Supported by Native APIs +# Native API Standard Libraries - [libc](third_party_libc/musl.md) +- [libc++](third_party_libc/cpp.md) - [Node-API](third_party_napi/napi.md) - [libuv](third_party_libuv/libuv.md) - [OpenSL ES](third_party_opensles/opensles.md) +- [OpenGL ES](third_party_opengl/opengles.md) +- [EGL](third_party_opengl/egl.md) +- [zlib](third_party_zlib/zlib.md) - Appendix - [Native API Symbols Not Exported](third_party_libc/musl-peculiar-symbol.md) - [Native API Symbols That May Fail to Be Invoked Due to Permission Control](third_party_libc/musl-permission-control-symbol.md) diff --git a/en/application-dev/reference/native-lib/third_party_libc/cpp.md b/en/application-dev/reference/native-lib/third_party_libc/cpp.md new file mode 100644 index 0000000000000000000000000000000000000000..ab373884f2a7f50f451e2f6aaa2682b9020bc745 --- /dev/null +++ b/en/application-dev/reference/native-lib/third_party_libc/cpp.md @@ -0,0 +1,29 @@ + +# libc++ + +Currently, OpenHarmony uses the C++ standard library [(libc++)](https://libcxx.llvm.org/) of the LLVM project. + +## Version + +From OpenHarmony 3.0, libc++ uses Clang/LLVM 10.0.1. + +From OpenHarmony 3.2, libc++ is upgraded to Clang/LLVM 12.0.1. + +From OpenHarmony 4.0, libc++ is upgraded to Clang/LLVM 15.0.4. + +## Supported Capabilities + +The C++11 and C++14 standards are supported, and the C++17 and C++20 standards are on the way. For details about the standards supported by language features, see the corresponding Release Notes at [https://libcxx.llvm.org/](https://libcxx.llvm.org/). + +## ABI Compatibility +In OpenHarmony, both the system library and application native library use the libc++. However, the two libc++ are different. The libc++ of the system library is updated with the image version, while the libc++ of the application native library is updated with the SDK version used for compilation. Both the libc++ libraries cross multiple major versions, which may cause Application Binary Interface (ABI) compatibility issues. To solve this problem, OpenHarmony differentiates the libc++ libraries as follows: + * System library: uses **libc++.so**, which is released with the system image. + * Application native library: uses **libc++_shared.so**, which is released with the application. + +The two libc++ libraries use different namespaces. **libc++_shared.so** uses **__n1** as the namespace for C++ symbols, and **libc++.so** uses **__h** as the namespace for C++ symbols. + +> **CAUTION** +> +> Currently, the Native API supports C only. The system library can use any programming language. + + \ No newline at end of file diff --git a/en/application-dev/reference/native-lib/third_party_libc/musl-permission-control-symbol.md b/en/application-dev/reference/native-lib/third_party_libc/musl-permission-control-symbol.md index ee2eb1bf6c1ab5473369e86287298349c54098eb..da2a9a0bef4cbd2a4122ddeae93eb0405cbab91d 100644 --- a/en/application-dev/reference/native-lib/third_party_libc/musl-permission-control-symbol.md +++ b/en/application-dev/reference/native-lib/third_party_libc/musl-permission-control-symbol.md @@ -1,12 +1,14 @@ # Native API Symbols That May Fail to Be Invoked Due to Permission Control +Before using the following interfaces, ensure that the application entity has the corresponding permission. + | Symbol| Possible Cause| | --- | --- | -| mlockall | User namespace isolation or lack of the CAP_IPC_LOCK privilege.| -| swapon | User namespace isolation. | -| swapoff | User namespace isolation. | -| stime | User namespace isolation or lack of the CAP_SYS_TIME privilege.| -| settimeofday | User namespace isolation or lack of the CAP_SYS_TIME privilege.| -| adjtime | User namespace isolation or lack of the CAP_SYS_TIME privilege.| -| clock_settime | User namespace isolation or lack of the CAP_SYS_TIME privilege.| -| klogctl | User namespace isolation or lack of the CAP_SYS_ADMIN/CAP_SYSLOG privilege.| +| mlockall | usr namespace isolation or lack of CAP_IPC_LOCK privilege | +| swapon | usr namespace isolation | +| swapoff | usr namespace isolation | +| stime | usr namespace isolation or lack of CAP_SYS_TIME privilege | +| settimeofday | usr namespace isolation or lack of CAP_SYS_TIME privilege | +| adjtime | usr namespace isolation or lack of CAP_SYS_TIME privilege | +| clock_settime | usr namespace isolation or lack of CAP_SYS_TIME privilege | +| klogctl | usr namespace isolation or lack of CAP_SYS_ADMIN/CAP_SYSLOG privilege | diff --git a/en/application-dev/reference/native-lib/third_party_libc/musl.md b/en/application-dev/reference/native-lib/third_party_libc/musl.md index cf74c7efdf1a796acd0de7f27883cec9a7cbb85f..460040d4f205ddc055f321eb3af30bde7e183271 100644 --- a/en/application-dev/reference/native-lib/third_party_libc/musl.md +++ b/en/application-dev/reference/native-lib/third_party_libc/musl.md @@ -1,85 +1,66 @@ -# Native Standard Libraries Supported by OpenHarmony +# libc ## Overview +The C standard library (libc) provides standard header files and common library implementations (such as input/output processing and string handling) in C language programming. -**Table 1** Standard libraries supported by OpenHarmony +OpenHarmony uses musl as the libc. musl is a lightweight, fast, simple, and free open-source libc. For details, see [musl libc Reference Manual](http://musl.libc.org/manual.html). -| Library | Description | -| :-------- | :----------------------------------------------------------- | -| C standard library | C11 standard library implemented by [libc, libm, and libdl](https://en.cppreference.com/w/c/header). | -| C++ standard library ([libc++](https://libcxx.llvm.org/))| An implementation of the C++ standard library. | -| Open Sound Library for Embedded Systems ([OpenSL ES](https://www.khronos.org/registry/OpenSL-ES/))| An embedded, cross-platform audio processing library.| -| [zlib](https://zlib.net/) | A general data compression library implemented in C/C++.| -| [EGL](https://www.khronos.org/egl/) | A standard software interface between rendering APIs and the underlying native window system.| -| Open Graphics Library for Embedded Systems ([OpenGL ES](https://www.khronos.org/opengles/))| A cross-platform software interface for rendering 3D graphics on embedded and mobile systems.| +For details about the differences between musl and glibc, see [Functional differences from glibc](https://wiki.musl-libc.org/functional-differences-from-glibc.html). -## C Standard Library +## libc Components -The C standard library is a C11 standard library implemented by: +C11 is implemented by [libc, libm, and libdl](https://en.cppreference.com/w/c/header). -- libc: provides thread-related functions and a majority of standard functions. +libc: provides thread-related interfaces and a majority of standard interfaces. +libm: provides mathematical library interfaces. Currently, OpenHarmony provides a link to libm, and the interfaces are defined in libc. -- libm: provides basic mathematical functions. +libdl: provides dynamic linker interfaces such as dlopen. Currently, OpenHarmony provides a link to libdl, and the interfaces are defined in libc. - -- libdl: provides functions related to dynamic linking, such as **dlopen**. - - -**Version** +## musl Version 1.2.0 -**Capabilities** - -C standard library includes a set of header files in accordance with standard C and provides common functions, such as the functions related to input/output (I/O) and string control. - -**musl** - +From OpenHarmony 4.0, musl 1.2.3 is supported. + +## Supported Capabilities +OpenHarmony provides header files and library interfaces that are compatible (not fully compatible) with C99, C11, and POSIX, and supports Armv7-A, Arm64, and x86_64 architectures. + +To better adapt to the basic features of OpenHarmony devices, such as high performance, low memory, high security, lightweight, and multi-form support, OpenHarmony has optimized the musl library and removed the interfaces that are not applicable to embedded devices. + +### New Capabilities +1. The dynamic loader supports isolation by namespace. The dynamic libraries that can be loaded by **dlopen()** are restricted by the system namespace. For example, the system dynamic libraries cannot be opened. +2. **dlclose()** can be used to unload a dynamic library. This capability is not supported by musl. +3. The symbol-versioning is supported. +4. **dlopen()** can directly load uncompressed files in a .zip package. + +### Debugging Capabilities +The libc provides dynamic settings of the basic log functions (disabled by default) for developers to view internal exceptions of the libc. You can set the **param** to enable or disable the log functions, without recompiling the libc. However, you are advised not to use the log functions in official release versions because they affect the running performance. + +#### 1. musl.log +Set **musl.log.enable** to **true** to enable the **musl.log** function. To print other logs, you need to enable this function first. +``` +setparam musl.log.enable true +``` + +#### 2. Loader log function +The loader starts applications and invokes dlopen() and dlclose() in libc. To view exceptions in the dynamic loading process, enable the loader log function. +* Enable the loader log of all applications (exercise caution when using this function). +``` +param set musl.log.ld.app true +``` +* Enable the loader log of the specified application. {app_name} specifies the target application. +``` +param set musl.log.ld.all false +param set musl.log.ld.app.{app_name} true +``` +* Enable the loader log of all applications except the specified application. +``` +param set musl.log.ld.all true +param set musl.log.ld.app.{app_name} false +``` + +## Interfaces Not Supported by musl [Native API Symbols Not Exported](musl-peculiar-symbol.md) - [Native API Symbols That May Fail to Be Invoked Due to Permission Control](musl-permission-control-symbol.md) -## libc++ - -[libc++](https://libcxx.llvm.org/) is an implementation of the C++ standard library. - -**Version** - -10.0.1 - -**Capabilities** - -The C++11 and C++14 standards are supported, and the C++17 and C++20 standards are on the way. - -## OpenSL ES - -[OpenGL ES](https://www.khronos.org/opengles/) is an embedded, cross-platform audio processing library. - -**Capabilities** - -[OpenSL ES Interfaces Supported by Native APIs](../third_party_opensles/opensles.md) - -## zlib - -[zlib](https://zlib.net/) is a general data compression library implemented in C/C++. - -## EGL - -EGL is an interface between Khronos rendering APIs (such as OpenGL ES and OpenVG) and the underlying native window system. OpenHarmony supports EGL. - -**Symbols Exported from the Standard Library** - -[EGL Symbols Exported from Native APIs](../third_party_opengl/egl-symbol.md) - -## OpenGL ES - -OpenGL is a cross-platform software interface for 3D graphics processing. [OpenGL ES](https://www.khronos.org/opengles/) is a OpenGL specification for embedded devices. OpenHarmony supports OpenGL ES 3.0. - -**Capabilities** - -OpenGL ES 3.0 - -**Symbols Exported from the Standard Library** - -[OpenGL ES 3.0 Symbols Exported from Native APIs](../third_party_opengl/openglesv3-symbol.md) diff --git a/en/application-dev/reference/native-lib/third_party_opengl/egl.md b/en/application-dev/reference/native-lib/third_party_opengl/egl.md new file mode 100644 index 0000000000000000000000000000000000000000..a74e6ef1c85df1a3df081fbcc010b3bae4379ec5 --- /dev/null +++ b/en/application-dev/reference/native-lib/third_party_opengl/egl.md @@ -0,0 +1,9 @@ + +# EGL + +EGL is an interface between Khronos rendering APIs (such as OpenGL ES and OpenVG) and the underlying native window system. OpenHarmony supports EGL. + +## **Symbols Exported from the NAPI Library** + +[EGL Symbols Exported fom Native APIs](egl-symbol.md) + diff --git a/en/application-dev/reference/native-lib/third_party_opengl/opengles.md b/en/application-dev/reference/native-lib/third_party_opengl/opengles.md new file mode 100644 index 0000000000000000000000000000000000000000..b73c456300b7b9abe4dff24fa6933a311fb950a3 --- /dev/null +++ b/en/application-dev/reference/native-lib/third_party_opengl/opengles.md @@ -0,0 +1,12 @@ +# OpenGL ES + +OpenGL is a cross-platform software interface for 3D graphics processing. [OpenGL ES](https://www.khronos.org/opengles/) is a OpenGL specification for embedded devices. OpenHarmony supports OpenGL ES 3.0. + +## Supported Capabilities + +OpenGL ES 3.0 + +## **Symbols Exported from the NAPI Library** + +[OpenGL ES 3.0 Symbols Exported from Native APIs](openglesv3-symbol.md) + diff --git a/en/application-dev/reference/native-lib/third_party_zlib/zlib.md b/en/application-dev/reference/native-lib/third_party_zlib/zlib.md new file mode 100644 index 0000000000000000000000000000000000000000..a1a3600569bb1de9ba360269bfeaf067aba4ad3a --- /dev/null +++ b/en/application-dev/reference/native-lib/third_party_zlib/zlib.md @@ -0,0 +1,3 @@ +# zlib + +[zlib](https://zlib.net/) is a general data compression library implemented in C/C++. \ No newline at end of file diff --git a/en/device-dev/device-test/figures/smartperf_frame.png b/en/device-dev/device-test/figures/smartperf_frame.png new file mode 100644 index 0000000000000000000000000000000000000000..4cd602ed03837c570efee4dc3887272414b391e5 Binary files /dev/null and b/en/device-dev/device-test/figures/smartperf_frame.png differ diff --git a/en/device-dev/device-test/smartperf-host.md b/en/device-dev/device-test/smartperf-host.md new file mode 100644 index 0000000000000000000000000000000000000000..ec92a1ba4c2c5ca57957702de1e9fe9c8cb54c9c --- /dev/null +++ b/en/device-dev/device-test/smartperf-host.md @@ -0,0 +1,83 @@ +# Smartperf-Host +## Overview +Smartperf-Host is an intuitive performance and power optimization tool that offers in-depth data mining and fine-grained data visualization. In this tool, you can gain visibility into a multitude of metrics in terms of CPU scheduling, frequency, process and thread time slices, heap memory, frame rate, and more, in swimlanes. Better yet, you can analyze the collected data intuitively on the GUI. +## Architecture +![System Architecture](figures/smartperf_frame.png) + +Smartperf-Host consists of the device end and PC end, which exchange data with each other based on gRPC – a high-performance remote procedure call (RPC) framework. + +The device end consists of modules such as Native Hook (application-embedded component), hiprofiler_command (command-line tool), hiprofilerd (performance profiler service), a set of performance profiler plug-ins, and some system tools and kernels. The device end provides the plug-in extension capability by exposing plug-in interfaces for external systems. By drawing on this capability, you can integrate custom plug-ins into the framework. For details about the preset plug-ins, see [Performance Profiler Component](https://gitee.com/openharmony/developtools_profiler). + +The PC end is accessible from the Smartperf-Host website. It consists of modules such as Trace Streamer, SQLite, HDC device management, data import, UI drawing, and data analysis. +## Project Directory +``` +/smartperf_host +├── host # Smartperf-Host related code +│ ├── doc # Smartperf-Host documentation +│ ├── ide # Smartperf-Host IDE module +│ │ └── src # Profiler module +│ │ │ ├── base-ui # Basic components +│ │ │ └── Trace # Service logic +│ ├── trace_streamer # Trace Streamer module +│ │ ├── base # Basic functionality +│ │ ├── cfg # Configuration +│ │ ├── filter # Filter +│ │ ├── include # Header files +│ │ ├── multi_platform # Platform adaptation +│ │ ├── parser # Parsing service logic +│ │ │ ├── bytrace_parser # byTrace service logic +│ │ │ └── htrace_parser # hTrace service logic +│ │ ├── table # Table structure +│ │ ├── trace_data # Trace structure +│ │ ├── trace_streamer # Trace Streamer structure +│ │ │ └── kits # JS APIs and native APIs +``` +## Function Description +- Loading Trace Files on Web Pages + + Load local trace files (such as htrace and ftrace) and display the data in swimlanes. For details, see [Loading Trace Files on Web Pages](https://gitee.com/openharmony-sig/developtools_smartperf_host/blob/master/ide/src/doc/md/quickstart_systemtrace.md). +- Capturing Traces Online + + Use Smartperf_Host to capture traces online, with the content, duration, and save path all customizable. For details, see [Capturing Traces on Web Pages](https://gitee.com/openharmony-sig/developtools_smartperf_host/blob/master/ide/src/doc/md/quickstart_web_record.md). +- Capturing Traces on a Device + + Capture traces on the target device, with the content, duration, and save path all customizable. For details, see [Capturing Traces from a Device](https://gitee.com/openharmony-sig/developtools_smartperf_host/blob/master/ide/src/doc/md/quickstart_device_record.md). +- Using Ability Monitor + + With Ability Monitor in Smartperf_Host, you can learn the CPU, memory, disk I/O, and network usage of your application. For details, see [Ability Monitor Usage](https://gitee.com/openharmony-sig/developtools_smartperf_host/blob/master/ide/src/doc/md/quickstart_ability_monitor.md). +- Using Native Memory + + With Native Memory in Smartperf_Host, you can track the allocation and release of your application's native memory (specific to C and C++). For details, see [Native Memory Usage](https://gitee.com/openharmony-sig/developtools_smartperf_host/blob/master/ide/src/doc/md/quickstart_native_memory.md). +- Using Hiperf + + With Hiperf in Smartperf_Host, you can view the CPU usage of your application and the call stack. For details, see [Hiperf Usage](https://gitee.com/openharmony-sig/developtools_smartperf_host/blob/master/ide/src/doc/md/quickstart_hiperf.md). +- Using HiSystemEvent + + With HiSystemEvent in Smartperf_Host, you can inspect the power consumption of each category (CPU, network, and location, and more) of your application, resource application and usage records (WorkScheduler, Runninglock, Alarm, and Location Request), power consumption exceptions, and system states associated with the power consumption (battery level and screen status). For details, see [HiSystemEvent Usage](https://gitee.com/openharmony-sig/developtools_smartperf_host/blob/master/ide/src/doc/md/quickstart_hisystemevent.md). +- Collecting FileSystem Records + + In Smartperf_Host, you can find out the system invoking information and read/write invoking times of all file systems. For details, see [Usage of FileSystem Recording](https://gitee.com/openharmony-sig/developtools_smartperf_host/blob/master/ide/src/doc/md/quickstart_filesystem.md). +- Collecting Page Fault Records + + In Smartperf_Host, you can collect page fault records, covering various aspects such as start time, duration, triggering process, triggering thread, event type, memory address, and memory size of page memory events. For details, see [Usage of Page Fault Recording](https://gitee.com/openharmony-sig/developtools_smartperf_host/blob/master/ide/src/doc/md/quickstart_page_fault.md). +- Collecting BIO Records + + In Smartperf_Host, you can collect I/O operation records, which provide the following information: start time, total latency, process, average latency of every 4 KB data, thread, operation (write data, page swap-in, and metadata), access traffic, path, block number, priority, and backtrace call stack. For details, see [Usage of BIO Latency Recording](https://gitee.com/openharmony-sig/developtools_smartperf_host/blob/master/ide/src/doc/md/quickstart_bio.md). +- Collecting Smaps Records + + In Smartperf_Host, you can collect the smaps data (type, Pss, Rss, Vss, and more) on a process-by-process basis. The data source is **/proc/$pid/smaps**. For details, see [Smaps Usage](https://gitee.com/openharmony-sig/developtools_smartperf_host/blob/master/ide/src/doc/md/quickstart_smaps.md). +- Using SQL Analysis and Metrics + + You can use Query (SQL) and Metrics features to quickly locate the trace data. For details, see [SQL Analysis and Metrics Usage](https://gitee.com/openharmony-sig/developtools_smartperf_host/blob/master/ide/src/doc/md/quickstart_sql_metrics.md). +## Compilation Guidance +Project compilation includes Trace Streamer compilation and Smartperf-Host compilation and deployment. +### Prerequisites +- C++ version: 11 or later +- Node.js version: 16.15.1 or later +- npm version: 8.13.2 or later +- TypeScript version: 4.2.3 or later +- Go version: 1.13.8 or later +### Compiling Trace Streamer +To set up the Smartperf_Host website, you need to compile the WASM version of Trace Streamer for the web page to parse the original trace data. For details about the compilation process, see [Compiling Trace Streamer](https://gitee.com/openharmony-sig/developtools_smartperf_host/blob/master/trace_streamer/doc/compile_trace_streamer.md). +### Compiling and Deploying Smartperf-Host +For details about the compilation and deployment process, see [SmartPerf Compilation and Deployment Guide](https://gitee.com/openharmony-sig/developtools_smartperf_host/blob/master/ide/README_zh.md)). After successful deployment, you can start to use Smartperf_Host by visiting **https://[*IP address of the device where SmartPerf is deployed*]:9000/application/**. diff --git a/en/device-dev/driver/driver-peripherals-codec-des.md b/en/device-dev/driver/driver-peripherals-codec-des.md index 735c38fa84ae0ae500b7fac604398cc3562b14eb..bb0c7f8cabb0b242703a8d0604761fc69eeed189 100644 --- a/en/device-dev/driver/driver-peripherals-codec-des.md +++ b/en/device-dev/driver/driver-peripherals-codec-des.md @@ -39,7 +39,7 @@ Before you get started, understand the following concepts: - Component - An OpenMAX IL component, which is an abstraction of modules in video streams. The components in this document refer to codec components for video encoding and decoding. + An OpenMAX IL component, which is an abstraction of modules in video streams. The components in this document refer to codec components used for video encoding and decoding. ### Constraints @@ -54,33 +54,33 @@ The codec module implements hardware encoding and decoding of video data. It con ### Available APIs -- codec_component_manager.h +- icodec_component_manager.h | API | Description | | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------| - | int32_t (*CreateComponent)(struct CodecComponentType **component, uint32_t *componentId, char *compName, int64_t appData, struct CodecCallbackType *callbacks) | Creates a codec component instance. | - | int32_t (*DestroyComponent)(uint32_t componentId) | Destroys a component instance. | - -- codec_component _if.h - - | API | Description | - | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- | - | int32_t (*SendCommand)(struct CodecComponentType *self, enum OMX_COMMANDTYPE cmd, uint32_t param, int8_t *cmdData, uint32_t cmdDataLen) | Sends commands to a component. | - | int32_t (*GetParameter)(struct CodecComponentType *self, uint32_t paramIndex, int8_t *paramStruct, uint32_t paramStructLen) | Obtains component parameter settings. | - | int32_t (*SetParameter)(struct CodecComponentType *self, uint32_t index, int8_t *paramStruct, uint32_t paramStructLen) | Sets component parameters. | - | int32_t (*GetState)(struct CodecComponentType *self, enum OMX_STATETYPE *state) | Obtains the component status. | - | int32_t (*UseBuffer)(struct CodecComponentType *self, uint32_t portIndex, struct OmxCodecBuffer *buffer) | Specifies the buffer of a component port. | - | int32_t (*FreeBuffer)(struct CodecComponentType *self, uint32_t portIndex, const struct OmxCodecBuffer *buffer) | Releases the buffer. | - | int32_t (*EmptyThisBuffer)(struct CodecComponentType *self, const struct OmxCodecBuffer *buffer) | Empties this buffer. | - | int32_t (*FillThisBuffer)(struct CodecComponentType *self, const struct OmxCodecBuffer *buffer) | Fills this buffer. | - -- codec_callback_if.h - - | API | Description | - | ---------------------------------------------------------------------------------------------------------------- |----------------------------------- | - | int32_t (*EventHandler)(struct CodecCallbackType *self, enum OMX_EVENTTYPE event, struct EventInfo *info) | Reports an event. | - | int32_t (*EmptyBufferDone)(struct CodecCallbackType *self, int64_t appData, const struct OmxCodecBuffer *buffer) | Reports an event indicating that the encoding or decoding in the input buffer is complete.| - | int32_t (*FillBufferDone)(struct CodecCallbackType *self, int64_t appData, const struct OmxCodecBuffer *buffer) | Reports an event indicating that the output buffer is filled. | + | int32_t CreateComponent(sptr& component, uint32_t& componentId,
const std::string& compName, int64_t appData, const sptr& callbacks) | Creates a codec component instance. | + | int32_t DestoryComponent(uint32_t componentId) | Destroys a codec component instance. | + +- icodec_component.h + + | API | Description | + | ------------------------------------------------------------ | ---------------------- | + | int32_t SendCommand(CodecCommandType cmd, uint32_t param, const std::vector& cmdData) | Sends commands to a component. | + | int32_t GetParameter(uint32_t index, const std::vector& inParamStruct, std::vector& outParamStruct) | Obtains component parameter settings. | + | int32_t SetParameter(uint32_t index, const std::vector& paramStruct) | Sets component parameters. | + | int32_t GetState(CodecStateType& state) | Obtains the component status. | + | int32_t UseBuffer(uint32_t portIndex, const OmxCodecBuffer& inBuffer, OmxCodecBuffer& outBuffer) | Requests a port buffer for the component. | + | int32_t FreeBuffer(uint32_t portIndex, const OmxCodecBuffer& buffer) | Releases the buffer. | + | int32_t EmptyThisBuffer(const OmxCodecBuffer& buffer) | Empties this buffer.| + | int32_t FillThisBuffer(const OmxCodecBuffer& buffer) | Fills this buffer. | + +- icodec_callback.h + + | API | Description | + | ------------------------------------------------------------ | ---------------------------------- | + | int32_t EventHandler(CodecEventType event, const EventInfo& info) | Called to report an event. | + | int32_t EmptyBufferDone(int64_t appData, const OmxCodecBuffer& buffer) | Called to report an event indicating that the encoding or decoding in the input buffer is complete.| + | int32_t FillBufferDone(int64_t appData, const OmxCodecBuffer& buffer) | Called to report an event indicating that the output buffer is filled. | For more information, see [codec](https://gitee.com/openharmony/drivers_peripheral/tree/master/codec). @@ -88,83 +88,86 @@ For more information, see [codec](https://gitee.com/openharmony/drivers_peripher The codec HDI driver development procedure is as follows: #### Registering and Initializing the Driver -Define the **HdfDriverEntry** structure (which defines the driver initialization method) and fill in the **g_codecComponentDriverEntry** structure to implement the **Bind()**, **Init()**, and **Release()** pointers. +Define the **HdfDriverEntry** struct (which defines the driver initialization method) and fill in the **g_codeccomponentmanagerDriverEntry** struct to implement the **Bind()**, **Init()**, and **Release()** pointers. ```c -struct HdfDriverEntry g_codecComponentDriverEntry = { +static struct HdfDriverEntry g_codeccomponentmanagerDriverEntry = { .moduleVersion = 1, - .moduleName = "codec_hdi_omx_server", - .Bind = HdfCodecComponentTypeDriverBind, - .Init = HdfCodecComponentTypeDriverInit, - .Release = HdfCodecComponentTypeDriverRelease, -}; -HDF_INIT(g_codecComponentDriverEntry); // Register HdfDriverEntry of the codec HDI with the HDF. + .moduleName = "codec_component_manager_service", + .Bind = HdfCodecComponentManagerDriverBind, + .Init = HdfCodecComponentManagerDriverInit, + .Release = HdfCodecComponentManagerDriverRelease, +}; // Register the HdfDriverEntry struct of the codec HDI with the HDF. ``` -- **HdfCodecComponentTypeDriverBind**: binds the device in the HDF to **CodecComponentTypeHost** and registers the codec service with the HDF. +- **HdfCodecComponentManagerDriverBind**: binds the device in the HDF to the **HdfCodecComponentManagerHost** and registers the codec service with the HDF. ```c - int32_t HdfCodecComponentTypeDriverBind(struct HdfDeviceObject *deviceObject) + static int HdfCodecComponentManagerDriverBind(struct HdfDeviceObject *deviceObject) { - HDF_LOGI("HdfCodecComponentTypeDriverBind enter."); - struct HdfCodecComponentTypeHost *omxcomponenttypeHost = - (struct HdfCodecComponentTypeHost *)OsalMemAlloc(sizeof(struct HdfCodecComponentTypeHost)); - if (omxcomponenttypeHost == NULL) { - HDF_LOGE("HdfCodecComponentTypeDriverBind OsalMemAlloc HdfCodecComponentTypeHost failed!"); + CODEC_LOGI("HdfCodecComponentManagerDriverBind enter"); + + auto *hdfCodecComponentManagerHost = new (std::nothrow) HdfCodecComponentManagerHost; + if (hdfCodecComponentManagerHost == nullptr) { + CODEC_LOGE("failed to create create HdfCodecComponentManagerHost object"); return HDF_FAILURE; } - int ret = HdfDeviceObjectSetInterfaceDesc(deviceObject, COMPONENT_MANAGER_SERVICE_DESC); - if (ret != HDF_SUCCESS) { - HDF_LOGE("Failed to set interface desc"); - return ret; + + hdfCodecComponentManagerHost->ioService.Dispatch = CodecComponentManagerDriverDispatch; + hdfCodecComponentManagerHost->ioService.Open = NULL; + hdfCodecComponentManagerHost->ioService.Release = NULL; + + auto serviceImpl = ICodecComponentManager::Get(true); + if (serviceImpl == nullptr) { + CODEC_LOGE("failed to get of implement service"); + delete hdfCodecComponentManagerHost; + return HDF_FAILURE; } - - omxcomponenttypeHost->ioservice.Dispatch = CodecComponentTypeDriverDispatch; - omxcomponenttypeHost->ioservice.Open = NULL; - omxcomponenttypeHost->ioservice.Release = NULL; - omxcomponenttypeHost->service = CodecComponentManagerSerivceGet(); - if (omxcomponenttypeHost->service == NULL) { - OsalMemFree(omxcomponenttypeHost); + + hdfCodecComponentManagerHost->stub = + OHOS::HDI::ObjectCollector::GetInstance().GetOrNewObject(serviceImpl, ICodecComponentManager::GetDescriptor()); + if (hdfCodecComponentManagerHost->stub == nullptr) { + CODEC_LOGE("failed to get stub object"); + delete hdfCodecComponentManagerHost; return HDF_FAILURE; } - - deviceObject->service = &omxcomponenttypeHost->ioservice; + + deviceObject->service = &hdfCodecComponentManagerHost->ioService; return HDF_SUCCESS; } ``` -- **HdfCodecComponentTypeDriverInit**: loads the attribute configuration from the HDF configuration source (HCS). +- **HdfCodecComponentManagerDriverInit**: loads the attribute configuration from the HDF Configuration Source (HCS). ```c - int32_t HdfCodecComponentTypeDriverInit(struct HdfDeviceObject *deviceObject) + static int HdfCodecComponentManagerDriverInit(struct HdfDeviceObject *deviceObject) { - HDF_LOGI("HdfCodecComponentTypeDriverInit enter."); - if (deviceObject == NULL) { - return HDF_FAILURE; - } - InitDataNode(deviceObject->property); - if (LoadCapabilityData() != HDF_SUCCESS) { - ClearCapabilityData(); + CODEC_LOGI("HdfCodecComponentManagerDriverInit enter"); + if (DevHostRegisterDumpHost(CodecDfxService::DevCodecHostDump) != HDF_SUCCESS) { + CODEC_LOGE("DevHostRegisterDumpHost error!"); } return HDF_SUCCESS; } ``` - + - **HdfCodecComponentTypeDriverRelease**: releases the driver instance. ```c - void HdfCodecComponentTypeDriverRelease(struct HdfDeviceObject *deviceObject) + static void HdfCodecComponentManagerDriverRelease(struct HdfDeviceObject *deviceObject) { - HDF_LOGI("HdfCodecComponentTypeDriverRelease enter."); - struct HdfCodecComponentTypeHost *omxcomponenttypeHost = - CONTAINER_OF(deviceObject->service, struct HdfCodecComponentTypeHost, ioservice); - OmxComponentManagerSeriveRelease(omxcomponenttypeHost->service); - OsalMemFree(omxcomponenttypeHost); - ClearCapabilityData(); + CODEC_LOGI("HdfCodecComponentManagerDriverRelease enter"); + if (deviceObject->service == nullptr) { + CODEC_LOGE("HdfCodecComponentManagerDriverRelease not initted"); + return; + } + + auto *hdfCodecComponentManagerHost = + CONTAINER_OF(deviceObject->service, struct HdfCodecComponentManagerHost, ioService); + delete hdfCodecComponentManagerHost; } ``` -#### Driver HCS +#### Configuring the Driver HCS The HCS consists of the following: - Device configuration @@ -172,48 +175,53 @@ The HCS consists of the following: The HCS includes the driver node, loading sequence, and service name. For details about the HCS syntax, see [Configuration Management](driver-hdf-manage.md). -Configuration file Path of the standard system: -vendor/hihope/rk3568/hdf_config/uhdf/ +The following uses the RK3568 development board as an example. The configuration files of the standard system are in the **vendor/hihope/rk3568/hdf_config/uhdf/** directory. + +1. Configure the device. + + Add the **codec_component_manager_service** configuration to **codec_host** in **device_info.hcs**. -1. Device configuration + Example: - Add the **codec_omx_service** configuration to **codec_host** in **device_info.hcs**. The following is an example: ```c codec :: host { hostName = "codec_host"; priority = 50; gid = ["codec_host", "uhdf_driver", "vendor_mpp_driver"]; - codec_omx_device :: device { + codec_omx_idl_device :: device { device0 :: deviceNode { policy = 2; // Automatic loading, not lazy loading. priority = 100; // Priority. - moduleName = "libcodec_hdi_omx_server.z.so"; // Dynamic library of the driver. - serviceName = "codec_hdi_omx_service"; // Service name of the driver. - deviceMatchAttr = "codec_component_capabilities"; //Attribute configuration. + moduleName = "libcodec_driver.z.so"; // Dynamic library of the driver. + serviceName = "codec_component_manager_service"; // Service name of the driver. + deviceMatchAttr = "media_codec_capabilities"; // Attribute configuration. } } } ``` -2. Configuration of supported components +2. Configure supported components. - Add the component configuration to the **media_codec\codec_component_capabilities.hcs file**. The following is an example: + Add the component configuration to the **media_codec\media_codec_capabilities.hcs** file. + + Example: + ```c /* node name explanation -- HDF_video_hw_enc_avc_rk: ** ** HDF____________video__________________hw____________________enc____________avc_______rk ** | | | | | | - ** HDF or OMX video or audio hardware or software encoder or decoder mime vendor + ** HDF or OMX video or audio hardware or software encoder or decoder MIME vendor */ HDF_video_hw_enc_avc_rk { - role = 1; // Role of the AvCodec. + role = 1; // Role of the audio and video codec. type = 1; // Codec type. name = "OMX.rk.video_encoder.avc"; // Component name. supportProfiles = [1, 32768, 2, 32768, 8, 32768]; // Supported profiles. maxInst = 4; // Maximum number of instances. isSoftwareCodec = false; // Whether it is software codec. processModeMask = []; // Codec processing mode. - capsMask = [0x01]; // Codec playback capabilities. + capsMask = [0x01]; // CodecCapsMask configuration. minBitRate = 1; // Minimum bit rate. maxBitRate = 40000000; // Maximum bit rate. minWidth = 176; // Minimum video width. @@ -228,10 +236,10 @@ vendor/hihope/rk3568/hdf_config/uhdf/ maxBlocksPerSecond = 0xFFFFFFFF; blockSizeWidth = 0xFFFFFFFF; blockSizeHeight = 0xFFFFFFFF; - supportPixelFmts = [28, 24, 30, 22, 7, 3, 14, 13, 20, 26, 27, 12]; // List of supported colors. + supportPixelFmts = [28, 24, 20, 12]; // List of colors supported by the display. measuredFrameRate = [320, 240, 165, 165, 720, 480, 149, 149, 1280, 720, 73, 73, 1920, 1080, 18, 18]; - bitRateMode = [1, 2]; // Bit rate mode. - minFrameRate = 0; // Frame rate. + bitRateMode = [1, 2]; // Bit rate mode. + minFrameRate = 0; // Frame rate. maxFrameRate = 0; } ``` @@ -239,42 +247,37 @@ vendor/hihope/rk3568/hdf_config/uhdf/ ### Development Example After completing codec module driver adaptation, use the HDI APIs provided by the codec module for further development. The codec HDI provides the following features: -1. Provides codec HDI APIs for video services to implement encoding and decoding of video services. -2. Provides standard interfaces for device developers to ensure that the OEM vendors comply with the HDI adapter standard. This promises a healthy evolution of the ecosystem. +- Provides codec HDI APIs for video services to implement encoding and decoding for video services. +- Provides standard interfaces for device developers to ensure that the OEM vendors comply with the HDI adapter standard. This promises a healthy evolution of the ecosystem. The development procedure is as follows: 1. Initialize the driver, including initializing the instances, callbacks, and component. 2. Set codec parameters and information such as the video width, height, and bit rate. 3. Apply for input and output buffers. -4. Flip codec buffers, enable the component to enter the **OMX_Executing** state, and process the callbacks. -5. Deinitialize the interface instance, destroy the buffers, close the component, and releases all interface objects. +4. Flip codec buffers, enable the component to enter the **CODEC_STATE_EXECUTING** state, and process the callbacks. +5. Deinitialize the interface instance, destroy the buffers, close the component, and releases all interface instances. #### Initializing the Driver Initialize the interface instance and callbacks, and create a component. ```cpp // Initialize the codec HDI ComponentManager instance. -omxMgr_ = GetCodecComponentManager(); - +omxMgr_ = ICodecComponentManager::Get(false); +if ((omxMgr_ == nullptr)) { + HDF_LOGE("%{public}s omxMgr_ is null", __func__); + return false; +} // Initialize the callback. -callback_ = CodecCallbackTypeStubGetInstance(); -if (!omxMgr_ || !callback_) { - FUNC_EXIT_ERR(); +callback_ = new CodecHdiCallback(shared_from_this()); +if ((callback_ == nullptr)) { + HDF_LOGE("%{public}s callback_ is null", __func__); return false; } -// Set the callback pointers. -callback_->EventHandler = &OMXCore::OnEvent; -callback_->EmptyBufferDone = &OMXCore::OnEmptyBufferDone; -callback_->FillBufferDone = &OMXCore::OnFillBufferDone; - // Create a component instance. -uint32_t err = HDF_SUCCESS; -if (codec == codecMime::AVC) { - err = omxMgr_->CreateComponent(&client_, &componentId_, const_cast(DECODER_AVC), (int64_t)this, - callback_); -} else { - err = omxMgr_->CreateComponent(&client_, &componentId_, const_cast(DECODER_HEVC), (int64_t)this, - callback_); +err = omxMgr_->CreateComponent(client_, componentId_, compName, reinterpret_cast(this), callback_); +if (err != HDF_SUCCESS) { + HDF_LOGE("%{public}s failed to CreateComponent", __func__); + return false; } ``` @@ -283,64 +286,79 @@ Set the width and height of the input and output data, input data format, and ou ```cpp // Set the width and height of the input image. OMX_PARAM_PORTDEFINITIONTYPE param; -InitParam(param); -param.nPortIndex = (uint32_t)PortIndex::PORT_INDEX_INPUT; -auto err = client_->GetParameter(client_, OMX_IndexParamPortDefinition, (int8_t *)¶m, sizeof(param)); +if (util_->InitParam(param) != HDF_SUCCESS) { + return HDF_FAILURE; +} +param.nPortIndex = static_cast(PortIndex::PORT_INDEX_INPUT); + +std::vector inVec, outVec; +util_->ObjectToVector(param, inVec); +auto err = client_->GetParameter(OMX_IndexParamPortDefinition, inVec, outVec); if (err != HDF_SUCCESS) { - HDF_LOGE("%{public}s failed PortIndex::PORT_INDEX_INPUT, index is OMX_IndexParamPortDefinition", __func__); - return false; + HDF_LOGE("%{public}s failed PortIndex::PORT_INDEX_INPUT, index is OMX_IndexParamPortDefinition", __func__); + return err; } +util_->VectorToObject(outVec, param); + HDF_LOGI("PortIndex::PORT_INDEX_INPUT: eCompressionFormat = %{public}d, eColorFormat = %{public}d ", param.format.video.eCompressionFormat, param.format.video.eColorFormat); -param.format.video.nFrameWidth = width_; -param.format.video.nFrameHeight = height_; -param.format.video.nStride = width_; -param.format.video.nSliceHeight = height_; -err = client_->SetParameter(client_, OMX_IndexParamPortDefinition, (int8_t *)¶m, sizeof(param)); +util_->setParmValue(param, width_, height_, stride_); +util_->ObjectToVector(param, inVec); +err = client_->SetParameter(OMX_IndexParamPortDefinition, inVec); if (err != HDF_SUCCESS) { HDF_LOGE("%{public}s failed with PortIndex::PORT_INDEX_INPUT, index is OMX_IndexParamPortDefinition", __func__); - return false; + return err; } // Set the output width, height, and format. -InitParam(param); -param.nPortIndex = (uint32_t)PortIndex::PORT_INDEX_OUTPUT; -err = client_->GetParameter(client_, OMX_IndexParamPortDefinition, (int8_t *)¶m, sizeof(param)); +if (util_->InitParam(param) != HDF_SUCCESS) { + return HDF_FAILURE; +} +param.nPortIndex = static_cast(PortIndex::PORT_INDEX_OUTPUT); +util_->ObjectToVector(param, inVec); +err = client_->GetParameter(OMX_IndexParamPortDefinition, inVec, outVec); if (err != HDF_SUCCESS) { - HDF_LOGE("%{public}s failed with PortIndex::PORT_INDEX_OUTPUT, index is OMX_IndexParamPortDefinition", __func__); - return false; + HDF_LOGE("%{public}s failed with PortIndex::PORT_INDEX_OUTPUT, index is OMX_IndexParamPortDefinition", + __func__); + return err; } +util_->VectorToObject(outVec, param); + HDF_LOGI("PortIndex::PORT_INDEX_OUTPUT eCompressionFormat = %{public}d, eColorFormat=%{public}d", param.format.video.eCompressionFormat, param.format.video.eColorFormat); -param.format.video.nFrameWidth = width_; -param.format.video.nFrameHeight = height_; -param.format.video.nStride = width_; -param.format.video.nSliceHeight = height_; +util_->setParmValue(param, width_, height_, stride_); param.format.video.eColorFormat = AV_COLOR_FORMAT; // Set the output data format to YUV420SP. -err = client_->SetParameter(client_, OMX_IndexParamPortDefinition, (int8_t *)¶m, sizeof(param)); +err = client_->SetParameter(OMX_IndexParamPortDefinition, inVec); if (err != HDF_SUCCESS) { HDF_LOGE("%{public}s failed with PortIndex::PORT_INDEX_OUTPUT, index is OMX_IndexParamPortDefinition", __func__); - return false; + return err; } // Set the input data format to H.264/H.265. OMX_VIDEO_PARAM_PORTFORMATTYPE param; -InitParam(param); +if (util_->InitParam(param) != HDF_SUCCESS) { + return false; +} param.nPortIndex = (uint32_t)PortIndex::PORT_INDEX_INPUT; -auto err = client_->GetParameter(client_, OMX_IndexParamVideoPortFormat, (int8_t *)¶m, sizeof(param)); +std::vector inVec, outVec; +util_->ObjectToVector(param, inVec); +auto err = client_->GetParameter(OMX_IndexParamVideoPortFormat, inVec, outVec); if (err != HDF_SUCCESS) { HDF_LOGE("%{public}s failed with PortIndex::PORT_INDEX_INPUT", __func__); return false; } +util_->VectorToObject(outVec, param); + HDF_LOGI("set Format PortIndex::PORT_INDEX_INPUT eCompressionFormat = %{public}d, eColorFormat=%{public}d", param.eCompressionFormat, param.eColorFormat); -param.xFramerate = FRAME; // Set the frame rate to 30. +param.xFramerate = FRAME // Set the frame rate to 30. if (codecMime_ == codecMime::AVC) { param.eCompressionFormat = OMX_VIDEO_CodingAVC; // H264 } else { param.eCompressionFormat = (OMX_VIDEO_CODINGTYPE)CODEC_OMX_VIDEO_CodingHEVC; // H265 } -err = client_->SetParameter(client_, OMX_IndexParamVideoPortFormat, (int8_t *)¶m, sizeof(param)); +util_->ObjectToVector(param, inVec); +err = client_->SetParameter(OMX_IndexParamVideoPortFormat, inVec); if (err != HDF_SUCCESS) { HDF_LOGE("%{public}s failed with PortIndex::PORT_INDEX_INPUT", __func__); return false; @@ -352,90 +370,97 @@ Perform the following steps: 1. Use **UseBuffer()** to apply for input and output buffers and save the buffer IDs. The buffer IDs can be used for subsequent buffer flipping. 2. Check whether the corresponding port is enabled. If not, enable the port first. -3. Use **SendCommand()** to change the component status to OMX_StateIdle, and wait until the operation result is obtained. +3. Use **SendCommand()** to change the component status to **CODEC_STATE_IDLE**, and wait until the operation result is obtained. ```cpp // Apply for the input buffer. -auto ret = UseBufferOnPort(PortIndex::PORT_INDEX_INPUT); -if (!ret) { +auto err = UseBufferOnPort(PortIndex::PORT_INDEX_INPUT); +if (err != HDF_SUCCESS) { HDF_LOGE("%{public}s UseBufferOnPort PortIndex::PORT_INDEX_INPUT error", __func__); return false; } // Apply for the output buffer. -ret = UseBufferOnPort(PortIndex::PORT_INDEX_OUTPUT); -if (!ret) { +err = UseBufferOnPort(PortIndex::PORT_INDEX_OUTPUT); +if (err != HDF_SUCCESS) { HDF_LOGE("%{public}s UseBufferOnPort PortIndex::PORT_INDEX_OUTPUT error", __func__); return false; } // Enable the component to enter the OMX_StateIdle state. -auto err = client_->SendCommand(client_, OMX_CommandStateSet, OMX_StateIdle, NULL, 0); +std::vector cmdData; +auto err = client_->SendCommand(CODEC_COMMAND_STATE_SET, CODEC_STATE_IDLE, cmdData); if (err != HDF_SUCCESS) { - HDF_LOGE("%{public}s failed to SendCommand with OMX_CommandStateSet:OMX_StateIdle", __func__); + HDF_LOGE("%{public}s failed to SendCommand with CODEC_COMMAND_STATE_SET:CODEC_STATE_IDLE", __func__); return false; } -HDF_LOGI("Wait for OMX_StateIdle status"); -this->WaitForStatusChanged(); ``` -Implement **UseBufferOnPort** as follows: +Implement **UseBufferOnPort()** as follows: ```cpp -bool CodecHdiDecode::UseBufferOnPort(enum PortIndex portIndex) +int32_t CodecHdiDecode::UseBufferOnPort(PortIndex portIndex) { HDF_LOGI("%{public}s enter, portIndex = %{public}d", __func__, portIndex); int bufferSize = 0; int bufferCount = 0; - bool bPortEnable = false; + bool PortEnable = false; // Obtain parameters of the port buffer. OMX_PARAM_PORTDEFINITIONTYPE param; - InitParam(param); - param.nPortIndex = (OMX_U32)portIndex; - auto err = client_->GetParameter(client_, OMX_IndexParamPortDefinition, (int8_t *)¶m, sizeof(param)); + if (util_->InitParam(param) != HDF_SUCCESS) { + return HDF_FAILURE; + } + param.nPortIndex = static_cast(portIndex); + + std::vector inVec, outVec; + util_->ObjectToVector(param, inVec); + auto err = client_->GetParameter(OMX_IndexParamPortDefinition, inVec, outVec); if (err != HDF_SUCCESS) { HDF_LOGE("%{public}s failed to GetParameter with OMX_IndexParamPortDefinition : portIndex[%{public}d]", - __func__, portIndex); - return false; + __func__, portIndex); + return err; } + util_->VectorToObject(outVec, param); + bufferSize = param.nBufferSize; bufferCount = param.nBufferCountActual; - bPortEnable = param.bEnabled; + portEnable = param.bEnabled; HDF_LOGI("buffer index [%{public}d], buffer size [%{public}d], " - "buffer count [%{public}d], portEnable[%{public}d], err [%{public}d]", - portIndex, bufferSize, bufferCount, bPortEnable, err); - { - OMX_PARAM_BUFFERSUPPLIERTYPE param; - InitParam(param); - param.nPortIndex = (uint32_t)portIndex; - auto err = client_->GetParameter(client_, OMX_IndexParamCompBufferSupplier, (int8_t *)¶m, sizeof(param)); - HDF_LOGI("param.eBufferSupplier[%{public}d] isSupply [%{public}d], err [%{public}d]", param.eBufferSupplier, - this->isSupply_, err); - } + "buffer count [%{public}d], portEnable[%{public}d], ret [%{public}d]", + portIndex, bufferSize, bufferCount, portEnable, err); // Set the port buffer. - UseBufferOnPort(portIndex, bufferCount, bufferSize); + if (useBufferHandle_ && portIndex == PortIndex::PORT_INDEX_OUTPUT) { + err = UseBufferHandle(bufferCount, bufferSize); + } else { + err = UseBufferOnPort(portIndex, bufferCount, bufferSize); + } // Check whether the port is available. - if (!bPortEnable) { - auto err = client_->SendCommand(client_, OMX_CommandPortEnable, (uint32_t)portIndex, NULL, 0); + if (!portEnable) { + err = client_->SendCommand(CODEC_COMMAND_PORT_ENABLE, static_cast(portIndex), {}); if (err != HDF_SUCCESS) { HDF_LOGE("%{public}s SendCommand OMX_CommandPortEnable::PortIndex::PORT_INDEX_INPUT error", __func__); - return false; + return err; } } - return true; + return HDF_SUCCESS; } -bool CodecHdiDecode::UseBufferOnPort(enum PortIndex portIndex, int bufferCount, int bufferSize) +int32_t CodecHdiDecode::UseBufferOnPort(PortIndex portIndex, int bufferCount, int bufferSize) { + if (bufferCount <= 0 || bufferSize <= 0) { + HDF_LOGE("UseBufferOnPort bufferCount <= 0 or bufferSize <= 0"); + return HDF_ERR_INVALID_PARAM; + } for (int i = 0; i < bufferCount; i++) { - OmxCodecBuffer *omxBuffer = new OmxCodecBuffer(); - memset_s(omxBuffer, sizeof(OmxCodecBuffer), 0, sizeof(OmxCodecBuffer)); + std::shared_ptr omxBuffer = std::make_shared(); omxBuffer->size = sizeof(OmxCodecBuffer); omxBuffer->version.s.nVersionMajor = 1; - omxBuffer->bufferType = BUFFER_TYPE_AVSHARE_MEM_FD; + omxBuffer->bufferType = CODEC_BUFFER_TYPE_AVSHARE_MEM_FD; int fd = AshmemCreate(0, bufferSize); shared_ptr sharedMem = make_shared(fd, bufferSize); - omxBuffer->bufferLen = FD_SIZE; - omxBuffer->buffer = (uint8_t *)(unsigned long)fd; + omxBuffer->fd = fd; + omxBuffer->bufferhandle = nullptr; omxBuffer->allocLen = bufferSize; omxBuffer->fenceFd = -1; + omxBuffer->pts = 0; + omxBuffer->flag = 0; if (portIndex == PortIndex::PORT_INDEX_INPUT) { omxBuffer->type = READ_ONLY_TYPE; // ReadOnly @@ -444,84 +469,75 @@ bool CodecHdiDecode::UseBufferOnPort(enum PortIndex portIndex, int bufferCount, omxBuffer->type = READ_WRITE_TYPE; sharedMem->MapReadOnlyAshmem(); } - auto err = client_->UseBuffer(client_, (uint32_t)portIndex, omxBuffer); + OmxCodecBuffer outBuffer; + auto err = client_->UseBuffer((uint32_t)portIndex, *omxBuffer.get(), outBuffer); if (err != HDF_SUCCESS) { HDF_LOGE("%{public}s failed to UseBuffer with portIndex[%{public}d]", __func__, portIndex); sharedMem->UnmapAshmem(); sharedMem->CloseAshmem(); sharedMem = nullptr; - return false; + return err; } - omxBuffer->bufferLen = 0; + omxBuffer->bufferId = outBuffer.bufferId; + omxBuffer->fd = -1; HDF_LOGI("UseBuffer returned bufferID [%{public}d]", omxBuffer->bufferId); - BufferInfo *bufferInfo = new BufferInfo; + std::shared_ptr bufferInfo = std::make_shared(); bufferInfo->omxBuffer = omxBuffer; bufferInfo->avSharedPtr = sharedMem; bufferInfo->portIndex = portIndex; - omxBuffers_.insert(std::make_pair(omxBuffer->bufferId, std::move(bufferInfo))); + omxBuffers_.emplace(std::make_pair(omxBuffer->bufferId, bufferInfo)); if (portIndex == PortIndex::PORT_INDEX_INPUT) { unUsedInBuffers_.push_back(omxBuffer->bufferId); } else { unUsedOutBuffers_.push_back(omxBuffer->bufferId); } - int fdret = (int)omxBuffer->buffer; - HDF_LOGI("{bufferID = %{public}d, srcfd = %{public}d, retfd = %{public}d}", omxBuffer->bufferId, fd, fdret); } - return true; + + return HDF_SUCCESS; } ``` -#### Codec Buffer Flipping -Set the component to the **OMX_StateExecuting** state, fill the input buffer, read data from the output buffer, and flip the buffers. +#### Flipping Codec Buffers +Set the component to the **CODEC_STATE_EXECUTING** state, fill the input buffer, read data from the output buffer, and flip the buffers. ```cpp // Set the component to the OMX_StateExecuting state and start buffer flipping. -HDF_LOGI("...command to OMX_StateExecuting...."); -auto err = client_->SendCommand(client_, OMX_CommandStateSet, OMX_StateExecuting, NULL, 0); +HDF_LOGI("...command to CODEC_STATE_EXECUTING...."); +auto err = client_->SendCommand(CODEC_COMMAND_STATE_SET, CODEC_STATE_EXECUTING, {}); if (err != HDF_SUCCESS) { - HDF_LOGE("%{public}s failed to SendCommand with OMX_CommandStateSet:OMX_StateIdle", __func__); + HDF_LOGE("%{public}s failed to SendCommand with CODEC_COMMAND_STATE_SET:CODEC_STATE_IDLE", __func__); return; } -// Set the output buffer. -for (auto bufferId : unUsedOutBuffers_) { - HDF_LOGI("fill bufferid [%{public}d]", bufferId); - auto iter = omxBuffers_.find(bufferId); - if (iter != omxBuffers_.end()) { - BufferInfo *bufferInfo = iter->second; - auto err = client_->FillThisBuffer(client_, bufferInfo->pOmxBuffer); - if (err != HDF_SUCCESS) { - HDF_LOGE("FillThisBuffer error"); - FUNC_EXIT_ERR(); - return; - } - } +// Set the output buffer to fill. +if (!FillAllTheBuffer()) { + HDF_LOGE("%{public}s FillAllTheBuffer error", __func__); + return; } // Fill the input buffer. -bool bEndOfFile = false; -while (!bEndOfFile) { - int bufferID = GetFreeBufferId(); +auto t1 = std::chrono::system_clock::now(); +bool eosFlag = false; +while (!eosFlag) { if (this->exit_) { break; } + int bufferID = GetFreeBufferId(); if (bufferID < 0) { - usleep(10000); + usleep(10000); // 10000 for wait 10ms continue; } auto iter = omxBuffers_.find(bufferID); if (iter == omxBuffers_.end()) { continue; } - BufferInfo *bufferInfo = iter->second; - void *sharedAddr = (void *)bufferInfo->avSharedPtr->ReadFromAshmem(0, 0); - bool bEOS = (size_t)this->ReadOnePacket(fpIn_, (char *)sharedAddr, bufferInfo->omxBuffer->filledLen); - HDF_LOGI("read data size is %{public}d", bufferInfo->omxBuffer->filledLen); + auto bufferInfo = iter->second; + void *sharedAddr = const_cast(bufferInfo->avSharedPtr->ReadFromAshmem(0, 0)); + eosFlag = this->ReadOnePacket(fpIn_, static_cast(sharedAddr), bufferInfo->omxBuffer->filledLen); bufferInfo->omxBuffer->offset = 0; - if (bEOS) { + if (eosFlag) { bufferInfo->omxBuffer->flag = OMX_BUFFERFLAG_EOS; - bEndOfFile = true; } - auto err = client_->EmptyThisBuffer(client_, bufferInfo->omxBuffer); + err = client_->EmptyThisBuffer(*bufferInfo->omxBuffer.get()); if (err != HDF_SUCCESS) { HDF_LOGE("%{public}s EmptyThisBuffer error", __func__); return; @@ -529,181 +545,186 @@ while (!bEndOfFile) { } // Wait. while (!this->exit_) { - usleep(10000); - continue; + usleep(10000); // 10000 for wait 10ms } // Enable the component to enter the OMX_StateIdle state after decoding. -client_->SendCommand(client_, OMX_CommandStateSet, OMX_StateIdle, NULL, 0); +auto t2 = std::chrono::system_clock::now(); +std::chrono::duration diff = t2 - t1; +HDF_LOGI("cost %{public}f, count=%{public}d", diff.count(), count_); +(void)client_->SendCommand(CODEC_COMMAND_STATE_SET, CODEC_STATE_IDLE, {}); +return; +} ``` Automatic framing is not supported in rk OMX decoding. Therefore, you need to manually divide data into frames. Currently, data is divided into frames from code 0x000001 or 0x00000001 and sent to the server for processing. The sample code is as follows: ```cpp // Read a file by frame. -bool OMXCore::ReadOnePacket(FILE* fp, char* buf, uint32_t& nFilled) +bool CodecHdiDecode::ReadOnePacket(FILE *fp, char *buf, uint32_t &filledCount) { - // Read four bytes first. - size_t t = fread(buf, 1, 4, fp); - if (t < 4) { - // The file reading ends. + // Read the start code. + size_t t = fread(buf, 1, START_CODE_SIZE_FRAME, fp); + if (t < START_CODE_SIZE_FRAME) { return true; } - size_t filled = 0; - filled = 4; - - bool bRet = true; + char *temp = buf; + temp += START_CODE_SIZE_FRAME; + bool ret = true; while (!feof(fp)) { - fread(buf + filled, 1, 1, fp); - if (buf[filled] == 1) { - // Check the start code. - if ((buf[filled - 1] == 0) && - (buf[filled - 2] == 0) && - (buf[filled - 3] == 0)) { - fseek(fp, -4, SEEK_CUR); - filled -= 3; - bRet = false; - break; - } else if ((buf[filled - 1] == 0) && - (buf[filled - 2] == 0)) { - fseek(fp, -3, SEEK_CUR); - filled -= 2; - bRet = false; - break; + (void)fread(temp, 1, 1, fp); + if (*temp != START_CODE) { + temp++; + continue; + } + // Check the start code. + if ((temp[START_CODE_OFFSET_ONE] == 0) && (temp[START_CODE_OFFSET_SEC] == 0) && + (temp[START_CODE_OFFSET_THIRD] == 0)) { + fseek(fp, -START_CODE_SIZE_FRAME, SEEK_CUR); + temp -= (START_CODE_SIZE_FRAME - 1); + ret = false; + break; } + if ((temp[START_CODE_OFFSET_ONE] == 0) && (temp[START_CODE_OFFSET_SEC] == 0)) { + fseek(fp, -START_CODE_SIZE_SLICE, SEEK_CUR); + temp -= (START_CODE_SIZE_SLICE - 1); + ret = false; + break; } - filled++; + temp++; } - nFilled = filled; - return bRet; + filledCount = (temp - buf); + return ret; } ``` The codec HDI provides the following callbacks: -- **EventHandler**: Called when a command is executed. For example, when the command for changing the component state from **OMX_StateIdle** to **OMX_StateExecuting** is executed, this callback is invoked to return the result. -- **EmptyBufferDone**: Called when the input data is consumed. If the client needs to fill in data to encode or decode, call **EmptyThisBuffer()**. -- **FillBufferDone**: Called when the output data is filled. If the client needs to read the encoded or decoded data, call **FillThisBuffer()**. +- **EventHandler**: Called when a command is executed. For example, when the command for changing the component state from **CODEC_STATE_IDLE** to **CODEC_STATE_EXECUTING** is executed, this callback is invoked to return the result. +- **EmptyBufferDone**: Called when the input data is consumed. If the client needs to fill data to encode or decode, it must call **EmptyThisBuffer()** again. +- **FillBufferDone**: Called when the output data is filled. If the client needs to read the encoded or decoded data, it must call **FillThisBuffer()** again. ```cpp // EmptyBufferDone example -int32_t OMXCore::OnEmptyBufferDone(struct CodecCallbackType *self, int8_t *pAppData, uint32_t pAppDataLen, - const struct OmxCodecBuffer *pBuffer) -{ - HDF_LOGI("onEmptyBufferDone: pBuffer.bufferID [%{public}d]", pBuffer->bufferId); - g_core->OnEmptyBufferDone(pBuffer); - return HDF_SUCCESS; -} -int32_t OMXCore::OnEmptyBufferDone(const struct OmxCodecBuffer *pBuffer) +int32_t CodecHdiDecode::OnEmptyBufferDone(const struct OmxCodecBuffer &buffer) { - unique_lock ulk(mLockInputBuffers_); - unUsedInBuffers_.push_back(pBuffer->bufferId); + HDF_LOGI("OnEmptyBufferDone, bufferId [%{public}d]", buffer.bufferId); + unique_lock ulk(lockInputBuffers_); + unUsedInBuffers_.push_back(buffer.bufferId); return HDF_SUCCESS; } // FillBufferDone example -int32_t OMXCore::OnFillBufferDone(struct CodecCallbackType *self, int8_t *pAppData, uint32_t pAppDataLen, - struct OmxCodecBuffer *pBuffer) +int32_t CodecHdiDecode::OnFillBufferDone(const struct OmxCodecBuffer &buffer) { - HDF_LOGI("onFillBufferDone: pBuffer.bufferID [%{public}d]", pBuffer->bufferId); - g_core->OnFillBufferDone(pBuffer); - return HDF_SUCCESS; -} -int32_t OMXCore::onFillBufferDone(struct OmxCodecBuffer* pBuffer) -{ - // Locate the buffer based on the buffer ID. - if (bExit_) { + HDF_LOGI("OnFillBufferDone, bufferId [%{public}d]", buffer.bufferId); + if (exit_) { return HDF_SUCCESS; } - auto iter = omxBuffers_.find(pBuffer->bufferId); - if (iter == omxBuffers_.end() || !iter->second) { + auto iter = omxBuffers_.find(buffer.bufferId); + if ((iter == omxBuffers_.end()) || (iter->second == nullptr)) { return HDF_SUCCESS; } - // Obtain the output data. - BufferInfo *pBufferInfo = iter->second; - const void *addr = pBufferInfo->avSharedPtr->ReadFromAshmem(pBuffer->filledLen, pBuffer->offset); - // Decode the data and save it to a file. - fwrite(addr, 1, pBuffer->filledLen, fpOut_.get()); - fflush(fpOut_.get()); - // Reset the buffer data. - pBuffer->offset = 0; - pBuffer->filledLen = 0; - if (pBuffer->flag == OMX_BUFFERFLAG_EOS) { - // End - bExit_ = true; + count_++; + // read buffer + auto bufferInfo = iter->second; + if (bufferInfo->avSharedPtr != nullptr) { + const void *addr = bufferInfo->avSharedPtr->ReadFromAshmem(buffer.filledLen, buffer.offset); + (void)fwrite(addr, 1, buffer.filledLen, fpOut_); + } else if (bufferInfo->bufferHandle != nullptr && gralloc_ != nullptr) { + gralloc_->Mmap(*bufferInfo->bufferHandle); + (void)fwrite(bufferInfo->bufferHandle->virAddr, 1, buffer.filledLen, fpOut_); + gralloc_->Unmap(*bufferInfo->bufferHandle); + } + + (void)fflush(fpOut_); + if (buffer.flag == OMX_BUFFERFLAG_EOS) { + // end + exit_ = true; HDF_LOGI("OnFillBufferDone the END coming"); return HDF_SUCCESS; } - // Call FillThisBuffer() again. - auto err = client_->FillThisBuffer(client_, pBufferInfo->pOmxBuffer); + // call fillthisbuffer again + auto err = client_->FillThisBuffer(*bufferInfo->omxBuffer.get()); if (err != HDF_SUCCESS) { - HDF_LOGE("FillThisBuffer error"); + HDF_LOGE("%{public}s FillThisBuffer error", __func__); return HDF_SUCCESS; } return HDF_SUCCESS; } - // EventHandler example -int32_t CodecHdiDecode::OnEvent(struct CodecCallbackType *self, enum OMX_EVENTTYPE event, struct EventInfo *info) +int32_t CodecHdiDecode::EventHandler(CodecEventType event, const EventInfo &info) { - HDF_LOGI("onEvent: appData[0x%{public}p], eEvent [%{public}d], " - "nData1[%{public}d]", - info->appData, event, info->data1); switch (event) { - case OMX_EventCmdComplete: { - OMX_COMMANDTYPE cmd = (OMX_COMMANDTYPE)info->data1; - if (OMX_CommandStateSet == cmd) { - HDF_LOGI("OMX_CommandStateSet reached, status is %{public}d", info->data2); - g_core->onStatusChanged(); + case CODEC_EVENT_CMD_COMPLETE: { + CodecCommandType cmd = (CodecCommandType)info.data1; + if (CODEC_COMMAND_STATE_SET == cmd) { + HDF_LOGI("CODEC_COMMAND_STATE_SET reached, status is %{public}d", info.data2); + this->OnStatusChanged(); } break; } + case OMX_EventPortSettingsChanged: { + HDF_LOGI("OMX_EventPortSeetingsChanged reached"); + this->HandleEventPortSettingsChanged(info.data1, info.data2); + } + default: break; } + return HDF_SUCCESS; } ``` #### Destroying a Component -Change the component state to IDLE, release the input and output buffers, change the component state to **OMX_StateLoaded**, and call **DestoryComponent** to destroy the component. +Change the component state to **CODEC_STATE_IDLE**, release the input and output buffers, change the component state to **CODEC_STATE_LOADED**, and call **DestoryComponent** to destroy the component. -##### Example of Releasing Buffers +##### Releasing Buffers ```cpp // Change the component state to OMX_StateLoaded. -client_->SendCommand(client_, OMX_CommandStateSet, OMX_StateLoaded, nullptr, 0); +client_->SendCommand(CODEC_COMMAND_STATE_SET, CODEC_STATE_LOADED, {}); // Release all buffers in use. auto iter = omxBuffers_.begin(); while (iter != omxBuffers_.end()) { - BufferInfo *bufferInfo = iter->second; - client_->FreeBuffer(client_, (uint32_t)bufferInfo->portIndex, bufferInfo->omxBuffer); - delete bufferInfo; - iter++; + auto bufferInfo = iter->second; + iter = omxBuffers_.erase(iter); + (void)client_->FreeBuffer((uint32_t)bufferInfo->portIndex, *bufferInfo->omxBuffer.get()); + bufferInfo = nullptr; } -omxBuffers_.clear(); + unUsedInBuffers_.clear(); unUsedOutBuffers_.clear(); -enum OMX_STATETYPE status; -client_->GetState(client_, &status); // After the buffers are released, the component enters the OMX_StateLoaded state. -if (status != OMX_StateLoaded) { - HDF_LOGI("Wait for OMX_StateLoaded status"); - this->WaitForStatusChanged(); -} else { - HDF_LOGI(" status is %{public}d", status); -} +CodecStateType status = CODEC_STATE_INVALID; +int32_t err = HDF_SUCCESS; +int32_t tryCount = 3; +do { + err = client_->GetState(status); + if (err != HDF_SUCCESS) { + HDF_LOGE("%s GetState error [%{public}x]", __func__, err); + break; + } + if (status != CODEC_STATE_LOADED) { + HDF_LOGI("Wait for OMX_StateLoaded status"); + this->WaitForStatusChanged(); + } + tryCount--; +} while ((status != CODEC_STATE_LOADED) && (tryCount > 0)); ``` -##### Example of Destroying a Component Instance +##### Destroying a Component Instance ```cpp // Destroy a component instance. -void OMXCore::Release() { - omxMgr_->DestoryComponent(client_); +void CodecHdiDecode::Release() +{ + omxMgr_->DestoryComponent(componentId_); client_ = nullptr; - CodecComponentManagerRelease(); + callback_ = nullptr; + omxMgr_ = nullptr; } ``` @@ -721,7 +742,7 @@ OpenMAX does not support framing. **Solution** -Transfer data frame by frame when **EmptyThisBuffer** is called. +When **EmptyThisBuffer** is call, only one frame can be passed in at a time. ## Only Green Screen Displayed During the Decoding Process @@ -745,15 +766,12 @@ After the generated video stream (H.264 stream) is written to a file, the video **Possible Causes** -- The **xFramerate** parameter of the output port is incorrectly set. -- The **OMX_VIDEO_PARAM_AVCTYPE** parameter is correctly set. - +1. The **xFramerate** parameter of the output port is incorrectly set. +2. The **OMX_VIDEO_PARAM_AVCTYPE** parameter is correctly set. **Solution** -View the **codec_host** log generated during encoding, search for "encode params init settings", and check for incorrect parameters. If **framerate** is **0**, **xFramerate** is incorrectly set. In this case, move the framerate leftwards by 16 bits. - -Check the value of **OMX_VIDEO_PARAM_AVCTYPE**, and set it correctly. +View the **codec_host** log generated during encoding, search for "encode params init settings", and check for incorrect parameters. If **framerate** is **0**, **xFramerate** is incorrectly set. In this case, move the frame rate leftwards by 16 bits.
In other cases, correct the setting of **OMX_VIDEO_PARAM_AVCTYPE**. # Reference diff --git a/en/device-dev/driver/driver-peripherals-external-des.md b/en/device-dev/driver/driver-peripherals-external-des.md index d2b681dcad9172b622cb261d81c9efdf3a0b86cc..04f0d7631555e55f7481da003d214a1715f5533d 100644 --- a/en/device-dev/driver/driver-peripherals-external-des.md +++ b/en/device-dev/driver/driver-peripherals-external-des.md @@ -3,164 +3,152 @@ ## Overview -### WLAN +### Function -The Wireless Local Area Network (WLAN) driver module is developed based on OpenHarmony Hardware Driver Foundation (HDF). It supports modular assembly and building, automatic adaptation to device differences, and cross-OS porting. +A wireless LAN (WLAN) allows users to easily connect to a wireless network to transmit and share data and move around within the area and remain connected to the network. The WLAN driver developed based on the Hardware Driver Foundation (HDF) shields hardware component differences and provides stable basic capability interfaces for upper-layer WLAN services, including starting a scan, associating with or disassociating from a hotspot, obtaining or setting MAC addresses, and obtaining link information. -### Working Principles - -You can modify your driver code based on the unified APIs provided by the WLAN module. The WLAN module provides: - -- APIs for the underlying layer to implement capabilities, such as opening or closing a WLAN hotspot, scanning hotspots, and connecting to or disconnecting from a hotspot. -- APIs for the Hardware Device Interface (HDI) layer to implement capabilities, such as setting or obtaining the device Media Access Control (MAC) address and setting the transmit power. - -The following figure shows the WLAN architecture. The WLAN driver module implements startup loading, parses configuration files, and provides bus abstraction APIs. The WLAN chip driver module provides the MAC Sublayer Management Entity (MLME). - - **Figure 1** WLAN architecture - - ![image](figures/WLAN_architecture.png "WLAN architecture") +### Basic Concepts - The following figure shows the WLAN driver architecture. +Before development, you need to understand the following basic concepts related to WLAN: - **Figure 2** WLAN driver architecture +- AP + + A wireless access point (AP) is a central node of a network that provides the wireless access service. Once connecting to the wireless network, the device can access data. - ![image](figures/WLAN_driver_architecture.png "WLAN driver architecture") +- STA + + A station (STA) is a basic component of a WLAN. Each terminal connected to a WLAN, such as a notebook and a personal digital assistant (PDA), is an STA. -The WLAN driver consists of the following modules: +- SSID + + A service set identifier (SSID) identifies a wireless network. Each WLAN has its SSID. -1. WLAN Message: provides an independent interface for each service or a composite service interface for multiple dependent services. It can run in the user mode, kernel mode, and MCU to implement complete decoupling between components. +- bssid + + A basic service set identifier (BSSID) is a 48-bit MAC address that uniquely identifies a basic service set on a WLAN. + +- Scan -2. WLAN Configuration Core: parses WLAN configuration files. + A terminal device scans the wireless network to obtain visible wireless network information, including the hotspot SSID, operating frequency band, and signal strength. -3. Access point (AP): allows devices to connect to the WLAN. +- Associate -4. Station (STA): a device that has access to the WLAN system and allows transmission and reception of data. + When a terminal device is associated with a valid hotspot, it can communicate with the AP. A device (STA) can set up a connection with only one AP at a time. -5. mac80211: defines MAC-layer APIs for underlying drivers. - -6. Bus: provides a unified bus abstract interface for the upper layer. It shields the differences between different kernels by calling the Secure Digital Input Output (SDIO) interfaces provided by the platform layer and encapsulating the adapted USB and PCIe interfaces. It also encapsulates different types of bus operations in a unified manner to shield differences between different chipsets. The complete bus driving capabilities provided by the bus module help simplify and streamline the development of different chip vendors. - -7. NetDevice: creates dedicated network devices to shield differences between OSs, provides unified interfaces for Wi-Fi drivers, unified HDF NetDevice data structure, and unified management, registration, and deregistration capabilities, and connects to the Linux network device layer on mini-, small-, standard, and large-system devices. - -8. NetBuf: encapsulates the unified data structure of the Linux or LiteOS native network data buffer and the operation interfaces for network data. +### Working Principles -9. FlowCtl: processes data based on the priority when the data volume is too large. +This document describes how to develop WLAN functions based on the HDF. The following figure shows the WLAN framework. -10. HCC-CFG: configures WLAN parameters, including the board configuration, driver configuration, and module configuration. +![image](figures/WLAN-driver-framework.png "WLAN Framework") -The relationships between the main modules are as follows: +1. The upper-layer service calls a hardware device interface (HDI) based on service requirements to deliver user-mode messages to the client through the Wi-Fi Protected Access (WPA) layer or hardware abstraction layer (HAL). The WPA layer provides interfaces for setting the encryption mode, associating with a hotspot, setting a channel, and hiding the hotspot. As a supplement to the WPA layer, the HAL provides APIs for setting the country code or MAC address and obtaining channel information. + +2. The Message module distributes user-mode messages to modules, such as the AP and STA, by component. + +3. Hdf_Mac80211 defines MAC-layer interfaces for underlying drivers. The command field is delivered to Hdf_Mac80211 and then sent to the WLAN chip firmware through the Bus module. + +4. The Bus module provides unified bus abstraction interfaces for the upper layer. It shields the differences between kernels by calling the Secure Digital Input Output (SDIO) interfaces provided by the platform layer and encapsulating the USB and PCIe interfaces. The Bus module also encapsulates different types of bus operations in a unified manner to shield differences between chipsets. The interfaces provided by the Bus module simplify and streamline the development of different chip vendors. + +5. Extensible Authentication Protocol (EAP) over LAN (EAPOL) is a LAN-based extended authentication protocol. It is used to transmit EAP packets between a client and a device (access device or server) so that EAP packets can be transmitted on a LAN to complete the authentication process and enable the device to go online. + +6. NetDevice creates dedicated network devices to shield differences between OSs. It provides unified interfaces for Wi-Fi drivers, unified HDF NetDevice data structs, and unified management, registration, and deregistration capabilities, and connects to the Linux network device layer on OpenHarmony devices. + +7. NetBuf encapsulates the unified data structure of the Linux or LiteOS native network data buffer and the operation interfaces for network data. + +8. The protocol stack works with the NetDevice and NetBuf modules to exchange data flows. -1. The WLAN driver works with HCC-CFG and WLAN Configuration Core to parse and load configuration files. +### Constraints -2. The WLAN Message module distributes user-mode messages to the AP and STA by component. +The WLAN driver provides basic capability interfaces for upper-layer WLAN services. The HDI interfaces apply to the standard system, and the HAL interfaces apply to mini and small systems. -3. Commands are delivered to mac80211, and then forwarded by the Bus module to the WLAN chip firmware. +## Development Guidelines -4. The protocol stack works with the NetDevice, NetBuf, and FlowCtl modules to exchange data flows. +### When to Use -## How to Develop +The WLAN driver provides basic capability interfaces for upper-layer WLAN services to ensure that users can easily access the wireless network and transmit and share data. Refer to the following when you adapt your WLAN module to OpenHarmony. ### Available APIs -The WLAN module provides the following types of APIs: +The WLAN module provides the following APIs: -1. HDI and Hardware Abstraction Layer (HAL) APIs for upper-layer services +1. HDI and HAL APIs for upper-layer services 2. APIs for vendors 3. WLAN APIs directly called by drivers - **Figure 3** WLAN driver APIs - - ![image](figures/WLAN_driver_APIs.png "WLAN Driver APIs") - - -- The WLAN module provides HAL APIs for upper-layer services (applicable to small and mini systems). **Table 1** and **Table 2** describe some APIs. +- This interfaces provided by the WLAN Driver module for upper-layer services can be used to create or destroy an IWiFi object, and set MAC addresses or transmit power. Table 1 and Table 2 list the C function interfaces generated based on the IDL interface description. For details about the interface declaration, see the IDL files (**/drivers/interface/wlan/v1_1/**). **Table 1** wifi_hal.h | API| Description| | -------- | -------- | - | int32_t WifiConstruct(struct IWiFi \*\*wifiInstance)| Creates an **IWiFi** instance with basic capabilities.| - | int32_t WifiDestruct(struct IWiFi \*\*wifiInstance)| Destroys an **IWiFi** instance.| - | int32_t (\*start)(struct IWiFi \*)| Creates a channel between the HAL and the driver and obtains the NICs supported by the driver.| - | int32_t (\*stop)(struct IWiFi \*)| Stops the channel between the HAL and the driver.| + | int32_t WifiConstruct(struct IWiFi \*\*wifiInstance) | Creates an **IWiFi** instance with basic capabilities.| + | int32_t WifiDestruct(struct IWiFi \*\*wifiInstance) | Destroys an **IWiFi** instance.| + | int32_t (\*start)(struct IWiFi \*) | Creates a channel between the HAL and the driver and obtains the NICs supported by the driver.| + | int32_t (\*stop)(struct IWiFi \*) | Stops the channel between the HAL and the driver.| **Table 2** wifi_hal_base_feature.h | API| Description| | -------- | -------- | - | int32_t (\*getFeatureType)(const struct IWiFiBaseFeature \*)| Obtains the feature type.| - | int32_t (\*setMacAddress)(const struct IWiFiBaseFeature \*, unsigned char \*, uint8_t)| Sets the MAC address.| - | int32_t (\*getDeviceMacAddress)(const struct IWiFiBaseFeature \*, unsigned char \*, uint8_t)| Obtains the device MAC address.| - | int32_t (\*setTxPower)(const struct IWiFiBaseFeature \*, int32_t)| Sets the transmit power.| + | int32_t (\*getFeatureType)(const struct IWiFiBaseFeature \*) | Obtains the feature type.| + | int32_t (\*setMacAddress)(const struct IWiFiBaseFeature \*, unsigned char \*, uint8_t) | Sets the MAC address.| + | int32_t (\*getDeviceMacAddress)(const struct IWiFiBaseFeature \*, unsigned char \*, uint8_t) | Obtains the device MAC address.| + | int32_t (\*setTxPower)(const struct IWiFiBaseFeature \*, int32_t) | Sets the transmit power.| -- The WLAN Driver module also provides APIs that you need to fill in the implementation. **Table 3** describes some APIs. +- The WLAN Driver module also provides APIs that you need to fill in the implementation. These APIs can be used to initialize or deregister a network device, open or stop a network device, and obtain network device status. Table 3 describes some APIs. **Table 3** net_device.h | API| Description| | -------- | -------- | - | int32_t (\*init)(struct NetDevice \*netDev)| Initializes a network device.| - | struct NetDevStats \*(\*getStats)(struct NetDevice \*netDev)| Obtains the state of a network device.| - | int32_t (\*setMacAddr)(struct NetDevice \*netDev, void \*addr)| Sets the MAC address.| - | void (\*deInit)(struct NetDevice \*netDev)| Deinitializes a network device.| - | int32_t (\*open)(struct NetDevice \*netDev)| Opens a network device.| - | int32_t (\*stop)(struct NetDevice \*netDev)| Stops a network device.| + | int32_t (\*init)(struct NetDevice \*netDev) | Initializes a network device.| + | struct NetDevStats \*(\*getStats)(struct NetDevice \*netDev) | Obtains the state of a network device.| + | int32_t (\*setMacAddr)(struct NetDevice \*netDev, void \*addr) | Sets the MAC address.| + | void (\*deInit)(struct NetDevice \*netDev) | Deinitializes a network device.| + | int32_t (\*open)(struct NetDevice \*netDev) | Opens a network device.| + | int32_t (\*stop)(struct NetDevice \*netDev) | Stops a network device.| -- The WLAN Driver module provides APIs that you can directly use to create or release a **WifiModule**, connect to or disconnect from a WLAN hotspot, request or release a **NetBuf**, and convert between the **pbuf** structure of Lightweight IP (lwIP) and a **NetBuf**. +- The WLAN Driver module provides APIs that you can directly use to create or release a **WifiModule**, connect to or disconnect from a WLAN hotspot, request or release a **NetBuf**, and convert between the **pbuf** struct of Lightweight IP (lwIP) and a **NetBuf**. - The following tables describe the APIs. + Tables 4 to 6 list the APIs that can be directly called. - **Table 4** wifi_module.h + **Table 4** wifi_module.h | API| Description| | -------- | -------- | - | struct WifiModule \*WifiModuleCreate(const struct HdfConfigWifiModuleConfig \*config)| Creates a **WifiModule**.| - | void WifiModuleDelete(struct WifiModule \*module)| Deletes a **WifiModule** and releases its data.| - | int32_t DelFeature(struct WifiModule \*module, uint16_t featureType)| Deletes a feature from a **WifiModule**.| - | int32_t AddFeature(struct WifiModule \*module, uint16_t featureType,
struct WifiFeature \*featureData)| Adds a feature to a **WifiModule**.| + | struct WifiModule \*WifiModuleCreate(const struct HdfConfigWifiModuleConfig \*config) | Creates a **WifiModule**.| + | void WifiModuleDelete(struct WifiModule \*module) | Deletes a **WifiModule** and releases its data.| + | int32_t DelFeature(struct WifiModule \*module, uint16_t featureType) | Deletes a feature from a **WifiModule**.| + | int32_t AddFeature(struct WifiModule \*module, uint16_t featureType,
 struct WifiFeature \*featureData) | Adds a feature to a **WifiModule**.| - **Table 5** wifi_mac80211_ops.h + **Table 5** wifi_mac80211_ops.h | API| Description| | -------- | -------- | - | int32_t (\*startAp)(NetDevice \*netDev)| Starts an AP.| - | int32_t (\*stopAp)(NetDevice \*netDev)| Stops an AP.| - | int32_t (\*connect)(NetDevice \*netDev, WifiConnectParams \*param)| Connects to a hotspot.| - | int32_t (\*disconnect)(NetDevice \*netDev, uint16_t reasonCode)| Disconnects from a hotspot.| + | int32_t (\*startAp)(NetDevice \*netDev) | Starts an AP.| + | int32_t (\*stopAp)(NetDevice \*netDev) | Stops an AP.| + | int32_t (\*connect)(NetDevice \*netDev, WifiConnectParams \*param) | Connects to a hotspot.| + | int32_t (\*disconnect)(NetDevice \*netDev, uint16_t reasonCode) | Disconnects from a hotspot.| - **Table 6** hdf_netbuf.h + **Table 6** hdf_netbuf.h | API| Description| | -------- | -------- | - | static inline void NetBufQueueInit(struct NetBufQueue \*q)| Initializes a **NetBuf** queue.| - | struct NetBuf \*NetBufAlloc(uint32_t size)| Allocates a **NetBuf**.| - | void NetBufFree(struct NetBuf \*nb)| Releases a **NetBuf**.| - | struct NetBuf \*Pbuf2NetBuf(const struct NetDevice \*netdev, struct pbuf \*lwipBuf)| Converts the **pbuf** structure of lwIP to a **NetBuf**.| - | struct pbuf \*NetBuf2Pbuf(const struct NetBuf \*nb)| Converts a **NetBuf** to the **pbuf** structure of lwIP.| - -### Development Procedure -#### WLAN Framework Adaptation - -The WLAN driver framework developed based on the HDF and Platform framework provides a unified driver model regardless of the OS and system on a chip (SoC). When developing your WLAN driver, you need to configure data based on the WLAN driver framework. -**Development Procedure** - -1. Configure hardware (such as modules and chips) parameters in the **wlan_platform.hcs** file. The HDF parses the file to generate structure objects with full configuration. - -2. Implement initialization and deinitialization of the WLAN module (such as initialize and deinitialize the WLAN chip and WLAN chip driver). + | static inline void NetBufQueueInit(struct NetBufQueue \*q) | Initializes a **NetBuf** queue.| + | struct NetBuf \*NetBufAlloc(uint32_t size) | Allocates a **NetBuf**.| + | void NetBufFree(struct NetBuf \*nb) | Releases a **NetBuf**.| + | struct NetBuf \*Pbuf2NetBuf(const struct NetDevice \*netdev, struct pbuf \*lwipBuf) | Converts the **pbuf** structure of lwIP to a **NetBuf**.| + | struct pbuf \*NetBuf2Pbuf(const struct NetBuf \*nb) | Converts a **NetBuf** to the **pbuf** structure of lwIP.| -3. Implement the delivery of control flow commands. +### How to Develop -4. Implement event reporting. +The WLAN driver framework developed based on the HDF and Platform framework provides a unified driver model for vendors regardless of the OS and system on a chip (SoC). When developing your WLAN driver based on the WLAN driver framework, you need to make adaptation. The following uses the Hi3881 WLAN chip as an example. -**Development Example** +#### Configuring the HCS for the Driver -The following uses the Hi3881 WLAN chip as an example to describe how to initialize a WLAN module. - -1. Configure the HDF configuration source (HCS) for the driver. - - The HCS includes device configuration and component configuration. + The HDF configuration source (HCS) includes device configuration and component configuration. - Device configuration @@ -223,8 +211,9 @@ The following uses the Hi3881 WLAN chip as an example to describe how to initial } ``` -2. Hook the **init** and **deinit** functions of the WLAN chip and WLAN chip driver. - - Implementing the driver adaptation entry function +#### Initializing and deinitializing the WLAN Chip and WLAN Chip Driver + + - Implement the driver adaptation entry function Define a variable of the HdfDriverEntry type based on the chip to hook functions of **Bind()**, **Init()**, and **Release()**. Call **HDF_INIT** to register the driver entry with the HDF. During driver loading, the HDF calls the **Bind** function and then the **Init** function to load the driver. If **Init()** fails to be called, the HDF calls **Release()** to release driver resources. ```c @@ -239,7 +228,7 @@ The following uses the Hi3881 WLAN chip as an example to describe how to initial HDF_INIT(g_hdfHisiChipEntry); ``` - - Registering the functions for initializing the chip and chip driver + - Register the functions for initializing the chip and chip driver Hook the chip initialization function to **InitChip()** and the chip deinitialization function to **DeinitChip()**. @@ -278,296 +267,308 @@ The following uses the Hi3881 WLAN chip as an example to describe how to initial } ``` - - Initializing and deinitializing the chip - ```c - /* Function for initializing the WLAN chip. */ - int32_t InitHi3881Chip(struct HdfWlanDevice *device) - { - uint8_t maxPortCount = 3; - int32_t ret = HI_SUCCESS; - uint8_t maxRetryCount = 3; - if (device == NULL || device->bus == NULL) { - HDF_LOGE("%s:NULL ptr!", __func__); - return HI_FAIL; - } - - do { - if (ret != HI_SUCCESS) { - if (device->reset != NULL && device->reset->Reset != NULL) { - device->reset->Reset(device->reset); - } - HDF_LOGE("%s:Retry init hi3881!last ret=%d", __func__, ret); - } - ret = hi_wifi_init(maxPortCount, device->bus); - } while (ret != 0 && --maxRetryCount > 0); - - if (ret != 0) { - HDF_LOGE("%s:Init hi3881 driver failed!", __func__); - return ret; - } - return HI_SUCCESS; - } - - /* Function for deinitializing the WLAN chip. */ - int32_t DeinitHi3881Chip(struct HdfWlanDevice *device) - { - (void)device; - int32_t ret = hi_wifi_deinit(); - if (ret != 0) { - HDF_LOGE("%s:Deinit failed!ret=%d", __func__, ret); - } - return ret; - } - ``` - - Initializing and deinitializing the chip driver - ```c - /* Hook the functions of the WLAN chip driver, mac80211, and chip. */ - static struct HdfChipDriver *BuildHi3881Driver(struct HdfWlanDevice *device, uint8_t ifIndex) - { - struct HdfChipDriver *specificDriver = NULL; - if (device == NULL) { - HDF_LOGE("%s fail: channel is NULL!", __func__); - return NULL; - } - (void)ifIndex; - specificDriver = (struct HdfChipDriver *)OsalMemCalloc(sizeof(struct HdfChipDriver)); - if (specificDriver == NULL) { - HDF_LOGE("%s fail: OsalMemCalloc fail!", __func__); - return NULL; - } - if (memset_s(specificDriver, sizeof(struct HdfChipDriver), 0, sizeof(struct HdfChipDriver)) != EOK) { - HDF_LOGE("%s fail: memset_s fail!", __func__); - OsalMemFree(specificDriver); - return NULL; - } - - if (strcpy_s(specificDriver->name, MAX_WIFI_COMPONENT_NAME_LEN, HI3881_DRIVER_NAME) != EOK) { - HDF_LOGE("%s fail: strcpy_s fail!", __func__); - OsalMemFree(specificDriver); - return NULL; - } - specificDriver->init = Hi3881Init; - specificDriver->deinit = Hi3881Deinit; - - HiMac80211Init(specificDriver); - - return specificDriver; - } - - /* Release the WLAN chip driver. */ - static void ReleaseHi3881Driver(struct HdfChipDriver *chipDriver) - { - if (chipDriver == NULL) { - return; - } - if (strcmp(chipDriver->name, HI3881_DRIVER_NAME) != 0) { - HDF_LOGE("%s:Not my driver!", __func__); - return; - } - OsalMemFree(chipDriver); - } - - /* Function for initializing the WLAN chip driver. */ - int32_t Hi3881Init(struct HdfChipDriver *chipDriver, struct NetDevice *netDevice) - { - hi_u16 mode; - int32_t ret; - nl80211_iftype_uint8 type; - (void)chipDriver; - HDF_LOGI("%s: start...", __func__); - mode = wal_get_vap_mode(); - if (mode >= WAL_WIFI_MODE_BUTT) { - oam_error_log1(0, 0, "wal_init_drv_netdev:: invalid mode[%d]", mode); - return HI_FAIL; - } - if (mode == WAL_WIFI_MODE_STA) { - type = NL80211_IFTYPE_STATION; - #ifdef _PRE_WLAN_FEATURE_P2P - if (InitNetdev(netDevice, NL80211_IFTYPE_P2P_DEVICE) != HI_SUCCESS) { - return HI_FAIL; - } - #endif - } else if (mode == WAL_WIFI_MODE_AP) { - type = NL80211_IFTYPE_AP; - } else { - oam_error_log1(0, 0, "wal_init_drv_netdev:: invalid mode[%d]", mode); - return HI_FAIL; - } - ret = wal_init_drv_wlan_netdev(type, WAL_PHY_MODE_11N, netDevice); - if (ret != HI_SUCCESS) { - oam_error_log2(0, OAM_SF_ANY, "wal_init_drv_netdev %s failed.l_return:%d\n", netDevice->name, ret); - } - return ret; - } - - /* Function for deinitializing the WLAN chip driver. */ - int32_t Hi3881Deinit(struct HdfChipDriver *chipDriver, struct NetDevice *netDevice) - { - int32_t ret; - (void)chipDriver; - ret = DeinitNetdev(NL80211_IFTYPE_P2P_DEVICE); - if (ret != HI_SUCCESS) { - oam_error_log1(0, OAM_SF_ANY, "Hi3881Deinit: DeinitNetdev p2p device fail, ret = %d\n", ret); - return ret; - } - return wal_deinit_drv_wlan_netdev(netDevice); - } - - ``` + 1. Initialize and deinitialize the chip. + + ```c + /* Function for initializing the WLAN chip. */ + int32_t InitHi3881Chip(struct HdfWlanDevice *device) + { + uint8_t maxPortCount = 3; + int32_t ret = HI_SUCCESS; + uint8_t maxRetryCount = 3; + if (device == NULL || device->bus == NULL) { + HDF_LOGE("%s:NULL ptr!", __func__); + return HI_FAIL; + } + + do { + if (ret != HI_SUCCESS) { + if (device->reset != NULL && device->reset->Reset != NULL) { + device->reset->Reset(device->reset); + } + HDF_LOGE("%s:Retry init hi3881!last ret=%d", __func__, ret); + } + ret = hi_wifi_init(maxPortCount, device->bus); + } while (ret != 0 && --maxRetryCount > 0); + + if (ret != 0) { + HDF_LOGE("%s:Init hi3881 driver failed!", __func__); + return ret; + } + return HI_SUCCESS; + } + + /* Function for deinitializing the WLAN chip. */ + int32_t DeinitHi3881Chip(struct HdfWlanDevice *device) + { + (void)device; + int32_t ret = hi_wifi_deinit(); + if (ret != 0) { + HDF_LOGE("%s:Deinit failed!ret=%d", __func__, ret); + } + return ret; + } + ``` - During the chip initialization process, call **NetDeviceInit()** to initialize a network device, call **NetDeviceAdd()** to add the network device to a protocol stack, and hook function pointers of **netdev**. + 2. Initialize and deinitialize the chip driver. + + ```c + /* Hook the functions of the WLAN chip driver, mac80211, and chip. */ + static struct HdfChipDriver *BuildHi3881Driver(struct HdfWlanDevice *device, uint8_t ifIndex) + { + struct HdfChipDriver *specificDriver = NULL; + if (device == NULL) { + HDF_LOGE("%s fail: channel is NULL!", __func__); + return NULL; + } + (void)ifIndex; + specificDriver = (struct HdfChipDriver *)OsalMemCalloc(sizeof(struct HdfChipDriver)); + if (specificDriver == NULL) { + HDF_LOGE("%s fail: OsalMemCalloc fail!", __func__); + return NULL; + } + if (memset_s(specificDriver, sizeof(struct HdfChipDriver), 0, sizeof(struct HdfChipDriver)) != EOK) { + HDF_LOGE("%s fail: memset_s fail!", __func__); + OsalMemFree(specificDriver); + return NULL; + } + + if (strcpy_s(specificDriver->name, MAX_WIFI_COMPONENT_NAME_LEN, HI3881_DRIVER_NAME) != EOK) { + HDF_LOGE("%s fail: strcpy_s fail!", __func__); + OsalMemFree(specificDriver); + return NULL; + } + specificDriver->init = Hi3881Init; + specificDriver->deinit = Hi3881Deinit; + + HiMac80211Init(specificDriver); + + return specificDriver; + } + + /* Release the WLAN chip driver. */ + static void ReleaseHi3881Driver(struct HdfChipDriver *chipDriver) + { + if (chipDriver == NULL) { + return; + } + if (strcmp(chipDriver->name, HI3881_DRIVER_NAME) != 0) { + HDF_LOGE("%s:Not my driver!", __func__); + return; + } + OsalMemFree(chipDriver); + } + + /* Function for initializing the WLAN chip driver. */ + int32_t Hi3881Init(struct HdfChipDriver *chipDriver, struct NetDevice *netDevice) + { + hi_u16 mode; + int32_t ret; + nl80211_iftype_uint8 type; + (void)chipDriver; + HDF_LOGI("%s: start...", __func__); + mode = wal_get_vap_mode(); + if (mode >= WAL_WIFI_MODE_BUTT) { + oam_error_log1(0, 0, "wal_init_drv_netdev:: invalid mode[%d]", mode); + return HI_FAIL; + } + if (mode == WAL_WIFI_MODE_STA) { + type = NL80211_IFTYPE_STATION; + #ifdef _PRE_WLAN_FEATURE_P2P + if (InitNetdev(netDevice, NL80211_IFTYPE_P2P_DEVICE) != HI_SUCCESS) { + return HI_FAIL; + } + #endif + } else if (mode == WAL_WIFI_MODE_AP) { + type = NL80211_IFTYPE_AP; + } else { + oam_error_log1(0, 0, "wal_init_drv_netdev:: invalid mode[%d]", mode); + return HI_FAIL; + } + ret = wal_init_drv_wlan_netdev(type, WAL_PHY_MODE_11N, netDevice); + if (ret != HI_SUCCESS) { + oam_error_log2(0, OAM_SF_ANY, "wal_init_drv_netdev %s failed.l_return:%d\n", netDevice->name, ret); + } + return ret; + } + + /* Function for deinitializing the WLAN chip driver. */ + int32_t Hi3881Deinit(struct HdfChipDriver *chipDriver, struct NetDevice *netDevice) + { + int32_t ret; + (void)chipDriver; + ret = DeinitNetdev(NL80211_IFTYPE_P2P_DEVICE); + if (ret != HI_SUCCESS) { + oam_error_log1(0, OAM_SF_ANY, "Hi3881Deinit: DeinitNetdev p2p device fail, ret = %d\n", ret); + return ret; + } + return wal_deinit_drv_wlan_netdev(netDevice); + } - ```c - hi_s32 wal_init_drv_wlan_netdev(nl80211_iftype_uint8 type, wal_phy_mode mode, oal_net_device_stru *netdev) - { - hi_char *ac_mode_str = NULL; - hi_s32 ret; - if (oal_unlikely(netdev == HI_NULL)) { - oam_error_log0(0, OAM_SF_ANY, "{netdev is null!}"); - return HI_ERR_CODE_PTR_NULL; - } + ``` - do { - /* Initialize the network device. */ - ret = wal_init_netdev(type, netdev); - if (ret != HI_SUCCESS) { - break; - } - - ret = wal_init_netif(type, netdev); - if (ret != HI_SUCCESS) { - break; - } - ac_mode_str = "11bgn"; - if (mode == WAL_PHY_MODE_11G) { - ac_mode_str = "11bg"; - } else if (mode == WAL_PHY_MODE_11B) { - ac_mode_str = "11b"; - } - - ret = wal_ioctl_set_mode(netdev, ac_mode_str); - } while (false); - - if (ret != HI_SUCCESS) { - wal_deinit_wlan_vap(netdev); - oal_net_unregister_netdev(netdev); - oal_net_clear_netdev(netdev); - return HI_FAIL; - } + During the chip initialization process, call **NetDeviceInit()** to initialize a network device, call **NetDeviceAdd()** to add the network device to a protocol stack, and hook function pointers of **netdev**. + + ```c + hi_s32 wal_init_drv_wlan_netdev(nl80211_iftype_uint8 type, wal_phy_mode mode, oal_net_device_stru *netdev) + { + hi_char *ac_mode_str = NULL; + hi_s32 ret; + if (oal_unlikely(netdev == HI_NULL)) { + oam_error_log0(0, OAM_SF_ANY, "{netdev is null!}"); + return HI_ERR_CODE_PTR_NULL; + } + + do { + /* Initialize the network device. */ + ret = wal_init_netdev(type, netdev); + if (ret != HI_SUCCESS) { + break; + } + + ret = wal_init_netif(type, netdev); + if (ret != HI_SUCCESS) { + break; + } + ac_mode_str = "11bgn"; + if (mode == WAL_PHY_MODE_11G) { + ac_mode_str = "11bg"; + } else if (mode == WAL_PHY_MODE_11B) { + ac_mode_str = "11b"; + } + + ret = wal_ioctl_set_mode(netdev, ac_mode_str); + } while (false); + + if (ret != HI_SUCCESS) { + wal_deinit_wlan_vap(netdev); + oal_net_unregister_netdev(netdev); + oal_net_clear_netdev(netdev); + return HI_FAIL; + } + + return HI_SUCCESS; + } + + /* Hook function pointers of netdev. For details, see NetDeviceInterFace. */ + oal_net_device_ops_stru g_wal_net_dev_ops = + { + .getStats = wal_netdev_get_stats, + .open = wal_netdev_open, + .stop = wal_netdev_stop, + .xmit = hmac_bridge_vap_xmit, + .ioctl = wal_net_device_ioctl, + .changeMtu = oal_net_device_change_mtu, + .init = oal_net_device_init, + .deInit = oal_net_free_netdev, + + ...... + + }; + + hi_s32 wal_init_netif(nl80211_iftype_uint8 type, oal_net_device_stru *netdev, const oal_wireless_dev *wdev) + { + /* Add the network device to the protocol stack. */ + hi_u32 ret = NetDeviceAdd(netdev, (Protocol80211IfType)type); + + ... + + return HI_SUCCESS; + } + ``` - return HI_SUCCESS; - } +#### Modifying the MAC Layer Interfaces - /* Hook function pointers of netdev. For details, see NetDeviceInterFace. */ - oal_net_device_ops_stru g_wal_net_dev_ops = - { - .getStats = wal_netdev_get_stats, - .open = wal_netdev_open, - .stop = wal_netdev_stop, - .xmit = hmac_bridge_vap_xmit, - .ioctl = wal_net_device_ioctl, - .changeMtu = oal_net_device_change_mtu, - .init = oal_net_device_init, - .deInit = oal_net_free_netdev, - - ... +After the user-mode message is delivered to the driver, the driver calls the corresponding MAC-layer capability interfaces. - }; + ```c + /* Define the functions for implementing the basic capabilities in the MAC layer for the driver. */ + static struct HdfMac80211BaseOps g_baseOps = { + .SetMode = WalSetMode, + .AddKey = WalAddKey, + .DelKey = WalDelKey, + .SetDefaultKey = WalSetDefaultKey, + .GetDeviceMacAddr = WalGetDeviceMacAddr, + .SetMacAddr = WalSetMacAddr, + .SetTxPower = WalSetTxPower, + .GetValidFreqsWithBand = WalGetValidFreqsWithBand, + .GetHwCapability = WalGetHwCapability + }; + + /* Define the functions for implementing the STA capabilities in the MAC layer for the driver. */ + static struct HdfMac80211STAOps g_staOps = { + .Connect = WalConnect, + .Disconnect = WalDisconnect, + .StartScan = WalStartScan, + .AbortScan = WalAbortScan, + .SetScanningMacAddress = WalSetScanningMacAddress, + }; + + /* Define the functions for implementing the AP capabilities in the MAC layer for the driver. */ + static struct HdfMac80211APOps g_apOps = { + .ConfigAp = WalConfigAp, + .StartAp = WalStartAp, + .StopAp = WalStopAp, + .ConfigBeacon = WalChangeBeacon, + .DelStation = WalDelStation, + .SetCountryCode = WalSetCountryCode, + .GetAssociatedStasCount = WalGetAssociatedStasCount, + .GetAssociatedStasInfo = WalGetAssociatedStasInfo + }; + + static struct HdfMac80211P2POps g_p2pOps = { + .RemainOnChannel = WalRemainOnChannel, + .CancelRemainOnChannel = WalCancelRemainOnChannel, + .ProbeReqReport = WalProbeReqReport, + .AddIf = WalAddIf, + .RemoveIf = WalRemoveIf, + .SetApWpsP2pIe = WalSetApWpsP2pIe, + .GetDriverFlag = WalGetDriverFlag + }; + + /* Initialize mac80211 and hook functions of the chip. */ + void HiMac80211Init(struct HdfChipDriver *chipDriver) + { + if (chipDriver == NULL) { + HDF_LOGE("%s:input is NULL!", __func__); + return; + } + chipDriver->ops = &g_baseOps; + chipDriver->staOps = &g_staOps; + chipDriver->apOps = &g_apOps; + chipDriver->p2pOps = &g_p2pOps; + } + ``` - hi_s32 wal_init_netif(nl80211_iftype_uint8 type, oal_net_device_stru *netdev, const oal_wireless_dev *wdev) - { - /* Add the network device to the protocol stack. */ - hi_u32 ret = NetDeviceAdd(netdev, (Protocol80211IfType)type); +#### Configuring Event Reporting - ... +The WLAN framework provides interfaces for event reporting. For details, see **hdf_wifi_event.c**. - return HI_SUCCESS; - } - ``` +The following presents how to use **HdfWiFiEventNewSta()** to report information about a newly associated STA. -3. Bind the commands to be delivered, including setting the MAC address and transmit power, implement STA connection and scan, start APs, and setting the country code. - - ```c - /* Implement the basic capabilities of the MAC layer. */ - static struct HdfMac80211BaseOps g_baseOps = { - .SetMode = WalSetMode, - .AddKey = WalAddKey, - .DelKey = WalDelKey, - .SetDefaultKey = WalSetDefaultKey, - .GetDeviceMacAddr = WalGetDeviceMacAddr, - .SetMacAddr = WalSetMacAddr, - .SetTxPower = WalSetTxPower, - .GetValidFreqsWithBand = WalGetValidFreqsWithBand, - .GetHwCapability = WalGetHwCapability - }; - - /* Implement the STA capabilities of the MAC layer. */ - static struct HdfMac80211STAOps g_staOps = { - .Connect = WalConnect, - .Disconnect = WalDisconnect, - .StartScan = WalStartScan, - .AbortScan = WalAbortScan, - .SetScanningMacAddress = WalSetScanningMacAddress, - }; - - /* Implement the AP capabilities of the MAC layer. */ - static struct HdfMac80211APOps g_apOps = { - .ConfigAp = WalConfigAp, - .StartAp = WalStartAp, - .StopAp = WalStopAp, - .ConfigBeacon = WalChangeBeacon, - .DelStation = WalDelStation, - .SetCountryCode = WalSetCountryCode, - .GetAssociatedStasCount = WalGetAssociatedStasCount, - .GetAssociatedStasInfo = WalGetAssociatedStasInfo - }; - - static struct HdfMac80211P2POps g_p2pOps = { - .RemainOnChannel = WalRemainOnChannel, - .CancelRemainOnChannel = WalCancelRemainOnChannel, - .ProbeReqReport = WalProbeReqReport, - .AddIf = WalAddIf, - .RemoveIf = WalRemoveIf, - .SetApWpsP2pIe = WalSetApWpsP2pIe, - .GetDriverFlag = WalGetDriverFlag - }; - - /* Initialize mac80211 and hook functions of the chip. */ - void HiMac80211Init(struct HdfChipDriver *chipDriver) - { - if (chipDriver == NULL) { - HDF_LOGE("%s:input is NULL!", __func__); - return; - } - chipDriver->ops = &g_baseOps; - chipDriver->staOps = &g_staOps; - chipDriver->apOps = &g_apOps; - chipDriver->p2pOps = &g_p2pOps; - } - ``` + ```c + hi_u32 oal_cfg80211_new_sta(oal_net_device_stru *net_device, const hi_u8 *mac_addr, hi_u8 addr_len, + oal_station_info_stru *station_info, oal_gfp_enum_uint8 en_gfp) + { + #if (_PRE_OS_VERSION_LINUX == _PRE_OS_VERSION) && !defined(_PRE_HDF_LINUX) + cfg80211_new_sta(net_device, mac_addr, station_info, en_gfp); + hi_unref_param(addr_len); + #elif (_PRE_OS_VERSION_LITEOS == _PRE_OS_VERSION) || defined(_PRE_HDF_LINUX) + struct StationInfo info = { 0 }; + info.assocReqIes = station_info->assoc_req_ies; + info.assocReqIesLen = station_info->assoc_req_ies_len; + HdfWifiEventNewSta(net_device, mac_addr, WLAN_MAC_ADDR_LEN, &info); + hi_unref_param(en_gfp); + hi_unref_param(addr_len); + #endif + + return HI_SUCCESS; + } + ``` -4. Invoke the event reporting APIs.
The WLAN framework provides the event reporting APIs. For details, see hdf_wifi_event.c.
For example, call **HdfWiFiEventNewSta AP** to report information about the newly associated STA. +### Debugging and Verification - ```c - hi_u32 oal_cfg80211_new_sta(oal_net_device_stru *net_device, const hi_u8 *mac_addr, hi_u8 addr_len, - oal_station_info_stru *station_info, oal_gfp_enum_uint8 en_gfp) - { - #if (_PRE_OS_VERSION_LINUX == _PRE_OS_VERSION) && !defined(_PRE_HDF_LINUX) - cfg80211_new_sta(net_device, mac_addr, station_info, en_gfp); - hi_unref_param(addr_len); - #elif (_PRE_OS_VERSION_LITEOS == _PRE_OS_VERSION) || defined(_PRE_HDF_LINUX) - struct StationInfo info = { 0 }; - info.assocReqIes = station_info->assoc_req_ies; - info.assocReqIesLen = station_info->assoc_req_ies_len; - HdfWifiEventNewSta(net_device, mac_addr, WLAN_MAC_ADDR_LEN, &info); - hi_unref_param(en_gfp); - hi_unref_param(addr_len); - #endif - - return HI_SUCCESS; - } - ``` -**Verification** +#### Driver Adaptation Verification Develop test cases in the WLAN module unit test to verify the basic features of the WLAN module. The following uses Hi3516D V300 standard system as an example. @@ -644,7 +645,9 @@ Develop test cases in the WLAN module unit test to verify the basic features of exit 0 ``` - - Create a **udhcpd.conf** file (used to start the **udhcpd**) and copy the following content to the file.
In the following, **opt dns** *x.x.x.x* *x.x.x.x* indicates two DNS servers configured. You can configure DNS servers as required. + - Create the **udhcpd.conf** file and copy the following content to the file. + + In the following example, "opt dns x.x.x.x x.x.x.x" indicates two DNS servers configured. You can configure DNS servers as required. ```text start 192.168.12.2 @@ -698,7 +701,7 @@ Develop test cases in the WLAN module unit test to verify the basic features of busybox udhcpd /vendor/etc/udhcpd.conf ``` - 4. On the mobile phone, select the network named **test** in the available Wi-Fi list and enter the password.
The network name and password are configured in the **hostapd.conf** file. You can see that network name in the connected Wi-Fi list if the connection is successful. + 4. On the mobile phone, select the network named **test** in the available Wi-Fi list and enter the password. (The network name and password are configured in the **hostapd.conf** file.) You can see that network name in the connected Wi-Fi list if the connection is successful. 5. Ping the test terminal from the development board. @@ -706,11 +709,11 @@ Develop test cases in the WLAN module unit test to verify the basic features of busybox ping xxx.xxx.xxx.xxx ``` - In the command, *xxx.xxx.xxx.xxx* indicates the IP address of the test terminal. If the test terminal can be pinged, the WLAN driver provides basic features normally. + In the command, xxx.xxx.xxx.xxx indicates the IP address of the test terminal. If the test terminal can be pinged, the WLAN driver provides basic features normally. - - Verify basic STA features. + - Verify basic STA functions - 1. Start the STA on the development board, and enable the hotspot on the test terminal.
The hotspot name and password are configured in the **hostapd.conf** file. The hotspot name is **test**, and the password is **12345678**. + 1. Start the STA on the development board, and enable the hotspot on the test terminal. (The hotspot name and password are configured in the **hostapd.conf** file. The hotspot name is **test**, and the password is **12345678**.) 2. Run the following command in the **cmd** window: @@ -737,8 +740,9 @@ Develop test cases in the WLAN module unit test to verify the basic features of In the command, xxx.xxx.xxx.xxx indicates the IP address of the test terminal. If the test terminal can be pinged, the WLAN driver provides basic features normally. -#### **API Invocation** -The WLAN driver module provides two types of capability interfaces for the upper layer: HDI interface and HAL interface. +#### API Usage Example + +The WLAN Driver module provides two types of capability interfaces for the upper layer: HDI APIs and HAL APIs. - HDI API invocation The following uses **GetSupportFeature** as an example to describe the development procedure: @@ -753,7 +757,7 @@ The WLAN driver module provides two types of capability interfaces for the upper 5. Call **WlanInterfaceRelease()** to destroy the WLAN service instance. - The sample code is as follows: + Example: ```c #include "v1_0/iwlan_interface.h" #include "wlan_callback_impl.h" @@ -848,7 +852,7 @@ The WLAN driver module provides two types of capability interfaces for the upper 7. Call **WifiDestruct()** to destroy the **IWiFi** instance. - The sample code is as follows: + Example: ```c #include "wifi_hal.h" @@ -947,17 +951,16 @@ The WLAN driver module provides two types of capability interfaces for the upper - Code paths: - Adaptation of WLAN FlowCtl component on LiteOS: **//drivers/hdf_core/adapter/khdf/liteos/model/network/wifi** - - Adaptation of HDF network model on LiteOS: **//drivers/hdf_core/adapter/khdf/liteos/model/network** + - Adaptation of WLAN FlowCtl component on LiteOS: **//drivers/hdf_core/adapter/khdf/liteos/model/network/wifi** - Adaptation of WLAN FlowCtl component on Linux, build of the HDF WLAN model, and build of the vendor's WLAN driver: **//drivers/hdf_core/adapter/khdf/linux/model/network/wifi** + - Adaptation of HDF network model on LiteOS: **//drivers/hdf_core/adapter/khdf/liteos/model/network** - Core code for implementing the WLAN module: **//drivers/hdf_core/framework/model/network/wifi** + - Adaptation of WLAN FlowCtl component on Linux, build of the HDF WLAN model, and build of the vendor's WLAN driver: **//drivers/hdf_core/adapter/khdf/linux/model/network/wifi** - External APIs of the WLAN module: **//drivers/hdf_core/framework/include/wifi** + - Core code for implementing the WLAN module: **//drivers/hdf_core/framework/model/network/wifi** - HDF network model APIs: **//drivers/hdf_core/framework/include/net** + - External APIs of the WLAN module: **//drivers/hdf_core/framework/include/wifi** - WLAN HDI server implementation: **//drivers/peripheral/wlan** + - HDF network model APIs: **//drivers/hdf_core/framework/include/net** + - WLAN HDI server implementation: **//drivers/peripheral/wlan** diff --git a/en/device-dev/driver/figures/WLAN-driver-framework.png b/en/device-dev/driver/figures/WLAN-driver-framework.png new file mode 100644 index 0000000000000000000000000000000000000000..4dbbe0b49a4e5a61993152d266fa21dad18014c7 Binary files /dev/null and b/en/device-dev/driver/figures/WLAN-driver-framework.png differ diff --git a/en/device-dev/driver/figures/WLAN_architecture.png b/en/device-dev/driver/figures/WLAN_architecture.png deleted file mode 100644 index 2479e5101bf555d57c0ed700d82e7671b868bc3a..0000000000000000000000000000000000000000 Binary files a/en/device-dev/driver/figures/WLAN_architecture.png and /dev/null differ diff --git a/en/device-dev/driver/figures/WLAN_driver_APIs.png b/en/device-dev/driver/figures/WLAN_driver_APIs.png deleted file mode 100644 index 19cee91371e94ae6c375c4011174f65b2e0f5664..0000000000000000000000000000000000000000 Binary files a/en/device-dev/driver/figures/WLAN_driver_APIs.png and /dev/null differ diff --git a/en/device-dev/driver/figures/WLAN_driver_architecture.png b/en/device-dev/driver/figures/WLAN_driver_architecture.png deleted file mode 100644 index a902741d5f92c6a3b80ad5e51cb2f9343ed91787..0000000000000000000000000000000000000000 Binary files a/en/device-dev/driver/figures/WLAN_driver_architecture.png and /dev/null differ diff --git a/zh-cn/application-dev/application-models/arkts-ui-widget-configuration.md b/zh-cn/application-dev/application-models/arkts-ui-widget-configuration.md index 2dfce1481a28ad72460eda0299a9632b1935e52e..6185654060f640e55da4100a86ad6c0509634bd9 100644 --- a/zh-cn/application-dev/application-models/arkts-ui-widget-configuration.md +++ b/zh-cn/application-dev/application-models/arkts-ui-widget-configuration.md @@ -54,6 +54,7 @@ | formVisibleNotify | 标识是否允许卡片使用卡片可见性通知。 | 字符串 | 可缺省,缺省值为空。 | | metadata | 表示卡片的自定义信息,包含customizeData数组标签。 | 对象 | 可缺省,缺省值为空。 | | dataProxyEnabled | 表示卡片是否支持[卡片代理刷新](./arkts-ui-widget-update-by-proxy.md),取值范围:
- true:表示支持代理刷新。
- false:表示不支持代理刷新。
设置为true时,[定时刷新和下次刷新不生效,但不影响定点刷新](./arkts-ui-widget-update-by-time.md) | 布尔类型 | 可缺省,缺省值为false。 | + | isDynamic | 表示此卡片是否为动态卡片(仅针对ArkTS卡片生效)。
- true:为动态卡片。
- false:为静态卡片,当卡片添加成功后,将以静态图显示。 | 布尔类型 | 可缺省,缺省值为true。 | 配置示例如下: diff --git a/zh-cn/application-dev/application-models/arkts-ui-widget-update-by-proxy.md b/zh-cn/application-dev/application-models/arkts-ui-widget-update-by-proxy.md index 6f995e544e3c27be0aac36f334b485c7e69baa22..109dad778e2361330dc7343cf0b51168c0f03640 100644 --- a/zh-cn/application-dev/application-models/arkts-ui-widget-update-by-proxy.md +++ b/zh-cn/application-dev/application-models/arkts-ui-widget-update-by-proxy.md @@ -28,7 +28,7 @@ 1. 数据提供方以`key + subscriberId`作为数据的标识,将数据存储到数据库。 2. 数据管理服务感知到数据库变化,将新的数据发布给当前注册的所有订阅实例。 3. 卡片管理服务从订阅实例中解析出数据,发送给卡片渲染服务。 -4. 卡片渲染服务运行卡片页面代码widgets.abc,widgets.abc按新数据进行渲染,并将渲染后的数据发送至卡片使用方对应的[卡片组件](https://gitee.com/openharmony/docs/blob/fd489446c497c09d86ffa3beafd73dad90f1adb6/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-formcomponent.md)。 +4. 卡片渲染服务运行卡片页面代码widgets.abc,widgets.abc按新数据进行渲染,并将渲染后的数据发送至卡片使用方对应的[卡片组件](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-formcomponent.md)。 数据提供方提供的共享数据有两种类型: @@ -177,7 +177,7 @@ } ``` -- 在卡片页面代码widgets.abc中,通过LocalStorage变量获取订阅到的数据,LocalStorage绑定了一个字符串,以key:value的键值对格式来刷新卡片订阅数据,其中key必须与卡片提供方订阅的key保持一致。示例中,通过'list'获取订阅的数据,并把第一个元素的值显示在Text组件上。 +- 在卡片页面代码文件(一般为工程中卡片目录下pages目录中的.ets文件)中,通过LocalStorage变量获取订阅到的数据,LocalStorage绑定了一个字符串,以key:value的键值对格式来刷新卡片订阅数据,其中key必须与卡片提供方订阅的key保持一致。示例中,通过'list'获取订阅的数据,并把第一个元素的值显示在Text组件上。 ```ts let storage = new LocalStorage(); @Entry(storage) diff --git a/zh-cn/application-dev/application-models/arkts-ui-widget-update-by-status.md b/zh-cn/application-dev/application-models/arkts-ui-widget-update-by-status.md index 50e72306f7ab210debc55ee69f04d084b641ab29..c987a54bf9f52e28025d4df47cc61a80e2bcf24d 100644 --- a/zh-cn/application-dev/application-models/arkts-ui-widget-update-by-status.md +++ b/zh-cn/application-dev/application-models/arkts-ui-widget-update-by-status.md @@ -20,7 +20,8 @@ }, "colorMode": "auto", "isDefault": true, - "updateEnabled": true,"scheduledUpdateTime": "07:00", + "updateEnabled": true, + "scheduledUpdateTime": "07:00", "updateDuration": 0, "defaultDimension": "2*2", "supportDimensions": ["2*2"] @@ -102,10 +103,15 @@ let isTempCard: boolean = want.parameters[formInfo.FormParam.TEMPORARY_KEY]; if (isTempCard === false) { // 如果为常态卡片,直接进行信息持久化 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((storeDB) => { + console.info("Succeeded to get preferences."); + storeDB.putSync('A' + formId, 'false'); + storeDB.putSync('B' + formId, 'false'); + storeDB.flush(); + }).catch((err) => { + console.info(`Failed to get preferences. ${JSON.stringify(err)}`); + }) } let formData = {}; return formBindingData.createFormBindingData(formData); @@ -113,54 +119,71 @@ 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((storeDB) => { + console.info("Succeeded to get preferences."); + storeDB.deleteSync('A' + formId); + storeDB.deleteSync('B' + formId); + }).catch((err) => { + console.info(`Failed to get preferences. ${JSON.stringify(err)}`); + }) } // 如果在添加时为临时卡片,则建议转为常态卡片时进行信息持久化 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((storeDB) => { + console.info("Succeeded to get preferences."); + storeDB.putSync('A' + formId, 'false'); + storeDB.putSync('B' + formId, 'false'); + 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() - // A状态选中则更新textA - if (stateA === 'true') { - let formInfo = formBindingData.createFormBindingData({ - 'textA': 'AAA' - }) - formProvider.updateForm(formId, formInfo) - } - // B状态选中则更新textB - if (stateB === 'true') { - let formInfo = formBindingData.createFormBindingData({ - 'textB': 'BBB' - }) - formProvider.updateForm(formId, formInfo) - } + let promise = dataPreferences.getPreferences(this.context, 'myStore'); + promise.then((storeDB) => { + console.info("Succeeded to get preferences."); + let stateA = storeDB.getSync('A' + formId, 'false').toString(); + let stateB = storeDB.getSync('B' + formId, 'false').toString(); + // A状态选中则更新textA + if (stateA === 'true') { + let formInfo = formBindingData.createFormBindingData({'textA': 'AAA'}); + formProvider.updateForm(formId, formInfo); + } + // B状态选中则更新textB + if (stateB === 'true') { + let formInfo = formBindingData.createFormBindingData({'textB': 'BBB'}); + 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) { // 存放卡片状态 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((storeDB) => { + console.info("Succeeded to get preferences."); + let msg = JSON.parse(message); + if (msg.selectA != undefined) { + console.info('onFormEvent selectA info:' + msg.selectA); + storeDB.putSync('A' + formId, msg.selectA); + } + if (msg.selectB != undefined) { + console.info('onFormEvent selectB info:' + msg.selectB); + storeDB.putSync('B' + formId, msg.selectB); + } + storeDB.flush(); + }).catch((err) => { + console.info(`Failed to get preferences. ${JSON.stringify(err)}`); + }) } }; ``` diff --git a/zh-cn/application-dev/application-models/hop-cross-device-migration.md b/zh-cn/application-dev/application-models/hop-cross-device-migration.md index 15ae649e92f317971c329da22f27318d5edde851..19ae439ffc1a931b131658a6fb342f47f6fa5f0f 100644 --- a/zh-cn/application-dev/application-models/hop-cross-device-migration.md +++ b/zh-cn/application-dev/application-models/hop-cross-device-migration.md @@ -11,6 +11,12 @@ - 支持应用兼容性检测。 +- 支持应用根据实际使用场景动态设置迁移状态(默认迁移状态为ACTIVE激活状态)。如编辑类应用在编辑文本的页面下才需要迁移,其他页面不需要迁移,则可以通过[setMissionContinueState](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissioncontinuestate10)进行控制。 + +- 支持应用动态选择是否进行页面栈恢复(默认进行页面栈信息恢复)。如应用希望自定义迁移到其他设备后显示的页面,则可以通过[SUPPORT_CONTINUE_PAGE_STACK_KEY](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams)进行控制。 + +- 支持应用动态选择流转成功后是否退出迁移发起端应用(默认流转成功后退出迁移发起端应用)。则可以通过[SUPPORT_CONTINUE_SOURCE_EXIT_KEY](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams)进行控制。 + ## 跨端迁移流程 @@ -125,3 +131,63 @@ } ``` - 如果是单实例应用,则采用同样的代码实现onNewWant()接口即可。 + +6. **可选配置:** 在应用支持迁移特性时,默认开启应用迁移状态开关,根据应用当前任务获取焦点/失去焦点通知周边的可信设备当前任务可流转/取消流转。若应用需要在特定场景下才通知周边设备可流转,则需要在应用打开时设置迁移状态为INACTIVE,在后续的业务流程中需要迁移时再设置迁移状态为ACTIVE。接口见[setMissionContinueState](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissioncontinuestate10)。 + + - 示例:应用启动不需要流转 + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + import AbilityConstant from '@ohos.app.ability.AbilityConstant'; + + onCreate(want, launchParam) { + this.context.setMissionContinueState(AbilityConstant.ContinueState.INACTIVE, (result) => { + console.info(`setMissionContinueState: ${JSON.stringify(result)}`); + }); + } + ``` + - 示例:应用在后续的业务流程中需要流转了 + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + import AbilityConstant from '@ohos.app.ability.AbilityConstant'; + + this.context.setMissionContinueState(AbilityConstant.ContinueState.ACTIVE, (result) => { + console.info(`setMissionContinueState: ${JSON.stringify(result)}`); + }); + ``` + +7. **可选配置:** 支持应用动态选择是否进行页面栈恢复(默认进行页面栈信息恢复)。如果应用不想使用系统默认恢复的页面栈,则可以设置不进行页面栈迁移,而需要在`onWindowStageRestore`设置流转后进入的页面,参数定义见[SUPPORT_CONTINUE_PAGE_STACK_KEY](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams)。 + + - 示例:应用迁移不需要自动流转页面栈信息 + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + import wantConstant from '@ohos.app.ability.wantConstant.d.ts'; + + onContinue(wantParam : {[key: string]: any}) { + console.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`) + wantParam[wantConstant.SUPPORT_CONTINUE_PAGE_STACK_KEY] = false; + return AbilityConstant.OnContinueResult.AGREE; + } + + onWindowStageRestore(windowStage) { + // 若不需要自动流转页面栈信息,则需要在此处设置应用流转后进入的页面 + windowStage.setUIContent(this.contex, "pages/index", null); + } + ``` + +8. **可选配置:** 支持应用动态选择迁移成功后是否退出迁移发起端应用(默认流转成功后退出迁移发起端应用)。如果应用不想让系统自动退出迁移发起端应用,则可以设置不退出,参数定义见参数定义见[SUPPORT_CONTINUE_SOURCE_EXIT_KEY](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams)。 + + - 示例:应用迁移设置不需要迁移成功后退出迁移发起端应用 + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + import wantConstant from '@ohos.app.ability.wantConstant.d.ts'; + + onContinue(wantParam : {[key: string]: any}) { + console.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`) + wantParam[wantConstant.SUPPORT_CONTINUE_SOURCE_EXIT_KEY] = false; + return AbilityConstant.OnContinueResult.AGREE; + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/application-models/inter-device-interaction-hop-overview.md b/zh-cn/application-dev/application-models/inter-device-interaction-hop-overview.md index 5ae4d34ac74c74effd322e9933cf39014c934e82..94f2d55e2a39282e55ec353192854301107c02ad 100644 --- a/zh-cn/application-dev/application-models/inter-device-interaction-hop-overview.md +++ b/zh-cn/application-dev/application-models/inter-device-interaction-hop-overview.md @@ -16,11 +16,11 @@ - **跨端迁移** - 在用户使用设备的过程中,当使用情境发生变化时(例如从室内走到户外或者周围有更合适的设备等),之前使用的设备可能已经不适合继续当前的任务,此时,用户可以选择新的设备来继续当前的任务,原设备退出任务,这就是跨端迁移场景。常见的跨端迁移场景实例:在平板上播放的视频,迁移到智慧屏继续播放,从而获得更佳的观看体验;平板上的视频应用退出。在应用开发层面,跨端迁移指在A端运行的UIAbility迁移到B端上,完成迁移后, B端UIAbility继续任务,而A端UIAbility退出。 + 在用户使用设备的过程中,当使用情境发生变化时(例如从室内走到户外或者周围有更合适的设备等),之前使用的设备可能已经不适合继续当前的任务,此时,用户可以选择新的设备来继续当前的任务,原设备可按需决定是否退出任务,这就是跨端迁移场景。常见的跨端迁移场景实例:在平板上播放的视频,迁移到智慧屏继续播放,从而获得更佳的观看体验;平板上的视频应用退出。在应用开发层面,跨端迁移指在A端运行的UIAbility迁移到B端上,完成迁移后, B端UIAbility继续任务,而A端UIAbility可按需决定是否退出。 - **多端协同** - 用户拥有的多个设备,可以作为一个整体,为用户提供比单设备更加高效、沉浸的体验,这就是多端协同场景。常见的多端协同场景实例:平板侧应用A做答题板,智慧屏侧应用B做直播,为用户提供更优的上网课体验。在应用开发层面,多端协同指多端上的不同UIAbility/ServiceExtensionAbility同时运行、或者交替运行实现完整的业务;或者多端上的相同UIAbility/ServiceExtensionAbility同时运行实现完整的业务。 + 用户拥有的多个设备,可以作为一个整体,为用户提供比单设备更加高效、沉浸的体验,这就是多端协同场景。常见的多端协同场景实例:场景一:两台设备A和B打开备忘录同一篇笔记进行双端协同编辑,在设备A上可以使用本地图库中的图片资源插入编辑,设备B上进行文字内容编辑。场景二:设备A上正在和客户进行聊天,客户需要的资料在设备B上,可以通过聊天软件打开设备B上的文档应用选择到想要的资料回传到设备A上,然后通过聊天软件发送给客户。在应用开发层面,多端协同指多端上的不同UIAbility/ServiceExtensionAbility同时运行、或者交替运行实现完整的业务;或者多端上的相同UIAbility/ServiceExtensionAbility同时运行实现完整的业务。 ## 流转架构 diff --git a/zh-cn/application-dev/database/share-data-by-silent-access.md b/zh-cn/application-dev/database/share-data-by-silent-access.md index eb531ac0880f9a0783c6ada9d333d644253b620f..60d13a072f7da5fe9420509790833ed40e541363 100644 --- a/zh-cn/application-dev/database/share-data-by-silent-access.md +++ b/zh-cn/application-dev/database/share-data-by-silent-access.md @@ -96,8 +96,8 @@ | 属性名称 | 备注说明 | 必填 | | ----------------------- | ---------------------------------------- | ---- | | uri | 数据使用的URI,是跨应用数据访问的唯一标识。 | 是 | - | requiredReadPermission | 访问数据时需要的权限,不配置默认不允许其他APP访问数据。 | 否 | - | requiredWritePermission | 修改数据时需要的权限,不配置默认不允许其他APP修改数据。 | 否 | + | requiredReadPermission | 标识从该数据代理读取数据时所需要的权限,不配置默认不允许其他APP访问数据。支持权限可参考[权限列表](../security/permission-list.md)。 | 否 | + | requiredWritePermission | 标识从该数据代理修改数据时所需要的权限,不配置默认不允许其他APP修改数据。支持权限可参考[权限列表](../security/permission-list.md)。 | 否 | | metadata | 数据源的信息,包含name和resource字段。
name类型固定为"dataProperties",是配置的唯一标识。
resource类型固定为"$profile:{fileName}",表示配置文件的名称为{fileName}.json。 | 是 | **module.json5配置样例:** @@ -107,7 +107,7 @@ { "uri": "datashareproxy://com.acts.ohos.data.datasharetest/test", "requiredReadPermission": "ohos.permission.GET_BUNDLE_INFO", - "requiredWritePermission": "ohos.permission.GET_BUNDLE_INFO", + "requiredWritePermission": "ohos.permission.KEEP_BACKGROUND_RUNNING", "metadata": { "name": "dataProperties", "resource": "$profile:my_config" @@ -244,8 +244,8 @@ | 属性名称 | 备注说明 | 必填 | | ----------------------- | ----------------------------- | ---- | | uri | 数据使用的URI,是跨应用数据访问的唯一标识。 | 是 | -| requiredReadPermission | 访问数据时需要的权限,不配置默认不允许其他APP访问数据。 | 否 | -| requiredWritePermission | 修改数据时需要的权限,不配置默认不允许其他APP修改数据。 | 否 | +| requiredReadPermission | 标识从该数据代理读取数据时所需要的权限,不配置默认不允许其他APP访问数据。支持权限可参考[权限列表](../security/permission-list.md)。 | 否 | +| requiredWritePermission | 标识从该数据代理修改数据时所需要的权限,不配置默认不允许其他APP访问数据。支持权限可参考[权限列表](../security/permission-list.md)。 | 否 | **module.json5配置样例:** @@ -254,7 +254,7 @@ { "uri": "datashareproxy://com.acts.ohos.data.datasharetest/weather", "requiredReadPermission": "ohos.permission.GET_BUNDLE_INFO", - "requiredWritePermission": "ohos.permission.GET_BUNDLE_INFO" + "requiredWritePermission": "ohos.permission.KEEP_BACKGROUND_RUNNING" } ] ``` diff --git a/zh-cn/application-dev/device/sensor-guidelines.md b/zh-cn/application-dev/device/sensor-guidelines.md index 7aff46d15fa239fa19f6c209a4d6a6c488f0312b..7f29c74cd246735a04cf89c5d89d6df465db66e5 100644 --- a/zh-cn/application-dev/device/sensor-guidelines.md +++ b/zh-cn/application-dev/device/sensor-guidelines.md @@ -33,10 +33,11 @@ 2. 以下场景以加速度传感器ACCELEROMETER为例。展示持续监听传感器接口的调用结果。 - ```js + ```ts import sensor from "@ohos.sensor"; - sensor.on(sensor.SensorId.ACCELEROMETER, function(data){ - console.info("Data obtained successfully. x: " + data.x + "y: " + data.y + "z: " + data.z); // 获取数据成功 + + sensor.on(sensor.SensorId.ACCELEROMETER, function (data) { + console.info("Succeeded in obtaining data. x: " + data.x + "y: " + data.y + "z: " + data.z); // 获取数据成功 }); ``` @@ -44,7 +45,7 @@ 3. 注销传感器数据监听。 - ```js + ```ts import sensor from "@ohos.sensor"; sensor.off(sensor.SensorId.ACCELEROMETER); ``` @@ -53,10 +54,11 @@ 4. 获取一次传感器数据变化。 - ```js + ```ts import sensor from "@ohos.sensor"; - sensor.once(sensor.SensorId.ACCELEROMETER, function(data) { - console.info("Data obtained successfully. x: " + data.x + "y: " + data.y + "z: " + data.z); // 获取数据成功 + + sensor.once(sensor.SensorId.ACCELEROMETER, function (data) { + console.info("Succeeded in obtaining data. x: " + data.x + "y: " + data.y + "z: " + data.z); // 获取数据成功 }); ``` @@ -64,15 +66,16 @@ 若接口调用不成功,建议使用try/catch语句捕获代码中可能出现的错误信息。例如: - ```js + ```ts import sensor from "@ohos.sensor"; - try { - sensor.once(sensor.SensorId.ACCELEROMETER, function(data) { - console.info("Data obtained successfully. x: " + data.x + "y: " + data.y + "z: " + data.z); // 获取数据成功 - }); - } catch (error) { - console.error("Get sensor data error. data:" + error.data, " msg:", error.message); - } + + try { + sensor.once(sensor.SensorId.ACCELEROMETER, function (data) { + console.info("Succeeded in obtaining data. x: " + data.x + "y: " + data.y + "z: " + data.z); // 获取数据成功 + }); + } catch (error) { + console.error(`Failed to get sensor data. Code: ${error.code}, message: ${error.message}`); + } ``` ## 相关实例 diff --git a/zh-cn/application-dev/device/vibrator-guidelines.md b/zh-cn/application-dev/device/vibrator-guidelines.md index f28e42dc65b4754fe863e8558b5d9e2be3424200..8e3b36af9cef3a6bee7f77d7ad87b423bc7e5fd2 100644 --- a/zh-cn/application-dev/device/vibrator-guidelines.md +++ b/zh-cn/application-dev/device/vibrator-guidelines.md @@ -110,171 +110,162 @@ Json文件共包含2个属性。 2. 根据指定振动效果和振动属性触发马达振动。 -```js +```ts import vibrator from '@ohos.vibrator'; + try { - vibrator.startVibration({ // 使用startVibration需要添加ohos.permission.VIBRATE权限 - type: 'time', - duration: 1000, - }, { - id: 0, - usage: 'alarm' - }, (error) => { - if (error) { - console.error('vibrate fail, error.code: ' + error.code + 'error.message: ', + error.message); - return; - } - console.log('Callback returned to indicate a successful vibration.'); - }); + vibrator.startVibration({ // 使用startVibration需要添加ohos.permission.VIBRATE权限 + type: 'time', + duration: 1000, + }, { + id: 0, + usage: 'alarm' + }, (error) => { + if (error) { + console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); + return; + } + console.info('Succeed in starting vibration.'); + }); } catch (err) { - console.error('errCode: ' + err.code + ' ,msg: ' + err.message); + console.error(`An unexpected error occurred. Code: ${err.code}, message: ${err.message}`); } ``` 3. 按照指定模式停止马达的振动。 -```js +```ts import vibrator from '@ohos.vibrator'; + try { - // 按照VIBRATOR_STOP_MODE_TIME模式停止振动, 使用stopVibration需要添加ohos.permission.VIBRATE权限 - vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_TIME, function (error) { - if (error) { - console.log('error.code' + error.code + 'error.message' + error.message); - return; - } - console.log('Callback returned to indicate successful.'); - }) + // 按照VIBRATOR_STOP_MODE_TIME模式停止振动, 使用stopVibration需要添加ohos.permission.VIBRATE权限 + vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_TIME, function (error) { + if (error) { + console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); + return; + } + console.info('Succeeded in stopping vibration.'); + }) } catch (err) { - console.info('errCode: ' + err.code + ' ,msg: ' + err.message); + console.error(`An unexpected error occurred. Code: ${err.code}, message: ${err.message}`); } ``` 4. 停止所有模式的马达振动。 -```js +```ts import vibrator from '@ohos.vibrator'; // 使用startVibration、stopVibration需要添加ohos.permission.VIBRATE权限 try { - vibrator.startVibration({ - type: 'time', - duration: 1000, - }, { - id: 0, - usage: 'alarm' - }, (error) => { - if (error) { - console.error('vibrate fail, error.code: ' + error.code + 'error.message: ', + error.message); - return; - } - console.log('Callback returned to indicate a successful vibration.'); - }); - // 停止所有类型的马达振动 - vibrator.stopVibration(function (error) { - if (error) { - console.log('error.code' + error.code + 'error.message' + error.message); - return; - } - console.log('Callback returned to indicate successful.'); - }) + vibrator.startVibration({ + type: 'time', + duration: 1000, + }, { + id: 0, + usage: 'alarm' + }, (error) => { + if (error) { + console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); + return; + } + console.info('Succeed in starting vibration'); + }); + // 停止所有类型的马达振动 + vibrator.stopVibration(function (error) { + if (error) { + console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); + return; + } + console.info('Succeed in stopping vibration'); + }) } catch (error) { - console.info('errCode: ' + error.code + ' ,msg: ' + error.message); + console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`); } ``` 5. 查询是否支持传入的参数effectId。 -```js +```ts import vibrator from '@ohos.vibrator'; + try { - // 查询是否支持'haptic.clock.timer' - vibrator.isSupportEffect('haptic.clock.timer', function (err, state) { - if (err) { - console.error('isSupportEffect failed, error:' + JSON.stringify(err)); - return; - } - console.log('The effectId is ' + (state ? 'supported' : 'unsupported')); - if (state) { - try { - vibrator.startVibration({ // 使用startVibration需要添加ohos.permission.VIBRATE权限 - type: 'preset', - effectId: 'haptic.clock.timer', - count: 1, - }, { - usage: 'unknown' - }, (error) => { - if(error) { - console.error('haptic.clock.timer vibrator error:' + JSON.stringify(error)); - } else { - console.log('haptic.clock.timer vibrator success'); - } - }); - } catch (error) { - console.error('Exception in, error:' + JSON.stringify(error)); - } - } - }) + // 查询是否支持'haptic.clock.timer' + vibrator.isSupportEffect('haptic.clock.timer', function (err, state) { + if (err) { + console.error(`Failed to query effect. Code: ${err.code}, message: ${err.message}`); + return; + } + console.info('Succeed in querying effect'); + if (state) { + try { + vibrator.startVibration({ // 使用startVibration需要添加ohos.permission.VIBRATE权限 + type: 'preset', + effectId: 'haptic.clock.timer', + count: 1, + }, { + usage: 'unknown' + }, (error) => { + if (error) { + console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); + } else { + console.info('Succeed in starting vibration'); + } + }); + } catch (error) { + console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`); + } + } + }) } catch (error) { - console.error('Exception in, error:' + JSON.stringify(error)); + console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`); } ``` 6. 启动和停止自定义振动 -```js +```ts import vibrator from '@ohos.vibrator'; -import resourceManager from '@ohos.resourceManager'; const FILE_NAME = "xxx.json"; -async function openResource(fileName) { - let fileDescriptor = undefined; - let mgr = await resourceManager.getResourceManager(); - await mgr.getRawFd(fileName).then(value => { - fileDescriptor = {fd: value.fd, offset: value.offset, length: value.length}; - console.log('openResource success fileName: ' + fileName); - }).catch(error => { - console.log('openResource err: ' + error); - }); - return fileDescriptor; -} - -async function closeResource(fileName) { - let mgr = await resourceManager.getResourceManager(); - await mgr.closeRawFd(fileName).then(()=> { - console.log('closeResource success fileName: ' + fileName); - }).catch(error => { - console.log('closeResource err: ' + error); - }); -} - // 获取振动文件资源描述符 -let rawFd = openResource(FILE_NAME); +let fileDescriptor = undefined; +getContext().resourceManager.getRawFd(FILE_NAME).then(value => { + fileDescriptor = { fd: value.fd, offset: value.offset, length: value.length }; + console.info('Succeed in getting resource file descriptor'); +}).catch(error => { + console.error(`Failed to get resource file descriptor. Code: ${error.code}, message: ${error.message}`); +}); // 使用startVibration、stopVibration需要添加ohos.permission.VIBRATE权限 try { - // 启动自定义振动 - vibrator.startVibration({ - type: "file", - hapticFd: { fd: rawFd.fd, offset: rawFd.offset, length: rawFd.length } - }, { - usage: "alarm" - }).then(() => { - console.info('startVibration success'); - }, (error) => { - console.info('startVibration error'); - }); - // 停止所有类型的马达振动 - vibrator.stopVibration(function (error) { - if (error) { - console.log('error.code' + error.code + 'error.message' + error.message); - return; - } - console.log('Callback returned to indicate successful.'); - }) + // 启动自定义振动 + vibrator.startVibration({ + type: "file", + hapticFd: { fd: fileDescriptor.fd, offset: fileDescriptor.offset, length: fileDescriptor.length } + }, { + usage: "alarm" + }).then(() => { + console.info('Succeed in starting vibration'); + }, (error) => { + console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); + }); + // 停止所有类型的马达振动 + vibrator.stopVibration(function (error) { + if (error) { + console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); + return; + } + console.info('Succeed in stopping vibration'); + }) } catch (error) { - console.info('errCode: ' + error.code + ' ,msg: ' + error.message); + console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`); } // 关闭振动文件资源 -closeResource(FILE_NAME); +getContext().resourceManager.closeRawFd(FILE_NAME).then(() => { + console.info('Succeed in closing resource file descriptor'); +}).catch(error => { + console.error(`Failed to close resource file descriptor. Code: ${error.code}, message: ${error.message}`); +}); ``` diff --git a/zh-cn/application-dev/napi/Readme-CN.md b/zh-cn/application-dev/napi/Readme-CN.md index c636ceb7e209fa44d8c8a151d059460121201b30..63e113fd565da1838c64a3c11d09bb4450e63efa 100644 --- a/zh-cn/application-dev/napi/Readme-CN.md +++ b/zh-cn/application-dev/napi/Readme-CN.md @@ -3,9 +3,13 @@ - [Native API在应用工程中的使用指导](napi-guidelines.md) - [Drawing开发指导](drawing-guidelines.md) - [Rawfile开发指导](rawfile-guidelines.md) +- [NativeBuffer开发指导](native-buffer-guidelines.md) +- [NativeImage开发指导](native-image-guidelines.md) +- [NativeVsync开发指导](native-vsync-guidelines.md) - [NativeWindow开发指导](native-window-guidelines.md) - [使用MindSpore Lite引擎进行模型推理](mindspore-lite-guidelines.md) - [使用MindSpore Lite进行离线模型的转换及推理](mindspore-lite-offline-model-guidelines.md) - [Neural Network Runtime对接AI推理框架开发指导](neural-network-runtime-guidelines.md) - [Purgeable memory开发指导](purgeable-memory-guidelines.md) -- [XComponent开发指导](xcomponent-guidelines.md) \ No newline at end of file +- [XComponent开发指导](xcomponent-guidelines.md) +- [USB DDK开发指导](usb-ddk-guidelines.md) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/Readme-CN.md b/zh-cn/application-dev/reference/apis/Readme-CN.md index 65b7259c43d51c7a0e5bfe68dfb9258137947bb8..3fa6dc388c00de7477e90d0d2163b801a5080e6f 100644 --- a/zh-cn/application-dev/reference/apis/Readme-CN.md +++ b/zh-cn/application-dev/reference/apis/Readme-CN.md @@ -418,7 +418,7 @@ - [@ohos.enterprise.dateTimeManager (系统时间管理)](js-apis-enterprise-dateTimeManager.md) - [@ohos.enterprise.deviceControl (设备控制管理)](js-apis-enterprise-deviceControl.md) - [@ohos.enterprise.deviceInfo (设备信息管理)](js-apis-enterprise-deviceInfo.md) - - [@ohos.enterprise.deviceSettings (设备设置管理)](js-apis-enterprise-deviceSetings.md) + - [@ohos.enterprise.deviceSettings (设备设置管理)](js-apis-enterprise-deviceSettings.md) - [@ohos.enterprise.EnterpriseAdminExtensionAbility (企业设备管理扩展能力)](js-apis-EnterpriseAdminExtensionAbility.md) - [@ohos.enterprise.networkManager (网络管理)](js-apis-enterprise-networkManager.md) - [@ohos.enterprise.wifiManager (WiFi管理)](js-apis-enterprise-wifiManager.md) diff --git a/zh-cn/application-dev/reference/apis/js-apis-animator.md b/zh-cn/application-dev/reference/apis/js-apis-animator.md index 3ac6b825f076091727b05439ad32a8afefaafcc5..b8c7db9204ff2d698da536c69a1836e33300b1fa 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-animator.md +++ b/zh-cn/application-dev/reference/apis/js-apis-animator.md @@ -6,7 +6,7 @@ > > 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > -> 该模块不支持在[UIAbility](./js-apis-app-ability-uiAbility.md)中使用,需要在创建组件实例后使用。 +> 该模块不支持在[UIAbility](./js-apis-app-ability-uiAbility.md)的文件声明处使用,即不能在UIAbility的生命周期中调用,需要在创建组件实例后使用。 > > 本模块功能依赖UI的执行上下文,不可在UI上下文不明确的地方使用,参见[UIContext](./js-apis-arkui-UIContext.md#uicontext)说明。 > diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md index cc9a9513625b22a83daa8b51ea3073ada17af722..55d8921d2a93b52d2b9b9739e55ad247cb3c5220 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md @@ -223,4 +223,25 @@ class MyAbility extends UIAbility { return AbilityConstant.OnSaveResult.ALL_AGREE; } } +``` + +## AbilityConstant.ContinueState10+ + +ContinueState说明枚举值。用于表示当前应用任务流转的状态。可配合[UIAbilityContext](js-apis-inner-application-uiAbilityContext.md)的[setMissionContinueState](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissioncontinuestate10)方法进行设置。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +| 名称 | 值 | 说明 | +| ------------- | --------- | ------------------------------------------------------------ | +| ACTIVE | 0 | 指示当前应用任务流转处于激活状态。 | +| INACTIVE | 1 | 指示当前应用任务流转处于未激活状态。 | + +**示例:** + +```ts + import AbilityConstant from '@ohos.app.ability.AbilityConstant'; + + this.context.setMissionContinueState(AbilityConstant.ContinueState.INACTIVE, (result) => { + console.info(`setMissionContinueState: ${JSON.stringify(result)}`); + }); ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-common.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-common.md index 101320203d58556a56d6d5d742dd87d573148a05..b9fa6aa45bdda2596691cc3fd04785c3b5a7ad72 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-common.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-common.md @@ -12,6 +12,7 @@ Common模块将二级模块API组织在一起方便开发者进行导出。 ```ts import common from '@ohos.app.ability.common'; ``` +## 属性 **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-configuration.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-configuration.md index 1dedb6e904e4e37555c7c69199bc7e72751108d9..67ff713322188b7817a183df43a4e2c4446e6b29 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-configuration.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-configuration.md @@ -12,6 +12,8 @@ import Configuration from '@ohos.app.ability.Configuration'; ``` +## 属性 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase | 名称 | 类型 | 可读 | 可写 | 说明 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-missionManager.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-missionManager.md index 720a5a6b78bef9c78c93594f32d59781816299cc..dd967e7981f4e2b3aee42a2d67a63440c89b0149 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-missionManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-missionManager.md @@ -1098,3 +1098,315 @@ try { console.error('moveMissionToFront failed. Cause: ${error.message}'); } ``` + +## missionManager.moveMissionsToForeground10+ + +moveMissionsToForeground(missionIds: Array<number>, callback: AsyncCallback<void>): void; + +将指定任务批量切到前台,以回调函数的方式返回。 + +**需要权限**:ohos.permission.MANAGE_MISSIONS + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Mission + +**系统接口**: 此接口为系统接口。 + +**参数:** + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | missionIds | Array<number> | 是 | 任务ID数组。 | + | callback | AsyncCallback<void> | 是 | 执行结果回调函数。 | + +**错误码**: + +以下错误码的详细介绍请参见[errcode-ability](../errorcodes/errorcode-ability.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000050 | Internal error. | + +**示例:** + +```ts +import abilityManager from '@ohos.app.ability.abilityManager'; +import missionManager from '@ohos.app.ability.missionManager'; + +try { + missionManager.getMissionInfos("", 10, (error, missionInfos) => { + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code)); + return; + } + if (missionInfos.length < 1) { + return; + } + + let toShows = new Array(); + for (let missionInfo of missionInfos) { + if (missionInfo.abilityState == abilityManager.AbilityState.BACKGROUND) { + toShows.push(missionInfo.missionId); + } + } + missionManager.moveMissionsToForeground(toShows, (err, data) => { + if (err) { + console.error('moveMissionsToForeground failed: ${err.message}'); + } else { + console.info('moveMissionsToForeground successfully: ${JSON.stringify(data)}'); + } + }); + }); +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} + +``` + +## missionManager.moveMissionsToForeground10+ + +moveMissionsToForeground(missionIds: Array<number>, topMission: number, callback: AsyncCallback<void>): void; + +将指定任务批量切换到前台,并将任务ID等于topMission的任务移动到最顶层,以回调函数的方式返回。 + +**需要权限**:ohos.permission.MANAGE_MISSIONS + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Mission + +**系统接口**: 此接口为系统接口。 + +**参数:** + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | missionIds | Array<number> | 是 | 任务ID数组。 | + | topMission | number | 是 | 待移动到最顶层的任务ID | + | callback | AsyncCallback<void> | 是 | 执行结果回调函数。 | + +**错误码**: + +以下错误码的详细介绍请参见[errcode-ability](../errorcodes/errorcode-ability.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000050 | Internal error. | + +**示例:** + +```ts +import abilityManager from '@ohos.app.ability.abilityManager'; +import missionManager from '@ohos.app.ability.missionManager'; + +try { + missionManager.getMissionInfos("", 10, (error, missionInfos) => { + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code)); + return; + } + if (missionInfos.length < 1) { + return; + } + + let toShows = new Array(); + for (let missionInfo of missionInfos) { + if (missionInfo.abilityState == abilityManager.AbilityState.BACKGROUND) { + toShows.push(missionInfo.missionId); + } + } + missionManager.moveMissionsToForeground(toShows, toShows[0], (err, data) => { + if (err) { + console.error('moveMissionsToForeground failed: ${err.message}'); + } else { + console.info('moveMissionsToForeground successfully: ${JSON.stringify(data)}'); + } + }); + }); +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} + +``` + +## missionManager.moveMissionsToForeground10+ + +moveMissionsToForeground(missionIds: Array<number>, topMission?: number): Promise<void>; + +将指定任务批量切到前台,并将任务ID等于topMission的任务移动到最顶层,以promise的方式返回。 + +**需要权限**:ohos.permission.MANAGE_MISSIONS + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Mission + +**系统接口**: 此接口为系统接口。 + +**参数:** + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | missionIds | Array<number> | 是 | 任务ID数组。 | + | topMission | number | 否 | 待移动到最顶层的任务ID | + +**返回值:** + + | 类型 | 说明 | + | -------- | -------- | + | Promise<void> | promise方式返回执行结果。 | + +**错误码**: + +以下错误码的详细介绍请参见[errcode-ability](../errorcodes/errorcode-ability.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000050 | Internal error. | + +**示例:** + +```ts +import abilityManager from '@ohos.app.ability.abilityManager'; +import missionManager from '@ohos.app.ability.missionManager'; + +try { + missionManager.getMissionInfos("", 10, (error, missionInfos) => { + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code)); + return; + } + if (missionInfos.length < 1) { + return; + } + + let toShows = new Array(); + for (let missionInfo of missionInfos) { + if (missionInfo.abilityState == abilityManager.AbilityState.BACKGROUND) { + toShows.push(missionInfo.missionId); + } + } + missionManager.moveMissionsToForeground(toShows, toShows[0]).then(() => { + console.log("moveMissionsToForeground is called" ); + }); + }); +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} + +``` + +## missionManager.moveMissionsToBackground10+ + +moveMissionsToBackground(missionIds: Array<number>, callback: AsyncCallback<Array<number>>): void; + +将指定任务批量切到后台,以回调函数的方式返回, 返回的结果任务ID按被隐藏时的任务层级排序。 + +**需要权限**:ohos.permission.MANAGE_MISSIONS + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Mission + +**系统接口**: 此接口为系统接口。 + +**参数:** + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | missionIds | Array<number> | 是 | 任务ID数组。 | + | callback | AsyncCallback<Array<number>> | 是 | 执行结果回调函数。 | + +**错误码**: + +以下错误码的详细介绍请参见[errcode-ability](../errorcodes/errorcode-ability.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000050 | Internal error. | + +**示例:** + +```ts +import abilityManager from '@ohos.app.ability.abilityManager'; +import missionManager from '@ohos.app.ability.missionManager'; + +try { + missionManager.getMissionInfos("", 10, (error, missionInfos) => { + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code)); + return; + } + + let toHides = new Array(); + for (let missionInfo of missionInfos) { + if (missionInfo.abilityState == abilityManager.AbilityState.FOREGROUND) { + toHides.push(missionInfo.missionId); + } + } + missionManager.moveMissionsToBackground(toHides, (err, data) => { + if (err) { + console.error('moveMissionsToBackground failed: ${err.message}'); + } else { + console.info('moveMissionsToBackground successfully: ${JSON.stringify(data)}'); + } + }); + }); +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} +``` + +## missionManager.moveMissionsToBackground10+ + +moveMissionsToBackground(missionIds : Array<number>): Promise<Array<number>>; + +将指定任务批量切到后台,以promise的方式返回, 返回的结果按被隐藏时的任务层级排序。 + +**需要权限**:ohos.permission.MANAGE_MISSIONS + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Mission + +**系统接口**: 此接口为系统接口。 + +**参数:** + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | missionIds | Array<number> | 是 | 任务ID数组。 | + +**返回值:** + + | 类型 | 说明 | + | -------- | -------- | + | Promise<Array<number>> | promise方式返回执行结果。 | + +**错误码**: + +以下错误码的详细介绍请参见[errcode-ability](../errorcodes/errorcode-ability.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000050 | Internal error. | + +**示例:** + +```ts +import abilityManager from '@ohos.app.ability.abilityManager'; +import missionManager from '@ohos.app.ability.missionManager'; + +try { + missionManager.getMissionInfos("", 10, (error, missionInfos) => { + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code)); + return; + } + + let toHides = new Array(); + for (let missionInfo of missionInfos) { + if (missionInfo.abilityState == abilityManager.AbilityState.FOREGROUND) { + toHides.push(missionInfo.missionId); + } + } + missionManager.moveMissionsToBackground(toHides).then((hideRes) => { + console.log("moveMissionsToBackground is called, res: "+ JSON.stringify(hideRes)); + }); + }); +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} + +``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-wantConstant.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-wantConstant.md index a1ce62ff8ab645783150a2e0fafe48fcf34ef2e0..1533356acf0b9414b5582b9e919f53872883a579 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-wantConstant.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-wantConstant.md @@ -30,6 +30,8 @@ want的Params操作的常量。 | CONTENT_TITLE_KEY10+ | ohos.extra.param.key.contentTitle | 指示原子化服务支持分享标题的参数的操作。 | | SHARE_ABSTRACT_KEY10+ | ohos.extra.param.key.shareAbstract | 指示原子化服务支持分享内容的参数的操作。 | | SHARE_URL_KEY10+ | ohos.extra.param.key.shareUrl | 指示原子化服务支持分享链接的参数的操作。 | +| SUPPORT_CONTINUE_PAGE_STACK_KEY10+ | ohos.extra.param.key.supportContinuePageStack | 指示在跨端迁移过程中是否迁移页面栈信息,默认值为true,自动迁移页面栈信息。| +| SUPPORT_CONTINUE_SOURCE_EXIT_KEY10+ | ohos.extra.param.key.supportContinueSourceExit | 指示跨端迁移源端应用是否退出,默认值为true,源端应用自动退出。| ## wantConstant.Flags diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-form-formInfo.md b/zh-cn/application-dev/reference/apis/js-apis-app-form-formInfo.md index 4191b41094a31bfc5d32a08d07336aa3eed484a7..e60d7e4a11f74dd9aec3c31e6366a9327b276a8d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-form-formInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-form-formInfo.md @@ -26,7 +26,7 @@ import formInfo from '@ohos.app.form.formInfo'; | name | string | 是 | 否 | 卡片名称。 | | description | string | 是 | 否 | 卡片描述。 | | descriptionId10+ | number | 是 | 否 | 卡片描述id。 | -| type | [FormType](#formtype) | 是 | 否 | 卡片类型。当前支持JS卡片。 | +| type | [FormType](#formtype) | 是 | 否 | 卡片类型。当前支持JS卡片、ArkTS卡片。 | | jsComponentName | string | 是 | 否 | js卡片的组件名。 | | colorMode | [ColorMode](#colormode) | 是 | 否 | 卡片颜色模式。 | | isDefault | boolean | 是 | 否 | 卡片是否是默认卡片。 | @@ -38,6 +38,7 @@ import formInfo from '@ohos.app.form.formInfo'; | defaultDimension | number | 是 | 否 | 表示卡片规格 | | supportDimensions | Array<number> | 是 | 否 | 卡片支持的规格。具体可选规格参考[FormDimension](#formdimension) | | customizeData | {[key: string]: [value: string]} | 是 | 否 | 卡片用户数据。 | +| isDynamic10+ | boolean | 是 | 否 | 卡片是否为动态卡片。
仅ArkTS卡片区分动静态卡片,JS卡片均为动态卡片。 | ## FormType diff --git a/zh-cn/application-dev/reference/apis/js-apis-curve.md b/zh-cn/application-dev/reference/apis/js-apis-curve.md index dea0941b2592982aa338e192be156562f1e0115b..e4613c22133d79781486ca2e11bd04f0843b493c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-curve.md +++ b/zh-cn/application-dev/reference/apis/js-apis-curve.md @@ -25,9 +25,9 @@ initCurve(curve?: Curve): ICurve **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ----------------------------------------------- | ---- | ----------------------------------- | -| curve | [Curve](../arkui-ts/ts-appendix-enums.md#curve) | 否 | 曲线类型。
默认值:Curve.Linear | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | --------------- | ---- | ----------------------------------- | +| curve | [Curve](#curve) | 否 | 曲线类型。
默认值:Curve.Linear | **返回值:** @@ -35,6 +35,28 @@ initCurve(curve?: Curve): ICurve | ---------------------------------- | ---------------- | | [ICurve](#icurve) | 曲线的插值对象。 | +## Curve + +从API version 9开始,该接口支持在ArkTS卡片中使用。 + +**系统能力:** SystemCapability.ArkUI.ArkUI.Full + +| 名称 | 描述 | +| ------------------- | ------------------------------------------------------------ | +| Linear | 表示动画从头到尾的速度都是相同的。 | +| Ease | 表示动画以低速开始,然后加快,在结束前变慢,CubicBezier(0.25, 0.1, 0.25, 1.0)。 | +| EaseIn | 表示动画以低速开始,CubicBezier(0.42, 0.0, 1.0, 1.0)。 | +| EaseOut | 表示动画以低速结束,CubicBezier(0.0, 0.0, 0.58, 1.0)。 | +| EaseInOut | 表示动画以低速开始和结束,CubicBezier(0.42, 0.0, 0.58, 1.0)。 | +| FastOutSlowIn | 标准曲线,cubic-bezier(0.4, 0.0, 0.2, 1.0)。 | +| LinearOutSlowIn | 减速曲线,cubic-bezier(0.0, 0.0, 0.2, 1.0)。 | +| FastOutLinearIn | 加速曲线,cubic-bezier(0.4, 0.0, 1.0, 1.0)。 | +| ExtremeDeceleration | 急缓曲线,cubic-bezier(0.0, 0.0, 0.0, 1.0)。 | +| Sharp | 锐利曲线,cubic-bezier(0.33, 0.0, 0.67, 1.0)。 | +| Rhythm | 节奏曲线,cubic-bezier(0.7, 0.0, 0.2, 1.0)。 | +| Smooth | 平滑曲线,cubic-bezier(0.4, 0.0, 0.4, 1.0)。 | +| Friction | 阻尼曲线,CubicBezier(0.2, 0.0, 0.2, 1.0)。 | + **示例:** ```ts @@ -310,9 +332,9 @@ init(curve?: Curve): string **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ----------------------------------------------- | ---- | ----------------------------------- | -| curve | [Curve](../arkui-ts/ts-appendix-enums.md#curve) | 否 | 曲线类型。
默认值:Curve.Linear | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | --------------- | ---- | ----------------------------------- | +| curve | [Curve](#curve) | 否 | 曲线类型。
默认值:Curve.Linear | ## Curves.steps(deprecated) diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-dataShare.md b/zh-cn/application-dev/reference/apis/js-apis-data-dataShare.md index 8eac658728dd5ebf6261a9ed8526762d3db71cba..9108469149f87ad75973ac02caab20f5ce975cee 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-dataShare.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-dataShare.md @@ -199,7 +199,7 @@ try { | 名称 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | key | string | 是 | 指定发布数据的键。 | -| data | string \| [Ashmem](js-apis-rpc.md#ashmem8) | 是 | 指定发布的数据。如果数据很大,请使用Ashmem。 | +| data | string \| ArrayBuffer | 是 | 指定发布的数据。如果发布数据大小超过20KB,建议使用ArrayBuffer。 | | subscriberId | string | 是 | 指定订阅者id。 | ## RdbDataChangeNode10+ @@ -478,18 +478,15 @@ on(type: 'publishedDataChange', uris: Array<string>, subscriberId: string, **示例:** ```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 @@ publish(data: Array<PublishedItem>, bundleName: string, version: number, c **示例:** ```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) { diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-storage.md b/zh-cn/application-dev/reference/apis/js-apis-data-storage.md index 02ecf783227dffe73b28db6f9a42c2b7330efc9f..85ded0652b406729e84635eda37da8fc5001c087 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-storage.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-storage.md @@ -8,8 +8,6 @@ > - 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > > - 从API Version 9开始,该接口不再维护,推荐使用新接口[`@ohos.data.preferences`](js-apis-data-preferences.md)。 -> -> - 本模块接口仅可在FA模型下使用。 ## 导入模块 diff --git a/zh-cn/application-dev/reference/apis/js-apis-device-info.md b/zh-cn/application-dev/reference/apis/js-apis-device-info.md index f99ebdc0d39627cce008ad9219093251df48256a..3d2b4f5d23d1c3f575403db5729da635272cc44d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-device-info.md +++ b/zh-cn/application-dev/reference/apis/js-apis-device-info.md @@ -54,3 +54,112 @@ import deviceInfo from '@ohos.deviceInfo' | distributionOSVersion10+ | String | 是 | 否 | 发行版系统版本号。 | | distributionOSApiVersion10+ | number| 是 | 否 | 发行版系统api版本。 | | distributionOSReleaseType10+ | String | 是 | 否 | 发行版系统类型。 | + +**示例** + +``` + 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/zh-cn/application-dev/reference/apis/js-apis-enterprise-adminManager.md b/zh-cn/application-dev/reference/apis/js-apis-enterprise-adminManager.md index 8a40383016240006d26233edf8b4ca95f485d221..bf67f0143711ccafe447658bf38d737c612a0147 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-enterprise-adminManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-enterprise-adminManager.md @@ -949,10 +949,10 @@ adminManager.unsubscribeManagedEvent(wantTemp, events).then(() => { **系统API**: 此接口为系统接口。 -| 名称 | 类型 | 可读 | 可写 | 说明 | -| ----------- | --------| ---- | ----- | ------------------------------- | -| name | string | 是 | 否 | 表示设备管理员应用所属企业的名称。 | -| description | string | 是 | 否 | 表示设备管理员应用所属企业的描述。 | +| 名称 | 类型 | 必填 | 说明 | +| ----------- | --------| ---- | ------------------------------- | +| name | string | 是 | 表示设备管理员应用所属企业的名称。 | +| description | string | 是 | 表示设备管理员应用所属企业的描述。 | ## AdminType diff --git a/zh-cn/application-dev/reference/apis/js-apis-enterprise-networkManager.md b/zh-cn/application-dev/reference/apis/js-apis-enterprise-networkManager.md index d78499bf78eb2bf3e493f8ebf65f8052a8cbda54..58aa91556894286b9ab1cf42b14779af7473c10e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-enterprise-networkManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-enterprise-networkManager.md @@ -487,4 +487,425 @@ networkManager.setNetworkInterfaceDisabled(wantTemp, 'eth0', true).then(() => { }).catch((err) => { console.error(`Failed to set network interface disabled. Code: ${err.code}, message: ${err.message}`); }); -``` \ No newline at end of file +``` + +## networkManager.addIptablesFilterRule + +addIptablesFilterRule(admin: Want, filterRule: AddFilterRule, callback: AsyncCallback\): void + +指定设备管理员应用添加网络包过滤规则,使用callback形式返回。 + +**需要权限:** ohos.permission.ENTERPRISE_MANAGE_NETWORK + +**系统能力:** SystemCapability.Customization.EnterpriseDeviceManager + +**系统API**: 此接口为系统接口。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ------------------------------- | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | +| filterRule | [AddFilterRule](#addfilterrule) | 是 | 添加网络包过滤规则。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当接口调用成功,err为null,否则err为错误对象。 | + +**错误码**: + +以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md) + +| 错误码ID | 错误信息 | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | + +**示例:** + +```js +let wantTemp = { + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', +}; +let filterRule = { + "ruleNo": 1, + "srcAddr": "192.168.1.1-192.188.22.66", + "destAddr": "10.1.1.1", + "srcPort": "8080", + "destPort": "8080", + "uid": "9696", + "method": networkManager.AddMethod.APPEND, + "direction": networkManager.Direction.OUTPUT, + "action": networkManager.Action.DENY, + "protocol": networkManager.Protocol.UDP, +} + +networkManager.addIptablesFilterRule(wantTemp, filterRule, (err) => { + if (err) { + console.error(`Failed to set iptables filter rule. Code: ${err.code}, message: ${err.message}`); + return; + } + console.info(`Succeeded in setting iptables filter rule`); +}); +``` + +## networkManager.addIptablesFilterRule + +addIptablesFilterRule(admin: Want, filterRule: AddFilterRule): Promise\ + +指定设备管理员应用添加网络包过滤规则,使用Promise形式返回。 + +**需要权限:** ohos.permission.ENTERPRISE_MANAGE_NETWORK + +**系统能力:** SystemCapability.Customization.EnterpriseDeviceManager + +**系统API**: 此接口为系统接口。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ----------------------------------- | ---- | ------- | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | +| filterRule | [AddFilterRule](#addfilterrule) | 是 | 添加网络包过滤规则。 | + +**返回值:** + +| 类型 | 说明 | +| --------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。当添加网络包过滤规则失败时抛出错误对象。 | + +**错误码**: + +以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md) + +| 错误码ID | 错误信息 | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | + +**示例:** + +```js +let wantTemp = { + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', +}; +let filterRule = { + "ruleNo": 1, + "srcAddr": "192.168.1.1-192.188.22.66", + "destAddr": "10.1.1.1", + "srcPort": "8080", + "destPort": "8080", + "uid": "9696", + "method": networkManager.AddMethod.APPEND, + "direction": networkManager.Direction.OUTPUT, + "action": networkManager.Action.DENY, + "protocol": networkManager.Protocol.UDP, +} + +networkManager.addIptablesFilterRule(wantTemp, filterRule).then(() => { + console.info(`Succeeded in setting iptables filter rule`); +}).catch((err) => { + console.error(`Failed to set iptables filter rule. Code: ${err.code}, message: ${err.message}`); +}); +``` + +## networkManager.removeIptablesFilterRule + +removeIptablesFilterRule(admin: Want, filterRule: RemoveFilterRule, callback: AsyncCallback\): void + +指定设备管理员应用移除网络包过滤规则,使用callback形式返回。 + +**需要权限:** ohos.permission.ENTERPRISE_MANAGE_NETWORK + +**系统能力:** SystemCapability.Customization.EnterpriseDeviceManager + +**系统API**: 此接口为系统接口。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ------------------------------- | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | +| filterRule | [RemoveFilterRule](#removefilterrule) | 是 | 移除网络包过滤规则。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当接口调用成功,err为null,否则err为错误对象。 | + +**错误码**: + +以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md) + +| 错误码ID | 错误信息 | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | + +**示例:** + +```js +let wantTemp = { + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', +}; +let filterRule = { + "srcAddr": "192.168.1.1-192.188.22.66", + "destAddr": "10.1.1.1", + "srcPort": "8080", + "destPort": "8080", + "uid": "9696", + "direction": networkManager.Direction.OUTPUT, + "action": networkManager.Action.DENY, + "protocol": networkManager.Protocol.UDP, +} + +networkManager.removeIptablesFilterRule(wantTemp, filterRule, (err) => { + if (err) { + console.error(`Failed to remove iptables filter rule. Code: ${err.code}, message: ${err.message}`); + return; + } + console.info(`Succeeded in removing iptables filter rule`); +}); +``` + +## networkManager.removeIptablesFilterRule + +removeIptablesFilterRule(admin: Want, filterRule: RemoveFilterRule): Promise\ + +指定设备管理员应用移除网络包过滤规则,使用Promise形式返回。 + +**需要权限:** ohos.permission.ENTERPRISE_MANAGE_NETWORK + +**系统能力:** SystemCapability.Customization.EnterpriseDeviceManager + +**系统API**: 此接口为系统接口。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ----------------------------------- | ---- | ------- | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | +| filterRule | [RemoveFilterRule](#removefilterrule) | 是 | 移除网络包过滤规则。 | + +**返回值:** + +| 类型 | 说明 | +| --------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。当移除网络包过滤规则失败时抛出错误对象。 | + +**错误码**: + +以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md) + +| 错误码ID | 错误信息 | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | + +**示例:** + +```js +let wantTemp = { + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', +}; +let filterRule = { + "srcAddr": "192.168.1.1-192.188.22.66", + "destAddr": "10.1.1.1", + "srcPort": "8080", + "destPort": "8080", + "uid": "9696", + "direction": networkManager.Direction.OUTPUT, + "action": networkManager.Action.DENY, + "protocol": networkManager.Protocol.UDP, +} + +networkManager.removeIptablesFilterRule(wantTemp, filterRule).then(() => { + console.info(`Succeeded in removing iptables filter rule`); +}).catch((err) => { + console.error(`Failed to remove iptables filter rule. Code: ${err.code}, message: ${err.message}`); +}); +``` + +## networkManager.listIptablesFilterRules + +listIptablesFilterRules(admin: Want, callback: AsyncCallback\): void + +指定设备管理员应用获取网络包过滤规则,使用callback形式返回。 + +**需要权限:** ohos.permission.ENTERPRISE_MANAGE_NETWORK + +**系统能力:** SystemCapability.Customization.EnterpriseDeviceManager + +**系统API**: 此接口为系统接口。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ------------------------------- | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | +| callback | AsyncCallback<string> | 是 | 回调函数。当接口调用成功,err为null,否则err为错误对象。 | + +**错误码**: + +以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md) + +| 错误码ID | 错误信息 | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | + +**示例:** + +```js +let wantTemp = { + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', +}; + +networkManager.listIptablesFilterRules(wantTemp, (err, result) => { + if (err) { + console.error(`Failed to get iptables filter rule. Code: ${err.code}, message: ${err.message}`); + return; + } + console.info(`Succeeded in getting iptables filter rule, result : ${result}`); +}); +``` + +## networkManager.listIptablesFilterRules + +listIptablesFilterRules(admin: Want): Promise\ + +指定设备管理员应用获取网络包过滤规则,使用Promise形式返回。 + +**需要权限:** ohos.permission.ENTERPRISE_MANAGE_NETWORK + +**系统能力:** SystemCapability.Customization.EnterpriseDeviceManager + +**系统API**: 此接口为系统接口。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ----------------------------------- | ---- | ------- | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | + +**返回值:** + +| 类型 | 说明 | +| --------------------- | ------------------------- | +| Promise<string> | Promise对象,返回网络包过滤规则。 | + +**错误码**: + +以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md) + +| 错误码ID | 错误信息 | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | + +**示例:** + +```js +let wantTemp = { + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', +}; + +networkManager.listIptablesFilterRules(wantTemp).then((result) => { + console.info(`Succeeded in getting iptables filter rule, result: ${result}`); +}).catch((err) => { + console.error(`Failed to remove iptables filter rule. Code: ${err.code}, message: ${err.message}`); +}); +``` + +## AddFilterRule + +添加网络包过滤规则 + +**系统能力:** SystemCapability.Customization.EnterpriseDeviceManager + +**系统API**: 此接口为系统接口。 + +| 名称 | 类型 | 必填 | 说明 | +| ----------- | --------| ---- | ------------------------------- | +| ruleNo | number | 否 | 规则序号。 | +| srcAddr | string | 否 | ip源地址。 | +| destAddr | string | 否 | ip目标地址。 | +| srcPort | string | 否 | ip源端口。 | +| destPort | string | 否 | ip目标端口。 | +| uid | string | 否 | 应用uid。 | +| method | [AddMethod](#addmethod) | 是 | 添加策略。 | +| direction | [Direction](#direction) | 是 | 规则链。 | +| action | [Action](#action) | 是 | 接收或者丢弃数据包。 | +| protocol | [Protocol](#protocol) | 否 | 网络协议。 | + +## RemoveFilterRule + +移除网络包过滤规则 + +**系统能力:** SystemCapability.Customization.EnterpriseDeviceManager + +**系统API**: 此接口为系统接口。 + +| 名称 | 类型 | 必填 | 说明 | +| ----------- | --------| ---- | ------------------------------- | +| srcAddr | string | 否 | ip源地址。 | +| destAddr | string | 否 | ip目标地址。 | +| srcPort | string | 否 | ip源端口。 | +| destPort | string | 否 | ip目标端口。 | +| uid | string | 否 | 应用uid。 | +| direction | [Direction](#direction) | 是 | 规则链。 | +| action | [Action](#action) | 否 | 接收或者丢弃数据包。 | +| protocol | [Protocol](#protocol) | 否 | 网络协议。 | + +## AddMethod + +添加网络包方法。 + +**系统能力:** SystemCapability.Customization.EnterpriseDeviceManager + +**系统API**: 此接口为系统接口。 + +| 名称 | 值 | 说明 | +| -------- | -------- | -------- | +| APPEND | 0 | 追加。 | +| INSERT | 1 | 插入。 | + +## Direction + +规则链。 + +**系统能力:** SystemCapability.Customization.EnterpriseDeviceManager + +**系统API**: 此接口为系统接口。 + +| 名称 | 值 | 说明 | +| -------- | -------- | -------- | +| INPUT | 0 | 输入链。 | +| OUTPUT | 1 | 输出链。 | + +## Action + +数据包的行为。 + +**系统能力:** SystemCapability.Customization.EnterpriseDeviceManager + +**系统API**: 此接口为系统接口。 + +| 名称 | 值 | 说明 | +| -------- | -------- | -------- | +| ALLOW | 0 | 接收数据包。 | +| DENY | 1 | 丢弃数据包。 | + +## Protocol + +网络协议。 + +**系统能力:** SystemCapability.Customization.EnterpriseDeviceManager + +**系统API**: 此接口为系统接口。 + +| 名称 | 值 | 说明 | +| -------- | -------- | -------- | +| ALL | 0 | 全部网络协议。 | +| TCP | 1 | 网络协议TCP。 | +| UDP | 2 | 网络协议UDP。 | +| ICMP | 3 | 网络协议ICMP。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-font.md b/zh-cn/application-dev/reference/apis/js-apis-font.md index c49a16b846bcaea7098f5f8e88771282f1d44e8e..0cd35ce7ca5352a1eb4affb0a5d9a58c33406976 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-font.md +++ b/zh-cn/application-dev/reference/apis/js-apis-font.md @@ -6,8 +6,6 @@ > > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > -> 本模块接口为系统接口。 -> > 本模块功能依赖UI的执行上下文,不可在UI上下文不明确的地方使用,参见[UIContext](./js-apis-arkui-UIContext.md#uicontext)说明。 > > 从API version 10开始,可以通过使用[UIContext](./js-apis-arkui-UIContext.md#uicontext)中的[getFont](./js-apis-arkui-UIContext.md#getfont)方法获取当前UI上下文关联的[Font](./js-apis-arkui-UIContext.md#font)对象。 @@ -38,8 +36,8 @@ registerFont(options: FontOptions): void | 名称 | 类型 | 必填 | 说明 | | ---------- | ------ | ---- | ------------ | -| familyName | string | 是 | 设置注册的字体名称。 | -| familySrc | string | 是 | 设置注册字体文件的路径。 | +| familyName | string\| [Resource](../arkui-ts/ts-types.md#resource)10+ | 是 | 设置注册的字体名称。 | +| familySrc | string\| [Resource](../arkui-ts/ts-types.md#resource)10+ | 是 | 设置注册字体文件的路径。 | **示例:** @@ -53,10 +51,23 @@ struct FontExample { @State message: string = '你好,世界' aboutToAppear() { + // familyName和familySrc都支持string font.registerFont({ familyName: 'medium', familySrc: '/font/medium.ttf' }) + + // familyName和familySrc都支持系统Resource + font.registerFont({ + familyName: $r('app.string.mediumFamilyName'), + familySrc: $r('app.string.mediumFamilySrc') + }) + + // familySrc支持RawFile + 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:注册自定义字体的名字 + .fontFamily('medium') // medium:注册自定义字体的名字($r('app.string.mediumFamilyName')、'mediumRawFile'等已注册字体也能正常使用) .height('100%') }.width('100%') } diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md index d5d3792be77922e70a687ea91091423ec7b74e92..5708145672bc59d6d1a93c5c79de61b71e0d136b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md @@ -12,6 +12,8 @@ import ability from '@ohos.ability.ability'; ``` +## 属性 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase | 名称 | 可读 | 可写 | 类型 | 必填 | 说明 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-connectOptions.md b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-connectOptions.md index 890bcd1d48ad6e678f47c601b6b268c688f5c092..81499edbf280f22ad979f9355317559bb5394867 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-connectOptions.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-connectOptions.md @@ -12,6 +12,8 @@ import common from '@ohos.app.ability.common'; ``` +## 属性 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core | 参数名 | 类型 | 必填 | 说明 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-dataAbilityOperation.md b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-dataAbilityOperation.md index 542a1a2f1bdeb58d17ab63e2f5a09bf2bdad341f..051953a537866d72ba86715e182b4be864e30d13 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-dataAbilityOperation.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-dataAbilityOperation.md @@ -13,6 +13,8 @@ import ability from '@ohos.ability.ability'; ``` +## 属性 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.FAModel | 名称 | 类型 | 必填| 说明 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md index 943a8bd636ce9a1bc71707a261163e56b8faed6d..a4f9f141f628816aa45dac99f0c0ed7b951a43ef 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md @@ -13,6 +13,8 @@ import ability from '@ohos.ability.ability'; ``` +## 属性 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.FAModel | 名称 | 类型 | 必填 | 说明 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-startAbilityParameter.md b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-startAbilityParameter.md index a119fe766061daf40bdf0f9e1daed2c8f67ad42d..3dcf2ddfbd08a06bfa89590c2ba6bf8f0774eab8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-startAbilityParameter.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-startAbilityParameter.md @@ -13,6 +13,8 @@ import ability from '@ohos.ability.ability'; ``` +## 属性 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.FAModel | 名称 | 类型 | 必填 | 说明 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-want.md b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-want.md index 97f8b12c1060d0a2ac1983c43e562666d2866fc2..5fc5be2faf9a75b3e4f5773982fd7c67d09f5900 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-want.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-want.md @@ -12,6 +12,8 @@ Want是对象间信息传递的载体, 可以用于应用组件间的信息传 import Want from '@ohos.app.ability.Want'; ``` +## 属性 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase | 名称 | 类型 | 必填 | 说明 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-app-appVersionInfo.md b/zh-cn/application-dev/reference/apis/js-apis-inner-app-appVersionInfo.md index d08a4d237ec97b5a76bc22a1fa11a206720871ad..2a8e062143317e3ebb9a77f4bf2b248417151d8c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-app-appVersionInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-app-appVersionInfo.md @@ -12,6 +12,8 @@ import featureAbility from '@ohos.ability.featureAbility'; ``` +## 属性 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core | 名称 | 类型 | 可读 | 可写 | 说明 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-app-processInfo.md b/zh-cn/application-dev/reference/apis/js-apis-inner-app-processInfo.md index bf576fce0b4b592a0a3b4c847e00310c625deecb..187f7206ad8ec7afe5c3c7f5cc89c132e1e86d58 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-app-processInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-app-processInfo.md @@ -12,6 +12,8 @@ import featureAbility from '@ohos.ability.featureAbility'; ``` +## 属性 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core | 名称 | 类型 | 可读 | 可写 | 说明 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md index 6f05c3a6175193585f19e1a10c039bd0ccac38e8..960feb5beac10ddfd2f5161b666ad47750881282 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md @@ -14,7 +14,7 @@ import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry ## 使用说明 -通过AbilityDelegatorRegistry中[getAbilityDelegator](js-apis-app-ability-abilityDelegatorRegistry.md#abilitydelegatorregistrygetabilitydelegator)方法获取。 +通过AbilityDelegatorRegistry中[getAbilityDelegator](js-apis-app-ability-abilityDelegatorRegistry.md#abilitydelegatorregistrygetabilitydelegator)方法获取。此接口只能在测试环境下使用。 ```ts import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md index a6008172ee8b41cba3539db17fec35f043fc3f5b..4ba721cc2e27ccb0bc6acd6392e16fc7eadd819b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md @@ -6,6 +6,8 @@ > > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +## 属性 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core | 名称 | 类型 | 可读 | 可写 | 说明 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityStateData.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityStateData.md index 0b5a78558c235ed70e7055da1afe081f96f8bae1..99e7167bf66f965b2f852a16bdc4e054ca151e20 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityStateData.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityStateData.md @@ -12,6 +12,8 @@ import appManager from '@ohos.application.appManager'; ``` +## 属性 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core | 名称 | 类型 | 可读 | 可写 | 说明 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-baseContext.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-baseContext.md index b0873a6584d298daf7a18c429d2e2fadb8e10466..00819c66f1af6650a0cc3546d7209017c17d5e81 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-baseContext.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-baseContext.md @@ -12,6 +12,8 @@ BaseContext抽象类用于表示继承的子类Context是Stage模型还是FA模 import common from '@ohos.app.ability.common'; ``` +## 属性 + **系统能力**:SystemCapability.Ability.AbilityRuntime.Core | 名称 | 类型 | 可读 | 可写 | 说明 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-continuableInfo.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-continuableInfo.md index 0e87d5c15627938449252f67e1a7e10617ca57dc..9ac8782c1d4bdf62bd834a5f9ebfb348accb556e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-continuableInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-continuableInfo.md @@ -13,6 +13,8 @@ import distributedMissionManager from '@ohos.distributedMissionManager'; ``` +## 属性 + **系统能力**:SystemCapability.Ability.AbilityRuntime.Mission | 名称 | 类型 | 可读 | 可写 | 说明 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-continueDeviceInfo.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-continueDeviceInfo.md index 7caece5795a344dbd331aee89aeef64dd6040ec3..3be9c897b9a8656b3896c8ab1fadf56a106b6883 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-continueDeviceInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-continueDeviceInfo.md @@ -6,6 +6,8 @@ > > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +## 属性 + **系统能力**:SystemCapability.Ability.AbilityRuntime.Mission | 名称 | 类型 | 可读 | 可写 | 说明 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-missionInfo.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-missionInfo.md index 62b3c93e69f80cd84f5a40061049320682c05e71..862f497eae6e40ea6b10259252304c00cba00c81 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-missionInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-missionInfo.md @@ -12,6 +12,8 @@ import missionManager from '@ohos.app.ability.missionManager'; ``` +## 属性 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Mission **系统API**: 此接口为系统接口,三方应用不支持调用。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-missionListener.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-missionListener.md index a8bef951f6836f13cec6bb8013469f4ffe0a3913..757c6029a084b70efd438f7cd921aab0864b6a9c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-missionListener.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-missionListener.md @@ -12,6 +12,8 @@ import missionManager from '@ohos.app.ability.missionManager'; ``` +## 属性 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Mission | 名称 | 类型 | 必填 | 说明 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-missionSnapshot.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-missionSnapshot.md index e4260dce7eadc7cfcaaf9a0d358e0fbca256bd2b..39523a3d373ad9adfa860cf4f5e4fdc37c6e5454 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-missionSnapshot.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-missionSnapshot.md @@ -13,6 +13,8 @@ import missionManager from '@ohos.app.ability.missionManager'; ``` +## 属性 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Mission | 名称 | 类型 | 可读 | 可写 | 说明 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-processData.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-processData.md index bfc8f25f899b234f767e25f2481689741294633c..2c8b741d66009227d6bb08bbcd5193386ef61ca3 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-processData.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-processData.md @@ -12,6 +12,8 @@ import appManager from '@ohos.application.appManager'; ``` +## 属性 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core **系统API**:该接口为系统接口,三方应用不支持调用。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md index e94eaf768ac911fe9f507f1a789ec27287a2b261..8d5da70ca93589878900fc34080b521ed21f1bf4 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md @@ -12,6 +12,8 @@ import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; ``` +## 属性 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core | 名称 | 类型 | 可读 | 可写 | 说明 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md index 6135b814ac23227fe65efa89371b00d6063b15e8..effa7580c6b49a927596bb511d854d10cb1f9740 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md @@ -2213,6 +2213,82 @@ setMissionIcon(icon: image.PixelMap): Promise\; console.error(`setMissionLabel failed, code is ${err.code}, message is ${err.message}`); }); ``` + +## UIAbilityContext.setMissionContinueState10+ + +setMissionContinueState(state: AbilityConstant.ContinueState, callback:AsyncCallback<void>): void; + +设置UIAbility任务中流转状态(callback形式)。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| state | [ContinueState](js-apis-app-ability-abilityConstant.md#abilityconstantcontinuestate10) | 是 | 流转状态。 | +| callback | AsyncCallback<void> | 是 | 回调函数,返回接口调用是否成功的结果。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | + +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + +**示例:** + + ```ts + import AbilityConstant from '@ohos.app.ability.AbilityConstant'; + + this.context.setMissionContinueState(AbilityConstant.ContinueState.INACTIVE, (result) => { + console.info(`setMissionContinueState: ${JSON.stringify(result)}`); + }); + ``` + +## UIAbilityContext.setMissionContinueState10+ + +setMissionContinueState(state: AbilityConstant.ContinueState): Promise<void>; + +设置UIAbility任务中流转状态(promise形式)。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| state | [ContinueState](js-apis-app-ability-abilityConstant.md#abilityconstantcontinuestate10) | 是 | 流转状态。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Promise<void> | 返回一个Promise,包含接口的结果。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | + +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + +**示例:** + + ```ts + import AbilityConstant from '@ohos.app.ability.AbilityConstant'; + + this.context.setMissionContinueState(AbilityConstant.ContinueState.INACTIVE).then(() => { + console.info('success'); + }).catch((err) => { + console.error(`setMissionContinueState failed, code is ${err.code}, message is ${err.message}`); + }); + ``` + ## UIAbilityContext.restoreWindowStage restoreWindowStage(localStorage: LocalStorage) : void; diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-wantAgent-triggerInfo.md b/zh-cn/application-dev/reference/apis/js-apis-inner-wantAgent-triggerInfo.md index 070f9c77989c361aa72cccf780dab30c21da06f3..0c83afc034eb50662d56bf798a680c1e0d4d5480 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-wantAgent-triggerInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-wantAgent-triggerInfo.md @@ -12,6 +12,8 @@ import wantAgent from '@ohos.app.ability.wantAgent'; ``` +## 属性 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core | 名称 | 类型 | 必填 | 说明 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md b/zh-cn/application-dev/reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md index 84bc35b73d4f87def3c8e005a1fd7794ccc2a605..caed7c6e296e3d5b06c16c76e15837604255809a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md @@ -12,6 +12,8 @@ import wantAgent from '@ohos.app.ability.wantAgent'; ``` +## 属性 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core | 名称 | 类型 | 必填 | 说明 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inputmethod.md b/zh-cn/application-dev/reference/apis/js-apis-inputmethod.md index 1ba5395b85a1bdbff81c26c46696238820b1eee2..53f1f3012ba9f6fbf34e0b9cea8cf36a8bbaa999 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inputmethod.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @@ -2107,6 +2107,180 @@ off(type: 'selectByMovement'): void inputMethodController.off('selectByMovement'); ``` +### on('getLeftTextOfCursor')10+ + +on(type: 'getLeftTextOfCursor', callback: (length: number) => string): void; + +订阅输入法应用获取光标左侧指定长度文本事件。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----- | ---- | ------ | +| type | string | 是 | 设置监听类型。
- type为‘getLeftTextOfCursor’时表示订阅输入法应用获取光标左侧指定长度文本事件监听。 | +| callback | (length: number) => string | 是 | 回调函数,获取光标左侧指定长度文本内容。
开发者需要在该函数中,获取编辑框最新状态下光标左侧指定length长度的文本内容并返回。 | + +**示例:** + +```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; + +取消订阅输入法应用获取光标左侧指定长度文本事件。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 设置监听类型。
- type为‘getLeftTextOfCursor’时表示取消订阅输入法应用获取光标左侧指定长度文本事件监听。 | +| callback | (length: number) => string | 否 | 回调函数,获取光标左侧指定长度文本内容。需要与on接口传入的保持一致。| + +**示例:** + +```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; + +订阅输入法应用获取光标右侧指定长度文本事件。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----- | ---- | ------ | +| type | string | 是 | 设置监听类型。
- type为‘getRightTextOfCursor’时表示订阅输入法应用获取光标右侧指定长度文本事件监听。 | +| callback | (length: number) => string | 是 | 回调函数,获取光标右侧指定长度文本内容。
开发者需要在该函数中,获取编辑框最新状态下光标右侧指定length长度的文本内容并返回。 | + +**示例:** + +```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; + +取消订阅输入法应用获取光标右侧指定长度文本事件。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 设置监听类型。
- type为‘getRightTextOfCursor’时表示取消订阅输入法应用获取光标右侧指定长度文本事件监听。 | +| callback | (length: number) => string | 否 | 回调函数,获取光标右侧指定长度文本内容。需要与on接口传入的保持一致。| + +**示例:** + +```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; + +订阅输入法应用获取光标处文本索引事件。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----- | ---- | ------ | +| type | string | 是 | 设置监听类型。
- type为‘getTextIndexAtCursor’时表示订阅输入法应用获取光标处文本索引事件监听。 | +| callback | () => number | 是 | 回调函数,获取光标处文本索引。
开发者需要在该函数中,获取编辑框最新状态下光标处文本索引并返回。 | + +**示例:** + +```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; + +取消订阅输入法应用获取光标处文本索引事件。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 设置监听类型。
- type为‘getTextIndexAtCursor’时表示取消订阅输入法应用获取光标处文本索引事件监听。 | +| callback | () => number | 否 | 回调函数,获取光标处文本索引。需要与on接口传入的保持一致。| + +**示例:** + +```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+ 下列API示例中都需使用[getSetting](#inputmethodgetsetting9)获取到InputMethodSetting实例,再通过此实例调用对应方法。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-installer.md b/zh-cn/application-dev/reference/apis/js-apis-installer.md index 195ee7dcdeaa8588ff65bbb7b6f44075e6a5ccba..9d87e39f6edf9365a3e63258f4e8b5d81ca51efa 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-installer.md +++ b/zh-cn/application-dev/reference/apis/js-apis-installer.md @@ -789,7 +789,7 @@ try { | 名称 | 类型 | 必填 | 说明 | | ------------------------------ | ------------------------------ | ------------------ | ------------------ | | userId | number | 否 | 指示用户id,默认值:调用方所在用户,取值范围:大于等于0,可使用[queryOsAccountLocalIdFromProcess](js-apis-osAccount.md#getOsAccountLocalId)获取当前进程所在用户。 | -| installFlag | number | 否 | 指示安装标志,枚举值:0:应用初次安装,1:应用覆盖安装,默认值为应用初次安装 | +| installFlag | number | 否 | 指示安装标志,枚举值:0x00:应用初次安装,0x01:应用覆盖安装,0x10:应用免安装,默认值为应用初次安装。 | | isKeepData | boolean | 否 | 卸载时是否保留数据目录,默认值为false。 | | hashParams | Array<[HashParam](#hashparam)> | 否 | 哈希值参数,默认值为空。 | | crowdtestDeadline| number | 否 | 众测活动的截止日期,默认值为-1,表示无截止日期约束。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-matrix4.md b/zh-cn/application-dev/reference/apis/js-apis-matrix4.md index 3945062df5b6f40b0bf7cb9a39f7501b10f8d6d0..28c94b5cc90b09fe7d691cc9f00230bd2cabbc96 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-matrix4.md +++ b/zh-cn/application-dev/reference/apis/js-apis-matrix4.md @@ -466,6 +466,8 @@ struct Test { ## TranslateOption +**系统能力:** SystemCapability.ArkUI.ArkUI.Full + | 名称 | 类型 | 必填 | 说明 | | ---- | ------ | ---- | ----------------------------------------------------------- | | x | number | 否 | x轴的平移距离,单位px。
默认值:0
取值范围 (-∞, +∞) | @@ -474,6 +476,8 @@ struct Test { ## ScaleOption +**系统能力:** SystemCapability.ArkUI.ArkUI.Full + | 名称 | 类型 | 必填 | 说明 | | ------- | ------ | ---- | ------------------------------------------------------------ | | x | number | 否 | x轴的缩放倍数。x>1时以x轴方向放大,x<1时以x轴方向缩小。
默认值:1
取值范围 [0, +∞)
**说明:**
设置小于0的值时,按照默认值处理。 | @@ -484,6 +488,8 @@ struct Test { ## RotateOption +**系统能力:** SystemCapability.ArkUI.ArkUI.Full + | 名称 | 类型 | 必填 | 说明 | | ------- | ------ | ---- | ------------------------------------------------------- | | x | number | 否 | 旋转轴向量x坐标。
默认值:1。
取值范围 (-∞, +∞) | diff --git a/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md b/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md index 8a018b9032da3414e2a2c9c614def2b31c34def9..6c181358df81b5d44dc7b123c9bea33d62f3865c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md +++ b/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md @@ -82,6 +82,9 @@ getFileAssets(options: MediaFetchOptions, callback: AsyncCallback<FetchFileRe 获取文件资源,使用callback方式返回异步结果。 +> **说明:** +> 在API version 10上,摒弃了物理目录作为相册的设计,采用了逻辑相册的设计,一个相册中可以添加多个文件,一个文件也可以在多个相册中呈现。新的设计将带来parent、albumId、albumUri和albumName属性使用上的不兼容,无法作为MediaFetchOptions的参数在getFileAssets接口中使用。请参考[changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md)。 + **需要权限**:ohos.permission.READ_MEDIA **系统能力**:SystemCapability.Multimedia.MediaLibrary.Core @@ -150,6 +153,9 @@ getFileAssets(options: MediaFetchOptions): Promise<FetchFileResult> 获取文件资源,使用Promise方式返回结果。 +> **说明:** +> 在API version 10上,摒弃了物理目录作为相册的设计,采用了逻辑相册的设计,一个相册中可以添加多个文件,一个文件也可以在多个相册中呈现。新的设计将带来parent、albumId、albumUri和albumName属性使用上的不兼容,无法作为MediaFetchOptions的参数在getFileAssets接口中使用。请参考[changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md)。 + **需要权限**:ohos.permission.READ_MEDIA **系统能力**:SystemCapability.Multimedia.MediaLibrary.Core @@ -265,6 +271,9 @@ createAsset(mediaType: MediaType, displayName: string, relativePath: string, cal 创建媒体资源,使用callback方式返回结果。 +> **说明:** +> 由于API version 10的SDK上relativePath和相册没有关联关系,文件创建成功后,relativePath的最后一级目录不会作为相册呈现。变更详情请参考[changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md)。 + **需要权限**:ohos.permission.READ_MEDIA, ohos.permission.WRITE_MEDIA **系统能力**:SystemCapability.Multimedia.MediaLibrary.Core @@ -302,6 +311,9 @@ createAsset(mediaType: MediaType, displayName: string, relativePath: string): Pr 创建媒体资源,使用Promise方式返回结果。 +> **说明:** +> 由于API version 10的SDK上relativePath和相册没有关联关系,文件创建成功后,relativePath的最后一级目录不会作为相册呈现。变更详情请参考[changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md)。 + **需要权限**:ohos.permission.READ_MEDIA, ohos.permission.WRITE_MEDIA **系统能力**:SystemCapability.Multimedia.MediaLibrary.Core @@ -502,6 +514,9 @@ getAlbums(options: MediaFetchOptions, callback: AsyncCallback<Array<Album& 获取相册列表,使用callback 方式返回结果。 +> **说明:** +> 由于API version 10的SDK上relativePath和相册没有关联关系,在使用getAlbums时不支持relativePath作为查询条件,当前仅支持“Camera”和“ScreenShots”两类相册,变更详情请参考[changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md)。 + **需要权限**:ohos.permission.READ_MEDIA **系统能力**:SystemCapability.Multimedia.MediaLibrary.Core @@ -517,10 +532,9 @@ getAlbums(options: MediaFetchOptions, callback: AsyncCallback<Array<Album& ```js async function example() { - // 获取相册需要先预置相册和资源,示例代码为预置的新建相册1。 let AlbumNoArgsfetchOp = { selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?', - selectionArgs: ['新建相册1'], + selectionArgs: ['Camera'], }; media.getAlbums(AlbumNoArgsfetchOp, (error, albumList) => { if (albumList != undefined) { @@ -538,6 +552,9 @@ getAlbums(options: MediaFetchOptions): Promise<Array<Album>> 获取相册列表,使用 promise 方式返回结果。 +> **说明:** +> 由于API version 10的SDK上relativePath和相册没有关联关系,在使用getAlbums时不支持relativePath作为查询条件.当前仅支持“Camera”和“ScreenShots”两类相册,变更详情请参考[changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md)。 + **需要权限**:ohos.permission.READ_MEDIA **系统能力**:SystemCapability.Multimedia.MediaLibrary.Core @@ -558,10 +575,9 @@ getAlbums(options: MediaFetchOptions): Promise<Array<Album>> ```js async function example() { - // 获取相册需要先预置相册和资源,示例代码为预置的新建相册1。 let AlbumNoArgsfetchOp = { selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?', - selectionArgs: ['新建相册1'], + selectionArgs: ['Camera'], }; media.getAlbums(AlbumNoArgsfetchOp).then((albumList) => { console.info('getAlbums successfully: ' + JSON.stringify(albumList)); @@ -1047,7 +1063,7 @@ async function example() { | displayName | string | 是 | 是 | 显示文件名,包含后缀名。 | | title | string | 是 | 是 | 文件标题。 | | relativePath8+ | string | 是 | 是 | 相对公共目录路径。 | -| parent8+ | number | 是 | 否 | 父目录id。 | +| parent8+ | number | 是 | 否 | 父目录id。由于API version 10的SDK上Asset可以存在多个相册,该属性不兼容。获取值始终为0。 | | size | number | 是 | 否 | 文件大小(单位:字节)。 | | dateAdded | number | 是 | 否 | 添加日期(添加文件时间到1970年1月1日的秒数值)。 | | dateModified | number | 是 | 否 | 修改日期(修改文件时间到1970年1月1日的秒数值,修改文件名不会改变此值,当文件内容发生修改时才会更新)。| @@ -1058,9 +1074,9 @@ async function example() { | height | number | 是 | 否 | 图片高度(单位:像素)。 | | orientation | number | 是 | 是 | 图片显示方向(顺时针旋转角度,如0,90,180 单位:度)。 | | duration8+ | number | 是 | 否 | 持续时间(单位:毫秒)。 | -| albumId | number | 是 | 否 | 文件所归属的相册编号。 | -| albumUri8+ | string | 是 | 否 | 文件所归属相册uri。 | -| albumName | string | 是 | 否 | 文件所归属相册名称。 | +| albumId | number | 是 | 否 | 文件所归属的相册编号。由于API version 10的SDK上Asset可以存在多个相册,该属性不兼容。获取值始终为0。 | +| albumUri8+ | string | 是 | 否 | 文件所归属相册uri。由于API version 10的SDK上Asset可以存在多个相册,该属性不兼容。获取值始终为空字符串。 | +| albumName | string | 是 | 否 | 文件所归属相册名称。由于API version 10的SDK上Asset可以存在多个相册,该属性不兼容。获取值始终为空字符串。 | ### isDirectory8+ @@ -1146,6 +1162,9 @@ commitModify(callback: AsyncCallback<void>): void 修改文件的元数据,使用callback方式返回异步结果。 +> **说明:** +> 由于API version 10的SDK上audio没有orientation属性,在使用commitModify接口时将无法对audio资源的orientation属性进行修改。请参考[changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md)。 + **需要权限**:ohos.permission.READ_MEDIA, ohos.permission.WRITE_MEDIA **系统能力**:SystemCapability.Multimedia.MediaLibrary.Core @@ -1183,6 +1202,9 @@ commitModify(): Promise<void> 修改文件的元数据,使用promise方式返回异步结果。 +> **说明:** +> 由于API version 10的SDK上audio没有orientation属性,在使用commitModify接口时将无法对audio资源的orientation属性进行修改。请参考[changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md)。 + **需要权限**:ohos.permission.READ_MEDIA, ohos.permission.WRITE_MEDIA **系统能力**:SystemCapability.Multimedia.MediaLibrary.Core diff --git a/zh-cn/application-dev/reference/apis/js-apis-mediaquery.md b/zh-cn/application-dev/reference/apis/js-apis-mediaquery.md index 4950d8c8b82fd6d1f17c675abad4c490f0f563a5..5277999966fe8f6d57f4bd059f23f7d5f332f54e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-mediaquery.md +++ b/zh-cn/application-dev/reference/apis/js-apis-mediaquery.md @@ -6,7 +6,7 @@ > > 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > -> 该模块不支持在[UIAbility](./js-apis-app-ability-uiAbility.md)中使用,需要在创建组件实例后使用。 +> 该模块不支持在[UIAbility](./js-apis-app-ability-uiAbility.md)的文件声明处使用,即不能在UIAbility的生命周期中调用,需要在创建组件实例后使用。 > > 本模块功能依赖UI的执行上下文,不可在UI上下文不明确的地方使用,参见[UIContext](./js-apis-arkui-UIContext.md#uicontext)说明。 > diff --git a/zh-cn/application-dev/reference/apis/js-apis-nfcTag.md b/zh-cn/application-dev/reference/apis/js-apis-nfcTag.md index d135c536ff844bee319dedc9d3a49f72a959d61a..e76ade03c260c0fb743228e94b12ab728c71f18a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-nfcTag.md +++ b/zh-cn/application-dev/reference/apis/js-apis-nfcTag.md @@ -34,7 +34,7 @@ { "name": "tag-tech", "value": "IsoDep" - }, + } // add other technology if neccessary, // such as: NfcB/NfcF/NfcV/Ndef/MifareClassic/MifareUL/NdefFormatable ] @@ -66,59 +66,61 @@ import tag from '@ohos.nfc.tag'; 在对相关Tag类型卡片进行读写之前,必须先获取TagInfo相关属性值,以确认设备读取到的Tag卡片支持哪些技术类型。这样Tag应用程序才能调用正确的接口和所读取到的Tag卡片进行通信。 ```js import tag from '@ohos.nfc.tag'; +import UIAbility from '@ohos.app.ability.UIAbility'; -onCreate(want, launchParam) { - // add other code here... - - // want is initialized by nfc service, contains tag info for this found tag - var tagInfo; - try { - tagInfo = tag.getTagInfo(want); - } catch (error) { - console.log("tag.getTagInfo catched error: " + error); - } - if (tagInfo == null || tagInfo == undefined) { - console.log("no TagInfo to be created, ignore it."); - return; - } +export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + // add other code here... - // 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 nfc service, contains tag info for this found tag + var tagInfo; + try { + tagInfo = tag.getTagInfo(want); + } catch (error) { + console.log("tag.getTagInfo catched error: " + error); + } + if (tagInfo == null || tagInfo == undefined) { + console.log("no TagInfo to be created, ignore it."); + return; } - if (tagInfo.technology[i] == tag.ISO_DEP) { - isIsoDepTag = true; + // 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/NDEF/MIFARE_CLASSIC/MIFARE_ULTRALIGHT/NDEF_FORMATABLE } - // also check for technology: tag.NFC_B/NFC_F/NFC_V/NDEF/MIFARE_CLASSIC/MIFARE_ULTRALIGHT/NDEF_FORMATABLE - } - // use NfcA APIs to access the found tag. - if (isNfcATag) { - var nfcA; - try { - nfcA = tag.getNfcATag(tagInfo); - } catch (error) { - console.log("tag.getNfcATag catched 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 catched error: " + error); + } + // other code to read or write this found tag. } - // other code to read or write this found tag. - } - // use getIsoDep APIs to access the found tag. - if (isIsoDepTag) { - var isoDep; - try { - isoDep = tag.getIsoDep(tagInfo); - } catch (error) { - console.log("tag.getIsoDep catched error: " + error); + // use getIsoDep APIs to access the found tag. + if (isIsoDepTag) { + var isoDep; + try { + isoDep = tag.getIsoDep(tagInfo); + } catch (error) { + console.log("tag.getIsoDep catched error: " + error); + } + // other code to read or write this found tag. } - // other code to read or write this found tag. + // use the same code to handle for "NfcA/NfcB/NfcF/NfcV/Ndef/MifareClassic/MifareUL/NdefFormatable". } - - // use the same code to handle for "NfcA/NfcB/NfcF/NfcV/Ndef/MifareClassic/MifareUL/NdefFormatable". } ``` @@ -135,14 +137,14 @@ getNfcATag(tagInfo: [TagInfo](#taginfo)): [NfcATag](js-apis-nfctech.md#nfcatag) **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| --------- | ------------------------- | ---- | ---------------------------------------- | -| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------------- | ---- | ------------------------------------------------------------- | +| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 | **返回值:** -| **类型** | **说明** | -| ------------------------------------- | ------------- | +| **类型** | **说明** | +| ------------------------------------- | ------------------ | | [NfcATag](js-apis-nfctech.md#nfcatag) | NFC A类型Tag对象。 | ## tag.getNfcA9+ @@ -155,23 +157,23 @@ getNfcA(tagInfo: [TagInfo](#taginfo)): [NfcATag](js-apis-nfctech.md#nfcatag) **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| --------- | ------------------------- | ---- | ---------------------------------------- | -| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------------- | ---- | ------------------------------------------------------------- | +| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 | **返回值:** -| **类型** | **说明** | -| ------------------------------------- | ------------- | +| **类型** | **说明** | +| ------------------------------------- | ------------------ | | [NfcATag](js-apis-nfctech.md#nfcatag) | NFC A类型Tag对象。 | **错误码:** 以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 -| 错误码ID | 错误信息 | -| ------- | ---------------------------------------- | -| 3100201 | Tag running state is abnormal in service. | +| 错误码ID | 错误信息 | +| -------- | ----------------------------------------- | +| 3100201 | Tag running state is abnormal in service. | ## tag.getNfcBTag @@ -186,14 +188,14 @@ getNfcBTag(tagInfo: [TagInfo](#taginfo)): [NfcBTag](js-apis-nfctech.md#nfcbtag) **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| --------- | ------------------------- | ---- | ---------------------------------------- | -| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------------- | ---- | ------------------------------------------------------------- | +| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 | **返回值:** -| **类型** | **说明** | -| ------------------------------------- | ------------- | +| **类型** | **说明** | +| ------------------------------------- | ------------------ | | [NfcBTag](js-apis-nfctech.md#nfcbtag) | NFC B类型Tag对象。 | ## tag.getNfcB9+ @@ -206,23 +208,23 @@ getNfcB(tagInfo: [TagInfo](#taginfo)): [NfcBTag](js-apis-nfctech.md#nfcbtag) **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| --------- | ------------------------- | ---- | ---------------------------------------- | -| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------------- | ---- | ------------------------------------------------------------- | +| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 | **返回值:** -| **类型** | **说明** | -| ------------------------------------- | ------------- | +| **类型** | **说明** | +| ------------------------------------- | ------------------ | | [NfcBTag](js-apis-nfctech.md#nfcbtag) | NFC B类型Tag对象。 | **错误码:** 以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 -| 错误码ID | 错误信息 | -| ------- | ---------------------------------------- | -| 3100201 | Tag running state is abnormal in service. | +| 错误码ID | 错误信息 | +| -------- | ----------------------------------------- | +| 3100201 | Tag running state is abnormal in service. | ## tag.getNfcFTag @@ -237,14 +239,14 @@ getNfcFTag(tagInfo: [TagInfo](#taginfo)): [NfcFTag](js-apis-nfctech.md#nfcftag) **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| --------- | ------------------------- | ---- | ---------------------------------------- | -| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------------- | ---- | ------------------------------------------------------------- | +| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 | **返回值:** -| **类型** | **说明** | -| ------------------------------------- | ------------- | +| **类型** | **说明** | +| ------------------------------------- | ------------------ | | [NfcFTag](js-apis-nfctech.md#nfcftag) | NFC F类型Tag对象。 | ## tag.getNfcF9+ @@ -257,23 +259,23 @@ getNfcF(tagInfo: [TagInfo](#taginfo)): [NfcFTag](js-apis-nfctech.md#nfcftag) **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| --------- | ------------------------- | ---- | ---------------------------------------- | -| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------------- | ---- | ------------------------------------------------------------- | +| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 | **返回值:** -| **类型** | **说明** | -| ------------------------------------- | ------------- | +| **类型** | **说明** | +| ------------------------------------- | ------------------ | | [NfcFTag](js-apis-nfctech.md#nfcftag) | NFC F类型Tag对象。 | **错误码:** 以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 -| 错误码ID | 错误信息 | -| ------- | ---------------------------------------- | -| 3100201 | Tag running state is abnormal in service. | +| 错误码ID | 错误信息 | +| -------- | ----------------------------------------- | +| 3100201 | Tag running state is abnormal in service. | ## tag.getNfcVTag @@ -288,14 +290,14 @@ getNfcVTag(tagInfo: [TagInfo](#taginfo)): [NfcVTag](js-apis-nfctech.md#nfcvtag) **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| --------- | ------------------------- | ---- | ---------------------------------------- | -| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------------- | ---- | ------------------------------------------------------------- | +| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 | **返回值:** -| **类型** | **说明** | -| ------------------------------------- | ------------- | +| **类型** | **说明** | +| ------------------------------------- | ------------------ | | [NfcVTag](js-apis-nfctech.md#nfcvtag) | NFC V类型Tag对象。 | ## tag.getNfcV9+ @@ -308,23 +310,23 @@ getNfcV(tagInfo: [TagInfo](#taginfo)): [NfcVTag](js-apis-nfctech.md#nfcvtag) **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| --------- | ------------------------- | ---- | ---------------------------------------- | -| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------------- | ---- | ------------------------------------------------------------- | +| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 | **返回值:** -| **类型** | **说明** | -| ------------------------------------- | ------------- | +| **类型** | **说明** | +| ------------------------------------- | ------------------ | | [NfcVTag](js-apis-nfctech.md#nfcvtag) | NFC V类型Tag对象。 | **错误码:** 以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 -| 错误码ID | 错误信息 | -| ------- | ---------------------------------------- | -| 3100201 | Tag running state is abnormal in service. | +| 错误码ID | 错误信息 | +| -------- | ----------------------------------------- | +| 3100201 | Tag running state is abnormal in service. | ## tag.getIsoDep9+ @@ -336,23 +338,23 @@ getIsoDep(tagInfo: [TagInfo](#taginfo)): [IsoDepTag](js-apis-nfctech.md#isoDepTa **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------- | ------------------- | ---- | ---------------------------------------- | -| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------------- | ---- | ------------------------------------------------------------- | +| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 | **返回值:** -| **类型** | **说明** | -| ---------------------------------------- | ----------------------------------- | +| **类型** | **说明** | +| ------------------------------------------ | ------------------------------------------------------- | | [IsoDepTag](js-apis-nfctech.md#isodeptag9) | IsoDep类型Tag对象,通过该对象访问IsoDep类型的相关接口。 | **错误码:** 以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 -| 错误码ID | 错误信息 | -| ------- | ---------------------------------------- | -| 3100201 | Tag running state is abnormal in service. | +| 错误码ID | 错误信息 | +| -------- | ----------------------------------------- | +| 3100201 | Tag running state is abnormal in service. | ## tag.getNdef9+ @@ -364,23 +366,23 @@ getNdef(tagInfo: [TagInfo](#taginfo)): [NdefTag](js-apis-nfctech.md#ndeftag9) **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------- | ------------------- | ---- | ---------------------------------------- | -| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------------- | ---- | ------------------------------------------------------------- | +| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 | **返回值:** -| **类型** | **说明** | -| -------------------------------------- | ------------------------------- | +| **类型** | **说明** | +| -------------------------------------- | --------------------------------------------------- | | [NdefTag](js-apis-nfctech.md#ndeftag9) | NDEF类型Tag对象,通过该对象访问NDEF类型的相关接口。 | **错误码:** 以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 -| 错误码ID | 错误信息 | -| ------- | ---------------------------------------- | -| 3100201 | Tag running state is abnormal in service. | +| 错误码ID | 错误信息 | +| -------- | ----------------------------------------- | +| 3100201 | Tag running state is abnormal in service. | ## tag.getMifareClassic9+ @@ -392,23 +394,23 @@ getMifareClassic(tagInfo: [TagInfo](#taginfo)): [MifareClassicTag](js-apis-nfcte **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------- | ------------------- | ---- | ---------------------------------------- | -| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------------- | ---- | ------------------------------------------------------------- | +| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 | **返回值:** -| **类型** | **说明** | -| ---------------------------------------- | ---------------------------------------- | +| **类型** | **说明** | +| --------------------------------------------------------- | ----------------------------------------------------------------------- | | [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) | MIFARE Classic类型Tag对象,通过该对象访问MIFARE Classic类型的相关接口。 | **错误码:** 以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 -| 错误码ID | 错误信息 | -| ------- | ---------------------------------------- | -| 3100201 | Tag running state is abnormal in service. | +| 错误码ID | 错误信息 | +| -------- | ----------------------------------------- | +| 3100201 | Tag running state is abnormal in service. | ## tag.getMifareUltralight9+ @@ -419,23 +421,23 @@ getMifareUltralight(tagInfo: [TagInfo](#taginfo)): [MifareUltralightTag](js-apis **系统能力:** SystemCapability.Communication.NFC.Tag **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------- | ------------------- | ---- | ---------------------------------------- | -| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------------- | ---- | ------------------------------------------------------------- | +| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 | **返回值:** -| **类型** | **说明** | -| ---------------------------------------- | ---------------------------------------- | +| **类型** | **说明** | +| -------------------------------------------------------------- | ----------------------------------------------------------------------------- | | [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9) | MIFARE Ultralight类型Tag对象,通过该对象访问MIFARE Ultralight类型的相关接口。 | **错误码:** 以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 -| 错误码ID | 错误信息 | -| ------- | ---------------------------------------- | -| 3100201 | Tag running state is abnormal in service. | +| 错误码ID | 错误信息 | +| -------- | ----------------------------------------- | +| 3100201 | Tag running state is abnormal in service. | ## tag.getNdefFormatable9+ @@ -447,17 +449,17 @@ getNdefFormatable(tagInfo: [TagInfo](#taginfo)): [NdefFormatableTag](js-apis-nfc **返回值:** -| **类型** | **说明** | -| ---------------------------------------- | ---------------------------------------- | +| **类型** | **说明** | +| --------------------------------------------------------- | ------------------------------------------------------------------------- | | [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag) | NDEF Formatable类型Tag对象,通过该对象访问NDEF Formatable类型的相关接口。 | **错误码:** 以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 -| 错误码ID | 错误信息 | -| ------- | ---------------------------------------- | -| 3100201 | Tag running state is abnormal in service. | +| 错误码ID | 错误信息 | +| -------- | ----------------------------------------- | +| 3100201 | Tag running state is abnormal in service. | ## tag.getTagInfo9+ @@ -469,14 +471,14 @@ getTagInfo(want: [Want](js-apis-app-ability-want.md#Want)): [TagInfo](#taginfo) **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---- | ---------------------------------------- | ---- | --------------------------------- | -| want | [Want](js-apis-app-ability-want.md#Want) | 是 | 分发Ability时,在系统onCreate入口函数的参数中获取。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---------------------------------------- | ---- | --------------------------------------------------- | +| want | [Want](js-apis-app-ability-want.md#Want) | 是 | 分发Ability时,在系统onCreate入口函数的参数中获取。 | **返回值:** -| **类型** | **说明** | -| ------------------- | --------------------------- | +| **类型** | **说明** | +| ------------------- | -------------------------------------------- | | [TagInfo](#taginfo) | TagInfo对象,用于获取不同技术类型的Tag对象。 | @@ -490,14 +492,14 @@ makeUriRecord(uri: string): [NdefRecord](#ndefrecord9); **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---- | ------ | ---- | ---------------------- | -| uri | string | 是 | 写入到NDEF Record里面的数据内容。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | --------------------------------- | +| uri | string | 是 | 写入到NDEF Record里面的数据内容。 | **返回值:** -| **类型** | **说明** | -| -------------------------- | ---------------------------------------- | +| **类型** | **说明** | +| -------------------------- | ------------------------------------------------------------ | | [NdefRecord](#ndefrecord9) | NDEF标签的Record,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | **示例:** @@ -529,15 +531,15 @@ makeTextRecord(text: string, locale: string): [NdefRecord](#ndefrecord9); **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------------------------ | -| text | string | 是 | 写入到NDEF Record里面的文本数据内容。 | -| locale | string | 是 | 文本数据内容的编码方式。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------------------------- | +| text | string | 是 | 写入到NDEF Record里面的文本数据内容。 | +| locale | string | 是 | 文本数据内容的编码方式。 | **返回值:** -| **类型** | **说明** | -| -------------------------- | ---------------------------------------- | +| **类型** | **说明** | +| -------------------------- | ------------------------------------------------------------ | | [NdefRecord](#ndefrecord9) | NDEF标签的Record,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | **示例:** @@ -571,15 +573,15 @@ makeMimeRecord(mimeType: string, mimeData: number[]): [NdefRecord](#ndefrecord9) **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | ---- | ---------------------------------------- | -| mimeType | string | 是 | 符合RFC规则的MIME类型,比如"text/plain"或"image/jpeg"。 | -| mimeData | number[] | 是 | MIME数据内容,每个number十六进制表示,范围是0x00~0xFF。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | ---- | ------------------------------------------------------- | +| mimeType | string | 是 | 符合RFC规则的MIME类型,比如"text/plain"或"image/jpeg"。 | +| mimeData | number[] | 是 | MIME数据内容,每个number十六进制表示,范围是0x00~0xFF。 | **返回值:** -| **类型** | **说明** | -| -------------------------- | ---------------------------------------- | +| **类型** | **说明** | +| -------------------------- | ------------------------------------------------------------ | | [NdefRecord](#ndefrecord9) | NDEF标签的Record,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | **示例:** @@ -611,16 +613,16 @@ makeExternalRecord(domainName: string, type: string, externalData: number[]): [N **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------------ | -------- | ---- | ----------------------------------- | -| domainName | string | 是 | 外部数据发布组织的域名,一般是应用程序的包名。 | -| type | string | 是 | 外部数据的指定类型。 | -| externalData | number[] | 是 | 外部数据内容,每个number十六进制表示,范围是0x00~0xFF。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------------ | -------- | ---- | ------------------------------------------------------- | +| domainName | string | 是 | 外部数据发布组织的域名,一般是应用程序的包名。 | +| type | string | 是 | 外部数据的指定类型。 | +| externalData | number[] | 是 | 外部数据内容,每个number十六进制表示,范围是0x00~0xFF。 | **返回值:** -| **类型** | **说明** | -| -------------------------- | ---------------------------------------- | +| **类型** | **说明** | +| -------------------------- | ------------------------------------------------------------ | | [NdefRecord](#ndefrecord9) | NDEF标签的Record,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | **示例:** @@ -654,14 +656,14 @@ messageToBytes(ndefMessage: [NdefMessage](js-apis-nfctech.md#ndefmessage9)): num **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ----------- | ---------------------------------------- | ---- | ----------- | -| ndefMessage | [NdefMessage](js-apis-nfctech.md#ndefmessage9) | 是 | NDEF消息数据对象。 | +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ---------------------------------------------- | ---- | ------------------ | +| ndefMessage | [NdefMessage](js-apis-nfctech.md#ndefmessage9) | 是 | NDEF消息数据对象。 | **返回值:** -| **类型** | **说明** | -| -------- | ---------------------------------------- | +| **类型** | **说明** | +| -------- | ------------------------------------------------------------------------------------- | | number[] | NDEF消息数据对象,所转换成的字节格式的数据。每个number十六进制表示,范围是0x00~0xFF。 | **示例:** @@ -695,14 +697,14 @@ createNdefMessage(data: number[]): [NdefMessage](js-apis-nfctech.md#ndefmessage9 **参数:** -| **参数名** | **类型** | **必填** | **说明** | -| ------- | -------- | ------ | ---------------------------------------- | -| data | number[] | 是 | 原始字节,每个number十六进制表示,范围是0x00~0xFF。要求必须满足NDEF Record的格式。 | +| **参数名** | **类型** | **必填** | **说明** | +| ---------- | -------- | -------- | ---------------------------------------------------------------------------------- | +| data | number[] | 是 | 原始字节,每个number十六进制表示,范围是0x00~0xFF。要求必须满足NDEF Record的格式。 | **返回值:** -| **类型** | **说明** | -| ---------------------------------------- | ---------------------------------------- | +| **类型** | **说明** | +| ---------------------------------------------- | ------------------------------------------------------------- | | [NdefMessage](js-apis-nfctech.md#ndefmessage9) | NDEF标签的Message,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | **示例:** @@ -729,14 +731,14 @@ createNdefMessage(ndefRecords: NdefRecord[]): [NdefMessage](js-apis-nfctech.md#n **参数:** -| **参数名** | **类型** | **必填** | **说明** | -| ----------- | ---------------------------------------- | ------ | ---------------------------------------- | -| ndefRecords | [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] | 是 | NDEF标签的Record列表,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | +| **参数名** | **类型** | **必填** | **说明** | +| ----------- | --------------------------------------------- | -------- | ---------------------------------------------------------------- | +| ndefRecords | [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] | 是 | NDEF标签的Record列表,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | **返回值:** -| **类型** | **说明** | -| ---------------------------------------- | ---------------------------------------- | +| **类型** | **说明** | +| ---------------------------------------------- | ------------------------------------------------------------- | | [NdefMessage](js-apis-nfctech.md#ndefmessage9) | NDEF标签的Message,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | **示例:** @@ -764,113 +766,113 @@ NFC服务在读取到标签时给出的对象,通过改对象属性,应用 **需要权限:** ohos.permission.NFC_TAG -| **名称** | **类型** | **可读** | **可写** | **说明** | -| ----------------------------- | ---------------------------------------- | ------ | ------ | ---------------------------------------- | -| uid9+ | number[] | 是 | 否 | 标签的uid,每个number值是十六进制表示,范围是0x00~0xFF。 | -| technology9+ | number[] | 是 | 否 | 支持的技术类型,每个number值表示所支持技术类型的常量值。 | -| supportedProfiles | number[] | 是 | 否 | 支持的技术类型,从API9开始不支持,使用[tag.TagInfo#technology](#tagtaginfo)替代。 | -| extrasData9+ | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap)[] | 是 | 否 | 标签所支持技术的扩展属性值。
**系统接口:** 此接口为系统接口。 | -| tagRfDiscId9+ | number | 是 | 否 | 标签发现时分配的ID值。
**系统接口:** 此接口为系统接口。 | -| remoteTagService9+ | [rpc.RemoteObject](js-apis-rpc.md#remoteobject) | 是 | 否 | NFC服务进程的远端对象,用于客户端和服务之间的接口通信。
**系统接口:** 此接口为系统接口。 | +| **名称** | **类型** | **可读** | **可写** | **说明** | +| ----------------------------- | ------------------------------------------------------------- | -------- | -------- | -------------------------------------------------------------------------------------------- | +| uid9+ | number[] | 是 | 否 | 标签的uid,每个number值是十六进制表示,范围是0x00~0xFF。 | +| technology9+ | number[] | 是 | 否 | 支持的技术类型,每个number值表示所支持技术类型的常量值。 | +| supportedProfiles | number[] | 是 | 否 | 支持的技术类型,从API9开始不支持,使用[tag.TagInfo#technology](#tagtaginfo)替代。 | +| extrasData9+ | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap)[] | 是 | 否 | 标签所支持技术的扩展属性值。
**系统接口:** 此接口为系统接口。 | +| tagRfDiscId9+ | number | 是 | 否 | 标签发现时分配的ID值。
**系统接口:** 此接口为系统接口。 | +| remoteTagService9+ | [rpc.RemoteObject](js-apis-rpc.md#remoteobject) | 是 | 否 | NFC服务进程的远端对象,用于客户端和服务之间的接口通信。
**系统接口:** 此接口为系统接口。 | ## NdefRecord9+ NDEF标签Record属性的定义,参考NDEF标签技术规范《NFCForum-TS-NDEF_1.0》的定义细节。 **系统能力:** SystemCapability.Communication.NFC.Tag -| **名称** | **类型** | **可读** | **可写** | **说明** | -| ------- | -------- | ------ | ------ | ---------------------------------------- | -| tnf | number | 是 | 否 | NDEF Record的TNF(Type Name Field)。 | -| rtdType | number[] | 是 | 否 | NDEF Record的RTD(Record Type Definition)类型值,每个number十六进制表示,范围是0x00~0xFF。 | -| id | number[] | 是 | 否 | NDEF Record的ID,每个number十六进制表示,范围是0x00~0xFF。 | -| payload | number[] | 是 | 否 | NDEF Record的PAYLOAD,每个number十六进制表示,范围是0x00~0xFF。 | +| **名称** | **类型** | **可读** | **可写** | **说明** | +| -------- | -------- | -------- | -------- | ----------------------------------------------------------------------------------------- | +| tnf | number | 是 | 否 | NDEF Record的TNF(Type Name Field)。 | +| rtdType | number[] | 是 | 否 | NDEF Record的RTD(Record Type Definition)类型值,每个number十六进制表示,范围是0x00~0xFF。 | +| id | number[] | 是 | 否 | NDEF Record的ID,每个number十六进制表示,范围是0x00~0xFF。 | +| payload | number[] | 是 | 否 | NDEF Record的PAYLOAD,每个number十六进制表示,范围是0x00~0xFF。 | ## 技术类型定义 NFC Tag有多种不同的技术类型,定义常量描述不同的技术类型。 **系统能力:** SystemCapability.Communication.NFC.Tag -| **名称** | **值** | **说明** | -| ---------------------------- | ----- | ------------------------ | -| NFC_A | 1 | NFC-A (ISO 14443-3A)技术。 | -| NFC_B | 2 | NFC-A (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技术。 | -| MIFARE_CLASSIC | 8 | MIFARE Classic技术。 | -| MIFARE_ULTRALIGHT | 9 | MIFARE Utralight技术。 | +| **名称** | **值** | **说明** | +| ---------------------------- | ------ | --------------------------- | +| NFC_A | 1 | NFC-A (ISO 14443-3A)技术。 | +| NFC_B | 2 | NFC-A (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技术。 | +| MIFARE_CLASSIC | 8 | MIFARE Classic技术。 | +| MIFARE_ULTRALIGHT | 9 | MIFARE Utralight技术。 | ## TnfType9+ NDEF Record的TNF(Type Name Field)类型值,参考NDEF标签技术规范《NFCForum-TS-NDEF_1.0》的定义细节。 **系统能力:** SystemCapability.Communication.NFC.Tag -| **名称** | **值** | **说明** | -| ---------------- | ----- | ---------------------------------------- | -| 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)。 | +| **名称** | **值** | **说明** | +| ---------------- | ------ | ------------------------------------------------ | +| 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)。 | ## NDEF Record RTD类型定义 NDEF Record的RTD(Record Type Definition)类型值,参考NDEF标签技术规范《NFCForum-TS-NDEF_1.0》的定义细节。 **系统能力:** SystemCapability.Communication.NFC.Tag -| **名称** | **值** | **说明** | -| --------------------- | ------ | ------------------ | -| RTD_TEXT9+ | [0x54] | 文本类型的NDEF Record。 | -| RTD_URI9+ | [0x55] | URI类型的NDEF Record。 | +| **名称** | **值** | **说明** | +| --------------------- | ------ | ----------------------- | +| RTD_TEXT9+ | [0x54] | 文本类型的NDEF Record。 | +| RTD_URI9+ | [0x55] | URI类型的NDEF Record。 | ## NfcForumType9+ NFC Forum标准里面Tag类型的定义。 **系统能力:** SystemCapability.Communication.NFC.Tag -| **名称** | **值** | **说明** | -| ---------------- | ----- | ----------------- | -| NFC_FORUM_TYPE_1 | 1 | NFC论坛类型1。 | -| NFC_FORUM_TYPE_2 | 2 | NFC论坛类型2。 | -| NFC_FORUM_TYPE_3 | 3 | NFC论坛类型3。 | -| NFC_FORUM_TYPE_4 | 4 | NFC论坛类型4。 | -| MIFARE_CLASSIC | 101 | MIFARE Classic类型。 | +| **名称** | **值** | **说明** | +| ---------------- | ------ | -------------------- | +| NFC_FORUM_TYPE_1 | 1 | NFC论坛类型1。 | +| NFC_FORUM_TYPE_2 | 2 | NFC论坛类型2。 | +| NFC_FORUM_TYPE_3 | 3 | NFC论坛类型3。 | +| NFC_FORUM_TYPE_4 | 4 | NFC论坛类型4。 | +| MIFARE_CLASSIC | 101 | MIFARE Classic类型。 | ## MifareClassicType9+ MIFARE Classic标签类型的定义。 **系统能力:** SystemCapability.Communication.NFC.Tag -| **名称** | **值** | **说明** | -| ------------ | ----- | ----------------- | -| TYPE_UNKNOWN | 0 | 未知的MIFARE类型。 | -| TYPE_CLASSIC | 1 | MIFARE Classic类型。 | -| TYPE_PLUS | 2 | MIFARE Plus类型。 | -| TYPE_PRO | 3 | MIFARE Pro类型。 | +| **名称** | **值** | **说明** | +| ------------ | ------ | -------------------- | +| TYPE_UNKNOWN | 0 | 未知的MIFARE类型。 | +| TYPE_CLASSIC | 1 | MIFARE Classic类型。 | +| TYPE_PLUS | 2 | MIFARE Plus类型。 | +| TYPE_PRO | 3 | MIFARE Pro类型。 | ## MifareClassicSize9+ MIFARE Classic标签存储大小的定义。 **系统能力:** SystemCapability.Communication.NFC.Tag -| **名称** | **值** | **说明** | -| ------------ | ----- | ------------------ | -| MC_SIZE_MINI | 320 | 每个标签5个扇区,每个扇区4个块。 | -| MC_SIZE_1K | 1024 | 每个标签16个扇区,每个扇区4个块。 | -| MC_SIZE_2K | 2048 | 每个标签32个扇区,每个扇区4个块。 | -| MC_SIZE_4K | 4096 | 每个标签40个扇区,每个扇区4个块。 | +| **名称** | **值** | **说明** | +| ------------ | ------ | --------------------------------- | +| MC_SIZE_MINI | 320 | 每个标签5个扇区,每个扇区4个块。 | +| MC_SIZE_1K | 1024 | 每个标签16个扇区,每个扇区4个块。 | +| MC_SIZE_2K | 2048 | 每个标签32个扇区,每个扇区4个块。 | +| MC_SIZE_4K | 4096 | 每个标签40个扇区,每个扇区4个块。 | ## MifareUltralightType9+ MIFARE Ultralight标签类型的定义。 **系统能力:** SystemCapability.Communication.NFC.Tag -| **名称** | **值** | **说明** | -| ----------------- | ----- | ---------------------- | -| TYPE_UNKNOWN | 0 | 未知的 MIFARE 类型。 | -| TYPE_ULTRALIGHT | 1 | MIFARE Ultralight类型。 | -| TYPE_ULTRALIGHT_C | 2 | MIFARE UltralightC 类型。 | +| **名称** | **值** | **说明** | +| ----------------- | ------ | ------------------------- | +| TYPE_UNKNOWN | 0 | 未知的 MIFARE 类型。 | +| TYPE_ULTRALIGHT | 1 | MIFARE Ultralight类型。 | +| TYPE_ULTRALIGHT_C | 2 | MIFARE UltralightC 类型。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-pasteboard.md b/zh-cn/application-dev/reference/apis/js-apis-pasteboard.md index 99cc968e8b41ed70b90e79149c564731d4f662ed..645a5d0e730358cb5f2566ab86688b4510edcab5 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-pasteboard.md +++ b/zh-cn/application-dev/reference/apis/js-apis-pasteboard.md @@ -1300,7 +1300,7 @@ setData(data: PasteData, callback: AsyncCallback<void>): void **示例:** ```js -let pasteData = pasteboard.createPlainTextData('content'); +let pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, 'content'); let systemPasteboard = pasteboard.getSystemPasteboard(); systemPasteboard.setData(pasteData, (err, data) => { if (err) { @@ -1343,7 +1343,7 @@ setData(data: PasteData): Promise<void> **示例:** ```js -let pasteData = pasteboard.createPlainTextData('content'); +let pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, 'content'); let systemPasteboard = pasteboard.getSystemPasteboard(); systemPasteboard.setData(pasteData).then((data) => { console.info('Succeeded in setting PasteData.'); diff --git a/zh-cn/application-dev/reference/apis/js-apis-promptAction.md b/zh-cn/application-dev/reference/apis/js-apis-promptAction.md index dadd7a444bef3466df10329c3f4a15a30b1b4284..1da49c28f040b142fbdea6f1b12b6259696184d0 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-promptAction.md +++ b/zh-cn/application-dev/reference/apis/js-apis-promptAction.md @@ -6,7 +6,7 @@ > > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > -> 该模块不支持在[UIAbility](./js-apis-app-ability-uiAbility.md)中使用,需要在创建组件实例后使用。 +> 该模块不支持在[UIAbility](./js-apis-app-ability-uiAbility.md)的文件声明处使用,即不能在UIAbility的生命周期中调用,需要在创建组件实例后使用。 > > 本模块功能依赖UI的执行上下文,不可在UI上下文不明确的地方使用,参见[UIContext](./js-apis-arkui-UIContext.md#uicontext)说明。 > diff --git a/zh-cn/application-dev/reference/apis/js-apis-secureElement.md b/zh-cn/application-dev/reference/apis/js-apis-secureElement.md index edfbbdf928576d517acd04cabc6343986d690561..b8f51b3a86a1d20e503ac4073f89a96105ef57b9 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-secureElement.md +++ b/zh-cn/application-dev/reference/apis/js-apis-secureElement.md @@ -43,10 +43,10 @@ newSEService(type: 'serviceState', callback: Callback<[ServiceState](#secureelem **参数:** -| **参数名** | **类型** | **说明** | -| ---------- | ---------------------------------------------------- | -------------------- | -| type | string | 'serviceState' | -| callback | Callback<[ServiceState](#secureelementservicestate)> | 返回SE服务状态的回调 | +| **参数名** | **类型** | **必填** | **说明** | +| ---------- | ---------------------------------------------------- | ------ | -------------------- | +| type | string | 是 | 'serviceState' | +| callback | Callback<[ServiceState](#secureelementservicestate)> | 是 | 返回SE服务状态的回调 | **返回值:** @@ -59,20 +59,18 @@ newSEService(type: 'serviceState', callback: Callback<[ServiceState](#secureelem ```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 @@ getReaders(): Reader[] ```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 @@ isConnected(): boolean ```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 @@ shutdown(): void ```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 @@ getVersion(): string ```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 @@ getName(): string ```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 @@ isSecureElementPresent(): boolean ```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 @@ try { ```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 @@ try { ```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 @@ getReader(): Reader ```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"; + 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 @@ getATR(): number[] ```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(); + 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 @@ close(): void ```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"; + 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 @@ isClosed(): boolean ```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(); + 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,15 +535,14 @@ closeChannels(): void ```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"; + nfcOmaSession.closeChannels(); + console.log("close Channels successfully"); } catch (e) { - this.result = "closeChannels exception:" + e.message; + console.log("closeChannels exception:" + e.message); } ``` @@ -568,9 +556,9 @@ openBasicChannel(aid: number[]): Promise **参数:** -| **参数名** | **类型** | **说明** | -| ---------- | -------- | ------------------------------------------------------------ | -| aid | number[] | 在此channel上选择的applet的AID数组或如果没有applet被选择时空的数组null。 | +| **参数名** | **类型** | **必填** | **说明** | +| ---------- | -------- | ------ | ------------------------------------------------------------ | +| aid | number[] | 是 |在此channel上选择的applet的AID数组或如果没有applet被选择时空的数组null。 | **返回值:** @@ -594,21 +582,20 @@ openBasicChannel(aid: number[]): Promise ```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 { // refer to 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); } ``` @@ -622,10 +609,10 @@ try { **参数:** -| **参数名** | **类型** | **说明** | -| ---------- | ---------------------- | ------------------------------------------------------------ | -| aid | number[] | 在此channel上选择的applet的AID数组或null 如果没有applet被选择。 | -| callback | AsyncCallback | callback返回可用Channel对象实例。 | +| **参数名** | **类型** | **必填** | **说明** | +| ---------- | ---------------------- | ------ | ------------------------------------------------------------ | +| aid | number[] | 是 | 在此channel上选择的applet的AID数组或null 如果没有applet被选择。 | +| callback | AsyncCallback | 是 | callback返回可用Channel对象实例。 | **错误码:** @@ -643,23 +630,22 @@ try { ```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 { // refer to 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); } ``` @@ -673,10 +659,10 @@ openBasicChannel(aid: number[], p2: number): Promise **参数:** -| **参数名** | **类型** | **说明** | -| ---------- | -------- | ------------------------------------------------------------ | -| aid | number[] | 在此channel上选择的applet的AID数组或null 如果没有applet被选择。 | -| p2 | number | 在该channel上执行的SELECT APDU的P2参数。 | +| **参数名** | **类型** | **必填** | **说明** | +| ---------- | -------- | ------ | ------------------------------------------------------------ | +| aid | number[] | 是 | 在此channel上选择的applet的AID数组或null 如果没有applet被选择。 | +| p2 | number | 是 |在该channel上执行的SELECT APDU的P2参数。 | **返回值:** @@ -700,23 +686,22 @@ openBasicChannel(aid: number[], p2: number): Promise ```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 { // refer to 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); } ``` @@ -730,11 +715,11 @@ openBasicChannel(aid: number[], p2:number, callback: AsyncCallback): vo **参数:** -| **参数名** | **类型** | **说明** | -| ---------- | ---------------------- | ------------------------------------------------------------ | -| aid | number[] | 在此channel上选择的applet的AID数组或null 如果没有applet被选择。 | -| p2 | number | 此channel上执行SELECT APDU命令的P2参数。 | -| callback | AsyncCallback | callback返回可用Channel对象实例。 | +| **参数名** | **类型** | **必填** | **说明** | +| ---------- | ---------------------- | ------ | ------------------------------------------------------------ | +| aid | number[] | 是 | 在此channel上选择的applet的AID数组或null 如果没有applet被选择。 | +| p2 | number | 是 | 此channel上执行SELECT APDU命令的P2参数。 | +| callback | AsyncCallback | 是 | callback返回可用Channel对象实例。 | **错误码:** @@ -752,24 +737,24 @@ openBasicChannel(aid: number[], p2:number, callback: AsyncCallback): vo ```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 { // refer to 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); } ``` @@ -783,9 +768,9 @@ openLogicalChannel(aid: number[]): Promise **参数:** -| **参数名** | **类型** | **说明** | -| ---------- | -------- | --------------------------------------- | -| aid | number[] | 在该Channel对象上选择的applet AID数组。 | +| **参数名** | **类型** | **必填** | **说明** | +| ---------- | -------- | ------ | --------------------------------------- | +| aid | number[] | 是 | 在该Channel对象上选择的applet AID数组。 | **返回值:** @@ -809,22 +794,21 @@ openLogicalChannel(aid: number[]): Promise ```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 { // refer to 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); } ``` @@ -838,10 +822,10 @@ try { **参数:** -| **参数名** | **类型** | **说明** | -| ---------- | ---------------------- | ------------------------------------------------------------ | -| aid | number[] | 在该Channel对象上被选择的applet AID数组。 | -| callback | AsyncCallback | callback返回可用Channel对象实例,SE不能提供新的channel或因缺乏可用逻辑Channel对象无法获取访问控制规则返回null。 | +| **参数名** | **类型** | **必填** | **说明** | +| ---------- | ---------------------- | ------ | ------------------------------------------------------------ | +| aid | number[] | 是 | 在该Channel对象上被选择的applet AID数组。 | +| callback | AsyncCallback | 是 | callback返回可用Channel对象实例,SE不能提供新的channel或因缺乏可用逻辑Channel对象无法获取访问控制规则返回null。 | **错误码:** @@ -859,23 +843,22 @@ try { ```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 { // refer to 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); } ``` @@ -895,10 +878,10 @@ P2通常为0x00。设备应允许P2的任何值,并且应允许以下值: 0x **参数:** -| **参数名** | **类型** | **说明** | -| ---------- | -------- | ----------------------------------------- | -| aid | number[] | 在该Channel对象上被选择的applet AID数组。 | -| p2 | number | 此channel上执行SELECT APDU命令的P2参数。 | +| **参数名** | **类型** | **必填** | **说明** | +| ---------- | -------- | ------ | ----------------------------------------- | +| aid | number[] | 是 | 在该Channel对象上被选择的applet AID数组。 | +| p2 | number | 是 | 此channel上执行SELECT APDU命令的P2参数。 | **错误码:** @@ -916,24 +899,24 @@ P2通常为0x00。设备应允许P2的任何值,并且应允许以下值: 0x ```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 { // refer to 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); } ``` @@ -953,11 +936,11 @@ P2通常为0x00。设备应允许P2的任何值,并且应允许以下值: 0x **参数:** -| **参数名** | **类型** | **说明** | -| ---------- | ---------------------- | ------------------------------------------------------------ | -| aid | number[] | 在该Channel对象上被选择的applet AID数组。 | -| p2 | number | 此channel上执行SELECT APDU命令的P2参数。 | -| callback | AsyncCallback | callback返回可用Channel对象实例,SE不能提供新的Channel对象或因缺乏可用逻辑Channel对象无法获取访问控制规则返回null。 | +| **参数名** | **类型** | **必填** | **说明** | +| ---------- | ---------------------- | ------ | ------------------------------------------------------------ | +| aid | number[] | 是 | 在该Channel对象上被选择的applet AID数组。 | +| p2 | number | 是 | 此channel上执行SELECT APDU命令的P2参数。 | +| callback | AsyncCallback | 是 | callback返回可用Channel对象实例,SE不能提供新的Channel对象或因缺乏可用逻辑Channel对象无法获取访问控制规则返回null。 | **错误码:** @@ -975,24 +958,23 @@ P2通常为0x00。设备应允许P2的任何值,并且应允许以下值: 0x ```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 { // refer to 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 @@ try { ```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 { // refer to 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 @@ close(): void ```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 { // refer to 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 @@ isBasicChannel(): boolean ```js import secureElement from '@ohos.secureElement'; -@State result: string = ''; -@State nfcOmaChannel: secureElement.Channel = null; +let nfcOmaChannel = null; try { // refer to 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异常:" + e.message; + console.log("isBasicChannel异常:" + e.message); } ``` @@ -1112,19 +1091,18 @@ isClosed(): boolean ```js import secureElement from '@ohos.secureElement'; -@State result: string = ''; -@State nfcOmaChannel: secureElement.Channel = null; +let nfcOmaChannel = null; try { // refer to 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 @@ getSelectResponse():number[] ```js import secureElement from '@ohos.secureElement'; -@State result: string = ''; -@State nfcOmaChannel: secureElement.Channel = null; +let str = ''; +let nfcOmaChannel = null; try { // refer to 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 @@ transmit(command: number[]): Promise **参数:** -| **参数名** | **类型** | **说明** | -| ---------- | -------- | ------------------------------------- | -| command | number[] | 在该channel上被选择的applet AID数组。 | +| **参数名** | **类型** | **必填** | **说明** | +| ---------- | -------- | ------ | ------------------------------------- | +| command | number[] | 是 | 在该channel上被选择的applet AID数组。 | **返回值:** @@ -1207,25 +1186,25 @@ transmit(command: number[]): Promise ```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]; // refer to 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 @@ transmit(command: number[], callback: AsyncCallback): void **参数:** -| **参数名** | **类型** | **说明** | -| ---------- | ----------------------- | ------------------------------------- | -| command | number[] | 在该Channel上被选择的applet AID数组。 | -| callback | AsyncCallback | 返回接收到的响应的回调,number数组。 | +| **参数名** | **类型** | **必填** | **说明** | +| ---------- | ----------------------- | ------ | ------------------------------------- | +| command | number[] | 是 | 在该Channel上被选择的applet AID数组。 | +| callback | AsyncCallback | 是 | 返回接收到的响应的回调,number数组。 | **错误码:** @@ -1259,25 +1238,26 @@ transmit(command: number[], callback: AsyncCallback): void ```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]; // refer to 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/zh-cn/application-dev/reference/apis/js-apis-sensor.md b/zh-cn/application-dev/reference/apis/js-apis-sensor.md index 739c2e99d2390413ee84ee90445dc4447e57fa8f..4b123db84ead1e9ef0ec2dad2e8b89703af4eac8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-sensor.md +++ b/zh-cn/application-dev/reference/apis/js-apis-sensor.md @@ -9,7 +9,7 @@ sensor模块提供了获取传感器数据的能力,包括获取传感器属 ## 导入模块 -```js +```ts import sensor from '@ohos.sensor'; ``` ## sensor.on @@ -42,14 +42,14 @@ on(type: SensorId.COLOR, callback: Callback\,options?: Options): **示例:** -```js +```ts try { - sensor.on(sensor.SensorId.COLOR, function (data) { - console.info('The intensity of light: ' + data.lightIntensity); - console.info('The color temperature: ' + data.colorTemperature); - }, { interval: 100000000 }); -} catch (err) { - console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.COLOR, function (data) { + console.info('Succeeded in getting the intensity of light: ' + data.lightIntensity); + console.info('Succeeded in getting the color temporature: ' + data.colorTemperature); + }, { interval: 100000000 }); +} catch (error) { + console.error(`Failed to invoke on. Code: ${error.code}, message: ${error.message}`); } ``` @@ -81,13 +81,13 @@ on(type: SensorId.SAR, callback: Callback\,options?: Options): void **示例:** -```js +```ts try { - sensor.on(sensor.SensorId.SAR, function (data) { - console.info('Specific absorption rate : ' + data.absorptionRatio); - }, { interval: 100000000 }); -} catch (err) { - console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.SAR, function (data) { + console.info('Succeeded in getting specific absorption rate : ' + data.absorptionRatio); + }, { interval: 100000000 }); +} catch (error) { + console.error(`Failed to invoke on. Code: ${error.code}, message: ${error.message}`); } ``` @@ -119,15 +119,15 @@ on(type: SensorId.ACCELEROMETER, callback: Callback<AccelerometerResponse> **示例:** -```js +```ts try { - sensor.on(sensor.SensorId.ACCELEROMETER, function (data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }, { interval: 100000000 }); -} catch (err) { - console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.ACCELEROMETER, function (data) { + console.info('Succeeded in invoking on. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking on. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking on. Z-coordinate component: ' + data.z); + }, { interval: 100000000 }); +} catch (error) { + console.error(`Failed to invoke on. Code: ${error.code}, message: ${error.message}`); } ``` @@ -159,18 +159,18 @@ on(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback: Callback<Acceleromete **示例:** -```js +```ts try { - sensor.on(sensor.SensorId.ACCELEROMETER_UNCALIBRATED, function (data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); - }, { interval: 100000000 }); -} catch (err) { - console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.ACCELEROMETER_UNCALIBRATED, function (data) { + console.info('Succeeded in invoking on. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking on. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking on. Z-coordinate component: ' + data.z); + console.info('Succeeded in invoking on. X-coordinate bias: ' + data.biasX); + console.info('Succeeded in invoking on. Y-coordinate bias: ' + data.biasY); + console.info('Succeeded in invoking on. Z-coordinate bias: ' + data.biasZ); + }, { interval: 100000000 }); +} catch (error) { + console.error(`Failed to invoke on. Code: ${error.code}, message: ${error.message}`); } ``` @@ -200,13 +200,13 @@ on(type: SensorId.AMBIENT_LIGHT, callback: Callback<LightResponse>, option **示例:** -```js +```ts try { - sensor.on(sensor.SensorId.AMBIENT_LIGHT, function (data) { - console.info('The ambient light intensity: ' + data.intensity); - }, { interval: 100000000 }); -} catch (err) { - console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.AMBIENT_LIGHT, function (data) { + console.info('Succeeded in getting the ambient light intensity: ' + data.intensity); + }, { interval: 100000000 }); +} catch (error) { + console.error(`Failed to invoke on. Code: ${error.code}, message: ${error.message}`); } ``` @@ -236,13 +236,13 @@ on(type: SensorId.AMBIENT_TEMPERATURE, callback: Callback<AmbientTemperatureR **示例:** -```js +```ts try { - sensor.on(sensor.SensorId.AMBIENT_TEMPERATURE, function (data) { - console.info('Temperature: ' + data.temperature); - }, { interval: 100000000 }); -} catch (err) { - console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.AMBIENT_TEMPERATURE, function (data) { + console.info('Succeeded in invoking on. Temperature: ' + data.temperature); + }, { interval: 100000000 }); +} catch (error) { + console.error(`Failed to invoke on. Code: ${error.code}, message: ${error.message}`); } ``` @@ -272,13 +272,13 @@ on(type: SensorId.BAROMETER, callback: Callback<BarometerResponse>, option **示例:** -```js +```ts try { - sensor.on(sensor.SensorId.BAROMETER, function (data) { - console.info('Atmospheric pressure: ' + data.pressure); - }, { interval: 100000000 }); -} catch (err) { - console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.BAROMETER, function (data) { + console.info('Succeeded in invoking on. Atmospheric pressure: ' + data.pressure); + }, { interval: 100000000 }); +} catch (error) { + console.error(`Failed to invoke on. Code: ${error.code}, message: ${error.message}`); } ``` @@ -308,15 +308,15 @@ on(type: SensorId.GRAVITY, callback: Callback<GravityResponse>,options?: O **示例:** -```js +```ts try { - sensor.on(sensor.SensorId.GRAVITY, function (data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }, { interval: 100000000 }); -} catch (err) { - console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.GRAVITY, function (data) { + console.info('Succeeded in invoking on. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking on. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking on. Z-coordinate component: ' + data.z); + }, { interval: 100000000 }); +} catch (error) { + console.error(`Failed to invoke on. Code: ${error.code}, message: ${error.message}`); } ``` @@ -348,15 +348,15 @@ on(type: SensorId.GYROSCOPE, callback: Callback<GyroscopeResponse>,options **示例:** -```js +```ts try { - sensor.on(sensor.SensorId.GYROSCOPE, function (data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }, { interval: 100000000 }); -} catch (err) { - console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.GYROSCOPE, function (data) { + console.info('Succeeded in invoking on. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking on. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking on. Z-coordinate component: ' + data.z); + }, { interval: 100000000 }); +} catch (error) { + console.error(`Failed to invoke on. Code: ${error.code}, message: ${error.message}`); } ``` @@ -389,18 +389,18 @@ on(type: SensorId.GYROSCOPE_UNCALIBRATED, callback: Callback<GyroscopeUncalib **示例:** -```js +```ts try { - sensor.on(sensor.SensorId.GYROSCOPE_UNCALIBRATED, function (data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); - }, { interval: 100000000 }); -} catch (err) { - console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.GYROSCOPE_UNCALIBRATED, function (data) { + console.info('Succeeded in invoking on. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking on. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking on. Z-coordinate component: ' + data.z); + console.info('Succeeded in invoking on. X-coordinate bias: ' + data.biasX); + console.info('Succeeded in invoking on. Y-coordinate bias: ' + data.biasY); + console.info('Succeeded in invoking on. Z-coordinate bias: ' + data.biasZ); + }, { interval: 100000000 }); +} catch (error) { + console.error(`Failed to invoke on. Code: ${error.code}, message: ${error.message}`); } ``` @@ -430,13 +430,13 @@ on(type: SensorId.HALL, callback: Callback<HallResponse>, options?: Option **示例:** -```js +```ts try { - sensor.on(sensor.SensorId.HALL, function (data) { - console.info('Hall status: ' + data.status); - }, { interval: 100000000 }); -} catch (err) { - console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.HALL, function (data) { + console.info('Succeeded in invoking on. Hall status: ' + data.status); + }, { interval: 100000000 }); +} catch (error) { + console.error(`Failed to invoke on. Code: ${error.code}, message: ${error.message}`); } ``` @@ -468,13 +468,13 @@ on(type: SensorId.HEART_RATE, callback: Callback<HeartRateResponse>,option **示例:** -```js +```ts try { - sensor.on(sensor.SensorId.HEART_RATE, function (data) { - console.info('Heart rate: ' + data.heartRate); - }, { interval: 100000000 }); -} catch (err) { - console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.HEART_RATE, function (data) { + console.info('Succeeded in invoking on. Heart rate: ' + data.heartRate); + }, { interval: 100000000 }); +} catch (error) { + console.error(`Failed to invoke on. Code: ${error.code}, message: ${error.message}`); } ``` @@ -504,13 +504,13 @@ on(type: SensorId.HUMIDITY, callback: Callback<HumidityResponse>,options?: **示例:** -```js +```ts try { - sensor.on(sensor.SensorId.HUMIDITY, function (data) { - console.info('Humidity: ' + data.humidity); - }, { interval: 100000000 }); -} catch (err) { - console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.HUMIDITY, function (data) { + console.info('Succeeded in invoking on. Humidity: ' + data.humidity); + }, { interval: 100000000 }); +} catch (error) { + console.error(`Failed to invoke on. Code: ${error.code}, message: ${error.message}`); } ``` @@ -543,15 +543,15 @@ on(type: SensorId.LINEAR_ACCELEROMETER, callback: Callback<LinearAcceleromete **示例:** -```js +```ts try { - sensor.on(sensor.SensorId.LINEAR_ACCELEROMETER, function (data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }, { interval: 100000000 }); -} catch (err) { - console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.LINEAR_ACCELEROMETER, function (data) { + console.info('Succeeded in invoking on. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking on. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking on. Z-coordinate component: ' + data.z); + }, { interval: 100000000 }); +} catch (error) { + console.error(`Failed to invoke on. Code: ${error.code}, message: ${error.message}`); } ``` @@ -581,15 +581,15 @@ on(type: SensorId.MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse> **示例:** -```js +```ts try { - sensor.on(sensor.SensorId.MAGNETIC_FIELD, function (data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }, { interval: 100000000 }); -} catch (err) { - console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.MAGNETIC_FIELD, function (data) { + console.info('Succeeded in invoking on. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking on. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking on. Z-coordinate component: ' + data.z); + }, { interval: 100000000 }); +} catch (error) { + console.error(`Failed to invoke on. Code: ${error.code}, message: ${error.message}`); } ``` @@ -619,18 +619,18 @@ on(type: SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback: Callback<MagneticFie **示例:** -```js +```ts try { - sensor.on(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, function (data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); - }, { interval: 100000000 }); -} catch (err) { - console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, function (data) { + console.info('Succeeded in invoking on. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking on. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking on. Z-coordinate component: ' + data.z); + console.info('Succeeded in invoking on. X-coordinate bias: ' + data.biasX); + console.info('Succeeded in invoking on. Y-coordinate bias: ' + data.biasY); + console.info('Succeeded in invoking on. Z-coordinate bias: ' + data.biasZ); + }, { interval: 100000000 }); +} catch (error) { + console.error(`Failed to invoke on. Code: ${error.code}, message: ${error.message}`); } ``` @@ -660,15 +660,15 @@ on(type: SensorId.ORIENTATION, callback: Callback<OrientationResponse>,opt **示例:** -```js +```ts try { - sensor.on(sensor.SensorId.ORIENTATION, function (data) { - console.info('The device rotates at an angle around the Z axis: ' + data.alpha); - console.info('The device rotates at an angle around the X axis: ' + data.beta); - console.info('The device rotates at an angle around the Y axis: ' + data.gamma); - }, { interval: 100000000 }); -} catch (err) { - console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.ORIENTATION, function (data) { + console.info('Succeeded in the device rotating at an angle around the Z axis: ' + data.alpha); + console.info('Succeeded in the device rotating at an angle around the X axis: ' + data.beta); + console.info('Succeeded in the device rotating at an angle around the Y axis: ' + data.gamma); + }, { interval: 100000000 }); +} catch (error) { + console.error(`Failed to invoke on. Code: ${error.code}, message: ${error.message}`); } ``` @@ -700,13 +700,13 @@ on(type: SensorId.PEDOMETER, callback: Callback<PedometerResponse>, option **示例:** -```js +```ts try { - sensor.on(sensor.SensorId.PEDOMETER, function (data) { - console.info('Step count: ' + data.steps); - }, { interval: 100000000 }); -} catch (err) { - console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.PEDOMETER, function (data) { + console.info('Succeeded in invoking on. Step count: ' + data.steps); + }, { interval: 100000000 }); +} catch (error) { + console.error(`Failed to invoke on. Code: ${error.code}, message: ${error.message}`); } ``` @@ -739,13 +739,13 @@ on(type: SensorId.PEDOMETER_DETECTION, callback: Callback<PedometerDetectionR **示例:** -```js +```ts try { - sensor.on(sensor.SensorId.PEDOMETER_DETECTION, function (data) { - console.info('Pedometer scalar: ' + data.scalar); - }, { interval: 100000000 }); -} catch (err) { - console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.PEDOMETER_DETECTION, function (data) { + console.info('Succeeded in invoking on. Pedometer scalar: ' + data.scalar); + }, { interval: 100000000 }); +} catch (error) { + console.error(`Failed to invoke on. Code: ${error.code}, message: ${error.message}`); } ``` @@ -775,13 +775,13 @@ on(type: SensorId.PROXIMITY, callback: Callback<ProximityResponse>, option **示例:** -```js +```ts try { - sensor.on(sensor.SensorId.PROXIMITY, function (data) { - console.info('Distance: ' + data.distance); - }, { interval: 100000000 }); -} catch (err) { - console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.PROXIMITY, function (data) { + console.info('Succeeded in invoking on. Distance: ' + data.distance); + }, { interval: 100000000 }); +} catch (error) { + console.error(`Failed to invoke on. Code: ${error.code}, message: ${error.message}`); } ``` @@ -812,16 +812,16 @@ on(type: SensorId.ROTATION_VECTOR, callback: Callback<RotationVectorResponse& **示例:** -```js +```ts try { - sensor.on(sensor.SensorId.ROTATION_VECTOR, function (data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('Scalar quantity: ' + data.w); - }, { interval: 100000000 }); -} catch (err) { - console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.ROTATION_VECTOR, function (data) { + console.info('Succeeded in invoking on. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking on. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking on. Z-coordinate component: ' + data.z); + console.info('Succeeded in invoking on. Scalar quantity: ' + data.w); + }, { interval: 100000000 }); +} catch (error) { + console.error(`Failed to invoke on. Code: ${error.code}, message: ${error.message}`); } ``` @@ -852,13 +852,13 @@ on(type: SensorId.SIGNIFICANT_MOTION, callback: Callback<SignificantMotionRes **示例:** -```js +```ts try { - sensor.on(sensor.SensorId.SIGNIFICANT_MOTION, function (data) { - console.info('Scalar data: ' + data.scalar); - }, { interval: 100000000 }); -} catch (err) { - console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.SIGNIFICANT_MOTION, function (data) { + console.info('Succeeded in invoking on. Scalar data: ' + data.scalar); + }, { interval: 100000000 }); +} catch (error) { + console.error(`Failed to invoke on. Code: ${error.code}, message: ${error.message}`); } ``` @@ -889,13 +889,13 @@ on(type: SensorId.WEAR_DETECTION, callback: Callback<WearDetectionResponse> **示例:** -```js +```ts try { - sensor.on(sensor.SensorId.WEAR_DETECTION, function (data) { - console.info('Wear status: ' + data.value); - }, { interval: 100000000 }); -} catch (err) { - console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.WEAR_DETECTION, function (data) { + console.info('Succeeded in invoking on. Wear status: ' + data.value); + }, { interval: 100000000 }); +} catch (error) { + console.error(`Failed to invoke on. Code: ${error.code}, message: ${error.message}`); } ``` @@ -928,15 +928,15 @@ once(type: SensorId.ACCELEROMETER, callback: Callback<AccelerometerResponse&g **示例:** -```js +```ts try { - sensor.once(sensor.SensorId.ACCELEROMETER, function (data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }); -} catch (err) { - console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.ACCELEROMETER, function (data) { + console.info('Succeeded in invoking once. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking once. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking once. Z-coordinate component: ' + data.z); + }); +} catch (error) { + console.error(`Failed to invoke once. Code: ${error.code}, message: ${error.message}`); } ``` @@ -967,18 +967,18 @@ once(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback: Callback<Accelerome **示例:** -```js +```ts try { - sensor.once(sensor.SensorId.ACCELEROMETER_UNCALIBRATED, function (data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); - }); -} catch (err) { - console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.ACCELEROMETER_UNCALIBRATED, function (data) { + console.info('Succeeded in invoking once. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking once. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking once. Z-coordinate component: ' + data.z); + console.info('Succeeded in invoking once. X-coordinate bias: ' + data.biasX); + console.info('Succeeded in invoking once. Y-coordinate bias: ' + data.biasY); + console.info('Succeeded in invoking once. Z-coordinate bias: ' + data.biasZ); + }); +} catch (error) { + console.error(`Failed to invoke once. Code: ${error.code}, message: ${error.message}`); } ``` @@ -1007,13 +1007,13 @@ once(type: SensorId.AMBIENT_LIGHT, callback: Callback<LightResponse>): voi **示例:** -```js +```ts try { - sensor.once(sensor.SensorId.AMBIENT_LIGHT, function (data) { - console.info('The ambient light intensity: ' + data.intensity); - }); -} catch (err) { - console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.AMBIENT_LIGHT, function (data) { + console.info('Succeeded in invoking once. the ambient light intensity: ' + data.intensity); + }); +} catch (error) { + console.error(`Failed to invoke once. Code: ${error.code}, message: ${error.message}`); } ``` @@ -1042,13 +1042,13 @@ once(type: SensorId.AMBIENT_TEMPERATURE, callback: Callback<AmbientTemperatur **示例:** -```js +```ts try { - sensor.once(sensor.SensorId.AMBIENT_TEMPERATURE, function (data) { - console.info('Temperature: ' + data.temperature); - }); -} catch (err) { - console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.AMBIENT_TEMPERATURE, function (data) { + console.info('Succeeded in invoking once. Temperature: ' + data.temperature); + }); +} catch (error) { + console.error(`Failed to invoke once. Code: ${error.code}, message: ${error.message}`); } ``` @@ -1077,13 +1077,13 @@ once(type: SensorId.BAROMETER, callback: Callback<BarometerResponse>): voi **示例:** -```js +```ts try { - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, function (data) { - console.info('Atmospheric pressure: ' + data.pressure); - }); -} catch (err) { - console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.BAROMETER, function (data) { + console.info('Succeeded in invoking once. Atmospheric pressure: ' + data.pressure); + }); +} catch (error) { + console.error(`Failed to invoke once. Code: ${error.code}, message: ${error.message}`); } ``` @@ -1112,15 +1112,15 @@ once(type: SensorId.GRAVITY, callback: Callback<GravityResponse>): void **示例:** -```js +```ts try { - sensor.once(sensor.SensorId.GRAVITY, function (data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }); -} catch (err) { - console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.GRAVITY, function (data) { + console.info('Succeeded in invoking once. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking once. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking once. Z-coordinate component: ' + data.z); + }); +} catch (error) { + console.error(`Failed to invoke once. Code: ${error.code}, message: ${error.message}`); } ``` @@ -1151,15 +1151,17 @@ once(type: SensorId.GYROSCOPE, callback: Callback<GyroscopeResponse>): voi **示例:** -```js +```ts +import sensor from '@ohos.sensor'; + try { - sensor.once(sensor.SensorId.GYROSCOPE, function (data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }); -} catch (err) { - console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.GYROSCOPE, function (data) { + console.info('Succeeded in invoking once. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking once. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking once. Z-coordinate component: ' + data.z); + }); +} catch (error) { + console.error(`Failed to invoke once. Code: ${error.code}, message: ${error.message}`); } ``` @@ -1190,18 +1192,18 @@ once(type: SensorId.GYROSCOPE_UNCALIBRATED, callback: Callback<GyroscopeUncal **示例:** -```js +```ts try { - sensor.once(sensor.SensorId.GYROSCOPE_UNCALIBRATED, function (data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); - }); -} catch (err) { - console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.GYROSCOPE_UNCALIBRATED, function (data) { + console.info('Succeeded in invoking once. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking once. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking once. Z-coordinate component: ' + data.z); + console.info('Succeeded in invoking once. X-coordinate bias: ' + data.biasX); + console.info('Succeeded in invoking once. Y-coordinate bias: ' + data.biasY); + console.info('Succeeded in invoking once. Z-coordinate bias: ' + data.biasZ); + }); +} catch (error) { + console.error(`Failed to invoke once. Code: ${error.code}, message: ${error.message}`); } ``` @@ -1230,13 +1232,13 @@ once(type: SensorId.HALL, callback: Callback<HallResponse>): void **示例:** -```js +```ts try { - sensor.once(sensor.SensorId.HALL, function (data) { - console.info('Status: ' + data.status); - }); -} catch (err) { - console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.HALL, function (data) { + console.info('Succeeded in invoking once. Status: ' + data.status); + }); +} catch (error) { + console.error(`Failed to invoke once. Code: ${error.code}, message: ${error.message}`); } ``` @@ -1267,13 +1269,13 @@ once(type: SensorId.HEART_RATE, callback: Callback<HeartRateResponse>): vo **示例:** -```js +```ts try { - sensor.once(sensor.SensorId.HEART_RATE, function (data) { - console.info('Heart rate: ' + data.heartRate); - }); -} catch (err) { - console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.HEART_RATE, function (data) { + console.info('Succeeded in invoking once. Heart rate: ' + data.heartRate); + }); +} catch (error) { + console.error(`Failed to invoke once. Code: ${error.code}, message: ${error.message}`); } ``` @@ -1302,13 +1304,13 @@ once(type: SensorId.HUMIDITY, callback: Callback<HumidityResponse>): void **示例:** -```js +```ts try { - sensor.once(sensor.SensorId.HUMIDITY, function (data) { - console.info('Humidity: ' + data.humidity); - }); -} catch (err) { - console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.HUMIDITY, function (data) { + console.info('Succeeded in invoking once. Humidity: ' + data.humidity); + }); +} catch (error) { + console.error(`Failed to invoke once. Code: ${error.code}, message: ${error.message}`); } ``` @@ -1339,15 +1341,15 @@ once(type: SensorId.LINEAR_ACCELEROMETER, callback: Callback<LinearAccelerome **示例:** -```js +```ts try { - sensor.once(sensor.SensorId.LINEAR_ACCELEROMETER, function (data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }); -} catch (err) { - console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.LINEAR_ACCELEROMETER, function (data) { + console.info('Succeeded in invoking once. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking once. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking once. Z-coordinate component: ' + data.z); + }); +} catch (error) { + console.error(`Failed to invoke once. Code: ${error.code}, message: ${error.message}`); } ``` @@ -1376,15 +1378,15 @@ once(type: SensorId.MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse& **示例:** -```js +```ts try { - sensor.once(sensor.SensorId.MAGNETIC_FIELD, function (data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }); -} catch (err) { - console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.MAGNETIC_FIELD, function (data) { + console.info('Succeeded in invoking once. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking once. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking once. Z-coordinate component: ' + data.z); + }); +} catch (error) { + console.error(`Failed to invoke once. Code: ${error.code}, message: ${error.message}`); } ``` @@ -1413,18 +1415,18 @@ once(type: SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback: Callback<MagneticF **示例:** -```js +```ts try { - sensor.once(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, function (data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); - }); -} catch (err) { - console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, function (data) { + console.info('Succeeded in invoking once. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking once. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking once. Z-coordinate component: ' + data.z); + console.info('Succeeded in invoking once. X-coordinate bias: ' + data.biasX); + console.info('Succeeded in invoking once. Y-coordinate bias: ' + data.biasY); + console.info('Succeeded in invoking once. Z-coordinate bias: ' + data.biasZ); + }); +} catch (error) { + console.error(`Failed to invoke once. Code: ${error.code}, message: ${error.message}`); } ``` @@ -1453,15 +1455,15 @@ once(type: SensorId.ORIENTATION, callback: Callback<OrientationResponse>): **示例:** -```js +```ts try { - sensor.once(sensor.SensorId.ORIENTATION, function (data) { - console.info('The device rotates at an angle around the X axis: ' + data.beta); - console.info('The device rotates at an angle around the Y axis: ' + data.gamma); - console.info('The device rotates at an angle around the Z axis: ' + data.alpha); - }); -} catch (err) { - console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.ORIENTATION, function (data) { + console.info('Succeeded in the device rotating at an angle around the X axis: ' + data.beta); + console.info('Succeeded in the device rotating at an angle around the Y axis: ' + data.gamma); + console.info('Succeeded in the device rotating at an angle around the Z axis: ' + data.alpha); + }); +} catch (error) { + console.error(`Failed to invoke once. Code: ${error.code}, message: ${error.message}`); } ``` @@ -1492,13 +1494,13 @@ once(type: SensorId.PEDOMETER, callback: Callback<PedometerResponse>): voi **示例:** -```js +```ts try { - sensor.once(sensor.SensorId.PEDOMETER, function (data) { - console.info('Step count: ' + data.steps); - }); -} catch (err) { - console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.PEDOMETER, function (data) { + console.info('Succeeded in invoking once. Step count: ' + data.steps); + }); +} catch (error) { + console.error(`Failed to invoke once. Code: ${error.code}, message: ${error.message}`); } ``` @@ -1529,13 +1531,13 @@ once(type: SensorId.PEDOMETER_DETECTION, callback: Callback<PedometerDetectio **示例:** -```js +```ts try { - sensor.once(sensor.SensorId.PEDOMETER_DETECTION, function (data) { - console.info('Scalar data: ' + data.scalar); - }); -} catch (err) { - console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.PEDOMETER_DETECTION, function (data) { + console.info('Succeeded in invoking once. Scalar data: ' + data.scalar); + }); +} catch (error) { + console.error(`Failed to invoke once. Code: ${error.code}, message: ${error.message}`); } ``` @@ -1564,13 +1566,13 @@ once(type: SensorId.PROXIMITY, callback: Callback<ProximityResponse>): voi **示例:** -```js +```ts try { - sensor.once(sensor.SensorId.PROXIMITY, function (data) { - console.info('Distance: ' + data.distance); - }); -} catch (err) { - console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.PROXIMITY, function (data) { + console.info('Succeeded in invoking once. Distance: ' + data.distance); + }); +} catch (error) { + console.error(`Failed to invoke once. Code: ${error.code}, message: ${error.message}`); } ``` @@ -1599,16 +1601,16 @@ once(type: SensorId.ROTATION_VECTOR, callback: Callback<RotationVectorRespons **示例:** -```js +```ts try { - sensor.once(sensor.SensorId.ROTATION_VECTOR, function (data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('Scalar quantity: ' + data.w); - }); -} catch (err) { - console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.ROTATION_VECTOR, function (data) { + console.info('Succeeded in invoking once. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking once. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking once. Z-coordinate component: ' + data.z); + console.info('Succeeded in invoking once. Scalar quantity: ' + data.w); + }); +} catch (error) { + console.error(`Failed to invoke once. Code: ${error.code}, message: ${error.message}`); } ``` @@ -1637,13 +1639,13 @@ once(type: SensorId.SIGNIFICANT_MOTION, callback: Callback<SignificantMotionR **示例:** -```js +```ts try { - sensor.once(sensor.SensorId.SIGNIFICANT_MOTION, function (data) { - console.info('Scalar data: ' + data.scalar); - }); -} catch (err) { - console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.SIGNIFICANT_MOTION, function (data) { + console.info('Succeeded in invoking once. Scalar data: ' + data.scalar); + }); +} catch (error) { + console.error(`Failed to invoke once. Code: ${error.code}, message: ${error.message}`); } ``` @@ -1672,13 +1674,13 @@ once(type: SensorId.WEAR_DETECTION, callback: Callback<WearDetectionResponse& **示例:** -```js +```ts try { - sensor.once(sensor.SensorId.WEAR_DETECTION, function (data) { - console.info("Wear status: " + data.value); - }); -} catch (err) { - console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.WEAR_DETECTION, function (data) { + console.info('Succeeded in invoking once. Wear status: ' + data.value); + }); +} catch (error) { + console.error(`Failed to invoke once. Code: ${error.code}, message: ${error.message}`); } ``` @@ -1703,22 +1705,24 @@ off(type: SensorId.COLOR, callback?: Callback\): void **示例:** -```js +```ts function callback1(data) { - console.info('Callback1 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); } + function callback2(data) { - console.info('Callback2 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); } + try { - sensor.on(sensor.SensorId.COLOR, callback1); - sensor.on(sensor.SensorId.COLOR, callback2); - // 仅取消callback1的注册 - sensor.off(sensor.SensorId.COLOR, callback1); - // 取消注册SensorId.COLOR的所有回调 - sensor.off(sensor.SensorId.COLOR); -} catch (err) { - console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.COLOR, callback1); + sensor.on(sensor.SensorId.COLOR, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.COLOR, callback1); + // 取消注册SensorId.COLOR的所有回调 + sensor.off(sensor.SensorId.COLOR); +} catch (error) { + console.error(`Failed to invoke off. Code: ${error.code}, message: ${error.message}`); } ``` @@ -1741,22 +1745,24 @@ off(type: SensorId.SAR, callback?: Callback\): void **示例:** -```js +```ts function callback1(data) { - console.info('Callback1 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); } + function callback2(data) { - console.info('Callback2 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); } + try { - sensor.on(sensor.SensorId.SAR, callback1); - sensor.on(sensor.SensorId.SAR, callback2); - // 仅取消callback1的注册 - sensor.off(sensor.SensorId.SAR, callback1); - // 取消注册SensorId.SAR的所有回调 - sensor.off(sensor.SensorId.SAR); -} catch (err) { - console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.SAR, callback1); + sensor.on(sensor.SensorId.SAR, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.SAR, callback1); + // 取消注册SensorId.SAR的所有回调 + sensor.off(sensor.SensorId.SAR); +} catch (error) { + console.error(`Failed to invoke off. Code: ${error.code}, message: ${error.message}`); } ``` @@ -1779,22 +1785,24 @@ off(type: SensorId.ACCELEROMETER, callback?: Callback<AccelerometerResponse&g **示例:** -```js +```ts function callback1(data) { - console.info('Callback1 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); } + function callback2(data) { - console.info('Callback2 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); } + try { - sensor.on(sensor.SensorId.ACCELEROMETER, callback1); - sensor.on(sensor.SensorId.ACCELEROMETER, callback2); - // 仅取消callback1的注册 - sensor.off(sensor.SensorId.ACCELEROMETER, callback1); - // 取消SensorId.ACCELEROMETER类型的所有回调 - sensor.off(sensor.SensorId.ACCELEROMETER); -} catch (err) { - console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.ACCELEROMETER, callback1); + sensor.on(sensor.SensorId.ACCELEROMETER, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.ACCELEROMETER, callback1); + // 取消SensorId.ACCELEROMETER类型的所有回调 + sensor.off(sensor.SensorId.ACCELEROMETER); +} catch (error) { + console.error(`Failed to invoke off. Code: ${error.code}, message: ${error.message}`); } ``` @@ -1817,22 +1825,24 @@ off(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback?: Callback<Accelerome **示例:** -```js +```ts function callback1(data) { - console.info('Callback1 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); } + function callback2(data) { - console.info('Callback2 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); } + try { - sensor.on(sensor.SensorId.ACCELEROMETER_UNCALIBRATED, callback1); - sensor.on(sensor.SensorId.ACCELEROMETER_UNCALIBRATED, callback2); - // 仅取消callback1的注册 - sensor.off(sensor.SensorId.ACCELEROMETER_UNCALIBRATED, callback1); - // 取消注册SensorId.ACCELEROMETER_UNCALIBRATED类型的所有回调 - sensor.off(sensor.SensorId.ACCELEROMETER_UNCALIBRATED); -} catch (err) { - console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.ACCELEROMETER_UNCALIBRATED, callback1); + sensor.on(sensor.SensorId.ACCELEROMETER_UNCALIBRATED, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.ACCELEROMETER_UNCALIBRATED, callback1); + // 取消注册SensorId.ACCELEROMETER_UNCALIBRATED类型的所有回调 + sensor.off(sensor.SensorId.ACCELEROMETER_UNCALIBRATED); +} catch (error) { + console.error(`Failed to invoke off. Code: ${error.code}, message: ${error.message}`); } ``` @@ -1853,22 +1863,24 @@ off(type: SensorId.AMBIENT_LIGHT, callback?: Callback<LightResponse>): voi **示例:** -```js +```ts function callback1(data) { - console.info('Callback1 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); } + function callback2(data) { - console.info('Callback2 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); } + try { - sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback1); - sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback2); - // 仅取消callback1的注册 - sensor.off(sensor.SensorId.AMBIENT_LIGHT, callback1); - // 取消注册SensorId.AMBIENT_LIGHT的所有回调 - sensor.off(sensor.SensorId.AMBIENT_LIGHT); -} catch (err) { - console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback1); + sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.AMBIENT_LIGHT, callback1); + // 取消注册SensorId.AMBIENT_LIGHT + sensor.off(sensor.SensorId.AMBIENT_LIGHT); +} catch (error) { + console.error(`Failed to invoke off. Code: ${error.code}, message: ${error.message}`); } ``` @@ -1889,22 +1901,24 @@ off(type: SensorId.AMBIENT_TEMPERATURE, callback?: Callback<AmbientTemperatur **示例:** -```js +```ts function callback1(data) { - console.info('Callback1 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); } + function callback2(data) { - console.info('Callback2 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); } + try { - sensor.on(sensor.SensorId.AMBIENT_TEMPERATURE, callback1); - sensor.on(sensor.SensorId.AMBIENT_TEMPERATURE, callback2); - // 仅取消callback1的注册 - sensor.off(sensor.SensorId.AMBIENT_TEMPERATURE, callback1); - // 取消注册SensorId.AMBIENT_TEMPERATURE的所有回调 - sensor.off(sensor.SensorId.AMBIENT_TEMPERATURE); -} catch (err) { - console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.AMBIENT_TEMPERATURE, callback1); + sensor.on(sensor.SensorId.AMBIENT_TEMPERATURE, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.AMBIENT_TEMPERATURE, callback1); + // 取消注册SensorId.AMBIENT_TEMPERATURE的所有回调 + sensor.off(sensor.SensorId.AMBIENT_TEMPERATURE); +} catch (error) { + console.error(`Failed to invoke off. Code: ${error.code}, message: ${error.message}`); } ``` @@ -1925,13 +1939,15 @@ off(type: SensorId.BAROMETER, callback?: Callback<BarometerResponse>): voi **示例:** -```js +```ts function callback1(data) { - console.info('Callback1 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); } + function callback2(data) { - console.info('Callback2 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); } + try { sensor.on(sensor.SensorId.BAROMETER, callback1); sensor.on(sensor.SensorId.BAROMETER, callback2); @@ -1939,8 +1955,8 @@ try { sensor.off(sensor.SensorId.BAROMETER, callback1); // 取消注册SensorId.BAROMETER的所有回调 sensor.off(sensor.SensorId.BAROMETER); -} catch (err) { - console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} catch (error) { + console.error(`Failed to invoke off. Code: ${error.code}, message: ${error.message}`); } ``` @@ -1961,22 +1977,24 @@ off(type: SensorId.GRAVITY, callback?: Callback<GravityResponse>): void **示例:** -```js +```ts function callback1(data) { - console.info('Callback1 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); } + function callback2(data) { - console.info('Callback2 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); } + try { - sensor.on(sensor.SensorId.GRAVITY, callback1); - sensor.on(sensor.SensorId.GRAVITY, callback2); - // 仅取消callback1的注册 - sensor.off(sensor.SensorId.GRAVITY, callback1); - // 取消注册SensorId.GRAVITY的所有回调 - sensor.off(sensor.SensorId.GRAVITY); -} catch (err) { - console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.GRAVITY, callback1); + sensor.on(sensor.SensorId.GRAVITY, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.GRAVITY, callback1); + // 取消注册SensorId.GRAVITY的所有回调 + sensor.off(sensor.SensorId.GRAVITY); +} catch (error) { + console.error(`Failed to invoke off. Code: ${error.code}, message: ${error.message}`); } ``` @@ -1999,22 +2017,24 @@ off(type: SensorId.GYROSCOPE, callback?: Callback<GyroscopeResponse>): voi **示例:** -```js +```ts function callback1(data) { - console.info('Callback1 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); } + function callback2(data) { - console.info('Callback2 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); } + try { - sensor.on(sensor.SensorId.GYROSCOPE, callback1); - sensor.on(sensor.SensorId.GYROSCOPE, callback2); - // 仅取消callback1的注册 - sensor.off(sensor.SensorId.GYROSCOPE, callback1); - // 取消注册SensorId.GYROSCOPE的所有回调 - sensor.off(sensor.SensorId.GYROSCOPE); -} catch (err) { - console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.GYROSCOPE, callback1); + sensor.on(sensor.SensorId.GYROSCOPE, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.GYROSCOPE, callback1); + // 取消注册SensorId.GYROSCOPE的所有回调 + sensor.off(sensor.SensorId.GYROSCOPE); +} catch (error) { + console.error(`Failed to invoke off. Code: ${error.code}, message: ${error.message}`); } ``` @@ -2037,22 +2057,24 @@ off(type: SensorId.GYROSCOPE_UNCALIBRATED, callback?: Callback<GyroscopeUncal **示例:** -```js +```ts function callback1(data) { - console.info('Callback1 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); } + function callback2(data) { - console.info('Callback2 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); } + try { - sensor.on(sensor.SensorId.GYROSCOPE_UNCALIBRATED, callback1); - sensor.on(sensor.SensorId.GYROSCOPE_UNCALIBRATED, callback2); - // 仅取消callback1的注册 - sensor.off(sensor.SensorId.GYROSCOPE_UNCALIBRATED, callback1); - // 取消注册SensorId.GYROSCOPE_UNCALIBRATED的所有回调 - sensor.off(sensor.SensorId.GYROSCOPE_UNCALIBRATED); -} catch (err) { - console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.GYROSCOPE_UNCALIBRATED, callback1); + sensor.on(sensor.SensorId.GYROSCOPE_UNCALIBRATED, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.GYROSCOPE_UNCALIBRATED, callback1); + // 取消注册SensorId.GYROSCOPE_UNCALIBRATED的所有回调 + sensor.off(sensor.SensorId.GYROSCOPE_UNCALIBRATED); +} catch (error) { + console.error(`Failed to invoke off. Code: ${error.code}, message: ${error.message}`); } ``` @@ -2073,22 +2095,24 @@ off(type: SensorId.HALL, callback?: Callback<HallResponse>): void **示例:** -```js +```ts function callback1(data) { - console.info('Callback1 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); } + function callback2(data) { - console.info('Callback2 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); } + try { - sensor.on(sensor.SensorId.HALL, callback1); - sensor.on(sensor.SensorId.HALL, callback2); - // 仅取消callback1的注册 - sensor.off(sensor.SensorId.HALL, callback1); - // 取消注册SensorId.HALL的所有回调 - sensor.off(sensor.SensorId.HALL); -} catch (err) { - console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.HALL, callback1); + sensor.on(sensor.SensorId.HALL, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.HALL, callback1); + // 取消注册SensorId.HALL的所有回调 + sensor.off(sensor.SensorId.HALL); +} catch (error) { + console.error(`Failed to invoke off. Code: ${error.code}, message: ${error.message}`); } ``` @@ -2111,22 +2135,24 @@ off(type: SensorId.HEART_RATE, callback?: Callback<HeartRateResponse>): vo **示例:** -```js +```ts function callback1(data) { - console.info('Callback1 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); } + function callback2(data) { - console.info('Callback2 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); } + try { - sensor.on(sensor.SensorId.HEART_RATE, callback1); - sensor.on(sensor.SensorId.HEART_RATE, callback2); - // 仅取消callback1的注册 - sensor.off(sensor.SensorId.HEART_RATE, callback1); - // 取消注册SensorId.HEART_RATE的所有回调 - sensor.off(sensor.SensorId.HEART_RATE); -} catch (err) { - console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.HEART_RATE, callback1); + sensor.on(sensor.SensorId.HEART_RATE, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.HEART_RATE, callback1); + // 取消注册SensorId.HEART_RATE的所有回调 + sensor.off(sensor.SensorId.HEART_RATE); +} catch (error) { + console.error(`Failed to invoke off. Code: ${error.code}, message: ${error.message}`); } ``` @@ -2147,22 +2173,24 @@ off(type: SensorId.HUMIDITY, callback?: Callback<HumidityResponse>): void **示例:** -```js +```ts function callback1(data) { - console.info('Callback1 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); } + function callback2(data) { - console.info('Callback2 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); } + try { - sensor.on(sensor.SensorId.HUMIDITY, callback1); - sensor.on(sensor.SensorId.HUMIDITY, callback2); - // 仅取消callback1的注册 - sensor.off(sensor.SensorId.HUMIDITY, callback1); - // 取消注册SensorId.HUMIDITY的所有回调 - sensor.off(sensor.SensorId.HUMIDITY); -} catch (err) { - console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.HUMIDITY, callback1); + sensor.on(sensor.SensorId.HUMIDITY, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.HUMIDITY, callback1); + // 取消注册SensorId.HUMIDITY的所有回调 + sensor.off(sensor.SensorId.HUMIDITY); +} catch (error) { + console.error(`Failed to invoke off. Code: ${error.code}, message: ${error.message}`); } ``` @@ -2185,22 +2213,24 @@ off(type: SensorId.LINEAR_ACCELEROMETER, callback?: Callback<LinearAccelerome **示例:** -```js +```ts function callback1(data) { - console.info('Callback1 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); } + function callback2(data) { - console.info('Callback2 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); } + try { - sensor.on(sensor.SensorId.LINEAR_ACCELEROMETER, callback1); - sensor.on(sensor.SensorId.LINEAR_ACCELEROMETER, callback2); - // 仅取消callback1的注册 - sensor.off(sensor.SensorId.LINEAR_ACCELEROMETER, callback1); - // 取消注册SensorId.LINEAR_ACCELEROMETER的所有回调 - sensor.off(sensor.SensorId.LINEAR_ACCELEROMETER); -} catch (err) { - console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.LINEAR_ACCELEROMETER, callback1); + sensor.on(sensor.SensorId.LINEAR_ACCELEROMETER, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.LINEAR_ACCELEROMETER, callback1); + // 取消注册SensorId.LINEAR_ACCELEROMETER的所有回调 + sensor.off(sensor.SensorId.LINEAR_ACCELEROMETER); +} catch (error) { + console.error(`Failed to invoke off. Code: ${error.code}, message: ${error.message}`); } ``` @@ -2221,22 +2251,24 @@ off(type: SensorId.MAGNETIC_FIELD, callback?: Callback<MagneticFieldResponse& **示例:** -```js +```ts function callback1(data) { - console.info('Callback1 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); } + function callback2(data) { - console.info('Callback2 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); } + try { - sensor.on(sensor.SensorId.MAGNETIC_FIELD, callback1); - sensor.on(sensor.SensorId.MAGNETIC_FIELD, callback2); - // 仅取消callback1的注册 - sensor.off(sensor.SensorId.MAGNETIC_FIELD, callback1); - // 取消注册SensorId.MAGNETIC_FIELD的所有回调 - sensor.off(sensor.SensorId.MAGNETIC_FIELD); -} catch (err) { - console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.MAGNETIC_FIELD, callback1); + sensor.on(sensor.SensorId.MAGNETIC_FIELD, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.MAGNETIC_FIELD, callback1); + // 取消注册SensorId.MAGNETIC_FIELD的所有回调 + sensor.off(sensor.SensorId.MAGNETIC_FIELD); +} catch (error) { + console.error(`Failed to invoke off. Code: ${error.code}, message: ${error.message}`); } ``` @@ -2257,22 +2289,24 @@ off(type: SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback?: Callback<MagneticF **示例:** -```js +```ts function callback1(data) { - console.info('Callback1 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); } + function callback2(data) { - console.info('Callback2 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); } + try { - sensor.on(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback1); - sensor.on(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback2); - // 仅取消callback1的注册 - sensor.off(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback1); - // 取消注册SensorId.MAGNETIC_FIELD_UNCALIBRATED的所有回调 - sensor.off(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED); -} catch (err) { - console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback1); + sensor.on(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback1); + // 取消注册SensorId.MAGNETIC_FIELD_UNCALIBRATED的所有回调 + sensor.off(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED); +} catch (error) { + console.error(`Failed to invoke off. Code: ${error.code}, message: ${error.message}`); } ``` @@ -2293,22 +2327,24 @@ off(type: SensorId.ORIENTATION, callback?: Callback<OrientationResponse>): **示例:** -```js +```ts function callback1(data) { - console.info('Callback1 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); } + function callback2(data) { - console.info('Callback2 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); } + try { - sensor.on(sensor.SensorId.ORIENTATION, callback1); - sensor.on(sensor.SensorId.ORIENTATION, callback2); - // 仅取消callback1的注册 - sensor.off(sensor.SensorId.ORIENTATION, callback1); - // 取消注册SensorId.ORIENTATION的所有回调 - sensor.off(sensor.SensorId.ORIENTATION); -} catch (err) { - console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.ORIENTATION, callback1); + sensor.on(sensor.SensorId.ORIENTATION, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.ORIENTATION, callback1); + // 取消注册SensorId.ORIENTATION的所有回调 + sensor.off(sensor.SensorId.ORIENTATION); +} catch (error) { + console.error(`Failed to invoke off. Code: ${error.code}, message: ${error.message}`); } ``` @@ -2331,22 +2367,24 @@ off(type: SensorId.PEDOMETER, callback?: Callback<PedometerResponse>): voi **示例:** -```js +```ts function callback1(data) { - console.info('Callback1 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); } + function callback2(data) { - console.info('Callback2 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); } + try { - sensor.on(sensor.SensorId.PEDOMETER, callback1); - sensor.on(sensor.SensorId.PEDOMETER, callback2); - // 仅取消callback1的注册 - sensor.off(sensor.SensorId.PEDOMETER, callback1); - // 取消注册SensorId.PEDOMETER的所有回调 - sensor.off(sensor.SensorId.PEDOMETER); -} catch (err) { - console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.PEDOMETER, callback1); + sensor.on(sensor.SensorId.PEDOMETER, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.PEDOMETER, callback1); + // 取消注册SensorId.PEDOMETER的所有回调 + sensor.off(sensor.SensorId.PEDOMETER); +} catch (error) { + console.error(`Failed to invoke off. Code: ${error.code}, message: ${error.message}`); } ``` @@ -2369,22 +2407,24 @@ off(type: SensorId.PEDOMETER_DETECTION, callback?: Callback<PedometerDetectio **示例:** -```js +```ts function callback1(data) { - console.info('Callback1 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); } + function callback2(data) { - console.info('Callback2 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); } + try { - sensor.on(sensor.SensorId.PEDOMETER_DETECTION, callback1); - sensor.on(sensor.SensorId.PEDOMETER_DETECTION, callback2); - // 仅取消callback1的注册 - sensor.off(sensor.SensorId.PEDOMETER_DETECTION, callback1); - // 取消注册SensorId.PEDOMETER_DETECTION的所有回调 - sensor.off(sensor.SensorId.PEDOMETER_DETECTION); -} catch (err) { - console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.PEDOMETER_DETECTION, callback1); + sensor.on(sensor.SensorId.PEDOMETER_DETECTION, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.PEDOMETER_DETECTION, callback1); + // 取消注册SensorId.PEDOMETER_DETECTION的所有回调 + sensor.off(sensor.SensorId.PEDOMETER_DETECTION); +} catch (error) { + console.error(`Failed to invoke off. Code: ${error.code}, message: ${error.message}`); } ``` @@ -2405,22 +2445,24 @@ off(type: SensorId.PROXIMITY, callback?: Callback<ProximityResponse>): voi **示例:** -```js +```ts function callback1(data) { - console.info('Callback1 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); } + function callback2(data) { - console.info('Callback2 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); } + try { - sensor.on(sensor.SensorId.PROXIMITY, callback1); - sensor.on(sensor.SensorId.PROXIMITY, callback2); - // 仅取消callback1的注册 - sensor.off(sensor.SensorId.PROXIMITY, callback1); - // 取消注册SensorId.PROXIMITY的所有回调 - sensor.off(sensor.SensorId.PROXIMITY); -} catch (err) { - console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.PROXIMITY, callback1); + sensor.on(sensor.SensorId.PROXIMITY, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.PROXIMITY, callback1); + // 取消注册SensorId.PROXIMITY的所有回调 + sensor.off(sensor.SensorId.PROXIMITY); +} catch (error) { + console.error(`Failed to invoke off. Code: ${error.code}, message: ${error.message}`); } ``` @@ -2441,22 +2483,24 @@ off(type: SensorId.ROTATION_VECTOR, callback?: Callback<RotationVectorRespons **示例:** -```js +```ts function callback1(data) { - console.info('Callback1 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); } + function callback2(data) { - console.info('Callback2 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); } + try { - sensor.on(sensor.SensorId.ROTATION_VECTOR, callback1); - sensor.on(sensor.SensorId.ROTATION_VECTOR, callback2); - // 仅取消callback1的注册 - sensor.off(sensor.SensorId.ROTATION_VECTOR, callback1); - // 取消注册SensorId.ROTATION_VECTOR的所有回调 - sensor.off(sensor.SensorId.ROTATION_VECTOR); -} catch (err) { - console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.ROTATION_VECTOR, callback1); + sensor.on(sensor.SensorId.ROTATION_VECTOR, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.ROTATION_VECTOR, callback1); + // 取消注册SensorId.ROTATION_VECTOR的所有回调 + sensor.off(sensor.SensorId.ROTATION_VECTOR); +} catch (error) { + console.error(`Failed to invoke off. Code: ${error.code}, message: ${error.message}`); } ``` @@ -2477,22 +2521,24 @@ off(type: SensorId.SIGNIFICANT_MOTION, callback?: Callback<SignificantMotionR **示例:** -```js +```ts function callback1(data) { - console.info('Callback1 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); } + function callback2(data) { - console.info('Callback2 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); } + try { - sensor.on(sensor.SensorId.SIGNIFICANT_MOTION, callback1); - sensor.on(sensor.SensorId.SIGNIFICANT_MOTION, callback2); - // 仅取消callback1的注册 - sensor.off(sensor.SensorId.SIGNIFICANT_MOTION, callback1); - // 取消注册SensorId.SIGNIFICANT_MOTION的所有回调 - sensor.off(sensor.SensorId.SIGNIFICANT_MOTION); -} catch (err) { - console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.SIGNIFICANT_MOTION, callback1); + sensor.on(sensor.SensorId.SIGNIFICANT_MOTION, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.SIGNIFICANT_MOTION, callback1); + // 取消注册SensorId.SIGNIFICANT_MOTION的所有回调 + sensor.off(sensor.SensorId.SIGNIFICANT_MOTION); +} catch (error) { + console.error(`Failed to invoke off. Code: ${error.code}, message: ${error.message}`); } ``` @@ -2513,22 +2559,24 @@ off(type: SensorId.WEAR_DETECTION, callback?: Callback<WearDetectionResponse& **示例:** -```js +```ts function callback1(data) { - console.info('Callback1 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback1 data: ' + JSON.stringify(data)); } + function callback2(data) { - console.info('Callback2 data: ' + JSON.stringify(data)); + console.info('Succeeded in getting callback2 data: ' + JSON.stringify(data)); } + try { - sensor.on(sensor.SensorId.WEAR_DETECTION, callback1); - sensor.on(sensor.SensorId.WEAR_DETECTION, callback2); - // 仅取消callback1的注册 - sensor.off(sensor.SensorId.WEAR_DETECTION, callback1); - // 取消注册SensorId.WEAR_DETECTION的所有回调 - sensor.off(sensor.SensorId.WEAR_DETECTION); -} catch (err) { - console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.WEAR_DETECTION, callback1); + sensor.on(sensor.SensorId.WEAR_DETECTION, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.WEAR_DETECTION, callback1); + // 取消注册SensorId.WEAR_DETECTION的所有回调 + sensor.off(sensor.SensorId.WEAR_DETECTION); +} catch (error) { + console.error(`Failed to invoke off. Code: ${error.code}, message: ${error.message}`); } ``` @@ -2558,23 +2606,23 @@ getGeomagneticInfo(locationOptions: LocationOptions, timeMillis: number, callbac **示例:** -```js +```ts try { - sensor.getGeomagneticInfo({ latitude: 80, longitude: 0, altitude: 0 }, 1580486400000, function (err, data) { - if (err) { - console.error('Get geomagneticInfo failed. Error code: ' + err.code + '; message: ' + err.message); - return; - } - console.info("GeomagneticInfo x" + data.x); - console.info("GeomagneticInfo y" + data.y); - console.info("GeomagneticInfo z" + data.z); - console.info("GeomagneticInfo geomagneticDip" + data.geomagneticDip); - console.info("GeomagneticInfo deflectionAngle" + data.deflectionAngle); - console.info("GeomagneticInfo levelIntensity" + data.levelIntensity); - console.info("GeomagneticInfo totalIntensity" + data.totalIntensity); - }); -} catch (err) { - console.error('Get geomagneticInfo failed. Error code: ' + err.code + '; message: ' + err.message); + sensor.getGeomagneticInfo({ latitude: 80, longitude: 0, altitude: 0 }, 1580486400000, function (err, data) { + if (err) { + console.error(`Failed to get geomagneticInfo. Code: ${err.code}, message: ${err.message}`); + return; + } + console.info("Succeeded in getting geomagneticInfo x" + data.x); + console.info("Succeeded in getting geomagneticInfo y" + data.y); + console.info("Succeeded in getting geomagneticInfo z" + data.z); + console.info("Succeeded in getting geomagneticInfo geomagneticDip" + data.geomagneticDip); + console.info("Succeeded in getting geomagneticInfo deflectionAngle" + data.deflectionAngle); + console.info("Succeeded in getting geomagneticInfo levelIntensity" + data.levelIntensity); + console.info("Succeeded in getting geomagneticInfo totalIntensity" + data.totalIntensity); + }); +} catch (error) { + console.error(`Failed to get geomagneticInfo. Code: ${error.code}, message: ${error.message}`); } ``` @@ -2609,22 +2657,22 @@ getGeomagneticInfo(locationOptions: LocationOptions, timeMillis: number): Promis **示例:** -```js +```ts try { - const promise = sensor.getGeomagneticInfo({ latitude: 80, longitude: 0, altitude: 0 }, 1580486400000); - promise.then((data) => { - console.info("GeomagneticInfo x" + data.x); - console.info("GeomagneticInfo y" + data.y); - console.info("GeomagneticInfo z" + data.z); - console.info("GeomagneticInfo geomagneticDip" + data.geomagneticDip); - console.info("GeomagneticInfo deflectionAngle" + data.deflectionAngle); - console.info("GeomagneticInfo levelIntensity" + data.levelIntensity); - console.info("GeomagneticInfo totalIntensity" + data.totalIntensity); - }, (err)=>{ - console.error('Get geomagneticInfo failed. Error code: ' + err.code + '; message: ' + err.message); - }); -} catch (err) { - console.error('Get geomagneticInfo. Error code: ' + err.code + '; message: ' + err.message); + const promise = sensor.getGeomagneticInfo({ latitude: 80, longitude: 0, altitude: 0 }, 1580486400000); + promise.then((data) => { + console.info("Succeeded in getting geomagneticInfo x" + data.x); + console.info("Succeeded in getting geomagneticInfo y" + data.y); + console.info("Succeeded in getting geomagneticInfo z" + data.z); + console.info("Succeeded in getting geomagneticInfo geomagneticDip" + data.geomagneticDip); + console.info("Succeeded in getting geomagneticInfo deflectionAngle" + data.deflectionAngle); + console.info("Succeeded in getting geomagneticInfo levelIntensity" + data.levelIntensity); + console.info("Succeeded in getting geomagneticInfo totalIntensity" + data.totalIntensity); + }, (err) => { + console.error(`Failed to get geomagneticInfo. Code: ${err.code}, message: ${err.message}`); + }); +} catch (error) { + console.error(`Failed to get geomagneticInfo. Code: ${error.code}, message: ${error.message}`); } ``` @@ -2654,19 +2702,19 @@ getDeviceAltitude(seaPressure: number, currentPressure: number, callback: AsyncC **示例:** -```js +```ts try { - let seaPressure = 1013.2; - let currentPressure = 1500.0; - sensor.getDeviceAltitude(seaPressure, currentPressure, function (err, data) { - if (err) { - console.error('Get altitude failed. Error code: ' + err.code + '; message: ' + err.message); - return; - } - console.info('altitude: ' + data); - }); -} catch (err) { - console.error('Get altitude failed. Error code: ' + err.code + '; message: ' + err.message); + let seaPressure = 1013.2; + let currentPressure = 1500.0; + sensor.getDeviceAltitude(seaPressure, currentPressure, function (err, data) { + if (err) { + console.error(`Failed to get altitude. Code: ${err.code}, message: ${err.message}`); + return; + } + console.info('Succeeded in getting altitude: ' + data); + }); +} catch (error) { + console.error(`Failed to get altitude. Code: ${error.code}, message: ${error.message}`); } ``` @@ -2701,18 +2749,18 @@ getDeviceAltitude(seaPressure: number, currentPressure: number): Promise<numb **示例:** -```js +```ts try { - let seaPressure = 1013.2; - let currentPressure = 1500.0; - const promise = sensor.getDeviceAltitude(seaPressure, currentPressure); - promise.then((data) => { - console.info('sensor_getDeviceAltitude_Promise success', data); - }, (err) => { - console.error('Get altitude failed. Error code: ' + err.code + '; message: ' + err.message); - }); -} catch (err) { - console.error('Get altitude failed. Error code: ' + err.code + '; message: ' + err.message); + let seaPressure = 1013.2; + let currentPressure = 1500.0; + const promise = sensor.getDeviceAltitude(seaPressure, currentPressure); + promise.then((data) => { + console.info('Succeeded in getting sensor_getDeviceAltitude_Promise', data); + }, (err) => { + console.error(`Failed to get altitude. Code: ${err.code}, message: ${err.message}`); + }); +} catch (error) { + console.error(`Failed to get altitude. Code: ${error.code}, message: ${error.message}`); } ``` @@ -2741,23 +2789,23 @@ getInclination(inclinationMatrix: Array<number>, callback: AsyncCallback&l **示例:** -```js +```ts try { - // inclinationMatrix可以为3*3,或者4*4 - let inclinationMatrix = [ - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 - ] - sensor.getInclination(inclinationMatrix, function (err, data) { - if (err) { - console.error('Get inclination failed. Error code: ' + err.code + '; message: ' + err.message); - return; - } - console.info('Inclination: ' + data); - }) -} catch (err) { - console.error('Get inclination failed. Error code: ' + err.code + '; message: ' + err.message); + // inclinationMatrix可以为3*3,或者4*4 + let inclinationMatrix = [ + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + ] + sensor.getInclination(inclinationMatrix, function (err, data) { + if (err) { + console.error(`Failed to get inclination. Code: ${err.code}, message: ${err.message}`); + return; + } + console.info('Succeeded in getting inclination: ' + data); + }) +} catch (error) { + console.error(`Failed to get inclination. Code: ${error.code}, message: ${error.message}`); } ``` @@ -2791,22 +2839,22 @@ try { **示例:** -```js +```ts try { - // inclinationMatrix可以为3*3,或者4*4 - let inclinationMatrix = [ - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 - ] - const promise = sensor.getInclination(inclinationMatrix); - promise.then((data) => { - console.info('Inclination: ' + data); - }, (err) => { - console.error('Get inclination failed. Error code: ' + err.code + '; message: ' + err.message); - }); -} catch (err) { - console.error('Get inclination failed. Error code: ' + err.code + '; message: ' + err.message); + // inclinationMatrix可以为3*3,或者4*4 + let inclinationMatrix = [ + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + ] + const promise = sensor.getInclination(inclinationMatrix); + promise.then((data) => { + console.info('Succeeded in getting inclination: ' + data); + }, (err) => { + console.error(`Failed to get inclination. Code: ${err.code}, message: ${err.message}`); + }); +} catch (error) { + console.error(`Failed to get inclination. Code: ${error.code}, message: ${error.message}`); } ``` @@ -2837,33 +2885,33 @@ try { **示例:** -```js +```ts try { - // 旋转矩阵可以为3*3,或者4*4 - let currentRotationMatrix = [ - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 - ]; - let preRotationMatrix = [ - 1, 0, 0, - 0, 0.87, -0.50, - 0, 0.50, 0.87 - ]; - sensor.getAngleVariation(currentRotationMatrix, preRotationMatrix, function (err, data) { - if (err) { - console.error('Get angle variation failed. Error code: ' + err.code + '; message: ' + err.message); - return; - } - if (data.length < 3) { - console.error("Get angle variation failed, length" + data.length); - } - console.info("Z: " + data[0]); - console.info("X: " + data[1]); - console.info("Y : " + data[2]); - }) -} catch (err) { - console.error('Get angle variation failed. Error code: ' + err.code + '; message: ' + err.message); + // 旋转矩阵可以为3*3,或者4*4 + let currentRotationMatrix = [ + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + ]; + let preRotationMatrix = [ + 1, 0, 0, + 0, 0.87, -0.50, + 0, 0.50, 0.87 + ]; + sensor.getAngleVariation(currentRotationMatrix, preRotationMatrix, function (err, data) { + if (err) { + console.error(`Failed to get angle variation. Code: ${err.code}, message: ${err.message}`); + return; + } + if (data.length < 3) { + console.error("Failed to get angle variation, length" + data.length); + } + console.info("Z: " + data[0]); + console.info("X: " + data[1]); + console.info("Y : " + data[2]); + }) +} catch (error) { + console.error(`Failed to get angle variation. Code: ${error.code}, message: ${error.message}`); } ``` @@ -2898,32 +2946,32 @@ getAngleVariation(currentRotationMatrix: Array<number>, preRotationMatrix: **示例:** -```js +```ts try { - // 旋转矩阵可以为3*3,或者4*4 - let currentRotationMatrix = [ - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 - ]; - let preRotationMatrix = [ - 1, 0, 0, - 0, 0.87, -0.50, - 0, 0.50, 0.87 - ]; - const promise = sensor.getAngleVariation(currentRotationMatrix, preRotationMatrix); - promise.then((data) => { - if (data.length < 3) { - console.error("Get angle variation failed, length" + data.length); - } - console.info("Z: " + data[0]); - console.info("X: " + data[1]); - console.info("Y : " + data[2]); - }, (err) => { - console.error('Get angle variation failed. Error code: ' + err.code + '; message: ' + err.message); - }); -} catch (err) { - console.error('Get angle variation failed. Error code: ' + err.code + '; message: ' + err.message); + // 旋转矩阵可以为3*3,或者4*4 + let currentRotationMatrix = [ + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + ]; + let preRotationMatrix = [ + 1, 0, 0, + 0, 0.87, -0.50, + 0, 0.50, 0.87 + ]; + const promise = sensor.getAngleVariation(currentRotationMatrix, preRotationMatrix); + promise.then((data) => { + if (data.length < 3) { + console.error("Failed to get angle variation, length" + data.length); + } + console.info("Z: " + data[0]); + console.info("X: " + data[1]); + console.info("Y : " + data[2]); + }, (err) => { + console.error(`Failed to get angle variation. Code: ${err.code}, message: ${err.message}`); + }); +} catch (error) { + console.error(`Failed to get angle variation. Code: ${error.code}, message: ${error.message}`); } ``` @@ -2952,20 +3000,20 @@ getRotationMatrix(rotationVector: Array<number>, callback: AsyncCallback&l **示例:** -```js +```ts try { - let rotationVector = [0.20046076, 0.21907, 0.73978853, 0.60376877]; - sensor.getRotationMatrix(rotationVector, function (err, data) { - if (err) { - console.error('Get rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); - return; - } - for (var i = 0; i < data.length; i++) { - console.info('data[' + i + ']: ' + data[i]); - } - }) -} catch (err) { - console.error('Get rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); + let rotationVector = [0.20046076, 0.21907, 0.73978853, 0.60376877]; + sensor.getRotationMatrix(rotationVector, function (err, data) { + if (err) { + console.error(`Failed to get rotationMatrix. Code: ${err.code}, message: ${err.message}`); + return; + } + for (var i = 0; i < data.length; i++) { + console.info('Succeeded in getting data[' + i + ']: ' + data[i]); + } + }) +} catch (error) { + console.error(`Failed to get rotationMatrix. Code: ${error.code}, message: ${error.message}`); } ``` @@ -2999,19 +3047,19 @@ getRotationMatrix(rotationVector: Array<number>): Promise<Array<numb **示例:** -```js +```ts try { - let rotationVector = [0.20046076, 0.21907, 0.73978853, 0.60376877]; - const promise = sensor.getRotationMatrix(rotationVector); - promise.then((data) => { - for (var i = 0; i < data.length; i++) { - console.info('data[' + i + ']: ' + data[i]); - } - }, (err) => { - console.error('Get rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); - }); -} catch (err) { - console.error('Get rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); + let rotationVector = [0.20046076, 0.21907, 0.73978853, 0.60376877]; + const promise = sensor.getRotationMatrix(rotationVector); + promise.then((data) => { + for (var i = 0; i < data.length; i++) { + console.info('Succeeded in getting data[' + i + ']: ' + data[i]); + } + }, (err) => { + console.error(`Failed to get rotationMatrix. Code: ${err.code}, message: ${err.message}`); + }); +} catch (error) { + console.error(`Failed to get rotationMatrix. Code: ${error.code}, message: ${error.message}`); } ``` @@ -3042,24 +3090,24 @@ transformRotationMatrix(inRotationVector: Array<number>, coordinates: Coor **示例:** -```js +```ts try { - let rotationMatrix = [ - 1, 0, 0, - 0, 0.87, -0.50, - 0, 0.50, 0.87 - ]; - sensor.transformRotationMatrix(rotationMatrix, { x: 1, y: 3 }, function (err, data) { - if (err) { - console.error('Transform rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); - return; - } - for (var i = 0; i < data.length; i++) { - console.info('data[' + i + '] = ' + data[i]); - } - }) -} catch (err) { - console.error('Transform rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); + let rotationMatrix = [ + 1, 0, 0, + 0, 0.87, -0.50, + 0, 0.50, 0.87 + ]; + sensor.transformRotationMatrix(rotationMatrix, { x: 1, y: 3 }, function (err, data) { + if (err) { + console.error(`Failed to transform rotationMatrix. Code: ${err.code}, message: ${err.message}`); + return; + } + for (var i = 0; i < data.length; i++) { + console.info('Succeeded in getting data[' + i + '] = ' + data[i]); + } + }) +} catch (error) { + console.error(`Failed to transform rotationMatrix. Code: ${error.code}, message: ${error.message}`); } ``` @@ -3094,23 +3142,23 @@ transformRotationMatrix(inRotationVector: Array<number>, coordinates: Coor **示例:** -```js +```ts try { - let rotationMatrix = [ - 1, 0, 0, - 0, 0.87, -0.50, - 0, 0.50, 0.87 - ]; - const promise = sensor.transformRotationMatrix(rotationMatrix, { x: 1, y: 3 }); - promise.then((data) => { - for (var i = 0; i < data.length; i++) { - console.info('data[' + i + ']: ' + data[i]); - } - }, (err) => { - console.error('Transform rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); - }); -} catch (err) { - console.error('Transform rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); + let rotationMatrix = [ + 1, 0, 0, + 0, 0.87, -0.50, + 0, 0.50, 0.87 + ]; + const promise = sensor.transformRotationMatrix(rotationMatrix, { x: 1, y: 3 }); + promise.then((data) => { + for (var i = 0; i < data.length; i++) { + console.info('Succeeded in getting data[' + i + ']: ' + data[i]); + } + }, (err) => { + console.error(`Failed to transform rotationMatrix. Code: ${err.code}, message: ${err.message}`); + }); +} catch (error) { + console.error(`Failed to transform rotationMatrix. Code: ${error.code}, message: ${error.message}`); } ``` @@ -3139,20 +3187,20 @@ getQuaternion(rotationVector: Array<number>, callback: AsyncCallback<Ar **示例:** -```js +```ts try { - let rotationVector = [0.20046076, 0.21907, 0.73978853, 0.60376877]; - sensor.getQuaternion(rotationVector, function (err, data) { - if (err) { - console.error('Get quaternion failed. Error code: ' + err.code + '; message: ' + err.message); - return; - } - for (var i = 0; i < data.length; i++) { - console.info('data[' + i + ']: ' + data[i]); - } - }) -} catch (err) { - console.error('Get quaternion failed. Error code: ' + err.code + '; message: ' + err.message); + let rotationVector = [0.20046076, 0.21907, 0.73978853, 0.60376877]; + sensor.getQuaternion(rotationVector, function (err, data) { + if (err) { + console.error(`Failed to get quaternion. Code: ${err.code}, message: ${err.message}`); + return; + } + for (var i = 0; i < data.length; i++) { + console.info('Succeeded in getting data[' + i + ']: ' + data[i]); + } + }) +} catch (error) { + console.error(`Failed to get quaternion. Code: ${error.code}, message: ${error.message}`); } ``` @@ -3186,19 +3234,19 @@ getQuaternion(rotationVector: Array<number>): Promise<Array<number&g **示例:** -```js +```ts try { let rotationVector = [0.20046076, 0.21907, 0.73978853, 0.60376877]; const promise = sensor.getQuaternion(rotationVector); promise.then((data) => { for (var i = 0; i < data.length; i++) { - console.info('data[' + i + ']: ' + data[i]); + console.info('Succeeded in getting data[' + i + ']: ' + data[i]); } }, (err) => { - console.error('Get quaternion failed. Error code: ' + err.code + '; message: ' + err.message); + console.error(`Failed to get quaternion. Code: ${err.code}, message: ${err.message}`); }); -} catch (err) { - console.error('Get quaternion failed. Error code: ' + err.code + '; message: ' + err.message); +} catch (error) { + console.error(`Failed to get quaternion. Code: ${error.code}, message: ${error.message}`); } ``` @@ -3227,27 +3275,27 @@ getOrientation(rotationMatrix: Array<number>, callback: AsyncCallback<A **示例:** -```js +```ts try { - let preRotationMatrix = [ - 1, 0, 0, - 0, 0.87, -0.50, - 0, 0.50, 0.87 - ]; - sensor.getOrientation(preRotationMatrix, function (err, data) { - if (err) { - console.error('Get orientation failed. Error code: ' + err.code + '; message: ' + err.message); - return; - } - if (data.length < 3) { - console.error("Get orientation failed, length" + data.length); - } - console.info("Z: " + data[0]); - console.info("X: " + data[1]); - console.info("Y : " + data[2]); - }) -} catch (err) { - console.error('Get orientation failed. Error code: ' + err.code + '; message: ' + err.message); + let preRotationMatrix = [ + 1, 0, 0, + 0, 0.87, -0.50, + 0, 0.50, 0.87 + ]; + sensor.getOrientation(preRotationMatrix, function (err, data) { + if (err) { + console.error(`Failed to get orientation. Code: ${err.code}, message: ${err.message}`); + return; + } + if (data.length < 3) { + console.error("Failed to get orientation, length" + data.length); + } + console.info("Succeeded in getting data. Z: " + data[0]); + console.info("Succeeded in getting data. X: " + data[1]); + console.info("Succeeded in getting data. Y: " + data[2]); + }) +} catch (error) { + console.error(`Failed to get orientation. Code: ${error.code}, message: ${error.message}`); } ``` @@ -3281,23 +3329,23 @@ getOrientation(rotationMatrix: Array<number>): Promise<Array<number& **示例:** -```js +```ts try { - let preRotationMatrix = [ - 1, 0, 0, - 0, 0.87, -0.50, - 0, 0.50, 0.87 - ]; - const promise = sensor.getOrientation(preRotationMatrix); - promise.then((data) => { - for (var i = 0; i < data.length; i++) { - console.info('data[' + i + ']: ' + data[i]); - } - }, (err) => { - console.error('getOrientation failed. Error code: ' + err.code + '; message: ' + err.message); - }); -} catch (err) { - console.error('getOrientation failed. Error code: ' + err.code + '; message: ' + err.message); + let preRotationMatrix = [ + 1, 0, 0, + 0, 0.87, -0.50, + 0, 0.50, 0.87 + ]; + const promise = sensor.getOrientation(preRotationMatrix); + promise.then((data) => { + for (var i = 0; i < data.length; i++) { + console.info('Succeeded in getting data[' + i + ']: ' + data[i]); + } + }, (err) => { + console.error(`Failed to getOrientatin. Code: ${err.code}, message: ${err.message}`); + }); +} catch (error) { + console.error(`Failed to getOrientatin Code: ${error.code}, message: ${error.message}`); } ``` @@ -3327,19 +3375,19 @@ getRotationMatrix(gravity: Array<number>, geomagnetic: Array<number> **示例:** -```js +```ts try { - let gravity = [-0.27775216, 0.5351276, 9.788099]; - let geomagnetic = [210.87253, -78.6096, -111.44444]; - sensor.getRotationMatrix(gravity, geomagnetic, function (err, data) { - if (err) { - console.error('Get rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); - return; - } - console.info('RotationMatrix' + JSON.stringify(data)); - }) -} catch (err) { - console.error('Get rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); + let gravity = [-0.27775216, 0.5351276, 9.788099]; + let geomagnetic = [210.87253, -78.6096, -111.44444]; + sensor.getRotationMatrix(gravity, geomagnetic, function (err, data) { + if (err) { + console.error(`Failed to get rotationMatrix. Code: ${err.code}, message: ${err.message}`); + return; + } + console.info('Succeeded in getting rotationMatrix' + JSON.stringify(data)); + }) +} catch (error) { +、 console.error(`Failed to get rotationMatrix. Code: ${error.code}, message: ${error.message}`); } ``` @@ -3374,18 +3422,18 @@ getRotationMatrix(gravity: Array<number>, geomagnetic: Array<number> **示例:** -```js +```ts try { - let gravity = [-0.27775216, 0.5351276, 9.788099]; - let geomagnetic = [210.87253, -78.6096, -111.44444]; - const promise = sensor.getRotationMatrix(gravity, geomagnetic); - promise.then((data) => { - console.info('RotationMatrix' + JSON.stringify(data)); - }, (err) => { - console.error('Get rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); - }); -} catch (err) { - console.error('Get rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); + let gravity = [-0.27775216, 0.5351276, 9.788099]; + let geomagnetic = [210.87253, -78.6096, -111.44444]; + const promise = sensor.getRotationMatrix(gravity, geomagnetic); + promise.then((data) => { + console.info('Succeeded in getting rotationMatrix' + JSON.stringify(data)); + }, (err) => { + console.error(`Failed to get rotationMatrix. Code: ${err.code}, message: ${err.message}`); + }); +} catch (error) { + console.error(`Failed to get rotationMatrix. Code: ${error.code}, message: ${error.message}`); } ``` @@ -3413,19 +3461,19 @@ getSensorList(callback: AsyncCallback<Array<Sensor>>): void **示例:** -```js +```ts try { - sensor.getSensorList((err, data) => { - if (err) { - console.error('Get sensorList failed. Error code: ' + err.code + '; message: ' + err.message); - return; - } - for (var i = 0; i < data.length; i++) { - console.info('data[' + i + ']: ' + JSON.stringify(data[i])); - } - }); -} catch (err) { - console.error('Get sensorList failed. Error code: ' + err.code + '; message: ' + err.message); + sensor.getSensorList((err, data) => { + if (err) { + console.error(`Failed to get sensorList. Code: ${err.code}, message: ${err.message}`); + return; + } + for (var i = 0; i < data.length; i++) { + console.info('Succeeded in getting data[' + i + ']: ' + JSON.stringify(data[i])); + } + }); +} catch (error) { + console.error(`Failed to get sensorList. Code: ${error.code}, message: ${error.message}`); } ``` @@ -3453,17 +3501,17 @@ try { **示例:** -```js +```ts try { - sensor.getSensorList().then((data) => { - for (var i = 0; i < data.length; i++) { - console.info('data[' + i + ']: ' + JSON.stringify(data[i])); - } - }, (err) => { - console.error('Get sensorList failed. Error code: ' + err.code + '; message: ' + err.message); - }); -} catch (err) { - console.error('Get sensorList failed. Error code: ' + err.code + '; message: ' + err.message); + sensor.getSensorList().then((data) => { + for (var i = 0; i < data.length; i++) { + console.info('Succeeded in getting data[' + i + ']: ' + JSON.stringify(data[i])); + } + }, (err) => { + console.error(`Failed to get sensorList. Code: ${err.code}, message: ${err.message}`); + }); +} catch (error) { + console.error(`Failed to get sensorList. Code: ${error.code}, message: ${error.message}`); } ``` @@ -3492,17 +3540,17 @@ getSingleSensor(type: SensorId, callback: AsyncCallback<Sensor>): void **示例:** -```js +```ts try { - sensor.getSingleSensor(sensor.SensorId.ACCELEROMETER, (err, data) => { - if (err) { - console.error('Get singleSensor failed. Error code: ' + err.code + '; message: ' + err.message); - return; - } - console.info('Sensor: ' + JSON.stringify(data)); - }); -} catch (err) { - console.error('Get singleSensor failed. Error code: ' + err.code + '; message: ' + err.message); + sensor.getSingleSensor(sensor.SensorId.ACCELEROMETER, (err, data) => { + if (err) { + console.error(`Failed to get singleSensor. Code: ${err.code}, message: ${err.message}`); + return; + } + console.info('Succeeded in getting sensor: ' + JSON.stringify(data)); + }); +} catch (error) { + console.error(`Failed to get singleSensor. Code: ${error.code}, message: ${error.message}`); } ``` @@ -3536,15 +3584,15 @@ try { **示例:** -```js +```ts try { - sensor.getSingleSensor(sensor.SensorId.ACCELEROMETER).then((data) => { - console.info('Sensor: ' + JSON.stringify(data)); - }, (err) => { - console.error('Get singleSensor failed. Error code: ' + err.code + '; message: ' + err.message); - }); -} catch (err) { - console.error('Get singleSensor failed. Error code: ' + err.code + '; message: ' + err.message); + sensor.getSingleSensor(sensor.SensorId.ACCELEROMETER).then((data) => { + console.info('Succeeded in getting sensor: ' + JSON.stringify(data)); + }, (err) => { + console.error(`Failed to get singleSensor . Code: ${err.code}, message: ${err.message}`); + }); +} catch (error) { + console.error(`Failed to get singleSensor . Code: ${error.code}, message: ${error.message}`); } ``` @@ -4033,15 +4081,15 @@ on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: Callback<Acceler **示例:** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }, - {interval: 100000000} - ); - ``` +```ts +sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function (data) { + console.info('Succeeded in invoking on. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking on. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking on. Z-coordinate component: ' + data.z); +}, + { interval: 100000000 } +); +``` ### LINEAR_ACCELERATION(deprecated) @@ -4084,18 +4132,19 @@ on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback: Callback | options | [Options](#options) | 否 | 可选参数列表,用于设置传感器上报频率,默认值为200000000ns。 | **示例:** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); - }, - {interval: 100000000} - ); - ``` + +```ts +sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, function (data) { + console.info('Succeeded in invoking on. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking on. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking on. Z-coordinate component: ' + data.z); + console.info('Succeeded in invoking on. X-coordinate bias: ' + data.biasX); + console.info('Succeeded in invoking on. Y-coordinate bias: ' + data.biasY); + console.info('Succeeded in invoking on. Z-coordinate bias: ' + data.biasZ); +}, + { interval: 100000000 } +); +``` ### GRAVITY(deprecated) @@ -4117,15 +4166,15 @@ on(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: Callback<GravityRespons **示例:** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }, - {interval: 100000000} - ); - ``` +```ts +sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, function (data) { + console.info('Succeeded in invoking on. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking on. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking on. Z-coordinate component: ' + data.z); +}, + { interval: 100000000 } +); +``` ### GYROSCOPE(deprecated) @@ -4148,15 +4197,16 @@ on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: Callback<GyroscopeRes | options | [Options](#options) | 否 | 可选参数列表,用于设置传感器上报频率,默认值为200000000ns。 | **示例:** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }, - {interval: 100000000} - ); - ``` + +```ts +sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, function (data) { + console.info('Succeeded in invoking on. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking on. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking on. Z-coordinate component: ' + data.z); +}, + { interval: 100000000 } +); +``` ### GYROSCOPE_UNCALIBRATED(deprecated) @@ -4179,18 +4229,19 @@ on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback:Callback<G | options | [Options](#options) | 否 | 可选参数列表,用于设置传感器上报频率,默认值为200000000ns。 | **示例:** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); - }, - {interval: 100000000} - ); - ``` + +```ts +sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, function (data) { + console.info('Succeeded in invoking on. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking on. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking on. Z-coordinate component: ' + data.z); + console.info('Succeeded in invoking on. X-coordinate bias: ' + data.biasX); + console.info('Succeeded in invoking on. Y-coordinate bias: ' + data.biasY); + console.info('Succeeded in invoking on. Z-coordinate bias: ' + data.biasZ); +}, + { interval: 100000000 } +); +``` ### SIGNIFICANT_MOTION(deprecated) @@ -4211,13 +4262,14 @@ on(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback: Callback<Sig | options | [Options](#options) | 否 | 可选参数列表,用于设置传感器上报频率,默认值为200000000ns。 | **示例:** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,function(data){ - console.info('Scalar data: ' + data.scalar); - }, - {interval: 100000000} - ); - ``` + +```ts +sensor.on(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, function (data) { + console.info('Succeeded in invoking on. Scalar data: ' + data.scalar); +}, + { interval: 100000000 } +); +``` ### PEDOMETER_DETECTION(deprecated) @@ -4240,13 +4292,14 @@ on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback: Callback<Pe | options | [Options](#options) | 否 | 可选参数列表,用于设置传感器上报频率,默认值为200000000ns。 | **示例:** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,function(data){ - console.info('Scalar data: ' + data.scalar); - }, - {interval: 100000000} - ); - ``` + +```ts +sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, function (data) { + console.info('Succeeded in invoking on. Scalar data: ' + data.scalar); +}, + { interval: 100000000 } +); +``` ### PEDOMETER(deprecated) @@ -4269,13 +4322,14 @@ on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: Callback<PedometerRes | options | [Options](#options) | 否 | 可选参数列表,用于设置传感器上报频率,默认值为200000000ns。 | **示例:** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER,function(data){ - console.info('Steps: ' + data.steps); - }, - {interval: 100000000} - ); - ``` + +```ts +sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, function (data) { + console.info('Succeeded in invoking on. Steps: ' + data.steps); +}, + { interval: 100000000 } +); +``` ### AMBIENT_TEMPERATURE(deprecated) @@ -4297,13 +4351,13 @@ on(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback:Callback<Ambi **示例:** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,function(data){ - console.info('Temperature: ' + data.temperature); - }, - {interval: 100000000} - ); - ``` +```ts +sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, function (data) { + console.info('Succeeded in invoking on. Temperature: ' + data.temperature); +}, + { interval: 100000000 } +); +``` ### MAGNETIC_FIELD(deprecated) @@ -4325,15 +4379,15 @@ on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: Callback<Magneti **示例:** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }, - {interval: 100000000} - ); - ``` +```ts +sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, function (data) { + console.info('Succeeded in invoking on. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking on. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking on. Z-coordinate component: ' + data.z); +}, + { interval: 100000000 } +); +``` ### MAGNETIC_FIELD_UNCALIBRATED(deprecated) @@ -4354,18 +4408,19 @@ on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback: Callbac | options | [Options](#options) | 否 | 可选参数列表,用于设置传感器上报频率,默认值为200000000ns。 | **示例:** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); - }, - {interval: 100000000} - ); - ``` + +```ts +sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, function (data) { + console.info('Succeeded in invoking on. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking on. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking on. Z-coordinate component: ' + data.z); + console.info('Succeeded in invoking on. X-coordinate bias: ' + data.biasX); + console.info('Succeeded in invoking on. Y-coordinate bias: ' + data.biasY); + console.info('Succeeded in invoking on. Z-coordinate bias: ' + data.biasZ); +}, + { interval: 100000000 } +); +``` ### PROXIMITY(deprecated) @@ -4386,13 +4441,14 @@ on(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: Callback<ProximityRes | options | [Options](#options) | 否 | 可选参数列表,用于设置传感器上报频率,默认值为200000000ns。 | **示例:** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY,function(data){ - console.info('Distance: ' + data.distance); - }, - {interval: 100000000} - ); - ``` + +```ts +sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, function (data) { + console.info('Succeeded in invoking on. Distance: ' + data.distance); +}, + { interval: 100000000 } +); +``` ### HUMIDITY(deprecated) @@ -4414,13 +4470,13 @@ on(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: Callback<HumidityRespo **示例:** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY,function(data){ - console.info('Humidity: ' + data.humidity); - }, - {interval: 100000000} - ); - ``` +```ts +sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, function (data) { + console.info('Succeeded in invoking on. Humidity: ' + data.humidity); +}, + { interval: 100000000 } +); +``` ### BAROMETER(deprecated) @@ -4442,13 +4498,13 @@ on(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: Callback<BarometerRes **示例:** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER,function(data){ - console.info('Atmospheric pressure: ' + data.pressure); - }, - {interval: 100000000} - ); - ``` +```ts +sensor.on(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, function (data) { + console.info('Succeeded in invoking on. Atmospheric pressure: ' + data.pressure); +}, + { interval: 100000000 } +); +``` ### HALL(deprecated) @@ -4469,13 +4525,14 @@ on(type: SensorType.SENSOR_TYPE_ID_HALL, callback: Callback<HallResponse>, | options | [Options](#options) | 否 | 可选参数列表,用于设置传感器上报频率,默认值为200000000ns。 | **示例:** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HALL,function(data){ - console.info('Status: ' + data.status); - }, - {interval: 100000000} - ); - ``` + +```ts +sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HALL, function (data) { + console.info('Succeeded in invoking on. Status: ' + data.status); +}, + { interval: 100000000 } +); +``` ### AMBIENT_LIGHT(deprecated) @@ -4497,13 +4554,13 @@ on(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: Callback<LightRes **示例:** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT,function(data){ - console.info(' Illumination: ' + data.intensity); - }, - {interval: 100000000} - ); - ``` +```ts +sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, function (data) { + console.info('Succeeded in invoking on. Illumination: ' + data.intensity); +}, + { interval: 100000000 } +); +``` ### ORIENTATION(deprecated) @@ -4524,15 +4581,16 @@ on(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: Callback<Orientatio | options | [Options](#options) | 否 | 可选参数列表,用于设置传感器上报频率,默认值为200000000ns。 | **示例:** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION,function(data){ - console.info('The device rotates at an angle around the X axis: ' + data.beta); - console.info('The device rotates at an angle around the Y axis: ' + data.gamma); - console.info('The device rotates at an angle around the Z axis: ' + data.alpha); - }, - {interval: 100000000} - ); - ``` + +```ts +sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, function (data) { + console.info('Succeeded in the device rotating at an angle around the X axis: ' + data.beta); + console.info('Succeeded in the device rotating at an angle around the Y axis: ' + data.gamma); + console.info('Succeeded in the device rotating at an angle around the Z axis: ' + data.alpha); +}, + { interval: 100000000 } +); +``` ### HEART_RATE(deprecated) @@ -4573,16 +4631,17 @@ on(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,callback: Callback<Rotatio | options | [Options](#options) | 否 | 可选参数列表,用于设置传感器上报频率,默认值为200000000ns。 | **示例:** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('Scalar quantity: ' + data.w); - }, - {interval: 100000000} - ); - ``` + +```ts +sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, function (data) { + console.info('Succeeded in invoking on. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking on. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking on. Z-coordinate component: ' + data.z); + console.info('Succeeded in invoking on. Scalar quantity: ' + data.w); +}, + { interval: 100000000 } +); +``` ### WEAR_DETECTION(deprecated) @@ -4603,13 +4662,14 @@ on(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: Callback<WearDet | options | [Options](#options) | 否 | 可选参数列表,用于设置传感器上报频率,默认值为200000000ns。 | **示例:** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION,function(data){ - console.info('Wear status: ' + data.value); - }, - {interval: 100000000} - ); - ``` + +```ts +sensor.on(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, function (data) { + console.info('Succeeded in invoking on. Wear status: ' + data.value); +}, + { interval: 100000000 } +); +``` ## sensor.once(deprecated) @@ -4633,14 +4693,14 @@ once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: Callback<Accele | callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | 是 | 注册一次加速度传感器的回调函数,上报的数据类型为AccelerometerResponse。 | **示例:** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - ); - ``` + +```ts +sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function (data) { + console.info('Succeeded in invoking once. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking once. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking once. Z-coordinate component: ' + data.z); +}); +``` ### LINEAR_ACCELERATION(deprecated) @@ -4681,17 +4741,17 @@ once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback: Callba | callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | 是 | 注册一次未校准加速度传感器的回调函数,上报的数据类型为AccelerometerUncalibratedResponse。 | **示例:** - ``` - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); - } - ); - ``` + +```ts +sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, function (data) { + console.info('Succeeded in invoking once. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking once. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking once. Z-coordinate component: ' + data.z); + console.info('Succeeded in invoking once. X-coordinate bias: ' + data.biasX); + console.info('Succeeded in invoking once. Y-coordinate bias: ' + data.biasY); + console.info('Succeeded in invoking once. Z-coordinate bias: ' + data.biasZ); +}); +``` ### GRAVITY(deprecated) @@ -4711,14 +4771,14 @@ once(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: Callback<GravityRespo | callback | Callback<[GravityResponse](#gravityresponse)> | 是 | 注册一次重力传感器的回调函数,上报的数据类型为GravityResponse。 | **示例:** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - ); - ``` + +```ts +sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, function (data) { + console.info('Succeeded in invoking once. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking once. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking once. Z-coordinate component: ' + data.z); + }); +``` ### GYROSCOPE(deprecated) @@ -4740,14 +4800,14 @@ once(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: Callback<GyroscopeR | callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | 是 | 注册一次陀螺仪传感器的回调函数,上报的数据类型为GyroscopeResponse。 | **示例:** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - ); - ``` + +```ts +sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, function (data) { + console.info('Succeeded in invoking once. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking once. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking once. Z-coordinate component: ' + data.z); +}); +``` ### GYROSCOPE_UNCALIBRATED(deprecated) @@ -4769,17 +4829,16 @@ once(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback: Callback&l | callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | 是 | 注册一次未校准陀螺仪传感器的回调函数,上报的数据类型为GyroscopeUncalibratedResponse。 | **示例:** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); - } - ); - ``` +```ts +sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, function(data) { + console.info('Succeeded in invoking once. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking once. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking once. Z-coordinate component: ' + data.z); + console.info('Succeeded in invoking once. X-coordinate bias: ' + data.biasX); + console.info('Succeeded in invoking once. Y-coordinate bias: ' + data.biasY); + console.info('Succeeded in invoking once. Z-coordinate bias: ' + data.biasZ); +}); +``` ### SIGNIFICANT_MOTION(deprecated) @@ -4799,12 +4858,12 @@ once(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,callback: Callback<Si | callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | 是 | 注册一次有效运动传感器的回调函数,上报的数据类型为SignificantMotionResponse。 | **示例:** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, function(data) { - console.info('Scalar data: ' + data.scalar); - } - ); - ``` + +```ts +sensor.once(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, function (data) { + console.info('Succeeded in invoking once. Scalar data: ' + data.scalar); +}); +``` ### PEDOMETER_DETECTION(deprecated) @@ -4826,12 +4885,12 @@ once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,callback: Callback<P | callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | 是 | 注册一次计步检测传感器的回调函数,上报的数据类型为PedometerDetectionResponse。 | **示例:** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, function(data) { - console.info('Scalar data: ' + data.scalar); - } - ); - ``` + +```ts +sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, function (data) { + console.info('Succeeded in invoking once. Scalar data: ' + data.scalar); +}); +``` ### PEDOMETER(deprecated) @@ -4853,12 +4912,12 @@ once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: Callback<PedometerR | callback | Callback<[PedometerResponse](#pedometerresponse)> | 是 | 注册一次计步传感器的回调函数,上报的数据类型为PedometerResponse。 | **示例:** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, function(data) { - console.info('Steps: ' + data.steps); - } - ); - ``` + +```ts +sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, function (data) { + console.info('Succeeded in invoking once. Steps: ' + data.steps); +}); +``` ### AMBIENT_TEMPERATURE(deprecated) @@ -4878,12 +4937,12 @@ once(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback: Callback<A | callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | 是 | 注册一次环境温度传感器的回调函数,上报的数据类型为AmbientTemperatureResponse。 | **示例:** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, function(data) { - console.info('Temperature: ' + data.temperature); - } - ); - ``` + +```ts +sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, function (data) { + console.info('Succeeded in invoking once. Temperature: ' + data.temperature); +}); +``` ### MAGNETIC_FIELD(deprecated) @@ -4903,14 +4962,14 @@ once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: Callback<Magne | callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | 是 | 注册一次磁场传感器的回调函数,上报的数据类型为MagneticFieldResponse。 | **示例:** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - ); - ``` + +```ts +sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, function (data) { + console.info('Succeeded in invoking once. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking once. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking once. Z-coordinate component: ' + data.z); +}); +``` ### MAGNETIC_FIELD_UNCALIBRATED(deprecated) @@ -4930,17 +4989,17 @@ once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback: Callb | callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | 是 | 注册一次未校准磁场传感器的回调函数,上报的数据类型为MagneticFieldUncalibratedResponse。 | **示例:** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); - } - ); - ``` + +```ts +sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, function (data) { + console.info('Succeeded in invoking once. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking once. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking once. Z-coordinate component: ' + data.z); + console.info('Succeeded in invoking once. X-coordinate bias: ' + data.biasX); + console.info('Succeeded in invoking once. Y-coordinate bias: ' + data.biasY); + console.info('Succeeded in invoking once. Z-coordinate bias: ' + data.biasZ); +}); +``` ### PROXIMITY(deprecated) @@ -4960,12 +5019,13 @@ once(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: Callback<ProximityR | callback | Callback<[ProximityResponse](#proximityresponse)> | 是 | 注册一次接近光传感器的回调函数,上报的数据类型为ProximityResponse。 | **示例:** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, function(data) { - console.info('Distance: ' + data.distance); - } - ); - ``` + +```ts +sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, function (data) { + console.info('Succeeded in invoking once. Distance: ' + data.distance); +} +); +``` ### HUMIDITY(deprecated) @@ -4985,12 +5045,12 @@ once(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: Callback<HumidityRes | callback | Callback<[HumidityResponse](#humidityresponse)> | 是 | 注册一次湿度传感器的回调函数,上报的数据类型为HumidityResponse。 | **示例:** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, function(data) { - console.info('Humidity: ' + data.humidity); - } - ); - ``` + +```ts +sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, function (data) { + console.info('Succeeded in invoking once. Humidity: ' + data.humidity); +}); +``` ### BAROMETER(deprecated) @@ -5010,12 +5070,12 @@ once(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: Callback<BarometerR | callback | Callback<[BarometerResponse](#barometerresponse)> | 是 | 注册一次气压计传感器的回调函数,上报的数据类型为BarometerResponse。 | **示例:** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, function(data) { - console.info('Atmospheric pressure: ' + data.pressure); - } - ); - ``` + +```ts +sensor.once(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, function (data) { + console.info('Succeeded in invoking once. Atmospheric pressure: ' + data.pressure); +}); +``` ### HALL(deprecated) @@ -5035,12 +5095,12 @@ once(type: SensorType.SENSOR_TYPE_ID_HALL, callback: Callback<HallResponse> | callback | Callback<[HallResponse](#hallresponse)> | 是 | 注册一次霍尔传感器的回调函数,上报的数据类型为HallResponse。 | **示例:** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HALL, function(data) { - console.info('Status: ' + data.status); - } - ); - ``` + +```ts +sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HALL, function (data) { + console.info('Succeeded in invoking once. Status: ' + data.status); +}); +``` ### AMBIENT_LIGHT(deprecated) @@ -5061,12 +5121,11 @@ once(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: Callback<LightR **示例:** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, function(data) { - console.info(' Illumination: ' + data.intensity); - } - ); - ``` +```ts +sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, function (data) { + console.info('Succeeded in invoking once. invoking once. Illumination: ' + data.intensity); +}); +``` ### ORIENTATION(deprecated) @@ -5086,14 +5145,14 @@ once(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: Callback<Orientat | callback | Callback<[OrientationResponse](#orientationresponse)> | 是 | 注册一次方向传感器的回调函数,上报的数据类型为OrientationResponse。 | **示例:** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, function(data) { - console.info('The device rotates at an angle around the X axis: ' + data.beta); - console.info('The device rotates at an angle around the Y axis: ' + data.gamma); - console.info('The device rotates at an angle around the Z axis: ' + data.alpha); - } - ); - ``` + +```ts +sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, function (data) { + console.info('Succeeded in invoking the device rotateing at an angle around the X axis: ' + data.beta); + console.info('Succeeded in invoking the device rotateing at an angle around the Y axis: ' + data.gamma); + console.info('Succeeded in invoking the device rotateing at an angle around the Z axis: ' + data.alpha); +}); +``` ### ROTATION_VECTOR(deprecated) @@ -5113,15 +5172,15 @@ once(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback: Callback<Rota | callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | 是 | 注册一次旋转矢量传感器的回调函数,上报的数据类型为RotationVectorResponse。 | **示例:** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('Scalar quantity: ' + data.w); - } - ); - ``` + +```ts +sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, function (data) { + console.info('Succeeded in invoking once. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking once. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking once. Z-coordinate component: ' + data.z); + console.info('Succeeded in invoking once. Scalar quantity: ' + data.w); +}); +``` ### HEART_RATE(deprecated) @@ -5160,12 +5219,11 @@ once(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: Callback<WearD | callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | 是 | 注册一次穿戴检测传感器的回调函数,上报的数据类型为WearDetectionResponse。 | **示例:** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, function(data) { - console.info("Wear status: "+ data.value); - } - ); - ``` +```ts +sensor.once(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, function (data) { + console.info("Succeeded in invoking once. Wear status: " + data.value); +}); +``` ## sensor.off(deprecated) @@ -5190,12 +5248,13 @@ off(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback?: Callback<Accele **示例:** -```js +```ts function callback(data) { - console.info('x-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); + console.info('Succeeded in invoking off. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking off. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking off. Z-coordinate component: ' + data.z); } + sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback); ``` @@ -5220,15 +5279,16 @@ off(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, callback?: Callb **示例:** -```js +```ts function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); + console.info('Succeeded in invoking off. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking off. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking off. Z-coordinate component: ' + data.z); + console.info('Succeeded in invoking off. X-coordinate bias: ' + data.biasX); + console.info('Succeeded in invoking off. Y-coordinate bias: ' + data.biasY); + console.info('Succeeded in invoking off. Z-coordinate bias: ' + data.biasZ); } + sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, callback); ``` @@ -5251,10 +5311,11 @@ off(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback?: Callback<LightR **示例:** -```js +```ts function callback(data) { - console.info(' Illumination: ' + data.intensity); + console.info('Succeeded in invoking off. Illumination: ' + data.intensity); } + sensor.off(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback); ``` @@ -5277,10 +5338,11 @@ off(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, callback?: Callback< **示例:** -```js +```ts function callback(data) { - console.info('Temperature: ' + data.temperature); + console.info('Succeeded in invoking off. Temperature: ' + data.temperature); } + sensor.off(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, callback); ``` @@ -5303,10 +5365,11 @@ off(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback?: Callback<BarometerR **示例:** -```js +```ts function callback(data) { - console.info('Atmospheric pressure: ' + data.pressure); + console.info('Succeeded in invoking off. Atmospheric pressure: ' + data.pressure); } + sensor.off(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, callback); ``` @@ -5329,13 +5392,14 @@ off(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback?: Callback<GravityRespo **示例:** -```js +```ts function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); + console.info('Succeeded in invoking off. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking off. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking off. Z-coordinate component: ' + data.z); } -sensor.off( sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, callback); + +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, callback); ``` ### GYROSCOPE(deprecated) @@ -5359,12 +5423,13 @@ off(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback?: Callback<GyroscopeR **示例:** -```js +```ts function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); + console.info('Succeeded in invoking off. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking off. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking off. Z-coordinate component: ' + data.z); } + sensor.off(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback); ``` @@ -5389,12 +5454,13 @@ off(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, callback?: Callback& **示例:** -```js +```ts function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); + console.info('Succeeded in invoking off. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking off. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking off. Z-coordinate component: ' + data.z); } + sensor.off(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, callback); ``` @@ -5417,10 +5483,11 @@ off(type: SensorType.SENSOR_TYPE_ID_HALL, callback?: Callback<HallResponse> **示例:** -```js +```ts function callback(data) { - console.info('Status: ' + data.status); + console.info('Succeeded in invoking off. Status: ' + data.status); } + sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HALL, callback); ``` @@ -5462,10 +5529,11 @@ off(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback?: Callback<HumidityRes **示例:** -```js +```ts function callback(data) { - console.info('Humidity: ' + data.humidity); + console.info('Succeeded in invoking off. Humidity: ' + data.humidity); } + sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, callback); ``` @@ -5507,12 +5575,13 @@ off(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, callback?: Callback< **示例:** -```js +```ts function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); + console.info('Succeeded in invoking off. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking off. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking off. Z-coordinate component: ' + data.z); } + sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback); ``` @@ -5535,15 +5604,16 @@ sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback); **示例:** -```js +```ts function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); + console.info('Succeeded in invoking off. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking off. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking off. Z-coordinate component: ' + data.z); + console.info('Succeeded in invoking off. X-coordinate bias: ' + data.biasX); + console.info('Succeeded in invoking off. Y-coordinate bias: ' + data.biasY); + console.info('Succeeded in invoking off. Z-coordinate bias: ' + data.biasZ); } + sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, callback); ``` @@ -5566,12 +5636,13 @@ sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, callbac **示例:** -```js +```ts function callback(data) { - console.info('The device rotates at an angle around the X axis: ' + data.beta); - console.info('The device rotates at an angle around the Y axis: ' + data.gamma); - console.info('The device rotates at an angle around the Z axis: ' + data.alpha); + console.info('Succeeded in invoking off. The device rotates at an angle around the X axis: ' + data.beta); + console.info('Succeeded in invoking off. The device rotates at an angle around the Y axis: ' + data.gamma); + console.info('Succeeded in invoking off. The device rotates at an angle around the Z axis: ' + data.alpha); } + sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, callback); ``` @@ -5596,10 +5667,11 @@ off(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback?: Callback<PedometerR **示例:** -```js +```ts function callback(data) { - console.info('Steps: ' + data.steps); + console.info('Succeeded in invoking off. Steps: ' + data.steps); } + sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, callback); ``` @@ -5624,10 +5696,11 @@ off(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback?: Callback< **示例:** -```js +```ts function callback(data) { - console.info('Scalar data: ' + data.scalar); + console.info('Succeeded in invoking off. Scalar data: ' + data.scalar); } + sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback); ``` @@ -5650,10 +5723,11 @@ off(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback?: Callback<ProximityR **示例:** -```js +```ts function callback(data) { - console.info('Distance: ' + data.distance); + console.info('Succeeded in invoking off. Distance: ' + data.distance); } + sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, callback); ``` @@ -5676,13 +5750,14 @@ off(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback?: Callback<Rota **示例:** -```js +```ts function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('Scalar quantity: ' + data.w); + console.info('Succeeded in invoking off. X-coordinate component: ' + data.x); + console.info('Succeeded in invoking off. Y-coordinate component: ' + data.y); + console.info('Succeeded in invoking off. Z-coordinate component: ' + data.z); + console.info('Succeeded in invoking off. Scalar quantity: ' + data.w); } + sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback); ``` @@ -5705,10 +5780,11 @@ off(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback?: Callback<S **示例:** -```js +```ts function callback(data) { - console.info('Scalar data: ' + data.scalar); + console.info('Succeeded in invoking off. Scalar data: ' + data.scalar); } + sensor.off(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback); ``` @@ -5731,10 +5807,11 @@ off(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback?: Callback<WearD **示例:** -```js +```ts function accCallback(data) { - console.info('Wear status: ' + data.value); + console.info('Succeeded in invoking off. Wear status: ' + data.value); } + sensor.off(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, accCallback); ``` @@ -5758,17 +5835,17 @@ transformCoordinateSystem(inRotationVector: Array<number>, coordinates: Co **示例:** -```js -sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}, function(err, data) { - if (err) { - console.error("Operation failed. Error code: " + err.code + ", message: " + err.message); - return; - } - console.info("Operation succeeded. Data obtained: " + data); - for (var i=0; i < data.length; i++) { - console.info("transformCoordinateSystem data[ " + i + "] = " + data[i]); - } - }) +```ts +sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], { x: 2, y: 3 }, function (err, data) { + if (err) { + console.error(`Failed to operate. Code: ${err.code}, message: ${err.message}`); + return; + } + console.info("Succeeded in starting Operation. Data obtained: " + data); + for (var i = 0; i < data.length; i++) { + console.info("Succeeded in getting transformCoordinateSystem data[ " + i + "] = " + data[i]); + } +}) ``` ## sensor.transformCoordinateSystem(deprecated) @@ -5795,15 +5872,15 @@ transformCoordinateSystem(inRotationVector: Array<number>, coordinates: Co **示例:** -```js -const promise = sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}); - promise.then((data) => { - console.info("Operation succeeded."); - for (var i=0; i < data.length; i++) { - console.info("transformCoordinateSystem data[ " + i + "] = " + data[i]); - } - }).catch((err) => { - console.info("Operation failed"); +```ts +const promise = sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], { x: 2, y: 3 }); +promise.then((data) => { + console.info("Succeeded in starting Operation"); + for (var i = 0; i < data.length; i++) { + console.info("Succeeded in getting transformCoordinateSystem data[ " + i + "] = " + data[i]); + } +}).catch((err) => { + console.error(`Failed to operate.`); }) ``` @@ -5826,15 +5903,16 @@ getGeomagneticField(locationOptions: LocationOptions, timeMillis: number, callba | callback | AsyncCallback<[GeomagneticResponse](#geomagneticresponse)> | 是 | 返回磁场信息。 | **示例:** -```js -sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000, function(err, data) { - if (err) { - console.error('Operation failed. Error code: ' + err.code + '; message: ' + err.message); - return; - } - console.info('sensor_getGeomagneticField_callback x: ' + data.x + ',y: ' + data.y + ',z: ' + - data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + - ',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity); + +```ts +sensor.getGeomagneticField({ latitude: 80, longitude: 0, altitude: 0 }, 1580486400000, function (err, data) { + if (err) { + console.error(`Failed to operate. Code: ${err.code}, message: ${err.message}`); + return; + } + console.info('Succeeded in getting sensor_getGeomagneticField_callback x: ' + data.x + ',y: ' + data.y + ',z: ' + + data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + + ',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity); }); ``` ## sensor.getGeomagneticField(deprecated) @@ -5860,16 +5938,17 @@ getGeomagneticField(locationOptions: LocationOptions, timeMillis: number): Promi | Promise<[GeomagneticResponse](#geomagneticresponse)> | 返回磁场信息。 | **示例:** - ```js - const promise = sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000); - promise.then((data) => { - console.info('sensor_getGeomagneticField_promise x: ' + data.x + ',y: ' + data.y + ',z: ' + - data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + - ',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity); - }).catch((reason) => { - console.info('Operation failed.'); - }) - ``` + +```ts +const promise = sensor.getGeomagneticField({ latitude: 80, longitude: 0, altitude: 0 }, 1580486400000); +promise.then((data) => { + console.info('Succeeded in getting sensor_getGeomagneticField_promise x: ' + data.x + ',y: ' + data.y + ',z: ' + + data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + + ',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity); +}).catch((reason) => { + console.error(`Failed to operate.`); +}) +``` ## sensor.getAltitude(deprecated) @@ -5891,16 +5970,15 @@ getAltitude(seaPressure: number, currentPressure: number, callback: AsyncCallbac **示例:** - ```js - sensor.getAltitude(0, 200, function(err, data) { - if (err) { - console.error( - "Operation failed. Error code: " + err.code + ", message: " + err.message); - return; - } - console.info("Succeeded to get getAltitude interface get data: " + data); - }); - ``` +```ts +sensor.getAltitude(0, 200, function (err, data) { + if (err) { + console.error(`Failed to operate. Code: ${err.code}, message: ${err.message}`); + return; + } + console.info("Succeeded in getting getAltitude interface get data: " + data); +}); +``` ## sensor.getAltitude(deprecated) @@ -5927,14 +6005,14 @@ getAltitude(seaPressure: number, currentPressure: number): Promise<number> **示例:** - ```js - const promise = sensor.getAltitude(0, 200); - promise.then((data) => { - console.info(' sensor_getAltitude_Promise success', data); - }).catch((err) => { - console.error("Operation failed"); - }) - ``` +```ts +const promise = sensor.getAltitude(0, 200); +promise.then((data) => { + console.info('Succeeded in getting sensor_getAltitude_Promise success', data); +}).catch((err) => { + console.error(`Failed to operate.`); +}) +``` ## sensor.getGeomagneticDip(deprecated) @@ -5956,16 +6034,15 @@ getGeomagneticDip(inclinationMatrix: Array<number>, callback: AsyncCallbac **示例:** - ```js - sensor.getGeomagneticDip([1, 0, 0, 0, 1, 0, 0, 0, 1], function(err, data) { - if (err) { - console.error('SensorJsAPI--->Failed to register data, error code is:' + err.code + ', message: ' + - err.message); - return; - } - console.info("Succeeded to get getGeomagneticDip interface get data: " + data); - }) - ``` +```ts +sensor.getGeomagneticDip([1, 0, 0, 0, 1, 0, 0, 0, 1], function (err, data) { + if (err) { + console.error(`Failed to register data. Code: ${err.code}, message: ${err.message}`); + return; + } + console.info("Succeeded in getting getGeomagneticDip interface get data: " + data); +}) +``` ## sensor.getGeomagneticDip(deprecated) @@ -5991,14 +6068,14 @@ getGeomagneticDip(inclinationMatrix: Array<number>): Promise<number> **示例:** - ```js - const promise = sensor.getGeomagneticDip([1, 0, 0, 0, 1, 0, 0, 0, 1]); - promise.then((data) => { - console.info('getGeomagneticDip_promise succeeded', data); - }).catch((err) => { - console.error("Operation failed"); - }) - ``` +```ts +const promise = sensor.getGeomagneticDip([1, 0, 0, 0, 1, 0, 0, 0, 1]); +promise.then((data) => { + console.info('Succeeded in get GeomagneticDip_promise', data); +}).catch((err) => { + console.error(`Failed to operate.`); +}) +``` ## sensor. getAngleModify(deprecated) @@ -6020,19 +6097,17 @@ getAngleModify(currentRotationMatrix: Array<number>, preRotationMatrix: Ar **示例:** - ```js - sensor. getAngleModify([1,0,0,0,1,0,0,0,1], [1, 0, 0, 0, 0.87, -0.50, 0, 0.50, 0.87], function(err, data) { - if (err) { - console.error('Failed to register data, error code is: ' + err.code + ', message: ' + - err.message); - return; - } - for (var i=0; i < data.length; i++) { - console.info("data[" + i + "]: " + data[i]); - } - }) - ``` - +```ts +sensor.getAngleModify([1, 0, 0, 0, 1, 0, 0, 0, 1], [1, 0, 0, 0, 0.87, -0.50, 0, 0.50, 0.87], function (err, data) { + if (err) { + console.error(`Failed to register data. Code: ${err.code}, message: ${err.message}`); + return; + } + for (var i = 0; i < data.length; i++) { + console.info("data[" + i + "]: " + data[i]); + } +}) +``` ## sensor. getAngleModify(deprecated) @@ -6059,18 +6134,17 @@ getAngleModify(currentRotationMatrix: Array<number>, preRotationMatrix: Ar **示例:** - ```js - const promise = sensor.getAngleModify([1,0,0,0,1,0,0,0,1], [1,0,0,0,0.87,-0.50,0,0.50,0.87]); - promise.then((data) => { - console.info('getAngleModify_promise success'); - for (var i=0; i < data.length; i++) { - console.info("data[" + i + "]: " + data[i]); - } - }).catch((reason) => { - console.info("promise::catch", reason); - }) - ``` - +```ts +const promise = sensor.getAngleModify([1, 0, 0, 0, 1, 0, 0, 0, 1], [1, 0, 0, 0, 0.87, -0.50, 0, 0.50, 0.87]); +promise.then((data) => { + console.info('Succeeded in getting AngleModify_promise.'); + for (var i = 0; i < data.length; i++) { + console.info("Succeeded in getting data[" + i + "]: " + data[i]); + } +}).catch((reason) => { + console.info("Succeeded in getting promise::catch", reason); +}) +``` ## sensor.createRotationMatrix(deprecated) @@ -6091,19 +6165,17 @@ createRotationMatrix(rotationVector: Array<number>, callback: AsyncCallbac **示例:** - ```js - sensor.createRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877], function(err, data) { - if (err) { - console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + - err.message); - return; - } - for (var i=0; i < data.length; i++) { - console.info("data[" + i + "]: " + data[i]); - } - }) - ``` - +```ts +sensor.createRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877], function (err, data) { + if (err) { + console.error(`Failed to register data. Code: ${err.code}, message: ${err.message}`); + return; + } + for (var i = 0; i < data.length; i++) { + console.info("Succeeded in getting data[" + i + "]: " + data[i]); + } +}) +``` ## sensor.createRotationMatrix(deprecated) @@ -6129,18 +6201,17 @@ createRotationMatrix(rotationVector: Array<number>): Promise<Array<n **示例:** - ```js - const promise = sensor.createRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877]); - promise.then((data) => { - console.info('createRotationMatrix_promise success'); - for (var i=0; i < data.length; i++) { - console.info("data[" + i + "]: " + data[i]); - } - }).catch((reason) => { - console.info("promise::catch", reason); - }) - ``` - + ```ts +const promise = sensor.createRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877]); +promise.then((data) => { + console.info('Succeeded in getting createRotationMatrix_promise'); + for (var i = 0; i < data.length; i++) { + console.info("data[" + i + "]: " + data[i]); + } +}).catch((reason) => { + console.info("Succeeded in getting promise::catch", reason); +}) +``` ## sensor.createQuaternion(deprecated) @@ -6161,19 +6232,17 @@ createQuaternion(rotationVector: Array<number>, callback: AsyncCallback< **示例:** - ```js - sensor.createQuaternion([0.20046076, 0.21907, 0.73978853, 0.60376877], function(err, data) { - if (err) { - console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + - err.message); - return; - } - for (var i=0; i < data.length; i++) { - console.info("data[" + i + "]: " + data[i]); - } - }) - ``` - +```ts +sensor.createQuaternion([0.20046076, 0.21907, 0.73978853, 0.60376877], function (err, data) { + if (err) { + console.error(`Failed to register data. Code: ${err.code}, message: ${err.message}`); + return; + } + for (var i = 0; i < data.length; i++) { + console.info("Succeeded in getting data[" + i + "]: " + data[i]); + } +}) +``` ## sensor.createQuaternion(deprecated) @@ -6199,18 +6268,17 @@ createQuaternion(rotationVector: Array<number>): Promise<Array<numbe **示例:** - ```js - const promise = sensor.createQuaternion([0.20046076, 0.21907, 0.73978853, 0.60376877]); - promise.then((data) => { - console.info('createQuaternion_promise succeeded'); - for (var i=0; i < data.length; i++) { - console.info("data[" + i + "]: " + data[i]); - } - }).catch((err) => { - console.info('promise failed'); - }) - ``` - +```ts +const promise = sensor.createQuaternion([0.20046076, 0.21907, 0.73978853, 0.60376877]); +promise.then((data) => { + console.info('Succeeded in getting createQuaternion_promise'); + for (var i = 0; i < data.length; i++) { + console.info("data[" + i + "]: " + data[i]); + } +}).catch((err) => { + console.info(`Failed to get promise.`); +}) +``` ## sensor.getDirection(deprecated) @@ -6231,20 +6299,18 @@ getDirection(rotationMatrix: Array<number>, callback: AsyncCallback<Arr **示例:** - ```js - sensor.getDirection([1, 0, 0, 0, 1, 0, 0, 0, 1], function(err, data) { - if (err) { - console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + - err.message); - return; - } - console.info("SensorJsAPI--->Succeeded to get getDirection interface get data: " + data); - for (var i = 1; i < data.length; i++) { - console.info("sensor_getDirection_callback" + data[i]); - } - }) - ``` - +```ts +sensor.getDirection([1, 0, 0, 0, 1, 0, 0, 0, 1], function (err, data) { + if (err) { + console.error(`Failed to register data. Code: ${err.code}, message: ${err.message}`); + return; + } + console.info("Succeeded in getting getDirection interface get data: " + data); + for (var i = 1; i < data.length; i++) { + console.info("Succeeded in getting sensor_getDirection_callback" + data[i]); + } +}) +``` ## sensor.getDirection(deprecated) @@ -6270,18 +6336,17 @@ getDirection(rotationMatrix: Array<number>): Promise<Array<number> **示例:** - ```js - const promise = sensor.getDirection([1, 0, 0, 0, 1, 0, 0, 0, 1]); - promise.then((data) => { - console.info('sensor_getAltitude_Promise success', data); - for (var i = 1; i < data.length; i++) { - console.info("sensor_getDirection_promise" + data[i]); - } - }).catch((err) => { - console.info('promise failed'); - }) - ``` - +```ts +const promise = sensor.getDirection([1, 0, 0, 0, 1, 0, 0, 0, 1]); +promise.then((data) => { + console.info('Succeeded in getting sensor_getAltitude_Promise', data); + for (var i = 1; i < data.length; i++) { + console.info("Succeeded in getting sensor_getDirection_promise" + data[i]); + } +}).catch((err) => { + console.info(`Failed to get promise.`); +}) +``` ## sensor.createRotationMatrix(deprecated) @@ -6303,16 +6368,15 @@ createRotationMatrix(gravity: Array<number>, geomagnetic: Array<number& **示例:** - ```js - sensor.createRotationMatrix([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444], function(err, data) { - if (err) { - console.error('error code is: ' + err.code + ', message: ' + err.message); - return; - } - console.info(JSON.stringify(data)); - }) - ``` - +```ts +sensor.createRotationMatrix([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444], function (err, data) { + if (err) { + console.error(`Failed to get create rotationMatrix. Code: ${err.code}, message: ${err.message}`); + return; + } + console.info(JSON.stringify(data)); +}) +``` ## sensor.createRotationMatrix(deprecated) @@ -6339,11 +6403,11 @@ createRotationMatrix(gravity: Array<number>, geomagnetic: Array<number& **示例:** - ```js - const promise = sensor.createRotationMatrix([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444]); - promise.then((data) => { - console.info(JSON.stringify(data)); - }).catch((err) => { - console.info('promise failed'); - }) - ``` +```ts +const promise = sensor.createRotationMatrix([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444]); +promise.then((data) => { + console.info(JSON.stringify(data)); +}).catch((err) => { + console.info(`Failed to get promise.`); +}) + ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-sim.md b/zh-cn/application-dev/reference/apis/js-apis-sim.md index f10afd47feb61ea8e116c59e97894a5c5b038eef..0ef2ad336dfcf391440b70dd7a8fa532c88acb08 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-sim.md +++ b/zh-cn/application-dev/reference/apis/js-apis-sim.md @@ -615,7 +615,7 @@ hasSimCard\(slotId: number, callback: AsyncCallback\\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------- | ---- | -------------------------------------- | | slotId | number | 是 | 卡槽ID。
- 0:卡槽1
- 1:卡槽2 | -| callback | AsyncCallback<boolean> | 是 | 回调函数。 | +| callback | AsyncCallback<boolean> | 是 | 回调返回指定卡槽是否插卡,如果插卡返回true。 | **错误码:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-socket.md b/zh-cn/application-dev/reference/apis/js-apis-socket.md index b6246b1be4dd2a945b332889a738d1648b28fb41..1dfd23745f6702e3563e74ac23dee3574e0b6540 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-socket.md +++ b/zh-cn/application-dev/reference/apis/js-apis-socket.md @@ -2398,7 +2398,7 @@ on(type: 'close', callback: Callback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------- | ---- | ----------------------------------- | | type | string | 是 | 订阅的事件类型。'close':关闭事件。 | -| callback | Callback\ | 否 | 回调函数。 | +| callback | Callback\ | 是 | 回调函数。 | **错误码:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-sensor.md b/zh-cn/application-dev/reference/apis/js-apis-system-sensor.md index 0c3b61ce72600829427bfeb8bb17e58d03813eac..cd5336f77bd2790f53e8901d2745cd2e423ba3a1 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-sensor.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-sensor.md @@ -37,16 +37,16 @@ import sensor from '@system.sensor'; **示例:** -```js +```ts sensor.subscribeAccelerometer({ interval: 'normal', - success: function(ret) { - console.log('X-axis data: ' + ret.x); - console.log('Y-axis data: ' + ret.y); - console.log('Z-axis data: ' + ret.z); + success: function (ret) { + console.info('Succeeded in subscribing. X-axis data: ' + ret.x); + console.info('Succeeded in subscribing. Y-axis data: ' + ret.y); + console.info('Succeeded in subscribing. Z-axis data: ' + ret.z); }, - fail: function(data, code) { - console.error('Subscription failed. Code: ' + code + '; Data: ' + data); + fail: function (data, code) { + console.error(`Failed to subscription. Code: ${code}, data: ${data}`); }, }); ``` @@ -66,7 +66,7 @@ unsubscribeAccelerometer(): void **示例:** -```js +```ts sensor.unsubscribeAccelerometer(); ``` @@ -86,13 +86,13 @@ sensor.unsubscribeAccelerometer(); **示例:** -```js +```ts sensor.subscribeCompass({ - success: function(ret) { - console.log('Get data direction:' + ret.direction); + success: function (ret) { + console.info('Succeeded in subscribing. Get data direction:' + ret.direction); }, - fail: function(data, code) { - console.error('Subscription failed. Code: ' + code + '; Data: ' + data); + fail: function (data, code) { + console.error(`Failed to subscription. Code: ${code}, data: ${data}`); }, }); ``` @@ -110,7 +110,7 @@ unsubscribeCompass(): void **示例:** -```js +```ts sensor.unsubscribeCompass(); ``` @@ -130,13 +130,14 @@ sensor.unsubscribeCompass(); **示例:** -```js +```ts sensor.subscribeProximity({ - success: function(ret) { - console.log('Get data distance:' + ret.distance); + success: function (ret) { + console.info('Succeeded in subscribing. Get data distance:' + ret.distance); }, - fail: function(data, code) { - console.error('Subscription failed. Code: ' + code + '; Data: ' + data); + fail: function (data, code) { + console.error(`Failed to subscription. Code: ${code}, data: ${data}`); + }, }); ``` @@ -154,7 +155,7 @@ unsubscribeProximity(): void **示例:** -```js +```ts sensor.unsubscribeProximity(); ``` @@ -174,13 +175,13 @@ sensor.unsubscribeProximity(); **示例:** -```js +```ts sensor.subscribeLight({ - success: function(ret) { - console.log('Get data intensity:' + ret.intensity); + success: function (ret) { + console.info('Succeeded in subscribing. Get data intensity:' + ret.intensity); }, - fail: function(data, code) { - console.error('Subscription failed. Code: ' + code + '; Data: ' + data); + fail: function (data, code) { + console.error(`Failed to subscription. Code: ${code}, data: ${data}`); }, }); ``` @@ -198,7 +199,7 @@ unsubscribeLight(): void **示例:** -```js +```ts sensor.unsubscribeLight(); ``` @@ -220,13 +221,13 @@ sensor.unsubscribeLight(); **示例:** -```js +```ts sensor.subscribeStepCounter({ - success: function(ret) { - console.log('Get step value:' + ret.steps); + success: function (ret) { + console.info('Succeeded in subscribing. Get step value:' + ret.steps); }, - fail: function(data, code) { - console.log('Subscription failed. Code: ' + code + '; Data: ' + data); + fail: function (data, code) { + console.error(`Failed to subscription. Code: ${code}, data: ${data}`); }, }); ``` @@ -246,7 +247,7 @@ unsubscribeStepCounter(): void **示例:** -```js +```ts sensor.unsubscribeStepCounter(); ``` @@ -267,13 +268,13 @@ subscribeBarometer(options: SubscribeBarometerOptions): void **示例:** -```js +```ts sensor.subscribeBarometer({ - success: function(ret) { - console.log('Get data value:' + ret.pressure); + success: function (ret) { + console.info('Succeeded in subscribing. Get data value:' + ret.pressure); }, - fail: function(data, code) { - console.log('Subscription failed. Code: ' + code + '; Data: ' + data); + fail: function (data, code) { + console.error(`Failed to subscription. Code: ${code}, data: ${data}`); }, }); ``` @@ -292,7 +293,7 @@ unsubscribeBarometer(): void **示例:** -```js +```ts sensor.unsubscribeBarometer(); ``` @@ -315,13 +316,13 @@ sensor.unsubscribeBarometer(); **示例:** -```js +```ts sensor.subscribeHeartRate({ - success: function(ret) { - console.log('Get heartrate value:' + ret.heartRate); + success: function (ret) { + console.info('Succeeded in subscribing. Get heartrate value:' + ret.heartRate); }, - fail: function(data, code) { - console.log('Subscription failed. Code: ' + code + '; Data: ' + data); + fail: function (data, code) { + console.error(`Failed to subscription. Code: ${code}, data: ${data}`); }, }); ``` @@ -342,7 +343,7 @@ unsubscribeHeartRate(): void **示例:** -```js +```ts sensor.unsubscribeHeartRate(); ``` @@ -362,13 +363,13 @@ sensor.unsubscribeHeartRate(); **示例:** -```js +```ts sensor.subscribeOnBodyState({ - success: function(ret) { - console.log('Get on-body state value:' + ret.value); + success: function (ret) { + console.info('Succeeded in subscribing. Get on-body state value:' + ret.value); }, - fail: function(data, code) { - console.log('Subscription failed. Code: ' + code + '; Data: ' + data); + fail: function (data, code) { + console.error(`Failed to subscription. Code: ${code}, data: ${data}`); }, }); ``` @@ -386,7 +387,7 @@ unsubscribeOnBodyState(): void **示例:** -```js +```ts sensor.unsubscribeOnBodyState(); ``` @@ -406,13 +407,13 @@ sensor.unsubscribeOnBodyState(); **示例:** -```js +```ts sensor.getOnBodyState({ - success: function(ret) { - console.log('On body state: ' + ret.value); + success: function (ret) { + console.info('Succeeded in subscribing. On body state: ' + ret.value); }, - fail: function(data, code) { - console.log('Subscription failed. Code: ' + code + '; Data: ' + data); + fail: function (data, code) { + console.error(`Failed to subscription. Code: ${code}, data: ${data}`); }, }); ``` @@ -435,17 +436,17 @@ sensor.getOnBodyState({ **示例:** -```js +```ts sensor.subscribeDeviceOrientation({ interval: 'normal', - success: function(ret) { - console.log('Alpha data: ' + ret.alpha); - console.log('Beta data: ' + ret.beta); - console.log('Gamma data: ' + ret.gamma); + success: function (ret) { + console.info('Succeeded in subscribing. Alpha data: ' + ret.alpha); + console.info('Succeeded in subscribing. Beta data: ' + ret.beta); + console.info('Succeeded in subscribing. Gamma data: ' + ret.gamma); }, - fail: function(data, code) { - console.error('Subscription failed. Code: ' + code + '; Data: ' + data); - } + fail: function (data, code) { + console.error(`Failed to subscription. Code: ${code}, data: ${data}`); + } }); ``` @@ -462,7 +463,7 @@ unsubscribeDeviceOrientation(): void **示例:** -```js +```ts sensor.unsubscribeDeviceOrientation(); ``` @@ -486,16 +487,16 @@ sensor.unsubscribeDeviceOrientation(); **示例:** -```js +```ts sensor.subscribeGyroscope({ interval: 'normal', - success: function(ret) { - console.log('X-axis data: ' + ret.x); - console.log('Y-axis data: ' + ret.y); - console.log('Z-axis data: ' + ret.z); + success: function (ret) { + console.info('Succeeded in subscribing. X-axis data: ' + ret.x); + console.info('Succeeded in subscribing. Y-axis data: ' + ret.y); + console.info('Succeeded in subscribing. Z-axis data: ' + ret.z); }, - fail: function(data, code) { - console.error('Subscription failed. Code: ' + code + '; data: ' + data); + fail: function (data, code) { + console.error(`Failed to subscription. Code: ${code}, data: ${data}`); } }); ``` @@ -515,7 +516,7 @@ unsubscribeGyroscope(): void **示例:** -```js +```ts sensor.unsubscribeGyroscope(); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-vibrate.md b/zh-cn/application-dev/reference/apis/js-apis-system-vibrate.md index 8de455db2a3f0c8399b5142e3b61bab695a4fcb9..6eced16953a0283befe2206102d05316cf2703f8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-vibrate.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-vibrate.md @@ -36,17 +36,17 @@ import vibrator from '@system.vibrator'; **示例:** -```js +```ts vibrator.vibrate({ mode: 'short', success: function() { - console.log('vibrate is successful'); + console.info('Succeed in vibrating'); }, fail: function(data, code) { - console.log("vibrate is failed, data: " + data + ", code: " + code); + console.info(`Failed to vibrate. Data: ${data}, code: ${code}`); }, complete: function() { - console.log('vibrate is completed'); + console.info('completed in vibrating'); } }); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-treemap.md b/zh-cn/application-dev/reference/apis/js-apis-treemap.md index b30d57cf7c47c0377aa5c7f8dfcedd89acd05bb4..439e6c1d006929a558b1becb2ff8591cf2161282 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-treemap.md +++ b/zh-cn/application-dev/reference/apis/js-apis-treemap.md @@ -4,7 +4,7 @@ TreeMap可用于存储具有关联关系的key-value键值对集合,存储元 TreeMap底层使用红黑树实现,可以利用二叉树特性快速查找键值对。key值有序存储,可以实现快速的插入和删除。 -TreeMap和[HashMap](js-apis-treemap.md)相比,HashMap依据键的hashCode存取数据,访问速度较快。而TreeMap是有序存取,效率较低。 +TreeMap和[HashMap](js-apis-hashmap.md)相比,HashMap依据键的hashCode存取数据,访问速度较快。而TreeMap是有序存取,效率较低。 **推荐使用场景:** 一般需要存储有序键值对的场景,可以使用TreeMap。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-util.md b/zh-cn/application-dev/reference/apis/js-apis-util.md index d826373bee42cfb60371833d3d941f56a6e828b6..78007e98fd55b345a82a8d766a4063930097284b 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-util.md +++ b/zh-cn/application-dev/reference/apis/js-apis-util.md @@ -2080,7 +2080,7 @@ let result = that.encodeSync(array); ### encodeToStringSync9+ -encodeToStringSync(src: Uint8Array): string +encodeToStringSync(src: Uint8Array, options?: Type): string 通过输入参数编码后输出对应文本。 @@ -2091,6 +2091,7 @@ encodeToStringSync(src: Uint8Array): string | 参数名 | 类型 | 必填 | 说明 | | ------ | ---------- | ---- | ------------------- | | src | Uint8Array | 是 | 编码输入Uint8数组。 | +| options10+ | [Type](#type10) | 否 | 从API version 10开始支持该参数,表示对应的编码格式。
此参数可选,可选值为:util.Type.BASIC和util.Type.MIME,默认值为:util.Type.BASIC。
- 当参数取值为util.Type.BASIC时,输出结果包含:64个可打印字符,包括大写字母A-Z、小写字母a-z、数字0-9共62个字符,再加上另外2个'+'和'/',没有回车符、换行符。
- 当参数取值为util.Type.MIME时,输出结果包含:64个可打印字符,包括大写字母A-Z、小写字母a-z、数字0-9共62个字符,再加上另外2个'+'和'/',编码输出每一行不超过76个字符,而且每行以'\r\n'符结束。| **返回值:** @@ -2102,14 +2103,14 @@ encodeToStringSync(src: Uint8Array): string ```js let that = new util.Base64Helper(); -let array = new Uint8Array([115,49,51]); -let result = that.encodeToStringSync(array); +let array = new Uint8Array([77,97,110,105,115,100,105,115,116,105,110,103,117,105,115,104,101,100,110,111,116,111,110,108,121,98,121,104,105,115,114,101,97,115,111,110,98,117,116,98,121,116,104,105,115,115,105,110,103,117,108,97,114,112,97,115,115,105,111,110,102,114,111,109,111,116,104,101,114,97,110,105,109,97,108,115,119,104,105,99,104,105,115,97,108,117,115,116,111,102,116,104,101,109,105,110,100,101,120,99,101,101,100,115,116,104,101,115,104,111,114,116,118,101,104,101,109,101,110,99,101,111,102,97,110,121,99,97,114,110,97,108,112,108,101,97,115,117,114,101]); +let result = that.encodeToStringSync(array, util.Type.MIME); ``` ### decodeSync9+ -decodeSync(src: Uint8Array | string): Uint8Array +decodeSync(src: Uint8Array | string, options?: Type): Uint8Array 通过输入参数解码后输出对应文本。 @@ -2120,6 +2121,7 @@ decodeSync(src: Uint8Array | string): Uint8Array | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------------------------ | ---- | ----------------------------- | | src | Uint8Array \| string | 是 | 解码输入Uint8数组或者字符串。 | +| options10+ | [Type](#type10) | 否 | 从API version 10开始支持该参数,表示对应的编码格式。
此参数可选,可选值为:util.Type.BASIC和util.Type.MIME,默认值为:util.Type.BASIC。
- 当参数取值为util.Type.BASIC时,表示入参包含:64个可打印字符,包括大写字母A-Z、小写字母a-z、数字0-9共62个字符,再加上另外2个'+'和'/',没有回车符、换行符。
- 当参数取值为util.Type.MIME时,表示入参包含:64个可打印字符,包括大写字母A-Z、小写字母a-z、数字0-9共62个字符,再加上另外2个'+'和'/',每一行不超过76个字符,而且每行以'\r\n'符结束。 | **返回值:** @@ -2131,8 +2133,8 @@ decodeSync(src: Uint8Array | string): Uint8Array ```js let that = new util.Base64Helper(); -let buff = 'czEz'; -let result = that.decodeSync(buff); +let buff = 'TWFuaXNkaXN0aW5ndWlzaGVkbm90b25seWJ5aGlzcmVhc29uYnV0Ynl0aGlzc2luZ3VsYXJwYXNz\r\naW9uZnJvbW90aGVyYW5pbWFsc3doaWNoaXNhbHVzdG9mdGhlbWluZGV4Y2VlZHN0aGVzaG9ydHZl\r\naGVtZW5jZW9mYW55Y2FybmFscGxlYXN1cmU=\r\n'; +let result = that.decodeSync(buff, util.Type.MIME); ``` @@ -2172,7 +2174,7 @@ that.encode(array).then(val=>{ ### encodeToString9+ -encodeToString(src: Uint8Array): Promise<string> +encodeToString(src: Uint8Array, options?: Type): Promise<string> 通过输入参数异步编码后输出对应文本。 @@ -2183,6 +2185,7 @@ encodeToString(src: Uint8Array): Promise<string> | 参数名 | 类型 | 必填 | 说明 | | ------ | ---------- | ---- | ----------------------- | | src | Uint8Array | 是 | 异步编码输入Uint8数组。 | +| options10+ | [Type](#type10) | 否 | 从API version 10开始支持该参数,表示对应的编码格式。
此参数可选,可选值为:util.Type.BASIC和util.Type.MIME,默认值为:util.Type.BASIC。
- 当参数取值为util.Type.BASIC时,输出结果包含:64个可打印字符,包括大写字母A-Z、小写字母a-z、数字0-9共62个字符,再加上另外2个'+'和'/',没有回车符、换行符。
- 当参数取值为util.Type.MIME时,输出结果包含:64个可打印字符,包括大写字母A-Z、小写字母a-z、数字0-9共62个字符,再加上另外2个'+'和'/',编码输出每一行不超过76个字符,而且每行以'\r\n'符结束。 | **返回值:** @@ -2194,16 +2197,16 @@ encodeToString(src: Uint8Array): Promise<string> ```js let that = new util.Base64Helper(); -let array = new Uint8Array([115,49,51]); -that.encodeToString(array).then(val=>{ - console.log(val) +let array = new Uint8Array([77,97,110,105,115,100,105,115,116,105,110,103,117,105,115,104,101,100,110,111,116,111,110,108,121,98,121,104,105,115,114,101,97,115,111,110,98,117,116,98,121,116,104,105,115,115,105,110,103,117,108,97,114,112,97,115,115,105,111,110,102,114,111,109,111,116,104,101,114,97,110,105,109,97,108,115,119,104,105,99,104,105,115,97,108,117,115,116,111,102,116,104,101,109,105,110,100,101,120,99,101,101,100,115,116,104,101,115,104,111,114,116,118,101,104,101,109,101,110,99,101,111,102,97,110,121,99,97,114,110,97,108,112,108,101,97,115,117,114,101]); +that.encodeToString(array, util.Type.MIME).then(val=>{ + // 根据开发者需求进行添加。 }) ``` ### decode9+ -decode(src: Uint8Array | string): Promise<Uint8Array> +decode(src: Uint8Array | string, options?: Type): Promise<Uint8Array> 通过输入参数异步解码后输出对应文本。 @@ -2214,6 +2217,7 @@ decode(src: Uint8Array | string): Promise<Uint8Array> | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------------------------ | ---- | --------------------------------- | | src | Uint8Array \| string | 是 | 异步解码输入Uint8数组或者字符串。 | +| options10+ | [Type](#type10) | 否 | 从API version 10开始支持该参数,表示对应的编码格式。
此参数可选,可选值为:util.Type.BASIC和util.Type.MIME,默认值为:util.Type.BASIC。
- 当参数取值为util.Type.BASIC时,表示入参包含:64个可打印字符,包括大写字母A-Z、小写字母a-z、数字0-9共62个字符,再加上另外2个'+'和'/',没有回车符、换行符。
- 当参数取值为util.Type.MIME时,表示入参包含:64个可打印字符,包括大写字母A-Z、小写字母a-z、数字0-9共62个字符,再加上另外2个'+'和'/',每一行不超过76个字符,而且每行以'\r\n'符结束。 | **返回值:** @@ -2225,15 +2229,25 @@ decode(src: Uint8Array | string): Promise<Uint8Array> ```js let that = new util.Base64Helper(); -let array = new Uint8Array([99,122,69,122]); -let rarray = new Uint8Array([115,49,51]); -that.decode(array).then(val=>{ - for (var i = 0; i < rarray.length; i++) { - console.log(val[i].toString()) - } +let array = 'TWFuaXNkaXN0aW5ndWlzaGVkbm90b25seWJ5aGlzcmVhc29uYnV0Ynl0aGlzc2luZ3VsYXJwYXNz\r\naW9uZnJvbW90aGVyYW5pbWFsc3doaWNoaXNhbHVzdG9mdGhlbWluZGV4Y2VlZHN0aGVzaG9ydHZl\r\naGVtZW5jZW9mYW55Y2FybmFscGxlYXN1cmU=\r\n'; +that.decode(array, util.Type.MIME).then(val=>{ + // 根据开发者需求进行添加。 }) ``` + +## Type10+ + +Base64编码格式枚举。 + +**系统能力:** SystemCapability.Utils.Lang + +| 名称 | 值 | 说明 | +| -------- | ------------------------ | ---------------- | +| BASIC | 0 | 表示BASIC编码格式 | +| MIME | 1 | 表示MIME编码格式。 | + + ## types8+ types为不同类型的内置对象提供类型检查,可以避免由于类型错误导致的异常或崩溃。该模块包含了多个工具函数,用于判断JS对象是否属于各种类型例如:ArrayBuffer、Map、Set等。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-vibrator.md b/zh-cn/application-dev/reference/apis/js-apis-vibrator.md index 77315d4d3b2f19f03481d67a5fa665035335eec8..4b07abbbc692bfff851eab2f465e1bbc425ac726 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-vibrator.md +++ b/zh-cn/application-dev/reference/apis/js-apis-vibrator.md @@ -9,7 +9,7 @@ vibrator模块提供控制马达振动启、停的能力。 ## 导入模块 -```js +```ts import vibrator from '@ohos.vibrator'; ``` @@ -41,24 +41,25 @@ startVibration(effect: VibrateEffect, attribute: VibrateAttribute, callback: Asy 示例: -```js +```ts import vibrator from '@ohos.vibrator'; + try { - vibrator.startVibration({ - type: 'time', - duration: 1000, - }, { - id: 0, - usage: 'alarm' - }, (error) => { - if (error) { - console.error('Vibrate fail, error.code: ' + error.code + 'error.message: ', + error.message); - return; - } - console.log('Callback returned to indicate a successful vibration.'); - }); + vibrator.startVibration({ + type: 'time', + duration: 1000, + }, { + id: 0, + usage: 'alarm' + }, (error) => { + if (error) { + console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); + return; + } + console.info('Succeed in starting vibration'); + }); } catch (err) { - console.error('errCode: ' + err.code + ' ,msg: ' + err.message); + console.error(`An unexpected error occurred. Code: ${err.code}, message: ${err.message}`); } ``` @@ -95,24 +96,25 @@ startVibration(effect: VibrateEffect, attribute: VibrateAttribute): Promise<v **示例:** - ```js +```ts import vibrator from '@ohos.vibrator'; + try { - vibrator.startVibration({ - type: 'time', - duration: 1000 - }, { - id: 0, - usage: 'alarm' - }).then(() => { - console.log('Promise returned to indicate a successful vibration'); - }, (error) => { - console.error('error.code' + error.code + 'error.message' + error.message); - }); + vibrator.startVibration({ + type: 'time', + duration: 1000 + }, { + id: 0, + usage: 'alarm' + }).then(() => { + console.info('Succeed in starting vibration'); + }, (error) => { + console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); + }); } catch (err) { - console.error('errCode: ' + err.code + ' ,msg: ' + err.message); + console.error(`An unexpected error occurred. Code: ${err.code}, message: ${err.message}`); } - ``` +``` ## vibrator.stopVibration9+ @@ -133,40 +135,41 @@ stopVibration(stopMode: VibratorStopMode, callback: AsyncCallback<void>): **示例:** - ```js +```ts import vibrator from '@ohos.vibrator'; + try { - // 按照固定时长振动 - vibrator.startVibration({ - type: 'time', - duration: 1000, - }, { - id: 0, - usage: 'alarm' - }, (error) => { - if (error) { - console.error('Vibrate fail, error.code: ' + error.code + 'error.message: ', + error.message); - return; - } - console.log('Callback returned to indicate a successful vibration.'); - }); + // 按照固定时长振动 + vibrator.startVibration({ + type: 'time', + duration: 1000, + }, { + id: 0, + usage: 'alarm' + }, (error) => { + if (error) { + console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); + return; + } + console.info('Succeed in starting vibration'); + }); } catch (err) { - console.error('errCode: ' + err.code + ' ,msg: ' + err.message); + console.error(`An unexpected error occurred. Code: ${err.code}, message: ${err.message}`); } try { - // 按照VIBRATOR_STOP_MODE_TIME模式停止振动 - vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_TIME, function (error) { - if (error) { - console.log('error.code' + error.code + 'error.message' + error.message); - return; - } - console.log('Callback returned to indicate successful.'); - }) + // 按照VIBRATOR_STOP_MODE_TIME模式停止振动 + vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_TIME, function (error) { + if (error) { + console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); + return; + } + console.info('Succeed in stopping vibration'); + }) } catch (err) { - console.info('errCode: ' + err.code + ' ,msg: ' + err.message); + console.error(`An unexpected error occurred. Code: ${err.code}, message: ${err.message}`); } - ``` +``` ## vibrator.stopVibration9+ @@ -192,36 +195,37 @@ stopVibration(stopMode: VibratorStopMode): Promise<void> **示例:** - ```js +```ts import vibrator from '@ohos.vibrator'; + try { - // 按照固定时长振动 - vibrator.startVibration({ - type: 'time', - duration: 1000 - }, { - id: 0, - usage: 'alarm' - }).then(() => { - console.log('Promise returned to indicate a successful vibration'); - }, (error) => { - console.error('error.code' + error.code + 'error.message' + error.message); - }); + // 按照固定时长振动 + vibrator.startVibration({ + type: 'time', + duration: 1000 + }, { + id: 0, + usage: 'alarm' + }).then(() => { + console.info('Succeed in starting vibration'); + }, (error) => { + console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); + }); } catch (err) { - console.error('errCode: ' + err.code + ' ,msg: ' + err.message); + console.error(`An unexpected error occurred. Code: ${err.code}, message: ${err.message}`); } try { - // 按照VIBRATOR_STOP_MODE_TIME模式停止振动 - vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then(() => { - console.log('Promise returned to indicate a successful vibration.'); - }, (error) => { - console.log('error.code' + error.code + 'error.message' + error.message); - }); + // 按照VIBRATOR_STOP_MODE_TIME模式停止振动 + vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then(() => { + console.info('Succeed in stopping vibration'); + }, (error) => { + console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); + }); } catch (err) { - console.info('errCode: ' + err.code + ' ,msg: ' + err.message); + console.error(`An unexpected error occurred. Code: ${err.code}, message: ${err.message}`); } - ``` +``` ## vibrator.stopVibration10+ @@ -241,40 +245,41 @@ stopVibration(callback: AsyncCallback<void>): void **示例:** - ```js +```ts import vibrator from '@ohos.vibrator'; + try { - // 按照固定时长振动 - vibrator.startVibration({ - type: 'time', - duration: 1000, - }, { - id: 0, - usage: 'alarm' - }, (error) => { - if (error) { - console.error('Vibrate fail, error.code: ' + error.code + 'error.message: ', + error.message); - return; - } - console.log('Callback returned to indicate a successful vibration.'); - }); + // 按照固定时长振动 + vibrator.startVibration({ + type: 'time', + duration: 1000, + }, { + id: 0, + usage: 'alarm' + }, (error) => { + if (error) { + console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); + return; + } + console.info('Succeed in starting vibration'); + }); } catch (error) { - console.error('errCode: ' + error.code + ' ,msg: ' + error.message); + console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`); } try { - // 停止所有模式的马达振动 - vibrator.stopVibration(function (error) { - if (error) { - console.log('error.code' + error.code + 'error.message' + error.message); - return; - } - console.log('Callback returned to indicate successful.'); - }) + // 停止所有模式的马达振动 + vibrator.stopVibration(function (error) { + if (error) { + console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); + return; + } + console.info('Succeed in stopping vibration'); + }) } catch (error) { - console.info('errCode: ' + error.code + ' ,msg: ' + error.message); + console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`); } - ``` +``` ## vibrator.stopVibration10+ @@ -294,36 +299,37 @@ stopVibration(): Promise<void> **示例:** - ```js +```ts import vibrator from '@ohos.vibrator'; + try { - // 按照固定时长振动 - vibrator.startVibration({ - type: 'time', - duration: 1000 - }, { - id: 0, - usage: 'alarm' - }).then(() => { - console.log('Promise returned to indicate a successful vibration'); - }, (error) => { - console.error('error.code' + error.code + 'error.message' + error.message); - }); + // 按照固定时长振动 + vibrator.startVibration({ + type: 'time', + duration: 1000 + }, { + id: 0, + usage: 'alarm' + }).then(() => { + console.info('Succeed in starting vibration'); + }, (error) => { + console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); + }); } catch (error) { - console.error('errCode: ' + error.code + ' ,msg: ' + error.message); + console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`); } try { - // 停止所有模式的马达振动 - vibrator.stopVibration().then(() => { - console.log('Promise returned to indicate a successful vibration.'); - }, (error) => { - console.log('error.code' + error.code + 'error.message' + error.message); - }); + // 停止所有模式的马达振动 + vibrator.stopVibration().then(() => { + console.info('Succeed in stopping vibration'); + }, (error) => { + console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); + }); } catch (error) { - console.info('errCode: ' + error.code + ' ,msg: ' + error.message); + console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`); } - ``` +``` ## vibrator.isSupportEffect10+ @@ -342,40 +348,41 @@ isSupportEffect(effectId: string, callback: AsyncCallback<boolean>): void **示例:** - ```js +```ts import vibrator from '@ohos.vibrator'; + try { - // 查询是否支持'haptic.clock.timer' - vibrator.isSupportEffect('haptic.clock.timer', function (err, state) { - if (err) { - console.error('isSupportEffect failed, error:' + JSON.stringify(err)); - return; - } - console.log('The effectId is ' + (state ? 'supported' : 'unsupported')); - if (state) { - try { - vibrator.startVibration({ // 使用startVibration需要添加ohos.permission.VIBRATE权限 - type: 'preset', - effectId: 'haptic.clock.timer', - count: 1, - }, { - usage: 'unknown' - }, (error) => { - if(error) { - console.error('haptic.clock.timer vibrator error:' + JSON.stringify(error)); - } else { - console.log('haptic.clock.timer vibrator success'); - } - }); - } catch (error) { - console.error('Exception in, error:' + JSON.stringify(error)); - } - } - }) + // 查询是否支持'haptic.clock.timer' + vibrator.isSupportEffect('haptic.clock.timer', function (err, state) { + if (err) { + console.error(`Failed to query effect. Code: ${err.code}, message: ${err.message}`); + return; + } + console.info('Succeed in querying effect'); + if (state) { + try { + vibrator.startVibration({ // 使用startVibration需要添加ohos.permission.VIBRATE权限 + type: 'preset', + effectId: 'haptic.clock.timer', + count: 1, + }, { + usage: 'unknown' + }, (error) => { + if (error) { + console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); + } else { + console.info('Succeed in starting vibration'); + } + }); + } catch (error) { + console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`); + } + } + }) } catch (error) { - console.error('Exception in, error:' + JSON.stringify(error)); + console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`); } - ``` +``` ## vibrator.isSupportEffect10+ @@ -399,36 +406,37 @@ isSupportEffect(effectId: string): Promise<boolean> **示例:** - ```js +```ts import vibrator from '@ohos.vibrator'; + try { - // 查询是否支持'haptic.clock.timer' - vibrator.isSupportEffect('haptic.clock.timer').then((state) => { - console.log('The effectId is ' + (state ? 'supported' : 'unsupported')); - if (state) { - try { - vibrator.startVibration({ - type: 'preset', - effectId: 'haptic.clock.timer', - count: 1, - }, { - usage: 'unknown' - }).then(()=>{ - console.log('Promise returned to indicate a successful vibration'); - }).catch((error)=>{ - console.error('Promise returned to indicate a failed vibration:' + JSON.stringify(error)); - }); - } catch (error) { - console.error('Exception in, error:' + JSON.stringify(error)); - } - } - }, (error) => { - console.error('isSupportEffect failed, error:' + JSON.stringify(error)); - }) + // 查询是否支持'haptic.clock.timer' + vibrator.isSupportEffect('haptic.clock.timer').then((state) => { + console.info(`The query result is ${state}`); + if (state) { + try { + vibrator.startVibration({ + type: 'preset', + effectId: 'haptic.clock.timer', + count: 1, + }, { + usage: 'unknown' + }).then(() => { + console.info('Succeed in starting vibration'); + }).catch((error) => { + console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); + }); + } catch (error) { + console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`); + } + } + }, (error) => { + console.error(`Failed to query effect. Code: ${error.code}, message: ${error.message}`); + }) } catch (error) { - console.error('Exception in, error:' + JSON.stringify(error)); + console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`); } - ``` +``` ## EffectId @@ -489,7 +497,7 @@ try { ## VibrateFromFile10+ -自定义振动类型,仅部分设备支持。 +自定义振动类型,仅部分设备支持,当设备不支持此振动类型时,返回[设备不支持错误码](../errorcodes/errorcode-universal.md)。 **系统能力**:SystemCapability.Sensors.MiscDevice @@ -565,13 +573,13 @@ vibrate(duration: number): Promise<void> **示例:** - ```js +```ts vibrator.vibrate(1000).then(() => { - console.log('Promise returned to indicate a successful vibration.'); + console.info('Succeed in vibrating'); }, (error) => { - console.log('error.code' + error.code + 'error.message' + error.message); + console.error(`Failed to vibrate. Code: ${error.code}, message: ${error.message}`); }); - ``` +``` ## vibrator.vibrate(deprecated) @@ -594,15 +602,15 @@ vibrate(duration: number, callback?: AsyncCallback<void>): void **示例:** - ```js +```ts vibrator.vibrate(1000, function (error) { - if (error) { - console.log('error.code' + error.code + 'error.message' + error.message); - } else { - console.log('Callback returned to indicate a successful vibration.'); - } + if (error) { + console.error(`Failed to vibrate. Code: ${error.code}, message: ${error.message}`); + } else { + console.info('Succeed in vibrating'); + } }) - ``` +``` ## vibrator.vibrate(deprecated) @@ -631,13 +639,13 @@ vibrate(effectId: EffectId): Promise<void> **示例:** - ```js +```ts vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER).then(() => { - console.log('Promise returned to indicate a successful vibration.'); + console.info('Succeed in vibrating'); }, (error) => { - console.log('error.code' + error.code + 'error.message' + error.message); + console.error(`Failed to vibrate. Code: ${error.code}, message: ${error.message}`); }); - ``` +``` ## vibrator.vibrate(deprecated) @@ -661,15 +669,15 @@ vibrate(effectId: EffectId, callback?: AsyncCallback<void>): void **示例:** - ```js +```ts vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER, function (error) { - if (error) { - console.log('error.code' + error.code + 'error.message' + error.message); - } else { - console.log('Callback returned to indicate a successful vibration.'); - } + if (error) { + console.error(`Failed to vibrate. Code: ${error.code}, message: ${error.message}`); + } else { + console.info('Succeed in vibrating'); + } }) - ``` +``` ## vibrator.stop(deprecated) @@ -697,22 +705,22 @@ stop(stopMode: VibratorStopMode): Promise<void> **示例:** - ```js +```ts // 按照effectId类型启动振动 vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER, function (error) { - if (error) { - console.log('error.code' + error.code + 'error.message' + error.message); - } else { - console.log('Callback returned to indicate a successful vibration.'); - } + if (error) { + console.error(`Failed to vibrate. Code: ${error.code}, message: ${error.message}`); + } else { + console.info('Succeed in vibrating'); + } }) // 使用VIBRATOR_STOP_MODE_PRESET模式停止振动 vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then(() => { - console.log('Promise returned to indicate a successful vibration.'); + console.info('Succeed in stopping'); }, (error) => { - console.log('error.code' + error.code + 'error.message' + error.message); + console.error(`Failed to stop. Code: ${error.code}, message: ${error.message}`); }); - ``` +``` ## vibrator.stop(deprecated) @@ -736,21 +744,21 @@ stop(stopMode: VibratorStopMode, callback?: AsyncCallback<void>): void **示例:** - ```js +```ts // 按照effectId类型启动振动 vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER, function (error) { - if (error) { - console.log('error.code' + error.code + 'error.message' + error.message); - } else { - console.log('Callback returned to indicate a successful vibration.'); - } + if (error) { + console.error(`Failed to vibrate. Code: ${error.code}, message: ${error.message}`); + } else { + console.info('Succeed in vibrating'); + } }) // 使用VIBRATOR_STOP_MODE_PRESET模式停止振动 vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET, function (error) { - if (error) { - console.log('error.code' + error.code + 'error.message' + error.message); - } else { - console.log('Callback returned to indicate successful.'); - } + if (error) { + console.error(`Failed to stop. Code: ${error.code}, message: ${error.message}`); + } else { + onsole.info('Succeed in stopping'); + } }) - ``` +``` diff --git a/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md b/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md index f3f9f1b32b2d3c4d4a36c646db3e455f109e7188..07c1e94d0ad797ce2799350f9861a750701f61bd 100644 --- a/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md +++ b/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md @@ -50,6 +50,7 @@ - [半模态转场](ts-universal-attributes-sheet-transition.md) - [隐私遮罩](ts-universal-attributes-obscured.md) - [文本通用](ts-universal-attributes-text-style.md) + - [拖拽控制](ts-universal-attributes-drag-drop.md) - 手势处理 - [绑定手势方法](ts-gesture-settings.md) - 基础手势 diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/datePicker.gif b/zh-cn/application-dev/reference/arkui-ts/figures/datePicker.gif index 0d83b0a08128d1e43f3fa633eb72cca66114a3d6..f9855aa32e2ffa7b2f72304fc8396f0fb4307cc4 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/datePicker.gif and b/zh-cn/application-dev/reference/arkui-ts/figures/datePicker.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/dragImage.gif b/zh-cn/application-dev/reference/arkui-ts/figures/dragImage.gif new file mode 100644 index 0000000000000000000000000000000000000000..1648465415bd1a9e85c23dcdb58767669f99b968 Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/dragImage.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/timePicker.gif b/zh-cn/application-dev/reference/arkui-ts/figures/timePicker.gif index 9ae06ee5b27f1b4ce369b8e90ef5602a1ea0f846..dcfe87d505109e349d426eb8ca772c78cfd9b127 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/timePicker.gif and b/zh-cn/application-dev/reference/arkui-ts/figures/timePicker.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md index 1f0d41d585cb1d0a3e40cd8a8e8a7138948bfee8..3612e6044ca1bcb7d5a9c2ca4f04f465b9e4432a 100755 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md @@ -2977,7 +2977,7 @@ onWindowNew(callback: (event: {isAlert: boolean, isUserTrigger: boolean, targetU ```ts // xxx.ets import web_webview from '@ohos.web.webview' - + //在同一page页有两个web组件。在WebComponent新开窗口时,会跳转到NewWebViewComp。 @CustomDialog struct NewWebViewComp { @@ -3333,8 +3333,8 @@ onFirstContentfulPaint(callback: (event?: { navigationStartTick: number, firstCo Column() { Web({ src:'www.example.com', controller: this.controller }) .onFirstContentfulPaint(event => { - console.log("onFirstContentfulPaint:" + "[navigationStartTick]:" + - event.navigationStartTick + ", [firstContentfulPaintMs]:" + + console.log("onFirstContentfulPaint:" + "[navigationStartTick]:" + + event.navigationStartTick + ", [firstContentfulPaintMs]:" + event.firstContentfulPaintMs) }) } @@ -3414,6 +3414,41 @@ onRequestSelected(callback: () => void) } ``` +### onOverScroll10+ + +onOverScroll(callback: (event: {xOffset: number, yOffset: number}) => void) + +通知网页过滚动偏移量。 + +**参数:** + +| 参数名 | 参数类型 | 参数描述 | +| ------- | ------ | ------------ | +| xOffset | number | 以网页最左端为基准,水平过滚动偏移量。 | +| yOffset | number | 以网页最上端为基准,竖直过滚动偏移量。 | + +**示例:** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .onOverScroll((event) => { + console.info("x = " + event.xOffset) + console.info("y = " + event.yOffset) + }) + } + } + } + ``` + ## ConsoleMessage Web组件获取控制台信息对象。示例代码参考[onConsole事件](#onconsole)。 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-list.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-list.md index 73a20b59e905f9164d13aef7f68cca4396d8ac90..772d8593a40e5ab0fe7ecea6ff096d5acaa72058 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-list.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-list.md @@ -121,11 +121,15 @@ List(value?:{space?: number | string, initialIndex?: number, scroller? 从API version 10开始,该接口支持在ArkTS卡片中使用。 -| 名称 | 描述 | -| ------ | ---------------------------------------------------------- | -| NONE | 默认无项目滚动对齐效果。滚动结束列表项何时将无限制地停止。 | +左右和上下这种两端对齐的样式:当列表位移至末端,则需要将末端的item完整显示,同时不能露出边界空白区域,此时另一端可以出现不限位对齐的现象。 + +只支持item等高场景限位,不等高场景可能存在不准确的情况。 + +| 名称 | 描述 | +| ------ | ------------------------------------------------------------ | +| NONE | 默认无项目滚动对齐效果。滚动结束列表项何时将无限制地停止。 | | START | 视图中的第一项将在列表的开头对齐。
**说明:**
当列表位移至末端,需要将末端的item完整显示,可能出现开头不对齐的情况。 | -| CENTER | 视图中的中间项将在列表中心对齐。
**说明:**
顶端和末尾的item都可以在列表中心对齐,列表显示可能露出空白。 | +| CENTER | 视图中的中间项将在列表中心对齐。
**说明:**
顶端和末尾的item都可以在列表中心对齐,列表显示可能露出空白,第一个或最后一个item会对齐到中间位置。 | | END | 视图中的最后一项将在列表末尾对齐。
**说明:**
当列表位移至顶端,需要将顶端的item完整显示,可能出现末尾不对齐的情况。 | ## 事件 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-swiper.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-swiper.md index 972e70ed7c8470a815a89db790b32bab2801a269..40f0ea0967f39be88371500cb3fbaf1e2f0b5598 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-swiper.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-swiper.md @@ -58,8 +58,8 @@ Swiper(controller?: SwiperController) | 名称 | 描述 | | --------------------------------- | ---------------------------------------- | -| Stretch(deprecated) | Swiper滑动一页的宽度为Swiper组件自身的宽度。
从API verdion 10开始不再维护,建议使用STRETCH代替。 | -| AutoLinear(deprecated) | Swiper滑动一页的宽度为子组件宽度中的最大值。
从API verdion 10开始不再维护,建议使用AUTO_LINEAR代替。 | +| Stretch(deprecated) | Swiper滑动一页的宽度为Swiper组件自身的宽度。
从API version 10开始不再维护,建议使用STRETCH代替。 | +| AutoLinear(deprecated) | Swiper滑动一页的宽度为子组件宽度中的最大值。
从API version 10开始不再维护,建议使用AUTO_LINEAR代替。 | | STRETCH10+ | Swiper滑动一页的宽度为Swiper组件自身的宽度。 | | AUTO_LINEAR10+ | Swiper滑动一页的宽度为视窗内最左侧子组件的宽度。 | @@ -148,8 +148,9 @@ finishAnimation(callback?: () => void): void | 名称 | 功能描述 | | ---------------------------------------- | ---------------------------------------- | | onChange(event: (index: number) => void) | 当前显示的子组件索引变化时触发该事件,返回值为当前显示的子组件的索引值。
- index:当前显示元素的索引。
**说明:**
Swiper组件结合LazyForEach使用时,不能在onChange事件里触发子页面UI的刷新。 | -| onAnimationStart9+(event: (index: number) => void) | 切换动画开始时触发该回调。
- index:当前显示元素的索引。
**说明:**
参数为动画开始前的index值(不是最终结束动画的index值),多列Swiper时,index为最左侧组件的索引。 | -| onAnimationEnd9+(event: (index: number) => void) | 切换动画结束时触发该回调。
- index:当前显示元素的索引。
**说明:**
当Swiper切换动效结束时触发,包括动画过程中手势中断,通过SwiperController调用finishAnimatio。参数为动画结束后的index值,多列Swiper时,index为最左侧组件的索引。 | +| onAnimationStart9+(event: (index: number, targetIndex10+: number, extraInfo10+: [SwiperAnimationEvent](ts-types.md#swiperanimationevent)) => void) | 切换动画开始时触发该回调。
- index:当前显示元素的索引。
- targetIndex:切换动画目标元素的索引。
- extraInfo:动画相关信息,包括主轴方向上当前显示元素和目标元素相对Swiper起始位置的位移,以及离手速度。
**说明:**
参数为动画开始前的index值(不是最终结束动画的index值),多列Swiper时,index为最左侧组件的索引。 | +| onAnimationEnd9+(event: (index: number, extraInfo: [SwiperAnimationEvent](ts-types.md#swiperanimationevent)) => void) | 切换动画结束时触发该回调。
- index:当前显示元素的索引。
- extraInfo:动画相关信息,只返回主轴方向上当前显示元素相对于Swiper起始位置的位移。
**说明:**
当Swiper切换动效结束时触发,包括动画过程中手势中断,通过SwiperController调用finishAnimation。参数为动画结束后的index值,多列Swiper时,index为最左侧组件的索引。 | +| onGestureSwipe10+(event: (index: number, extraInfo: [SwiperAnimationEvent](ts-types.md#swiperanimationevent)) => void) | 在页面跟手滑动过程中,逐帧触发该回调。
- index:当前显示元素的索引。
- extraInfo:动画相关信息,只返回主轴方向上当前显示元素相对于Swiper起始位置的位移。
**说明:**
多列Swiper时,index为最左侧组件的索引。 | ## 示例 @@ -219,6 +220,21 @@ struct SwiperExample { .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') diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-tabcontent.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-tabcontent.md index b2b768cbe1593d1e36dad9b674a84b3d99358548..6872c750f5bf2266051fa80160465a58de013383 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-tabcontent.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-tabcontent.md @@ -82,7 +82,7 @@ SubTabBarStyle的静态构造函数。 | -------- | -------- | -------- | -------------------------------- | | color | [ResourceColor](ts-types.md#resourcecolor) | 否 | 下划线的颜色和背板颜色。
默认值:#FF007DFF | | height | [Length](ts-types.md#length) | 否 | 下划线的高度(不支持百分比设置)。
默认值:2.0
单位:vp | -| width | [Length](ts-types.md#length) | 否 | 下划线的宽度(不支持百分比设置)。
默认值:0.0
单位:vp | +| width | [Length](ts-types.md#length) | 否 | 下划线的宽度(不支持百分比设置)。
默认值:0.0
单位:vp
**说明:**
宽度设置为0时,按页签文本宽度显示。| | borderRadius | [Length](ts-types.md#length) | 否 | 下划线的圆角半径(不支持百分比设置)。
默认值:0.0
单位:vp | | marginTop | [Length](ts-types.md#length) | 否 | 下划线与文字的间距(不支持百分比设置)。
默认值:8.0
单位:vp | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-types.md b/zh-cn/application-dev/reference/arkui-ts/ts-types.md index 54b73973b2ec7009e92771a864eff0638884a7c5..fbaeb23246e5e9f2c7f9c2da9141a1016e595e3d 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-types.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-types.md @@ -308,4 +308,14 @@ | 类型 | 说明 | | --------------------- | -------------------------------------- | -| {number}deg | 需要指定以deg像素单位,如'10deg'。 | \ No newline at end of file +| {number}deg | 需要指定以deg像素单位,如'10deg'。 | + +## SwiperAnimationEvent10+ + +Swiper组件动画相关信息集合。 + +| 名称 | 类型定义 | 描述 | +| ------------- | ---------------------- | ---------------------------------------- | +| currentOffset | number | Swiper当前显示元素在主轴方向上,相对于Swiper起始位置的位移。单位VP,默认值为0.| +| targetOffset | number | Swiper动画目标元素在主轴方向上,相对于Swiper起始位置的位移。单位VP,默认值为0.| +| velocity | number | Swiper离手动画开始时的离手速度。单位VP/S,默认值为0.| diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-drag-drop.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-drag-drop.md new file mode 100644 index 0000000000000000000000000000000000000000..6ec0f758243722986097550fb497502e2a57b056 --- /dev/null +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-drag-drop.md @@ -0,0 +1,157 @@ +# 拖拽控制 + +设置组件是否可以响应拖拽事件。 + +> **说明:** +> +> 从API Version 10开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 +> +> 支持拖拽控制的组件: +> +>[Text](ts-basic-components-text.md)、[Image](ts-basic-components-image.md)、[Video](ts-media-components-video.md)、[List](ts-container-list.md)、 +[Grid](ts-container-grid.md)。 + + +## 属性 + +| 名称 | 参数类型 | 描述 | +| -------- | -------- | -------- | +| allowDrop | Array\ | 设置该组件上允许落入的数据类型。
默认值:空
| +| draggable | boolean | 设置该组件是否允许进行拖拽。
默认值:false
| + + +## 示例 + +```ts +// xxx.ets +import UDMF from '@ohos.data.UDMF'; +@Entry +@Component +struct ImageExample { + @State uri: string = "" + @State AblockArr: string[] = [] + @State BblockArr: string[] = [] + @State AVisible: Visibility = Visibility.Visible + @State dragSuccess :Boolean = false + + @Builder pixelMapBuilder() { + Column() { + Column() + .width(100) + .height(100) + .borderRadius(10) + .backgroundColor(Color.Yellow) + } + } + + build() { + Column() { + Text('Image拖拽') + .fontSize('30dp') + Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceAround }) { + Image($r('app.media.1')) + .width(100) + .height(100) + .border({ width: 1 }) + .visibility(this.AVisible) + .draggable(true) + .onDragStart((event: DragEvent, extraParams: string) => { + let image = new UDMF.Image(); + let unifiedData = new UDMF.UnifiedData(image); + event.setData(unifiedData); + return this.pixelMapBuilder() + }) + .onDragEnd((event: DragEvent) => { + let ret = event.getResult(); + if(ret == 0) { + console.log("enter ret == 0") + this.AVisible = Visibility.Hidden; + } else { + console.log("enter ret != 0") + this.AVisible = Visibility.Visible; + } + }) + } + .margin({ bottom: 20 }) + Row() { + Column(){ + Text('不允许释放区域(显示不允许角标但可以释放)') + .fontSize('15dp') + .height('10%') + List(){ + ForEach(this.AblockArr, (item, index) => { + ListItem() { + Image(item) + .width(100) + .height(100) + .border({width: 1}) + } + .margin({ left: 30 , top : 30}) + }, item => item) + } + .height('90%') + .width('100%') + .allowDrop(["File.Media.Text", "File.Media.Image"]) + .onDrop((event: DragEvent, extraParams: string) => { + let jsonString = JSON.parse(extraParams); + this.uri = jsonString.extraInfo; + this.AblockArr.splice(jsonString.insertIndex, 0, this.uri); + console.log("ondrop not udmf data"); + }) + .border({width: 1}) + } + .height("50%") + .width("45%") + .border({ width: 1 }) + .margin({ left: 12 }) + Column(){ + Text('可释放区域') + .fontSize('15dp') + .height('10%') + List(){ + ForEach(this.BblockArr, (item, index) => { + ListItem() { + Image(item) + .width(100) + .height(100) + .border({width: 1}) + } + .margin({ left: 30 , top : 30}) + }, item => item) + } + .border({width: 1}) + .height('90%') + .width('100%') + .allowDrop(["File.Media.Image"]) + .onDrop((event: DragEvent, extraParams: string) => { + console.log("enter onDrop") + let dragData = event.getData(); + let summary = event.getSummary(); + if(dragData != undefined) { + let arr = dragData.getRecords(); + if(arr.length > 0) { + let image = (arr[0]); + this.uri = image.imageUri; + let jsonString = JSON.parse(extraParams); + this.BblockArr.splice(jsonString.insertIndex, 0, this.uri); + } else { + console.log(`dragData arr is null`) + } + } else { + console.log(`dragData is undefined`) + } + console.log("ondrop udmf data"); + this.dragSuccess = true + }) + } + .height("50%") + .width("45%") + .border({ width: 1 }) + .margin({ left: 12 }) + } + }.width('100%') + } +} +``` + +![dragImage.gif](figures/dragImage.gif) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md index 733e49cde195026da3d3ffb7c677c22dfac61704..75dbbed80b1aee046db310cefe34d2429d819cbd 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md @@ -6,13 +6,6 @@ > > 从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 -## 属性 - -拖拽事件相关组件除支持[通用属性](ts-universal-attributes-size.md)外,支持绑定以下属性: -| 名称 | 参数类型 | 描述 | -| -------- | -------- | -------- | -| allowDrop10+ | Array\ | 设置该组件上允许落入的数据类型。
默认值:空
| -| draggable10+ | boolean | 设置该组件是否允许进行拖拽。
默认值:false
| ## 事件 | 名称 | 支持冒泡 | 功能描述 | @@ -81,6 +74,8 @@ ### 示例1 ```ts +import UDMF from '@ohos.data.UDMF'; + @Observed class ClassA { public name: string @@ -105,11 +100,27 @@ class ClassA { struct DragExample { @State arr: ClassA[] = [new ClassA('A', true), new ClassA('B', true), new ClassA('C', true)] @State dragIndex: number = 0 + @State mTextNew: string = '' + @State mBool: boolean = false changeIndex(index1: number, index2: number) { // 交换数组位置 [this.arr[index1], this.arr[index2]] = [this.arr[index2], this.arr[index1]]; } + public getDataFromUDMFWithRetry(event: DragEvent) { + let records = event.getData().getRecords(); + if (records) { + let plainText = (records[0]) + this.mTextNew = plainText.textContent + this.mBool = false + return; + } + // 获取失败延时 1.5s 再次获取 + setTimeout(() => { + this.getDataFromUDMFWithRetry(event) + }, 1500) + } + build() { Column() { Row({ space: 15 }) { @@ -130,8 +141,7 @@ struct DragExample { } .listDirection(Axis.Horizontal) .onDrop((event: DragEvent, extraParams: string) => { // 绑定此事件的组件可作为拖拽释放目标,当在本组件范围内停止拖拽行为时,触发回调。 - let jsonString = JSON.parse(extraParams); - this.changeIndex(this.dragIndex, jsonString.insertIndex) + this.getDataFromUDMFWithRetry(event); }) }.padding({ top: 10, bottom: 10 }).margin(10) @@ -187,6 +197,8 @@ struct Child { ```ts // xxx.ets +import UDMF from '@ohos.data.UDMF'; + @Extend(Text) function textStyle () { .width('25%') .height(35) @@ -201,6 +213,8 @@ struct DragExample { @State numbers: string[] = ['one', 'two', 'three', 'four', 'five', 'six'] @State text: string = '' @State bool: boolean = true + @State mBool: boolean = false + @State mTextNew: string = '' @State eventType: string = '' @State appleVisible: Visibility = Visibility.Visible @State orangeVisible: Visibility = Visibility.Visible @@ -222,6 +236,20 @@ struct DragExample { } } + public getDataFromUDMFWithRetry(event: DragEvent) { + let records = event.getData().getRecords() + if (records) { + let plainText = (records[0]) + this.mTextNew = plainText.textContent + this.mBool = false + return; + } + // 获取失败延时 1.5s 再次获取 + setTimeout(() => { + this.getDataFromUDMFWithRetry(event) + }, 1500) + } + build() { Column() { Text('There are three Text elements here') @@ -298,6 +326,7 @@ struct DragExample { this.bool = false } this.fruitVisible[this.idx] = Visibility.None + this.getDataFromUDMFWithRetry(event); }) }.width('100%').height('100%').padding({ top: 20 }).margin({ top: 20 }) } diff --git a/zh-cn/application-dev/reference/native-apis/Readme-CN.md b/zh-cn/application-dev/reference/native-apis/Readme-CN.md index e3a94832d68cc432860665b9227aa07a5964cb78..e3bc11d96020f0556ac02ca15cdfb3be0c69da76 100644 --- a/zh-cn/application-dev/reference/native-apis/Readme-CN.md +++ b/zh-cn/application-dev/reference/native-apis/Readme-CN.md @@ -31,6 +31,7 @@ - [Memory](memory.md) - [UsbDdk](_usb_ddk.md) - [Hitrace](_hitrace.md) + - [Vulkan](_vulkan.md) - 头文件 - [drawing_bitmap.h](drawing__bitmap_8h.md) - [drawing_brush.h](drawing__brush_8h.md) @@ -92,6 +93,7 @@ - [usb_ddk_api.h](usb__ddk__api_8h.md) - [usb_ddk_types.h](usb__ddk__types_8h.md) - [trace.h](trace_8h.md) + - [vulkan_ohos.h](vulkan__ohos_8h.md) - 结构体 - [OH_Drawing_BitmapFormat](_o_h___drawing___bitmap_format.md) - [OH_NativeBuffer_Config](_o_h___native_buffer___config.md) @@ -148,3 +150,10 @@ - [UsbEndpointDescriptor](_usb_endpoint_descriptor.md) - [UsbInterfaceDescriptor](_usb_interface_descriptor.md) - [UsbRequestPipe](_usb_request_pipe.md) + - [VkExternalFormatOHOS](_vk_external_format_o_h_o_s.md) + - [VkImportNativeBufferInfoOHOS](_vk_import_native_buffer_info_o_h_o_s.md) + - [VkMemoryGetNativeBufferInfoOHOS](_vk_memory_get_native_buffer_info_o_h_o_s.md) + - [VkNativeBufferFormatPropertiesOHOS](_vk_native_buffer_format_properties_o_h_o_s.md) + - [VkNativeBufferPropertiesOHOS](_vk_native_buffer_properties_o_h_o_s.md) + - [VkNativeBufferUsageOHOS](_vk_native_buffer_usage_o_h_o_s.md) + - [VkSurfaceCreateInfoOHOS](_vk_surface_create_info_o_h_o_s.md) diff --git a/zh-cn/application-dev/reference/native-apis/_video_encoder.md b/zh-cn/application-dev/reference/native-apis/_video_encoder.md index 8d64bccf8dd94328800a4dcc968cb46828ba43ca..afa80160619f0fdfb1803378c529953044ef8c01 100644 --- a/zh-cn/application-dev/reference/native-apis/_video_encoder.md +++ b/zh-cn/application-dev/reference/native-apis/_video_encoder.md @@ -33,7 +33,7 @@ VideoEncoder模块提供用于视频编码功能的函数。 | 名称 | 描述 | | -------- | -------- | -| [OH_VideoEncodeBitrateMode](#oh_videoencodebitratemode) { **CBR** = 0, **VBR** = 1, **CQ** = 2 } | 视频编码器的比特率模式。 | +| [OH_VideoEncodeBitrateMode](#oh_videoencodebitratemode) {
    **CBR** = 0,
    **VBR** = 1,
    **CQ** = 2
} | 视频编码器的比特率模式。 | ### 函数 diff --git a/zh-cn/application-dev/reference/native-apis/_vk_external_format_o_h_o_s.md b/zh-cn/application-dev/reference/native-apis/_vk_external_format_o_h_o_s.md new file mode 100644 index 0000000000000000000000000000000000000000..92c151271151f8c8adb7d0e074245a0a040e0c40 --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/_vk_external_format_o_h_o_s.md @@ -0,0 +1,26 @@ +# VkExternalFormatOHOS + + +## 概述 + +表示外部定义的格式标识符。 + +**起始版本:** + +10 + +**相关模块:** + +[Vulkan](_vulkan.md) + + +## 汇总 + + +### 成员变量 + +| 名称 | 描述 | +| -------- | -------- | +| [sType](_vulkan.md#stype-77) | 结构体类型。 | +| [pNext](_vulkan.md#pnext-77) | 下一级结构体指针。 | +| [externalFormat](_vulkan.md#externalformat-22) | 外部定义的格式标识符。 | diff --git a/zh-cn/application-dev/reference/native-apis/_vk_import_native_buffer_info_o_h_o_s.md b/zh-cn/application-dev/reference/native-apis/_vk_import_native_buffer_info_o_h_o_s.md new file mode 100644 index 0000000000000000000000000000000000000000..2b2d1711d603b97539f311a6df350a3a26013c0a --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/_vk_import_native_buffer_info_o_h_o_s.md @@ -0,0 +1,26 @@ +# VkImportNativeBufferInfoOHOS + + +## 概述 + +包含了OH_NativeBuffer结构体的指针。 + +**起始版本:** + +10 + +**相关模块:** + +[Vulkan](_vulkan.md) + + +## 汇总 + + +### 成员变量 + +| 名称 | 描述 | +| -------- | -------- | +| [sType](_vulkan.md#stype-57) | 结构体类型。 | +| [pNext](_vulkan.md#pnext-57) | 下一级结构体指针。 | +| [buffer](_vulkan.md#buffer) | OH_NativeBuffer结构体的指针。 | diff --git a/zh-cn/application-dev/reference/native-apis/_vk_memory_get_native_buffer_info_o_h_o_s.md b/zh-cn/application-dev/reference/native-apis/_vk_memory_get_native_buffer_info_o_h_o_s.md new file mode 100644 index 0000000000000000000000000000000000000000..f5fbc4f58733aa35c35956e132db9c11c47d4195 --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/_vk_memory_get_native_buffer_info_o_h_o_s.md @@ -0,0 +1,26 @@ +# VkMemoryGetNativeBufferInfoOHOS + + +## 概述 + +用于从Vulkan内存中获取OH_NativeBuffer。 + +**起始版本:** + +10 + +**相关模块:** + +[Vulkan](_vulkan.md) + + +## 汇总 + + +### 成员变量 + +| 名称 | 描述 | +| -------- | -------- | +| [sType](_vulkan.md#stype-67) | 结构体类型。 | +| [pNext](_vulkan.md#pnext-67) | 下一级结构体指针。 | +| [memory](_vulkan.md#memory) | VkDeviceMemory对象。 | diff --git a/zh-cn/application-dev/reference/native-apis/_vk_native_buffer_format_properties_o_h_o_s.md b/zh-cn/application-dev/reference/native-apis/_vk_native_buffer_format_properties_o_h_o_s.md new file mode 100644 index 0000000000000000000000000000000000000000..0b571b4c0d151fe786ce59879a2a1598da578c45 --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/_vk_native_buffer_format_properties_o_h_o_s.md @@ -0,0 +1,33 @@ +# VkNativeBufferFormatPropertiesOHOS + + +## 概述 + +包含了NaitveBuffer的一些格式属性。 + +**起始版本:** + +10 + +**相关模块:** + +[Vulkan](_vulkan.md) + + +## 汇总 + + +### 成员变量 + +| 名称 | 描述 | +| -------- | -------- | +| [sType](_vulkan.md#stype-47) | 结构体类型。 | +| [pNext](_vulkan.md#pnext-47) | 下一级结构体指针。 | +| [format](_vulkan.md#format) | 格式说明。 | +| [externalFormat](_vulkan.md#externalformat-12) | 外部定义的格式标识符。 | +| [formatFeatures](_vulkan.md#formatfeatures) | 描述了与externalFormat对应的能力。 | +| [samplerYcbcrConversionComponents](_vulkan.md#samplerycbcrconversioncomponents) | 表示一组VkComponentSwizzle。 | +| [suggestedYcbcrModel](_vulkan.md#suggestedycbcrmodel) | 色彩模型。 | +| [suggestedYcbcrRange](_vulkan.md#suggestedycbcrrange) | 色彩数值范围。 | +| [suggestedXChromaOffset](_vulkan.md#suggestedxchromaoffset) | X色度偏移。 | +| [suggestedYChromaOffset](_vulkan.md#suggestedychromaoffset) | Y色度偏移。 | diff --git a/zh-cn/application-dev/reference/native-apis/_vk_native_buffer_properties_o_h_o_s.md b/zh-cn/application-dev/reference/native-apis/_vk_native_buffer_properties_o_h_o_s.md new file mode 100644 index 0000000000000000000000000000000000000000..ed90508c76c6a145c73ed70ec31e019b27856bd0 --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/_vk_native_buffer_properties_o_h_o_s.md @@ -0,0 +1,27 @@ +# VkNativeBufferPropertiesOHOS + + +## 概述 + +包含了NaitveBuffer的属性。 + +**起始版本:** + +10 + +**相关模块:** + +[Vulkan](_vulkan.md) + + +## 汇总 + + +### 成员变量 + +| 名称 | 描述 | +| -------- | -------- | +| [sType](_vulkan.md#stype-37) | 结构体类型。 | +| [pNext](_vulkan.md#pnext-37) | 下一级结构体指针 | +| [allocationSize](_vulkan.md#allocationsize) | 占用的内存大小。 | +| [memoryTypeBits](_vulkan.md#memorytypebits) | 内存类型。 | diff --git a/zh-cn/application-dev/reference/native-apis/_vk_native_buffer_usage_o_h_o_s.md b/zh-cn/application-dev/reference/native-apis/_vk_native_buffer_usage_o_h_o_s.md new file mode 100644 index 0000000000000000000000000000000000000000..64059120960df3fc6c18f39db6caed40f781d174 --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/_vk_native_buffer_usage_o_h_o_s.md @@ -0,0 +1,26 @@ +# VkNativeBufferUsageOHOS + + +## 概述 + +提供OpenHarmony NativeBuffer用途的说明。 + +**起始版本:** + +10 + +**相关模块:** + +[Vulkan](_vulkan.md) + + +## 汇总 + + +### 成员变量 + +| 名称 | 描述 | +| -------- | -------- | +| [sType](_vulkan.md#stype-27) | 结构体类型。 | +| [pNext](_vulkan.md#pnext-27) | 下一级结构体指针。 | +| [OHOSNativeBufferUsage](_vulkan.md#ohosnativebufferusage) | NativeBuffer的用途说明。 | diff --git a/zh-cn/application-dev/reference/native-apis/_vk_surface_create_info_o_h_o_s.md b/zh-cn/application-dev/reference/native-apis/_vk_surface_create_info_o_h_o_s.md new file mode 100644 index 0000000000000000000000000000000000000000..179ac0d0b7fea73a9526b7e291f877fdda5e4cad --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/_vk_surface_create_info_o_h_o_s.md @@ -0,0 +1,27 @@ +# VkSurfaceCreateInfoOHOS + + +## 概述 + +包含创建Vulkan Surface时必要的参数。 + +**起始版本:** + +10 + +**相关模块:** + +[Vulkan](_vulkan.md) + + +## 汇总 + + +### 成员变量 + +| 名称 | 描述 | +| -------- | -------- | +| [sType](_vulkan.md#stype-17) | 结构体类型。 | +| [pNext](_vulkan.md#pnext-17) | 下一级结构体指针。 | +| [flags](_vulkan.md#flags) | 预留的标志类型参数。 | +| [window](_vulkan.md#window) | OHNativeWindow指针。 | diff --git a/zh-cn/application-dev/reference/native-apis/_vulkan.md b/zh-cn/application-dev/reference/native-apis/_vulkan.md new file mode 100644 index 0000000000000000000000000000000000000000..f365769c13208df0f2c37d60a156e1f1f94c98cd --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/_vulkan.md @@ -0,0 +1,820 @@ +# Vulkan + + +## 概述 + +提供OpenHarmony平台扩展的Vulkan能力,扩展了使用OHNativeWindow创建Vulkan Surface的能力,以及获取OH_NativeBuffer和OH_NativeBuffer属性的能力。 + +\@syscap SystemCapability.Graphic.Vulkan + +**起始版本:** + +10 + + +## 汇总 + + +### 文件 + +| 名称 | 描述 | +| -------- | -------- | +| [vulkan_ohos.h](vulkan__ohos_8h.md) | 定义了OpenHarmony平台扩展的Vulkan接口。
引用文件:<vulkan/vulkan.h>。 | + + +### 结构体 + +| 名称 | 描述 | +| -------- | -------- | +| [VkSurfaceCreateInfoOHOS](_vk_surface_create_info_o_h_o_s.md) | 包含创建Vulkan Surface时必要的参数。 | +| [VkNativeBufferUsageOHOS](_vk_native_buffer_usage_o_h_o_s.md) | 提供OpenHarmony NativeBuffer用途的说明。 | +| [VkNativeBufferPropertiesOHOS](_vk_native_buffer_properties_o_h_o_s.md) | 包含了NaitveBuffer的属性。 | +| [VkNativeBufferFormatPropertiesOHOS](_vk_native_buffer_format_properties_o_h_o_s.md) | 包含了NaitveBuffer的一些格式属性。 | +| [VkImportNativeBufferInfoOHOS](_vk_import_native_buffer_info_o_h_o_s.md) | 包含了OH_NativeBuffer结构体的指针。 | +| [VkMemoryGetNativeBufferInfoOHOS](_vk_memory_get_native_buffer_info_o_h_o_s.md) | 用于从Vulkan内存中获取OH_NativeBuffer。 | +| [VkExternalFormatOHOS](_vk_external_format_o_h_o_s.md) | 表示外部定义的格式标识符。 | + + +### 宏定义 + +| 名称 | 描述 | +| -------- | -------- | +| [VK_OHOS_surface](#vk_ohos_surface) 1 | OpenHarmony平台Surface扩展宏定义。 | +| [VK_OHOS_SURFACE_SPEC_VERSION](#vk_ohos_surface_spec_version) 1 | OpenHarmony平台Surface扩展版本号。 | +| [VK_OHOS_SURFACE_EXTENSION_NAME](#vk_ohos_surface_extension_name) "VK_OHOS_surface" | OpenHarmony平台Surface扩展名。 | +| [VK_OHOS_external_memory](#vk_ohos_external_memory) 1 | OpenHarmony平台external_memory扩展宏定义。 | +| [VK_OHOS_EXTERNAL_MEMORY_SPEC_VERSION](#vk_ohos_external_memory_spec_version) 1 | OpenHarmony平台external_memory扩展版本号。 | +| [VK_OHOS_EXTERNAL_MEMORY_EXTENSION_NAME](#vk_ohos_external_memory_extension_name) "VK_OHOS_external_memory" | OpenHarmony平台external_memory扩展名。 | + + +### 类型定义 + +| 名称 | 描述 | +| -------- | -------- | +| [OHNativeWindow](#ohnativewindow) | OH本地窗口。 | +| [VkSurfaceCreateFlagsOHOS](#vksurfacecreateflagsohos) | 用于Vulkan Surface创建时使用到的VkFlags类型位掩码,预留的标志类型。 | +| [VkSurfaceCreateInfoOHOS](#vksurfacecreateinfoohos) | 包含创建Vulkan Surface时必要的参数。 | +| VkResult ([VKAPI_PTR *PFN_vkCreateSurfaceOHOS](#pfn_vkcreatesurfaceohos)) (VkInstance instance, const [VkSurfaceCreateInfoOHOS](_vk_surface_create_info_o_h_o_s.md) \*pCreateInfo, const VkAllocationCallbacks \*pAllocator, VkSurfaceKHR \*pSurface) | 创建Vulkan Surface的函数指针定义。 | +| [VkNativeBufferUsageOHOS](#vknativebufferusageohos) | 提供OpenHarmony NativeBuffer用途的说明。 | +| [VkNativeBufferPropertiesOHOS](#vknativebufferpropertiesohos) | 包含了NaitveBuffer的属性。 | +| [VkNativeBufferFormatPropertiesOHOS](#vknativebufferformatpropertiesohos) | 包含了NaitveBuffer的一些格式属性。 | +| [VkImportNativeBufferInfoOHOS](#vkimportnativebufferinfoohos) | 包含了OH_NativeBuffer结构体的指针。 | +| [VkMemoryGetNativeBufferInfoOHOS](#vkmemorygetnativebufferinfoohos) | 用于从Vulkan内存中获取OH_NativeBuffer。 | +| [VkExternalFormatOHOS](#vkexternalformatohos) | 表示外部定义的格式标识符。 | +| VkResult ([VKAPI_PTR *PFN_vkGetNativeBufferPropertiesOHOS](#pfn_vkgetnativebufferpropertiesohos)) (VkDevice device, const struct OH_NativeBuffer \*buffer, [VkNativeBufferPropertiesOHOS](_vk_native_buffer_properties_o_h_o_s.md) \*pProperties) | 获取OH_NativeBuffer属性的函数指针定义。 | +| VkResult ([VKAPI_PTR *PFN_vkGetMemoryNativeBufferOHOS](#pfn_vkgetmemorynativebufferohos)) (VkDevice device, const [VkMemoryGetNativeBufferInfoOHOS](_vk_memory_get_native_buffer_info_o_h_o_s.md) \*pInfo, struct OH_NativeBuffer \*\*pBuffer) | 获取OH_NativeBuffer的函数指针定义。 | + + +### 函数 + +| 名称 | 描述 | +| -------- | -------- | +| [vkCreateSurfaceOHOS](#vkcreatesurfaceohos) (VkInstance instance, const VkSurfaceCreateInfoOHOS \*pCreateInfo, const VkAllocationCallbacks \*pAllocator, VkSurfaceKHR \*pSurface) | 创建Vulkan Surface。 | +| [vkGetNativeBufferPropertiesOHOS](#vkgetnativebufferpropertiesohos) (VkDevice device, const struct OH_NativeBuffer \*buffer, VkNativeBufferPropertiesOHOS \*pProperties) | 获取OH_NativeBuffer属性。 | +| [vkGetMemoryNativeBufferOHOS](#vkgetmemorynativebufferohos) (VkDevice device, const VkMemoryGetNativeBufferInfoOHOS \*pInfo, struct OH_NativeBuffer \*\*pBuffer) | 获取OH_NativeBuffer。 | + + +### 变量 + +| 名称 | 描述 | +| -------- | -------- | +| [VkSurfaceCreateInfoOHOS::sType](#stype-17) | 结构体类型。 | +| [VkSurfaceCreateInfoOHOS::pNext](#pnext-17) | 下一级结构体指针。 | +| [VkSurfaceCreateInfoOHOS::flags](#flags) | 预留的标志类型参数。 | +| [VkSurfaceCreateInfoOHOS::window](#window) | OHNativeWindow指针。 | +| [VkNativeBufferUsageOHOS::sType](#stype-27) | 结构体类型。 | +| [VkNativeBufferUsageOHOS::pNext](#pnext-27) | 下一级结构体指针。 | +| [VkNativeBufferUsageOHOS::OHOSNativeBufferUsage](#ohosnativebufferusage) | NativeBuffer的用途说明。 | +| [VkNativeBufferPropertiesOHOS::sType](#stype-37) | 结构体类型。 | +| [VkNativeBufferPropertiesOHOS::pNext](#pnext-37) | 下一级结构体指针。 | +| [VkNativeBufferPropertiesOHOS::allocationSize](#allocationsize) | 占用的内存大小。 | +| [VkNativeBufferPropertiesOHOS::memoryTypeBits](#memorytypebits) | 内存类型。 | +| [VkNativeBufferFormatPropertiesOHOS::sType](#stype-47) | 结构体类型。 | +| [VkNativeBufferFormatPropertiesOHOS::pNext](#pnext-47) | 下一级结构体指针。 | +| [VkNativeBufferFormatPropertiesOHOS::format](#format) | 格式说明。 | +| [VkNativeBufferFormatPropertiesOHOS::externalFormat](#externalformat-12) | 外部定义的格式标识符。 | +| [VkNativeBufferFormatPropertiesOHOS::formatFeatures](#formatfeatures) | 描述了与externalFormat对应的能力。 | +| [VkNativeBufferFormatPropertiesOHOS::samplerYcbcrConversionComponents](#samplerycbcrconversioncomponents) | 表示一组VkComponentSwizzle。 | +| [VkNativeBufferFormatPropertiesOHOS::suggestedYcbcrModel](#suggestedycbcrmodel) | 色彩模型。 | +| [VkNativeBufferFormatPropertiesOHOS::suggestedYcbcrRange](#suggestedycbcrrange) | 色彩数值范围。 | +| [VkNativeBufferFormatPropertiesOHOS::suggestedXChromaOffset](#suggestedxchromaoffset) | X色度偏移。 | +| [VkNativeBufferFormatPropertiesOHOS::suggestedYChromaOffset](#suggestedychromaoffset) | Y色度偏移。 | +| [VkImportNativeBufferInfoOHOS::sType](#stype-57) | 结构体类型。 | +| [VkImportNativeBufferInfoOHOS::pNext](#pnext-57) | 下一级结构体指针。 | +| [VkImportNativeBufferInfoOHOS::buffer](#buffer) | OH_NativeBuffer结构体的指针。 | +| [VkMemoryGetNativeBufferInfoOHOS::sType](#stype-67) | 结构体类型。 | +| [VkMemoryGetNativeBufferInfoOHOS::pNext](#pnext-67) | 下一级结构体指针。 | +| [VkMemoryGetNativeBufferInfoOHOS::memory](#memory) | VkDeviceMemory对象。 | +| [VkExternalFormatOHOS::sType](#stype-77) | 结构体类型。 | +| [VkExternalFormatOHOS::pNext](#pnext-77) | 下一级结构体指针。 | +| [VkExternalFormatOHOS::externalFormat](#externalformat-22) | 外部定义的格式标识符。 | + + +## 宏定义说明 + + +### VK_OHOS_external_memory + + +``` +#define VK_OHOS_external_memory 1 +``` + +**描述:** + +OpenHarmony平台external_memory扩展宏定义。 + + +### VK_OHOS_EXTERNAL_MEMORY_EXTENSION_NAME + + +``` +#define VK_OHOS_EXTERNAL_MEMORY_EXTENSION_NAME "VK_OHOS_external_memory" +``` + +**描述:** + +OpenHarmony平台external_memory扩展名。 + + +### VK_OHOS_EXTERNAL_MEMORY_SPEC_VERSION + + +``` +#define VK_OHOS_EXTERNAL_MEMORY_SPEC_VERSION 1 +``` + +**描述:** + +OpenHarmony平台external_memory扩展版本号。 + + +### VK_OHOS_surface + + +``` +#define VK_OHOS_surface 1 +``` + +**描述:** + +OpenHarmony平台Surface扩展宏定义。 + + +### VK_OHOS_SURFACE_EXTENSION_NAME + + +``` +#define VK_OHOS_SURFACE_EXTENSION_NAME "VK_OHOS_surface" +``` + +**描述:** + +OpenHarmony平台Surface扩展名。 + + +### VK_OHOS_SURFACE_SPEC_VERSION + + +``` +#define VK_OHOS_SURFACE_SPEC_VERSION 1 +``` + +**描述:** + +OpenHarmony平台Surface扩展版本号。 + + +## 类型定义说明 + + +### OHNativeWindow + + +``` +typedef struct NativeWindow OHNativeWindow +``` + +**描述:** + +OH本地窗口。 + + +### PFN_vkCreateSurfaceOHOS + + +``` +typedef VkResult(VKAPI_PTR * PFN_vkCreateSurfaceOHOS) (VkInstance instance, const VkSurfaceCreateInfoOHOS *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkSurfaceKHR *pSurface) +``` + +**描述:** + +创建Vulkan Surface的函数指针定义。 + +\@syscap SystemCapability.Graphic.Vulkan + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| instance | Vulkan实例。 | +| pCreateInfo | 一个VkSurfaceCreateInfoOHOS结构体的指针,包含创建Vulkan Surface时必要的参数。 | +| pAllocator | 用户自定义内存分配的回调函数,如果不需要可以传入NULL,接口会使用默认的内存分配函数。 | +| pSurface | 出参,用于接收创建的Vulkan Surface,类型为VkSurfaceKHR。 | + +**返回:** + +返回一个VkResult类型的错误码,返回值为VK_SUCCESS表示执行成功。 + + +### PFN_vkGetMemoryNativeBufferOHOS + + +``` +typedef VkResult(VKAPI_PTR * PFN_vkGetMemoryNativeBufferOHOS) (VkDevice device, const VkMemoryGetNativeBufferInfoOHOS *pInfo, struct OH_NativeBuffer **pBuffer) +``` + +**描述:** + +获取OH_NativeBuffer的函数指针定义。 + +\@syscap SystemCapability.Graphic.Vulkan + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| device | VkDevice对象。 | +| pInfo | VkMemoryGetNativeBufferInfoOHOS结构体对象。 | +| pBuffer | 用于接收获取到的OH_NativeBuffer。 | + +**返回:** + +返回一个VkResult类型的错误码,返回值为VK_SUCCESS表示执行成功。 + + +### PFN_vkGetNativeBufferPropertiesOHOS + + +``` +typedef VkResult(VKAPI_PTR * PFN_vkGetNativeBufferPropertiesOHOS) (VkDevice device, const struct OH_NativeBuffer *buffer, VkNativeBufferPropertiesOHOS *pProperties) +``` + +**描述:** + +获取OH_NativeBuffer属性的函数指针定义。 + +\@syscap SystemCapability.Graphic.Vulkan + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| device | VkDevice对象。 | +| buffer | OH_NativeBuffer结构体指针。 | +| pProperties | 用于接收OH_NativeBuffer属性的结构体。 | + +**返回:** + +返回一个VkResult类型的错误码,返回值为VK_SUCCESS表示执行成功。 + + +### VkExternalFormatOHOS + + +``` +typedef struct VkExternalFormatOHOS VkExternalFormatOHOS +``` + +**描述:** + +表示外部定义的格式标识符。 + + +### VkImportNativeBufferInfoOHOS + + +``` +typedef struct VkImportNativeBufferInfoOHOS VkImportNativeBufferInfoOHOS +``` + +**描述:** + +包含了OH_NativeBuffer结构体的指针。 + + +### VkMemoryGetNativeBufferInfoOHOS + + +``` +typedef struct VkMemoryGetNativeBufferInfoOHOS VkMemoryGetNativeBufferInfoOHOS +``` + +**描述:** + +用于从Vulkan内存中获取OH_NativeBuffer。 + + +### VkNativeBufferFormatPropertiesOHOS + + +``` +typedef struct VkNativeBufferFormatPropertiesOHOS VkNativeBufferFormatPropertiesOHOS +``` + +**描述:** + +包含了NaitveBuffer的一些格式属性。 + + +### VkNativeBufferPropertiesOHOS + + +``` +typedef struct VkNativeBufferPropertiesOHOS VkNativeBufferPropertiesOHOS +``` + +**描述:** + +包含了NaitveBuffer的属性。 + + +### VkNativeBufferUsageOHOS + + +``` +typedef struct VkNativeBufferUsageOHOS VkNativeBufferUsageOHOS +``` + +**描述:** + +提供OpenHarmony NativeBuffer用途的说明。 + + +### VkSurfaceCreateFlagsOHOS + + +``` +typedef VkFlags VkSurfaceCreateFlagsOHOS +``` + +**描述:** + +用于Vulkan Surface创建时使用到的VkFlags类型位掩码,预留的标志类型。 + + +### VkSurfaceCreateInfoOHOS + + +``` +typedef struct VkSurfaceCreateInfoOHOS VkSurfaceCreateInfoOHOS +``` + +**描述:** + +包含创建Vulkan Surface时必要的参数。 + + +## 函数说明 + + +### vkCreateSurfaceOHOS() + + +``` +VKAPI_ATTR VkResult VKAPI_CALL vkCreateSurfaceOHOS (VkInstance instance, const VkSurfaceCreateInfoOHOS * pCreateInfo, const VkAllocationCallbacks * pAllocator, VkSurfaceKHR * pSurface ) +``` + +**描述:** + +创建Vulkan Surface。 + +\@syscap SystemCapability.Graphic.Vulkan + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| instance | Vulkan实例。 | +| pCreateInfo | 一个VkSurfaceCreateInfoOHOS结构体的指针,包含创建Vulkan Surface时必要的参数。 | +| pAllocator | 用户自定义内存分配的回调函数,如果不需要可以传入NULL,接口会使用默认的内存分配函数。 | +| pSurface | 出参,用于接收创建的Vulkan Surface,类型为VkSurfaceKHR。 | + +**返回:** + +返回一个VkResult类型的错误码,返回值为VK_SUCCESS表示执行成功。 + + +### vkGetMemoryNativeBufferOHOS() + + +``` +VKAPI_ATTR VkResult VKAPI_CALL vkGetMemoryNativeBufferOHOS (VkDevice device, const VkMemoryGetNativeBufferInfoOHOS * pInfo, struct OH_NativeBuffer ** pBuffer ) +``` + +**描述:** + +获取OH_NativeBuffer。 + +\@syscap SystemCapability.Graphic.Vulkan + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| device | VkDevice对象。 | +| pInfo | VkMemoryGetNativeBufferInfoOHOS结构体对象。 | +| pBuffer | 用于接收获取到的OH_NativeBuffer。 | + +**返回:** + +返回一个VkResult类型的错误码,返回值为VK_SUCCESS表示执行成功。 + + +### vkGetNativeBufferPropertiesOHOS() + + +``` +VKAPI_ATTR VkResult VKAPI_CALL vkGetNativeBufferPropertiesOHOS (VkDevice device, const struct OH_NativeBuffer * buffer, VkNativeBufferPropertiesOHOS * pProperties ) +``` + +**描述:** + +获取OH_NativeBuffer属性。 + +\@syscap SystemCapability.Graphic.Vulkan + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| device | VkDevice对象。 | +| buffer | OH_NativeBuffer结构体指针。 | +| pProperties | 用于接收OH_NativeBuffer属性的结构体。 | + +**返回:** + +返回一个VkResult类型的错误码,返回值为VK_SUCCESS表示执行成功。 + + +## 变量说明 + + +### allocationSize + + +``` +VkDeviceSize VkNativeBufferPropertiesOHOS::allocationSize +``` + +**描述:** + +占用的内存大小。 + + +### buffer + + +``` +struct OH_NativeBuffer* VkImportNativeBufferInfoOHOS::buffer +``` + +**描述:** + +OH_NativeBuffer结构体的指针。 + + +### externalFormat [1/2] + + +``` +uint64_t VkNativeBufferFormatPropertiesOHOS::externalFormat +``` + +**描述:** + +外部定义的格式标识符。 + + +### externalFormat [2/2] + + +``` +uint64_t VkExternalFormatOHOS::externalFormat +``` + +**描述:** + +外部定义的格式标识符。 + + +### flags + + +``` +VkSurfaceCreateFlagsOHOS VkSurfaceCreateInfoOHOS::flags +``` + +**描述:** + +预留的标志类型参数。 + + +### format + + +``` +VkFormat VkNativeBufferFormatPropertiesOHOS::format +``` + +**描述:** + +格式说明。 + + +### formatFeatures + + +``` +VkFormatFeatureFlags VkNativeBufferFormatPropertiesOHOS::formatFeatures +``` + +**描述:** + +描述了与externalFormat对应的能力。 + + +### memory + + +``` +VkDeviceMemory VkMemoryGetNativeBufferInfoOHOS::memory +``` + +**描述:** + +VkDeviceMemory对象。 + + +### memoryTypeBits + + +``` +uint32_t VkNativeBufferPropertiesOHOS::memoryTypeBits +``` + +**描述:** + +内存类型。 + + +### OHOSNativeBufferUsage + + +``` +uint64_t VkNativeBufferUsageOHOS::OHOSNativeBufferUsage +``` + +**描述:** + +NativeBuffer的用途说明。 + + +### pNext [1/7] + + +``` +const void* VkSurfaceCreateInfoOHOS::pNext +``` + +**描述:** + +下一级结构体指针。 + + +### pNext [2/7] + + +``` +void* VkNativeBufferUsageOHOS::pNext +``` + +**描述:** + +下一级结构体指针。 + + +### pNext [3/7] + + +``` +void* VkNativeBufferPropertiesOHOS::pNext +``` + +**描述:** + +下一级结构体指针。 + + +### pNext [4/7] + + +``` +void* VkNativeBufferFormatPropertiesOHOS::pNext +``` + +**描述:** + +下一级结构体指针。 + + +### pNext [5/7] + + +``` +const void* VkImportNativeBufferInfoOHOS::pNext +``` + +**描述:** + +下一级结构体指针。 + + +### pNext [6/7] + + +``` +const void* VkMemoryGetNativeBufferInfoOHOS::pNext +``` + +**描述:** + +下一级结构体指针。 + + +### pNext [7/7] + + +``` +void* VkExternalFormatOHOS::pNext +``` + +**描述:** + +下一级结构体指针。 + + +### samplerYcbcrConversionComponents + + +``` +VkComponentMapping VkNativeBufferFormatPropertiesOHOS::samplerYcbcrConversionComponents +``` + +**描述:** + +表示一组VkComponentSwizzle。 + + +### sType [1/7] + + +``` +VkStructureType VkSurfaceCreateInfoOHOS::sType +``` + +**描述:** + +结构体类型。 + + +### sType [2/7] + + +``` +VkStructureType VkNativeBufferUsageOHOS::sType +``` + +**描述:** + +结构体类型。 + + +### sType [3/7] + + +``` +VkStructureType VkNativeBufferPropertiesOHOS::sType +``` + +**描述:** + +结构体类型。 + + +### sType [4/7] + + +``` +VkStructureType VkNativeBufferFormatPropertiesOHOS::sType +``` + +**描述:** + +结构体类型。 + + +### sType [5/7] + + +``` +VkStructureType VkImportNativeBufferInfoOHOS::sType +``` + +**描述:** + +结构体类型。 + + +### sType [6/7] + + +``` +VkStructureType VkMemoryGetNativeBufferInfoOHOS::sType +``` + +**描述:** + +结构体类型。 + + +### sType [7/7] + + +``` +VkStructureType VkExternalFormatOHOS::sType +``` + +**描述:** + +结构体类型。 + + +### suggestedXChromaOffset + + +``` +VkChromaLocation VkNativeBufferFormatPropertiesOHOS::suggestedXChromaOffset +``` + +**描述:** + +X色度偏移。 + + +### suggestedYcbcrModel + + +``` +VkSamplerYcbcrModelConversion VkNativeBufferFormatPropertiesOHOS::suggestedYcbcrModel +``` + +**描述:** + +色彩模型。 + + +### suggestedYcbcrRange + + +``` +VkSamplerYcbcrRange VkNativeBufferFormatPropertiesOHOS::suggestedYcbcrRange +``` + +**描述:** + +色彩数值范围。 + + +### suggestedYChromaOffset + + +``` +VkChromaLocation VkNativeBufferFormatPropertiesOHOS::suggestedYChromaOffset +``` + +**描述:** + +Y色度偏移。 + + +### window + + +``` +OHNativeWindow* VkSurfaceCreateInfoOHOS::window +``` + +**描述:** + +OHNativeWindow指针。 diff --git a/zh-cn/application-dev/reference/native-apis/vulkan__ohos_8h.md b/zh-cn/application-dev/reference/native-apis/vulkan__ohos_8h.md new file mode 100644 index 0000000000000000000000000000000000000000..0a5414b122166d3a6d0ae98485d49a24b231c41c --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/vulkan__ohos_8h.md @@ -0,0 +1,69 @@ +# vulkan_ohos.h + + +## 概述 + +定义了OpenHarmony平台扩展的Vulkan接口。引用文件:<vulkan/vulkan.h>。 + +**起始版本:** + +10 + +**相关模块:** + +[Vulkan](_vulkan.md) + + +## 汇总 + + +### 结构体 + +| 名称 | 描述 | +| -------- | -------- | +| [VkSurfaceCreateInfoOHOS](_vk_surface_create_info_o_h_o_s.md) | 包含创建Vulkan Surface时必要的参数。 | +| [VkNativeBufferUsageOHOS](_vk_native_buffer_usage_o_h_o_s.md) | 提供OpenHarmony NativeBuffer用途的说明。 | +| [VkNativeBufferPropertiesOHOS](_vk_native_buffer_properties_o_h_o_s.md) | 包含了NaitveBuffer的属性。 | +| [VkNativeBufferFormatPropertiesOHOS](_vk_native_buffer_format_properties_o_h_o_s.md) | 包含了NaitveBuffer的一些格式属性。 | +| [VkImportNativeBufferInfoOHOS](_vk_import_native_buffer_info_o_h_o_s.md) | 包含了OH_NativeBuffer结构体的指针。 | +| [VkMemoryGetNativeBufferInfoOHOS](_vk_memory_get_native_buffer_info_o_h_o_s.md) | 用于从Vulkan内存中获取OH_NativeBuffer。 | +| [VkExternalFormatOHOS](_vk_external_format_o_h_o_s.md) | 表示外部定义的格式标识符。 | + + +### 宏定义 + +| 名称 | 描述 | +| -------- | -------- | +| [VK_OHOS_surface](_vulkan.md#vk_ohos_surface) 1 | OpenHarmony平台Surface扩展宏定义。 | +| [VK_OHOS_SURFACE_SPEC_VERSION](_vulkan.md#vk_ohos_surface_spec_version) 1 | OpenHarmony平台Surface扩展版本号。 | +| [VK_OHOS_SURFACE_EXTENSION_NAME](_vulkan.md#vk_ohos_surface_extension_name) "VK_OHOS_surface" | OpenHarmony平台Surface扩展名。 | +| [VK_OHOS_external_memory](_vulkan.md#vk_ohos_external_memory) 1 | OpenHarmony平台external_memory扩展宏定义。 | +| [VK_OHOS_EXTERNAL_MEMORY_SPEC_VERSION](_vulkan.md#vk_ohos_external_memory_spec_version) 1 | OpenHarmony平台external_memory扩展版本号。 | +| [VK_OHOS_EXTERNAL_MEMORY_EXTENSION_NAME](_vulkan.md#vk_ohos_external_memory_extension_name) "VK_OHOS_external_memory" | OpenHarmony平台external_memory扩展名。 | + + +### 类型定义 + +| 名称 | 描述 | +| -------- | -------- | +| [OHNativeWindow](_vulkan.md#ohnativewindow) | OH本地窗口。 | +| [VkSurfaceCreateFlagsOHOS](_vulkan.md#vksurfacecreateflagsohos) | 用于Vulkan Surface创建时使用到的VkFlags类型位掩码,预留的标志类型。 | +| [VkSurfaceCreateInfoOHOS](_vulkan.md#vksurfacecreateinfoohos) | 包含创建Vulkan Surface时必要的参数。 | +| VkResult ([VKAPI_PTR *PFN_vkCreateSurfaceOHOS](_vulkan.md#pfn_vkcreatesurfaceohos)) (VkInstance instance, const [VkSurfaceCreateInfoOHOS](_vk_surface_create_info_o_h_o_s.md) \*pCreateInfo, const VkAllocationCallbacks \*pAllocator, VkSurfaceKHR \*pSurface) | 创建Vulkan Surface的函数指针定义。 | +| [VkNativeBufferUsageOHOS](_vulkan.md#vknativebufferusageohos) | 提供OpenHarmony NativeBuffer用途的说明。 | +| [VkNativeBufferPropertiesOHOS](_vulkan.md#vknativebufferpropertiesohos) | 包含了NaitveBuffer的属性。 | +| [VkNativeBufferFormatPropertiesOHOS](_vulkan.md#vknativebufferformatpropertiesohos) | 包含了NaitveBuffer的一些格式属性。 | +| [VkImportNativeBufferInfoOHOS](_vulkan.md#vkimportnativebufferinfoohos) | 包含了OH_NativeBuffer结构体的指针。 | +| [VkMemoryGetNativeBufferInfoOHOS](_vulkan.md#vkmemorygetnativebufferinfoohos) | 用于从Vulkan内存中获取OH_NativeBuffer。 | +| [VkExternalFormatOHOS](_vulkan.md#vkexternalformatohos) | 表示外部定义的格式标识符。 | +| VkResult ([VKAPI_PTR *PFN_vkGetNativeBufferPropertiesOHOS](_vulkan.md#pfn_vkgetnativebufferpropertiesohos)) (VkDevice device, const struct OH_NativeBuffer \*buffer, [VkNativeBufferPropertiesOHOS](_vk_native_buffer_properties_o_h_o_s.md) \*pProperties) | 获取OH_NativeBuffer属性的函数指针定义。 | +| VkResult ([VKAPI_PTR *PFN_vkGetMemoryNativeBufferOHOS](_vulkan.md#pfn_vkgetmemorynativebufferohos)) (VkDevice device, const [VkMemoryGetNativeBufferInfoOHOS](_vk_memory_get_native_buffer_info_o_h_o_s.md) \*pInfo, struct OH_NativeBuffer \*\*pBuffer) | 获取OH_NativeBuffer的函数指针定义。 | + + +### 函数 + +| 名称 | 描述 | +| -------- | -------- | +| [vkCreateSurfaceOHOS](_vulkan.md#vkcreatesurfaceohos) (VkInstance instance, const [VkSurfaceCreateInfoOHOS](_vk_surface_create_info_o_h_o_s.md) \*pCreateInfo, const VkAllocationCallbacks \*pAllocator, VkSurfaceKHR \*pSurface) | 创建Vulkan Surface。 | +| [vkGetNativeBufferPropertiesOHOS](_vulkan.md#vkgetnativebufferpropertiesohos) (VkDevice device, const struct OH_NativeBuffer \*buffer, [VkNativeBufferPropertiesOHOS](_vk_native_buffer_properties_o_h_o_s.md) \*pProperties) | 获取OH_NativeBuffer属性。 | +| [vkGetMemoryNativeBufferOHOS](_vulkan.md#vkgetmemorynativebufferohos) (VkDevice device, const [VkMemoryGetNativeBufferInfoOHOS](_vk_memory_get_native_buffer_info_o_h_o_s.md) \*pInfo, struct OH_NativeBuffer \*\*pBuffer) | 获取OH_NativeBuffer。 | diff --git a/zh-cn/application-dev/reference/native-lib/third_party_napi/napi.md b/zh-cn/application-dev/reference/native-lib/third_party_napi/napi.md index afc5aa18d4d1c885670eebad2eafbce6e48b4d15..81ac5cf51a3b1316c0805bd29fbb9c8cf61e9edc 100644 --- a/zh-cn/application-dev/reference/native-lib/third_party_napi/napi.md +++ b/zh-cn/application-dev/reference/native-lib/third_party_napi/napi.md @@ -9,11 +9,9 @@ Node-API是用于封装JavaScript能力为Native插件的API,独立于底层Ja Node-API可以去除底层的JavaScript引擎的差异,提供一套稳定的接口。 -OpenHarmony的N-API组件对Node-API的接口进行了重新实现,底层对接了ArkJS等引擎。当前支持[Node-API](https://nodejs.org/docs/v14.9.0/api/n-api.html)标准库中的部分接口。 +OpenHarmony的N-API组件对Node-API的接口进行了重新实现,底层对接了ArkJS等引擎。当前支持Node-API标准库中的部分接口。 -## N-API组件扩展的符号列表 - -**标准库中导出的符号列表** +## N-API组件标准库中导出的符号列表 |符号类型|符号名|说明| | --- | --- | --- | @@ -146,4 +144,10 @@ OpenHarmony的N-API组件对Node-API的接口进行了重新实现,底层对 |FUNC|napi_object_seal|密封给定的对象。| |FUNC|napi_get_all_property_names|获取一个数组,其中包含此对象过滤后的属性名称。| |FUNC|napi_detach_arraybuffer|分离给定`ArrayBuffer`的底层数据。| -|FUNC|napi_is_detached_arraybuffe|判断给定的`ArrayBuffer`是否已被分离过。| +|FUNC|napi_is_detached_arraybuffer|判断给定的`ArrayBuffer`是否已被分离过。| + +## N-API组件扩展的符号列表 + +|符号类型|符号名|说明| +| --- | --- | --- | +|FUNC|napi_queue_async_work_with_qos|将异步工作对象加到队列,由底层根据传入的qos优先级去调度执行。| diff --git a/zh-cn/application-dev/security/permission-list.md b/zh-cn/application-dev/security/permission-list.md index 872d1a3f5f0e8973953af84c9f5ee2ff4b3af062..d53663e86573846fe913a2ab959a3235c1b38293 100644 --- a/zh-cn/application-dev/security/permission-list.md +++ b/zh-cn/application-dev/security/permission-list.md @@ -34,6 +34,16 @@ **ACL使能**:TRUE +## ohos.permission.ACCESS_BLUETOOTH + +允许应用接入蓝牙并使用蓝牙能力,例如配对、连接外围设备等。 + +**权限级别**:normal + +**授权方式**:user_grant + +**ACL使能**:FALSE + ## ohos.permission.INTERNET 允许使用Internet网络。 @@ -2148,6 +2158,26 @@ **ACL使能**:TRUE +## ohos.permission.CAPTURE_VOICE_DOWNLINK_AUDIO + +允许应用采集语音下行音频。 + +**权限级别**:system_basic + +**授权方式**:system_grant + +**ACL使能**:TRUE + +## ohos.permission.MANAGE_INTELLIGENT_VOICE + +允许应用访问智能语音服务接口。 + +**权限级别**: system_basic + +**授权方式**:system_grant + +**ACL使能**:TRUE + ## ohos.permission.INSTALL_ENTERPRISE_MDM_BUNDLE 允许在企业设备上安装企业MDM应用包。 diff --git a/zh-cn/application-dev/website.md b/zh-cn/application-dev/website.md index e7c7b4e44e112bcafc3ef160133aa58c556636b1..ee2def7baf812292edf5df6c979b8b601a8791f4 100644 --- a/zh-cn/application-dev/website.md +++ b/zh-cn/application-dev/website.md @@ -1096,7 +1096,7 @@ - [@ohos.enterprise.dateTimeManager (系统时间管理)](reference/apis/js-apis-enterprise-dateTimeManager.md) - [@ohos.enterprise.deviceControl (设备控制管理)](reference/apis/js-apis-enterprise-deviceControl.md) - [@ohos.enterprise.deviceInfo (设备信息管理)](reference/apis/js-apis-enterprise-deviceInfo.md) - - [@ohos.enterprise.deviceSettings (设备设置管理)](reference/apis/js-apis-enterprise-deviceSetings.md) + - [@ohos.enterprise.deviceSettings (设备设置管理)](reference/apis/js-apis-enterprise-deviceSettings.md) - [@ohos.enterprise.EnterpriseAdminExtensionAbility (企业设备管理扩展能力)](reference/apis/js-apis-EnterpriseAdminExtensionAbility.md) - [@ohos.enterprise.networkManager (网络管理)](reference/apis/js-apis-enterprise-networkManager.md) - [@ohos.enterprise.wifiManager (WiFi管理)](reference/apis/js-apis-enterprise-wifiManager.md) diff --git a/zh-cn/device-dev/Readme-CN.md b/zh-cn/device-dev/Readme-CN.md index 9cd7a0d6931579052033cd16a5a438281822120a..e5d6670cf77e16a64ad48817791d00b3f7c049f1 100644 --- a/zh-cn/device-dev/Readme-CN.md +++ b/zh-cn/device-dev/Readme-CN.md @@ -34,7 +34,6 @@ - [标准系统内核](kernel/kernel-standard-overview.md) - [驱动](driver/Readme-CN.md) - [编译构建](subsystems/subsys-build-all.md) - - [分布式远程启动](subsystems/subsys-remote-start.md) - [图形图像](subsystems/subsys-graphics-overview.md) - [媒体](subsystems/subsys-multimedia-camera-overview.md) - [公共基础](subsystems/subsys-utils-guide.md) diff --git a/zh-cn/device-dev/device-test/smartperf-host.md b/zh-cn/device-dev/device-test/smartperf-host.md index 0c02f2bb41a6ce9b96f77c79a6584ec669a813ee..847db0436f4ee0e8057f6dee216acdc6dba6fcfe 100644 --- a/zh-cn/device-dev/device-test/smartperf-host.md +++ b/zh-cn/device-dev/device-test/smartperf-host.md @@ -3,6 +3,7 @@ Smartperf-Host是一款深入挖掘数据、细粒度地展示数据的性能功耗调优工具,旨在为开发者提供一套性能调优平台,支持对CPU调度、频点、进程线程时间片、堆内存、帧率等数据进行采集和展示,展示方式为泳道图,支持GUI(图形用户界面)操作进行详细数据分析。 ## 架构图 ![系统架构图](figures/smartperf_frame.png) + 该组件整体分为设备端和PC端两部分,设备端和PC端基于gRPC(Remote Procedure Call)通信框架进行数据交互。 设备端内部分为应用程序内嵌组件、命令行工具、性能调优服务、性能调优插件集合、部分系统工具及部分系统内核等模块。设备端提供了插件扩展能力,对外提供了插件接口,基于该扩展能力可以按需定义自己的能力,并集成到框架中来,目前基于插件能力已经完成了native内存插件、trace插件等,详细介绍见[性能调优组件](https://gitee.com/openharmony/developtools_profiler)。 diff --git a/zh-cn/device-dev/device-test/xdevice.md b/zh-cn/device-dev/device-test/xdevice.md index 8f08fccebc1cef832feff16c0838992a91ef3791..9bdd6ffb7b123c4064103eddf7120ef21343d25b 100644 --- a/zh-cn/device-dev/device-test/xdevice.md +++ b/zh-cn/device-dev/device-test/xdevice.md @@ -46,7 +46,7 @@ environment环境相关配置,详解介绍如下。 - + @@ -63,7 +63,7 @@ environment环境相关配置,详解介绍如下。 - + @@ -75,7 +75,7 @@ environment环境相关配置,详解介绍如下。 - + @@ -383,7 +383,7 @@ run指令基本使用方法如下。 若AT命令串口和日志输出串口共用,可以配置为相同,即user_config中的type为cmd的com口与type为deploy的com口可配置为一样的端口,如COM18。 - ![L0-1](figures/L0-1.PNG) + ![轻量系统设备-1](figures/L0-1.PNG) user_config.xml的修改示例如下。 @@ -476,7 +476,7 @@ run指令基本使用方法如下。 type为cmd的com口对应板子上的AT命令串口,用于对设备发送指令,示例中配置为ChA(COM20)串口号。 - ![L0-1](figures/L0-1.PNG) + ![小型系统设备-1](figures/L0-1.PNG) ipcamera设备有两种连接方式,一种是本地串口连接,一种是通过局域网ip连接。 diff --git a/zh-cn/device-dev/driver/driver-peripherals-audio-des.md b/zh-cn/device-dev/driver/driver-peripherals-audio-des.md index b3ef6347a87331b81460c0c62694e323a40d551e..d3fe7f17380f9bb57d7499d029434e4398d6c039 100644 --- a/zh-cn/device-dev/driver/driver-peripherals-audio-des.md +++ b/zh-cn/device-dev/driver/driver-peripherals-audio-des.md @@ -11,7 +11,7 @@ ## Audio驱动框架介绍 -Audio驱动框架基于[HDF驱动框架](driver-hdf-overview.md)实现。Audio驱动架构组成: +Audio驱动框架基于[HDF驱动框架](driver-overview-foundation.md)实现。Audio驱动架构组成: ![](figures/Audio框架图.png) @@ -300,7 +300,7 @@ int32_t CodecDaiHwParams(const struct AudioCard *card, const struct AudioPcmHwPa #### Codec注册绑定到HDF -此处依赖HDF框架的驱动实现方式,具体流程可参考[HDF驱动框架](driver-hdf-overview.md)指导。 +此处依赖HDF框架的驱动实现方式,具体流程可参考[HDF驱动框架](driver-overview-foundation.md)指导。 填充g_codecDriverEntry结构体,moduleName与device_info.hcs中的moduleName匹配,实现Bind、Init、Release函数指针。 @@ -799,7 +799,7 @@ int32_t Tfa9879DaiHwParams(const struct AudioCard *card, const struct AudioPcmHw #### Codec注册绑定到HDF -此处依赖HDF框架的驱动实现方式,具体流程可参考[HDF驱动框架](driver-hdf-overview.md)。 +此处依赖HDF框架的驱动实现方式,具体流程可参考[HDF驱动框架](driver-overview-foundation.md)。 填充g_tfa9879DriverEntry结构体,moduleName与device_info.hcs中的moduleName匹配,实现Bind、Init、Release函数指针。 @@ -927,7 +927,7 @@ int32_t Hi3516DmaPointer(struct PlatformData *data, const enum AudioStreamType s #### Platform注册绑定到HDF -此处依赖HDF框架的驱动实现方式,具体流程可参考[HDF驱动框架](driver-hdf-overview.md)。 +此处依赖HDF框架的驱动实现方式,具体流程可参考[HDF驱动框架](driver-overview-foundation.md)。 - 填充g_platformDriverEntry结构体 - moduleName与device_info.hcs中的moduleName匹配 @@ -1091,7 +1091,7 @@ int32_t DaiStartup(const struct AudioCard *card, const struct DaiDevice *device) #### Dai注册绑定到HDF -此处依赖HDF框架的驱动实现方式,具体流程可参考[HDF驱动框架](driver-hdf-overview.md)。 +此处依赖HDF框架的驱动实现方式,具体流程可参考[HDF驱动框架](driver-overview-foundation.md)。 - 填充g_daiDriverEntry结构体 - moduleName与device_info.hcs中的moduleName匹配 diff --git a/zh-cn/device-dev/driver/driver-peripherals-light-des.md b/zh-cn/device-dev/driver/driver-peripherals-light-des.md index 6b36351d818e284a5117c92f8d083cd4add44cc6..4e95c7157d8ca181a09b3e1bf8268431129d5286 100644 --- a/zh-cn/device-dev/driver/driver-peripherals-light-des.md +++ b/zh-cn/device-dev/driver/driver-peripherals-light-des.md @@ -32,7 +32,7 @@ Light驱动模型为上层Light硬件服务层提供稳定的灯控制能力接 ### 场景介绍 -灯设备的控制,在实际生活中比比皆是,例如短信通知时闪灯、手机电量不足时预警、充电时根据充电进度变换灯的颜色等等。这些动作的实现,都需要使用Light驱动模型提供的接口,动态配置点灯模式、配置灯闪烁效果、点灯、熄灯等。 +灯设备的控制,在实际生活中比比皆是,例如短信通知时闪灯、终端电量不足时预警、充电时根据充电进度变换灯的颜色等等。这些动作的实现,都需要使用Light驱动模型提供的接口,动态配置点灯模式、配置灯闪烁效果、点灯、熄灯等。 ### 接口说明 diff --git a/zh-cn/device-dev/guide/device-camera-visual-prepare.md b/zh-cn/device-dev/guide/device-camera-visual-prepare.md index d9dce9afe76703bc0554c5f75ae705f26e35e943..898fad0b389c6dbf28d04bda7c876d2b72b9ac3e 100644 --- a/zh-cn/device-dev/guide/device-camera-visual-prepare.md +++ b/zh-cn/device-dev/guide/device-camera-visual-prepare.md @@ -10,18 +10,15 @@ ## 创建项目 1. 通过如下两种方式,打开工程创建向导界面。 - - 如果当前未打开任何工程,可以在DevEco Studio的欢迎页,选择**Create HarmonyOS Project**开始创建一个新工程。 - - 如果已经打开了工程,可以在菜单栏选择**File \> New \> New Project**来创建一个新工程。 + - 如果当前未打开任何工程,可以在DevEco Studio的欢迎页,选择**Create Project**开始创建一个新工程。 + - 如果已经打开了工程,可以在菜单栏选择**File \> New \> Create Project**来创建一个新工程。 -2. 选择“Smart Vision”下的“Empty Feature Ability”模板。 +2. 选择“Application”下的“Empty Ability”模板,点击**Next**。 ![](figures/empty-feature-ability.png) -3. 点击**Next**,进入到工程配置阶段,需要根据向导配置工程的基本信息。 - - **Project Name**:工程的名称,可以自定义。 - - **Package Name**:软件包名称,默认情况下,应用ID也会使用该名称,应用发布时,应用ID需要唯一。 - - **Save Location**:工程文件本地存储路径,存储路径中不能包含中文字符和空格。 - - **Compatible API Version**:兼容的SDK版本。 - -4. 点击**Finish**,工具会自动生成示例代码和相关资源,等待工程创建完成。 - +3. 填写工程相关信息,保持默认值即可,单击**Finish**。 + + 关于各个参数的详细介绍,请参考[《DevEco Studio使用指南》](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/create_new_project-0000001053342414-V3)。 + + 工程创建完成后,DevEco Studio会自动进行工程的同步。 diff --git a/zh-cn/device-dev/kernel/Readme-CN.md b/zh-cn/device-dev/kernel/Readme-CN.md index f43d4bf95505be7c75abf8748ecad4698d8ce9a0..ee6c4f01655e0b0fd13379abbc780bc46a2230ae 100755 --- a/zh-cn/device-dev/kernel/Readme-CN.md +++ b/zh-cn/device-dev/kernel/Readme-CN.md @@ -1,167 +1,166 @@ -# kernel +# 内核 -- 内核 - - [内核概述](kernel-overview.md) - - 轻量系统内核(LiteOS-M) - - [轻量系统内核概述](kernel-mini-overview.md) - - 基础内核 - - [中断管理](kernel-mini-basic-interrupt.md) - - [任务管理](kernel-mini-basic-task.md) - - [内存管理](kernel-mini-basic-memory.md) - - 内核通信机制 - - [事件](kernel-mini-basic-ipc-event.md) - - [互斥锁](kernel-mini-basic-ipc-mutex.md) - - [消息队列](kernel-mini-basic-ipc-queue.md) - - [信号量](kernel-mini-basic-ipc-sem.md) - - [时间管理](kernel-mini-basic-time.md) - - [软件定时器](kernel-mini-basic-soft.md) - - [双向链表](kernel-mini-basic-list.md) - - 扩展组件 - - [C++支持](kernel-mini-extend-support.md) - - [CPU占用率](kernel-mini-extend-cpup.md) - - [动态加载](kernel-mini-extend-dynamic-loading.md) - - [文件系统](kernel-mini-extend-file.md) - - 内核调测 - - [内存调测](kernel-mini-memory-debug.md) - - [异常调测](kernel-mini-memory-exception.md) - - [Trace调测](kernel-mini-memory-trace.md) - - [LMS调测](kernel-mini-memory-lms.md) - - [SHELL](kernel-mini-debug-shell.md) - - 附录 - - [内核编码规范](kernel-mini-appx-code.md) - - [标准库支持](kernel-mini-appx-lib.md) - - 小型系统内核(LiteOS-A) - - [小型系统内核概述](kernel-small-overview.md) - - 内核启动 - - [内核态启动](kernel-small-start-kernel.md) - - [用户态启动](kernel-small-start-user.md) - - 基础内核 - - [中断及异常处理](kernel-small-basic-interrupt.md) - - 进程管理 - - [进程](kernel-small-basic-process-process.md) - - [任务](kernel-small-basic-process-thread.md) - - [调度器](kernel-small-basic-process-scheduler.md) - - 内存管理 - - [堆内存管理](kernel-small-basic-memory-heap.md) - - [物理内存管理](kernel-small-basic-memory-physical.md) - - [虚拟内存管理](kernel-small-basic-memory-virtual.md) - - [虚实映射](kernel-small-basic-inner-reflect.md) - - 内核通信机制 - - [事件](kernel-small-basic-trans-event.md) - - [信号量](kernel-small-basic-trans-semaphore.md) - - [互斥锁](kernel-small-basic-trans-mutex.md) - - [消息队列](kernel-small-basic-trans-queue.md) - - [读写锁](kernel-small-basic-trans-rwlock.md) - - [用户态快速互斥锁](kernel-small-basic-trans-user-mutex.md) - - [信号](kernel-small-basic-trans-user-signal.md) - - [时间管理](kernel-small-basic-time.md) - - [软件定时器](kernel-small-basic-softtimer.md) - - [原子操作](kernel-small-basic-atomic.md) - - 扩展组件 - - [系统调用](kernel-small-bundles-system.md) - - [动态加载与链接](kernel-small-bundles-linking.md) - - [虚拟动态共享库](kernel-small-bundles-share.md) - - [轻量级进程间通信](kernel-small-bundles-ipc.md) - - [容器隔离](kernel-small-bundles-container.md) - - 文件系统 - - [虚拟文件系统](kernel-small-bundles-fs-virtual.md) - - [支持的文件系统](kernel-small-bundles-fs-support.md) - - [适配新的文件系统](kernel-small-bundles-fs-new.md) - - [Plimitsfs文件系统](kernel-small-plimits.md) - - 调测与工具 - - Shell - - [Shell介绍](kernel-small-debug-shell-overview.md) - - [Shell命令开发指导](kernel-small-debug-shell-guide.md) - - [Shell命令编程实例](kernel-small-debug-shell-build.md) - - Shell命令使用详解 - - 系统命令 - - [cpup](kernel-small-debug-shell-cmd-cpup.md) - - [date](kernel-small-debug-shell-cmd-date.md) - - [dmesg](kernel-small-debug-shell-cmd-dmesg.md) - - [exec](kernel-small-debug-shell-cmd-exec.md) - - [free](kernel-small-debug-shell-cmd-free.md) - - [help](kernel-small-debug-shell-cmd-help.md) - - [hwi](kernel-small-debug-shell-cmd-hwi.md) - - [kill](kernel-small-debug-shell-cmd-kill.md) - - [log](kernel-small-debug-shell-cmd-log.md) - - [memcheck](kernel-small-debug-shell-cmd-memcheck.md) - - [oom](kernel-small-debug-shell-cmd-oom.md) - - [pmm](kernel-small-debug-shell-cmd-pmm.md) - - [reset](kernel-small-debug-shell-cmd-reset.md) - - [sem](kernel-small-debug-shell-cmd-sem.md) - - [stack](kernel-small-debug-shell-cmd-stack.md) - - [su](kernel-small-debug-shell-cmd-su.md) - - [swtmr](kernel-small-debug-shell-cmd-swtmr.md) - - [systeminfo](kernel-small-debug-shell-cmd-sysinfo.md) - - [task](kernel-small-debug-shell-cmd-task.md) - - [uname](kernel-small-debug-shell-cmd-uname.md) - - [vmm](kernel-small-debug-shell-cmd-vmm.md) - - [watch](kernel-small-debug-shell-cmd-watch.md) - - [reboot](kernel-small-debug-shell-cmd-reboot.md) - - [top](kernel-small-debug-shell-cmd-top.md) - - 文件命令 - - [cat](kernel-small-debug-shell-file-cat.md) - - [cd](kernel-small-debug-shell-file-cd.md) - - [chgrp](kernel-small-debug-shell-file-chgrp.md) - - [chmod](kernel-small-debug-shell-file-chmod.md) - - [chown](kernel-small-debug-shell-file-chown.md) - - [cp](kernel-small-debug-shell-file-cp.md) - - [format](kernel-small-debug-shell-file-format.md) - - [ls](kernel-small-debug-shell-file-ls.md) - - [lsfd](kernel-small-debug-shell-file-lsfd.md) - - [mkdir](kernel-small-debug-shell-file-mkdir.md) - - [mount](kernel-small-debug-shell-file-mount.md) - - [partinfo](kernel-small-debug-shell-file-partinfo.md) - - [partition](kernel-small-debug-shell-file-partition.md) - - [pwd](kernel-small-debug-shell-file-pwd.md) - - [rm](kernel-small-debug-shell-file-rm.md) - - [rmdir](kernel-small-debug-shell-file-rmdir.md) - - [statfs](kernel-small-debug-shell-file-statfs.md) - - [sync](kernel-small-debug-shell-file-sync.md) - - [touch](kernel-small-debug-shell-file-touch.md) - - [writeproc](kernel-small-debug-shell-file-write.md) - - [umount](kernel-small-debug-shell-file-umount.md) - - [du](kernel-small-debug-shell-file-du.md) - - [mv](kernel-small-debug-shell-file-mv.md) - - 网络命令 - - [arp](kernel-small-debug-shell-net-arp.md) - - [dhclient](kernel-small-debug-shell-net-dhclient.md) - - [ifconfig](kernel-small-debug-shell-net-ifconfig.md) - - [ipdebug](kernel-small-debug-shell-net-ipdebug.md) - - [netstat](kernel-small-debug-shell-net-netstat.md) - - [ntpdate](kernel-small-debug-shell-net-ntpdate.md) - - [ping](kernel-small-debug-shell-net-ping.md) - - [ping6](kernel-small-debug-shell-net-ping6.md) - - [telnet](kernel-small-debug-shell-net-telnet.md) - - [tftp](kernel-small-debug-shell-net-tftp.md) - - [魔法键使用方法](kernel-small-debug-shell-magickey.md) - - [用户态异常信息说明](kernel-small-debug-shell-error.md) - - [Trace调测](kernel-small-debug-trace.md) - - [Perf调测](kernel-small-debug-perf.md) - - [LMS调测](kernel-small-memory-lms.md) - - [进程调测](kernel-small-debug-process-cpu.md) - - 内核态内存调测 - - [内存信息统计](kernel-small-debug-memory-info.md) - - [内存泄漏检测](kernel-small-debug-memory-leak.md) - - [踩内存检测](kernel-small-debug-memory-corrupt.md) - - [用户态内存调测](kernel-small-debug-user.md) - - 其他内核调测手段 - - [临终遗言](kernel-small-debug-trace-other-lastwords.md) - - [常见问题](kernel-small-debug-trace-other-faqs.md) - - 附录 - - 基本数据结构 - - [双向链表](kernel-small-apx-dll.md) - - [位操作](kernel-small-apx-bitwise.md) - - [标准库](kernel-small-apx-library.md) - - [内核编码规范](kernel-mini-appx-code.md) - - 标准系统内核(Linux) - - [标准系统内核概述](kernel-standard-overview.md) - - [OpenHarmony开发板Patch使用指导](kernel-standard-patch.md) - - [标准系统内核编译与构建指导](kernel-standard-build.md) - - [HCK内核解耦框架指导](kernel-standard-hck.md) - - 内核增强特性 - - [Enhanced SWAP特性介绍](kernel-standard-mm-eswap.md) - - [NewIP内核协议栈介绍](kernel-standard-newip.md) - - 任务调度 - - [关联线程组调度](kernel-standard-sched-rtg.md) - - [CPU轻量级隔离](kernel-standard-sched-cpuisolation.md) +- [内核概述](kernel-overview.md) +- 轻量系统内核(LiteOS-M) + - [轻量系统内核概述](kernel-mini-overview.md) + - 基础内核 + - [中断管理](kernel-mini-basic-interrupt.md) + - [任务管理](kernel-mini-basic-task.md) + - [内存管理](kernel-mini-basic-memory.md) + - 内核通信机制 + - [事件](kernel-mini-basic-ipc-event.md) + - [互斥锁](kernel-mini-basic-ipc-mutex.md) + - [消息队列](kernel-mini-basic-ipc-queue.md) + - [信号量](kernel-mini-basic-ipc-sem.md) + - [时间管理](kernel-mini-basic-time.md) + - [软件定时器](kernel-mini-basic-soft.md) + - [双向链表](kernel-mini-basic-list.md) + - 扩展组件 + - [C++支持](kernel-mini-extend-support.md) + - [CPU占用率](kernel-mini-extend-cpup.md) + - [动态加载](kernel-mini-extend-dynamic-loading.md) + - [文件系统](kernel-mini-extend-file.md) + - 内核调测 + - [内存调测](kernel-mini-memory-debug.md) + - [异常调测](kernel-mini-memory-exception.md) + - [Trace调测](kernel-mini-memory-trace.md) + - [LMS调测](kernel-mini-memory-lms.md) + - [SHELL](kernel-mini-debug-shell.md) + - 附录 + - [内核编码规范](kernel-mini-appx-code.md) + - [标准库支持](kernel-mini-appx-lib.md) +- 小型系统内核(LiteOS-A) + - [小型系统内核概述](kernel-small-overview.md) + - 内核启动 + - [内核态启动](kernel-small-start-kernel.md) + - [用户态启动](kernel-small-start-user.md) + - 基础内核 + - [中断及异常处理](kernel-small-basic-interrupt.md) + - 进程管理 + - [进程](kernel-small-basic-process-process.md) + - [任务](kernel-small-basic-process-thread.md) + - [调度器](kernel-small-basic-process-scheduler.md) + - 内存管理 + - [堆内存管理](kernel-small-basic-memory-heap.md) + - [物理内存管理](kernel-small-basic-memory-physical.md) + - [虚拟内存管理](kernel-small-basic-memory-virtual.md) + - [虚实映射](kernel-small-basic-inner-reflect.md) + - 内核通信机制 + - [事件](kernel-small-basic-trans-event.md) + - [信号量](kernel-small-basic-trans-semaphore.md) + - [互斥锁](kernel-small-basic-trans-mutex.md) + - [消息队列](kernel-small-basic-trans-queue.md) + - [读写锁](kernel-small-basic-trans-rwlock.md) + - [用户态快速互斥锁](kernel-small-basic-trans-user-mutex.md) + - [信号](kernel-small-basic-trans-user-signal.md) + - [时间管理](kernel-small-basic-time.md) + - [软件定时器](kernel-small-basic-softtimer.md) + - [原子操作](kernel-small-basic-atomic.md) + - 扩展组件 + - [系统调用](kernel-small-bundles-system.md) + - [动态加载与链接](kernel-small-bundles-linking.md) + - [虚拟动态共享库](kernel-small-bundles-share.md) + - [轻量级进程间通信](kernel-small-bundles-ipc.md) + - [容器隔离](kernel-small-bundles-container.md) + - 文件系统 + - [虚拟文件系统](kernel-small-bundles-fs-virtual.md) + - [支持的文件系统](kernel-small-bundles-fs-support.md) + - [适配新的文件系统](kernel-small-bundles-fs-new.md) + - [Plimitsfs文件系统](kernel-small-plimits.md) + - 调测与工具 + - Shell + - [Shell介绍](kernel-small-debug-shell-overview.md) + - [Shell命令开发指导](kernel-small-debug-shell-guide.md) + - [Shell命令编程实例](kernel-small-debug-shell-build.md) + - Shell命令使用详解 + - 系统命令 + - [cpup](kernel-small-debug-shell-cmd-cpup.md) + - [date](kernel-small-debug-shell-cmd-date.md) + - [dmesg](kernel-small-debug-shell-cmd-dmesg.md) + - [exec](kernel-small-debug-shell-cmd-exec.md) + - [free](kernel-small-debug-shell-cmd-free.md) + - [help](kernel-small-debug-shell-cmd-help.md) + - [hwi](kernel-small-debug-shell-cmd-hwi.md) + - [kill](kernel-small-debug-shell-cmd-kill.md) + - [log](kernel-small-debug-shell-cmd-log.md) + - [memcheck](kernel-small-debug-shell-cmd-memcheck.md) + - [oom](kernel-small-debug-shell-cmd-oom.md) + - [pmm](kernel-small-debug-shell-cmd-pmm.md) + - [reset](kernel-small-debug-shell-cmd-reset.md) + - [sem](kernel-small-debug-shell-cmd-sem.md) + - [stack](kernel-small-debug-shell-cmd-stack.md) + - [su](kernel-small-debug-shell-cmd-su.md) + - [swtmr](kernel-small-debug-shell-cmd-swtmr.md) + - [systeminfo](kernel-small-debug-shell-cmd-sysinfo.md) + - [task](kernel-small-debug-shell-cmd-task.md) + - [uname](kernel-small-debug-shell-cmd-uname.md) + - [vmm](kernel-small-debug-shell-cmd-vmm.md) + - [watch](kernel-small-debug-shell-cmd-watch.md) + - [reboot](kernel-small-debug-shell-cmd-reboot.md) + - [top](kernel-small-debug-shell-cmd-top.md) + - 文件命令 + - [cat](kernel-small-debug-shell-file-cat.md) + - [cd](kernel-small-debug-shell-file-cd.md) + - [chgrp](kernel-small-debug-shell-file-chgrp.md) + - [chmod](kernel-small-debug-shell-file-chmod.md) + - [chown](kernel-small-debug-shell-file-chown.md) + - [cp](kernel-small-debug-shell-file-cp.md) + - [format](kernel-small-debug-shell-file-format.md) + - [ls](kernel-small-debug-shell-file-ls.md) + - [lsfd](kernel-small-debug-shell-file-lsfd.md) + - [mkdir](kernel-small-debug-shell-file-mkdir.md) + - [mount](kernel-small-debug-shell-file-mount.md) + - [partinfo](kernel-small-debug-shell-file-partinfo.md) + - [partition](kernel-small-debug-shell-file-partition.md) + - [pwd](kernel-small-debug-shell-file-pwd.md) + - [rm](kernel-small-debug-shell-file-rm.md) + - [rmdir](kernel-small-debug-shell-file-rmdir.md) + - [statfs](kernel-small-debug-shell-file-statfs.md) + - [sync](kernel-small-debug-shell-file-sync.md) + - [touch](kernel-small-debug-shell-file-touch.md) + - [writeproc](kernel-small-debug-shell-file-write.md) + - [umount](kernel-small-debug-shell-file-umount.md) + - [du](kernel-small-debug-shell-file-du.md) + - [mv](kernel-small-debug-shell-file-mv.md) + - 网络命令 + - [arp](kernel-small-debug-shell-net-arp.md) + - [dhclient](kernel-small-debug-shell-net-dhclient.md) + - [ifconfig](kernel-small-debug-shell-net-ifconfig.md) + - [ipdebug](kernel-small-debug-shell-net-ipdebug.md) + - [netstat](kernel-small-debug-shell-net-netstat.md) + - [ntpdate](kernel-small-debug-shell-net-ntpdate.md) + - [ping](kernel-small-debug-shell-net-ping.md) + - [ping6](kernel-small-debug-shell-net-ping6.md) + - [telnet](kernel-small-debug-shell-net-telnet.md) + - [tftp](kernel-small-debug-shell-net-tftp.md) + - [魔法键使用方法](kernel-small-debug-shell-magickey.md) + - [用户态异常信息说明](kernel-small-debug-shell-error.md) + - [Trace调测](kernel-small-debug-trace.md) + - [Perf调测](kernel-small-debug-perf.md) + - [LMS调测](kernel-small-memory-lms.md) + - [进程调测](kernel-small-debug-process-cpu.md) + - 内核态内存调测 + - [内存信息统计](kernel-small-debug-memory-info.md) + - [内存泄漏检测](kernel-small-debug-memory-leak.md) + - [踩内存检测](kernel-small-debug-memory-corrupt.md) + - [用户态内存调测](kernel-small-debug-user.md) + - 其他内核调测手段 + - [临终遗言](kernel-small-debug-trace-other-lastwords.md) + - [常见问题](kernel-small-debug-trace-other-faqs.md) + - 附录 + - 基本数据结构 + - [双向链表](kernel-small-apx-dll.md) + - [位操作](kernel-small-apx-bitwise.md) + - [标准库](kernel-small-apx-library.md) + - [内核编码规范](kernel-mini-appx-code.md) +- 标准系统内核(Linux) + - [标准系统内核概述](kernel-standard-overview.md) + - [OpenHarmony开发板Patch使用指导](kernel-standard-patch.md) + - [标准系统内核编译与构建指导](kernel-standard-build.md) + - [HCK内核解耦框架指导](kernel-standard-hck.md) + - 内核增强特性 + - [Enhanced SWAP特性介绍](kernel-standard-mm-eswap.md) + - [NewIP内核协议栈介绍](kernel-standard-newip.md) + - 任务调度 + - [关联线程组调度](kernel-standard-sched-rtg.md) + - [CPU轻量级隔离](kernel-standard-sched-cpuisolation.md) diff --git a/zh-cn/device-dev/kernel/kernel-mini-memory-exception.md b/zh-cn/device-dev/kernel/kernel-mini-memory-exception.md index df848c5943caffd43d9e490dcbd5857383d2c2e2..ec89ec6b80c47e44ce527d4e76d47296214b53e8 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-memory-exception.md +++ b/zh-cn/device-dev/kernel/kernel-mini-memory-exception.md @@ -23,13 +23,14 @@ OpenHarmony LiteOS-M提供异常接管调测手段,帮助开发者定位分析 ## 接口说明 -OpenHarmony LiteOS-M内核的回溯栈模块提供下面几种功能,接口详细信息可以查看API参考。 +OpenHarmony LiteOS-M内核的回溯栈模块提供以下接口,接口详细信息可以查看API参考。 **表1** 回溯栈模块接口 -| 功能分类 | 接口名 | +| 接口名 | 功能 | | -------- | -------- | -| 回溯栈接口 | LOS_BackTrace:打印调用处的函数调用栈关系。
LOS_RecordLR:在无法打印的场景,用该接口获取调用处的函数调用栈关系。 | +| LOS_BackTrace | 打印调用处的函数调用栈关系。| +| LOS_RecordLR | 在无法打印的场景,用该接口获取调用处的函数调用栈关系。| ## 使用指导 @@ -40,16 +41,19 @@ OpenHarmony LiteOS-M内核的回溯栈模块提供下面几种功能,接口详 开启异常调测的典型流程如下: 1. 配置异常接管相关宏。 - 需要在target_config.h头文件中修改配置: - | 配置项 | 含义 | 设置值 | + + 需要在target_config.h头文件中修改配置: + + | 配置项 | 含义 | 设置值 | | -------- | -------- | -------- | | LOSCFG_BACKTRACE_DEPTH | 函数调用栈深度,默认15层 | 15 | | LOSCFG_BACKTRACE_TYPE | 回溯栈类型:
0:表示关闭该功能;
1:表示支持Cortex-m系列硬件的函数调用栈解析;
2:表示用于Risc-v系列硬件的函数调用栈解析; | 根据工具链类型设置1或2 | -1. 使用示例中有问题的代码,编译、运行工程,在串口终端中查看异常信息输出。示例代码模拟异常代码,实际产品开发时使用异常调测机制定位异常问题。 - 本示例演示异常输出,包含1个任务,该任务入口函数模拟若干函数调用,最终调用一个模拟异常的函数。代码实现如下: +2. 使用示例中有问题的代码,编译、运行工程,在串口终端中查看异常信息输出。示例代码模拟异常代码,实际产品开发时使用异常调测机制定位异常问题。 + + 本示例演示异常输出,包含1个任务,该任务入口函数模拟若干函数调用,最终调用一个模拟异常的函数。代码实现如下: - 本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleExcEntry。 + 本演示代码在`./kernel/liteos_m/testsuites/src/osTest.c`中编译验证,在TestTaskEntry中调用验证入口函数ExampleExcEntry。 ``` #include @@ -210,17 +214,17 @@ OpenHarmony LiteOS-M内核的回溯栈模块提供下面几种功能,接口详 异常接管一般的定位步骤如下: -0. 确认编译时关掉优化选项,否则下述的描述内容可能被优化掉。 +1. 确认编译时关掉优化选项,否则下述的描述内容可能被优化掉。 -1. 打开编译后生成的镜像反汇编(asm)文件。如果默认没有生成,可以使用objdump工具生成,命令为: +2. 打开编译后生成的镜像反汇编(asm)文件。如果默认没有生成,可以使用objdump工具生成,命令为: ``` - arm-none-eabi-objdump -S -l XXX.elf + arm-none-eabi-objdump -S -l XXX.elf ``` -1. 搜索PC指针(指向当前正在执行的指令)在asm中的位置,找到发生异常的函数。 - PC地址指向发生异常时程序正在执行的指令。在当前执行的二进制文件对应的asm文件中,查找PC值0x2101c61a,找到当前CPU正在执行的指令行,反汇编如下所示: +3. 搜索PC指针(指向当前正在执行的指令)在asm中的位置,找到发生异常的函数。 + PC地址指向发生异常时程序正在执行的指令。在当前执行的二进制文件对应的asm文件中,查找PC值0x2101c61a,找到当前CPU正在执行的指令行,反汇编如下所示: ``` 2101c60c : @@ -243,14 +247,14 @@ OpenHarmony LiteOS-M内核的回溯栈模块提供下面几种功能,接口详 2101c630: 21025f90 .word 0x21025f90 ``` -1. 可以看到: - 1. 异常时CPU正在执行的指令是ldr r3, [r3, #0],其中r3取值为0xffffffff,导致发生非法地址异常。 +4. 可以看到: + 1. 异常时CPU正在执行的指令是ldr r3, [r3, #0],其中r3取值为0xffffffff,导致发生非法地址异常。 2. 异常发生在函数GetResultException0中。 -2. 根据LR值查找异常函数的父函数。 +5. 根据LR值查找异常函数的父函数。 + 包含LR值0x2101c64d的反汇编如下所示: - ``` 2101c634 : 2101c634: b580 push {r7, lr} @@ -272,6 +276,6 @@ OpenHarmony LiteOS-M内核的回溯栈模块提供下面几种功能,接口详 2101c658: 21025fb0 .word 0x21025fb0 ``` -1. LR值2101c648上一行是bl 2101c60c ,此处调用了异常函数,调用异常函数的父函数为GetResultException1。 -2. 重复步骤3,解析异常信息中backtrace start至backtrace end之间的LR值,得到调用产生异常的函数调用栈关系,找到异常原因。 +7. 重复步骤3,解析异常信息中backtrace start至backtrace end之间的LR值,得到调用产生异常的函数调用栈关系,找到异常原因。 diff --git a/zh-cn/device-dev/kernel/kernel-overview.md b/zh-cn/device-dev/kernel/kernel-overview.md index 66b00c70b82c0d51e39776e120889629f0d3cadd..d2aad66886961b8ea2d268da4a9a0af270656fa5 100644 --- a/zh-cn/device-dev/kernel/kernel-overview.md +++ b/zh-cn/device-dev/kernel/kernel-overview.md @@ -27,7 +27,7 @@ - 负责本机操作系统和另外一个设备上操作系统通信的“网络”。 -OpenHarmony采用了多内核结构,支持Linux和LiteOS,开发者可按不同产品规格进行选择使用。linux和LiteOS均具备上述组成单元,只是实现方式有所不同。多个内核通过KAL(Kernel Abstraction Layer)模块,向上提供统一的标准接口。 +OpenHarmony采用了多内核结构,支持Linux和LiteOS,开发者可按不同产品规格进行选择使用。Linux和LiteOS均具备上述组成单元,只是实现方式有所不同。多个内核通过KAL(Kernel Abstraction Layer)模块,向上提供统一的标准接口。 内核子系统位于OpenHarmony下层。需要特别注意的是,由于OpenHarmony面向多种设备类型,这些设备有着不同的CPU能力,存储大小等。为了更好的适配这些不同的设备类型,内核子系统支持针对不同资源等级的设备选用适合的OS内核,内核抽象层(KAL,Kernel Abstract Layer)通过屏蔽内核间差异,对上层提供基础的内核能力。 diff --git a/zh-cn/device-dev/porting/porting-asr582x-combo-demo.md b/zh-cn/device-dev/porting/porting-asr582x-combo-demo.md index 94d215fb8b801cb89a358cede38fd47b101a9924..fcd91fc40a544a3d085c1df669a171bf9e22f3a4 100755 --- a/zh-cn/device-dev/porting/porting-asr582x-combo-demo.md +++ b/zh-cn/device-dev/porting/porting-asr582x-combo-demo.md @@ -693,9 +693,13 @@ dsoftbus组件的运行需至少预留80KB RAM。如资源不够,可对其它 在communication_dsoftbus仓中,加入了-fPIC编译选项,这样会让编译器产生与位置无关代码,并使用相对地址,但是在LiteOS-M核中使用的是静态库,不推荐使用。 建议开发者手动注释-fPIC编译选项,后续会推进OpenHarmony统一规划此编译选项的开关。修改方法是在如下的四个文件中,找到"-fPIC"选项,并全部注释: + `//foundation/communication/dsoftbus/core/common/BUILD.gn` + `//foundation/communication/dsoftbus/core/frame/BUILD.gn` + `//foundation/communication/dsoftbus/sdk/BUILD.gn` + `//foundation/communication/dsoftbus/components/nstackx_mini/nstackx_ctrl/BUILD.gn` 软总线的组网需要通过设备认证,在研发阶段,可以把认证跳过,先行调试组网以及传输能力,需将文件`//foundation/communication/dsoftbus/core/authentication/src/auth_manager.c`中的HandleReceiveDeviceId函数替换为如下实现: diff --git a/zh-cn/device-dev/porting/porting-smallchip-driver-plat.md b/zh-cn/device-dev/porting/porting-smallchip-driver-plat.md index 5ba5c7ed9d3ccf8b8482cee0319a6037546cfa25..a002077a26205777f0f8dd6702a0ae158b74b82f 100644 --- a/zh-cn/device-dev/porting/porting-smallchip-driver-plat.md +++ b/zh-cn/device-dev/porting/porting-smallchip-driver-plat.md @@ -1,13 +1,11 @@ # 平台驱动移植 -在这一步,我们会在源码目录//device/vendor_name/soc_name/drivers 目录下创建平台驱动,如果你要移植的SOC的厂商还没有创建仓库的话,请联系[sig_devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard_cn.md)创建。 +在这一步,我们会在源码目录`//device/vendor_name/soc_name/drivers`目录下创建平台驱动,如果你要移植的SOC的厂商还没有创建仓库的话,请联系[sig_devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard_cn.md)创建。 建议的目录结构: - - ``` device ├── vendor_name @@ -33,17 +31,15 @@ device │ ├── board_name ``` - - -HDF为所有的平台驱动都创建了驱动模型,移植平台驱动的主要工作是向模型注入实例。 这些模型你可以在源码目录//drivers/framework/support/platform/include中找到定义。 +HDF为所有的平台驱动都创建了驱动模型,移植平台驱动的主要工作是向模型注入实例。 这些模型你可以在源码目录`//drivers/hdf_core/framework/support/platform/include`中找到定义。 本节我们会以GPIO为例,讲解如何移植平台驱动,移植过程包含以下步骤: 1. 创建GPIO驱动 - 在源码目录//device/vendor_name/soc_name/drivers/gpio中创建文件soc_name_gpio.c 内容模板如下: + 在源码目录`//device/vendor_name/soc_name/drivers/gpio`中创建文件`soc_name_gpio.c`。内容模板如下: ``` #include "gpio_core.h" @@ -92,7 +88,8 @@ HDF为所有的平台驱动都创建了驱动模型,移植平台驱动的主 ``` 2. 创建厂商驱动构建入口 - 如前所述device/vendor_name/drivers/lite.mk是厂商驱动的构建的入口。我们需要从这个入口开始,进行构建 + + 如前所述`device/vendor_name/drivers/lite.mk`是厂商驱动的构建的入口。我们需要从这个入口开始,进行构建。 ``` @@ -147,7 +144,8 @@ HDF为所有的平台驱动都创建了驱动模型,移植平台驱动的主 ``` 5. 配置产品加载驱动 - 产品的所有设备信息被定义在源码文件//vendor/vendor_name/product_name/config/device_info/device_info.hcs中。 + + 产品的所有设备信息被定义在源码文件`//vendor/vendor_name/product_name/config/device_info/device_info.hcs`中。 平台驱动请添加到platform的host中。 diff --git a/zh-cn/device-dev/porting/porting-stm32mp15xx-on-smallsystem.md b/zh-cn/device-dev/porting/porting-stm32mp15xx-on-smallsystem.md index 0f12d0219895c462dfabf80211a3d80d0f19e575..3738ab388e81d4ba8129afa5dee32522326ea865 100644 --- a/zh-cn/device-dev/porting/porting-stm32mp15xx-on-smallsystem.md +++ b/zh-cn/device-dev/porting/porting-stm32mp15xx-on-smallsystem.md @@ -547,13 +547,13 @@ vendor `graphic`配置文件见 `//vendor/bearpi/bearpi_hm_micro/graphic_config/product_graphic_lite_config.h`。 -#### ACE开发框架子系统适配 +#### ArkUI开发框架子系统适配 -进行`ACE`开发框架子系统适配需要添加`ace_engine_lite`部件,直接在`config.json`配置即可。 +进行ArkUI开发框架子系统适配需要添加`ace_engine_lite`部件,直接在`config.json`配置即可。 ``` { - "subsystem": "ace", + "subsystem": "arkui", "components": [ { "component": "ace_engine_lite", diff --git a/zh-cn/device-dev/quick-start/quickstart-pkg-3516-burn.md b/zh-cn/device-dev/quick-start/quickstart-pkg-3516-burn.md index 130f18d0703c39bdd6e1bffbc26161d2f9c0faef..2d0b1f2620af9be878813bda7ce10d5b30a4d7d5 100644 --- a/zh-cn/device-dev/quick-start/quickstart-pkg-3516-burn.md +++ b/zh-cn/device-dev/quick-start/quickstart-pkg-3516-burn.md @@ -22,9 +22,7 @@ 1. 准备烧录相关文件。 1. 在客户端新建用于保存烧录文件的文件夹,例如“D:\liteos”或“D:\linux”。 2. 将烧录所需烧写配置文件和启动引导文件保存到新建的文件夹中。 - - 其L1_LiteOS烧写配置文件为L1_3516_liteos.xml,其启动引导文件为“[u-boot-hi3516dv300.bin](https://gitee.com/openharmony/device_board_hisilicon/tree/master/hispark_taurus/uboot/out/boot)”。 - 其中L1_3516_liteos.xml文件需要开发者自行准备,模板如下: - + - Hi3516DV300对应的LiteOS内核小型系统的启动引导文件为“[u-boot-hi3516dv300.bin](https://gitee.com/openharmony/device_board_hisilicon/tree/master/hispark_taurus/uboot/out/boot)”,烧写配置文件需要开发者自行准备(可自行命名,例如LS_3516_liteos.xml),模板如下: ``` @@ -35,9 +33,7 @@ ``` - - 其L1_Linux烧写配置文件为L1_3516_linux.xml,其启动引导文件为“[u-boot-hi3516dv300.bin](https://gitee.com/openharmony/device_board_hisilicon/tree/master/hispark_taurus/uboot/out/boot)”。 - 其中L1_3516_linux.xml文件需要开发者自行准备,模板如下: - + - Hi3516DV300对应的Linux内核小型系统的启动引导文件为“[u-boot-hi3516dv300.bin](https://gitee.com/openharmony/device_board_hisilicon/tree/master/hispark_taurus/uboot/out/boot)”,烧写配置文件需要开发者自行准备(可自行命名,例如LS_3516_linux.xml),模板如下 ``` @@ -51,17 +47,17 @@ ``` 3. 将编译完成的源码包下载至客户端并解压,将烧录相关文件拷贝至步骤1中新建的文件夹。 - 针对Hi3516开发板(轻量级系统使用LiteOS内核或Linux内核根据业务实际需要选择): + 针对Hi3516DV300开发板(系统使用LiteOS内核或Linux内核根据业务实际需要选择): - - 其L1_LiteOS烧写所需文件为:OHOS_Image.bin、rootfs_vfat.img、userfs_vfat.img - - 其L1_Linux烧写所需文件为:uImage_hi3516dv300_smp、rootfs_ext4.img、userfs_ext4.img、userdata_ext4.img + - LiteOS内核小型系统对应的烧写所需文件为:OHOS_Image.bin、rootfs_vfat.img、userfs_vfat.img + - Linux内核小型系统对应的烧写所需文件为:uImage_hi3516dv300_smp、rootfs_ext4.img、userfs_ext4.img、userdata_ext4.img 2. 使用HiTool烧录。 1. 打开HiTool。 2. 设置HiTool参数。 传输方式选择USB口,烧写方式选择烧写eMMC(单板的存储介质为eMMC)。 - 3. 单击浏览在步骤1创建的文件夹中选择烧写配置文件(例如L1_3516_linux.xml)。 + 3. 单击浏览在步骤1创建的文件夹中选择烧写配置文件(例如LS_3516_linux.xml)。 ![zh-cn_image_0000001249937195](figures/zh-cn_image_0000001249937195.png) 4. 单击烧写后,按住开发板上串口旁的按钮(Update键),并拔插USB线(上下电)。 @@ -77,7 +73,7 @@ 终端界面中出现“hisilicon \#”表示已连接开发板串口。 3. 在串口终端拷贝如下启动参数后,按回车完成配置。 - - 其L1_LiteOS对应的启动参数为: + - LiteOS内核小型系统对应的启动参数为: ``` setenv bootcmd "mmc read 0x0 0x80000000 0x800 0x4800;go 0x80000000"; @@ -85,7 +81,7 @@ saveenv sa;reset ``` - - 其L1_Linux对应的启动参数为: + - Linux内核小型系统对应的启动参数为: ``` setenv bootargs "mem=128M console=ttyAMA0,115200 root=/dev/mmcblk0p3 rw rootfstype=ext4 rootwait blkdevparts=mmcblk0:1M(boot),9M(kernel),50M(rootfs),50M(userfs),1024M(userdata)" diff --git a/zh-cn/device-dev/security/Readme-CN.md b/zh-cn/device-dev/security/Readme-CN.md index 4f87493a19db4014a20481e3151f8798e5cde7eb..872516a875ae98c1ff75ac048c199a9e0e6d69f7 100755 --- a/zh-cn/device-dev/security/Readme-CN.md +++ b/zh-cn/device-dev/security/Readme-CN.md @@ -1,7 +1,7 @@ -# security +# 隐私与安全 -- 隐私与安全 - - [隐私保护](security-privacy-protection.md) - - [安全指南](security-guidelines-overall.md) +- [隐私保护](security-privacy-protection.md) + +- [安全指南](security-guidelines-overall.md) diff --git a/zh-cn/device-dev/subsystems/Readme-CN.md b/zh-cn/device-dev/subsystems/Readme-CN.md index 590c7695a25ff6eef47216f09a666b0c02aa02b0..527c9eeb152ffb9cc6a69b51f57e84d9ce0dfddf 100644 --- a/zh-cn/device-dev/subsystems/Readme-CN.md +++ b/zh-cn/device-dev/subsystems/Readme-CN.md @@ -1,4 +1,4 @@ -# subsystems +# 子系统开发 - 编译构建 - [编译构建指导](subsys-build-all.md) @@ -24,7 +24,6 @@ - [Cargo2gn工具操作指导](subsys-build-cargo2gn-guide.md) - [ 常见问题](subsys-build-FAQ.md) - [ArkCompiler](subsys-arkcompiler-guide.md) -- [分布式远程启动](subsys-remote-start.md) - 小型系统图形图像 - [小型系统图形图像概述](subsys-graphics-overview.md) - [普通组件开发指导](subsys-graphics-common-guide.md) diff --git a/zh-cn/device-dev/subsystems/subsys-application-framework-guide.md b/zh-cn/device-dev/subsystems/subsys-application-framework-guide.md index 94a70866aa4a6b1d91fe20925a3abc1e6101afbe..528f5558c1553e68f333161f7d65521dc8f46d7d 100644 --- a/zh-cn/device-dev/subsystems/subsys-application-framework-guide.md +++ b/zh-cn/device-dev/subsystems/subsys-application-framework-guide.md @@ -111,11 +111,14 @@ } ``` -3. 实现Service相关的生命周期方法。Service也是一种Ability,Ability为服务提供了以下生命周期方法,用户可以重写这些方法来添加自己的处理。用户在重写的方法里,需要调用父类对应的方法。 - - OnStart() - 该方法在创建Service的时候调用,用于做一些Service初始化且耗时较短的工作,在Service的整个生命周期只会调用一次。 +3. 实现Service相关的生命周期方法。 - + Service也是一种Ability,Ability为服务提供了以下生命周期方法,用户可以重写这些方法来添加自己的处理。用户在重写的方法里,需要调用父类对应的方法。 + + - OnStart() + + 该方法在创建Service的时候调用,用于做一些Service初始化且耗时较短的工作,在Service的整个生命周期只会调用一次。 + ``` void MyServiceAbility::OnStart(const Want& want) { @@ -124,8 +127,8 @@ } ``` - OnConnect​() - 在组件和服务连接时调用,该方法返回SvcIdentity,组件可以通过它与服务交互。 - + + 在组件和服务连接时调用,该方法返回SvcIdentity,组件可以通过它与服务交互。 ``` const SvcIdentity *MyServiceAbility::OnConnect(const Want &want) @@ -135,14 +138,17 @@ } ``` - OnDisconnect​() - 在组件与绑定的Service断开连接时调用。 + + 在组件与绑定的Service断开连接时调用。 + - OnStop() - 在Service销毁时调用。Service应通过实现此方法来清理任何资源,如关闭线程、注册的侦听器等。 + + 在Service销毁时调用。Service应通过实现此方法来清理任何资源,如关闭线程、注册的侦听器等。 4. 重写消息处理方法。 - MsgHandle是Service用来处理客户端消息的方法。其中funcId是客户端传过来的消息类型,request是客户端传过来的序列化请求参数。如果用户在处理完成之后想要把结果传回去,需要把结果序列化后写入reply中。 - + MsgHandle是Service用来处理客户端消息的方法。其中funcId是客户端传过来的消息类型,request是客户端传过来的序列化请求参数。如果用户在处理完成之后想要把结果传回去,需要把结果序列化后写入reply中。 + ``` void ServiceAbility::MsgHandle(uint32_t funcId, IpcIo *request, IpcIo *reply) { @@ -157,6 +163,7 @@ ``` 5. 注册Service。 + Service也需要在应用清单文件config.json中进行注册,注册类型type需要设置为service。 @@ -173,8 +180,10 @@ ``` 6. 启动Service。 + - Ability为用户提供了StartAbility()方法来启动另外一个Ability,因为Service也是Ability的一种,开发者同样可以通过将Want传递给该方法来启动Service。 - 开发者可以通过Want的SetWantElement ()来设置目标服务信息。ElementName结构体的两个主要参数:第一个参数为包名称;第二个参数为目标Ability。 + + 开发者可以通过Want的SetWantElement ()来设置目标服务信息。ElementName结构体的两个主要参数:第一个参数为包名称;第二个参数为目标Ability。 ``` { @@ -191,10 +200,14 @@ StartAbility() 方法会立即执行,如果Service尚未运行,则系统首先会调用OnStart()。 - 停止Service。 - Service一旦创建就会一直保持在后台运行,开发者可以通过调用StopAbility()来停止Service。 + + Service一旦创建就会一直保持在后台运行,开发者可以通过调用StopAbility()来停止Service。 7. 连接Service。 - - 如果Service需要与Page Ability或其他应用组件中的Service进行交互,则应创建用于连接的Service。Service支持其他Ability通过ConnectAbility()与其进行连接,ConnectAbility()需要传入目标Service的Want,以及IAbilityConnection的实例来处理回调。IAbilityConnection提供了两个方法供用户实现,OnAbilityConnectDone()用来处理连接的回调,OnAbilityDisconnectDone()用来处理断开连接的回调。 + + - 如果Service需要与Page Ability或其他应用组件中的Service进行交互,则应创建用于连接的Service。 + + Service支持其他Ability通过ConnectAbility()与其进行连接,ConnectAbility()需要传入目标Service的Want,以及IAbilityConnection的实例来处理回调。IAbilityConnection提供了两个方法供用户实现,OnAbilityConnectDone()用来处理连接的回调,OnAbilityDisconnectDone()用来处理断开连接的回调。 ``` { @@ -264,12 +277,18 @@ 安装接口只能给内置的系统应用使用。根据应用的安装路径,可以在安装应用时进行选择: + - 将应用安装到系统默认的文件目录/storage/app/。 - 将应用安装到系统外挂的存储介质中,例如micro sdcard。 -这两种选择可以在创建InstallParam实例的时候指定,当InstallParam的成员变量installLocation为 INSTALL_LOCATION_INTERNAL_ONLY时,意味着应用将会被安装到/storage/app/目录下;当InstallParam的成员变量installLocation为INSTALL_LOCATION_PREFER_EXTERNAL时,意味着应用将被安装到存储介质,其安装目录是/sdcard/app/。由于安装应用的过程是异步的,所以需要使用类似信号量的机制来确保安装的回调可以被执行。 +这两种选择可以在创建InstallParam实例的时候指定, + +- 当InstallParam的成员变量installLocation为 INSTALL_LOCATION_INTERNAL_ONLY时,意味着应用将会被安装到/storage/app/目录下。 +- 当InstallParam的成员变量installLocation为INSTALL_LOCATION_PREFER_EXTERNAL时,意味着应用将被安装到存储介质,其安装目录是/sdcard/app/。 + +由于安装应用的过程是异步的,所以需要使用类似信号量的机制来确保安装的回调可以被执行。 安装应用的步骤如下(示例代码以安装到系统目录为例): @@ -384,8 +403,10 @@ 打包工具一般集成到开发工具或者IDE中,开发者一般不涉及直接使用该工具,下面的介绍开发者可以作为了解。打包工具的jar包在开源代码中的位置:developtools/packing_tool/jar。 + - 打包命令行参数 - **表2** 打包所需要的资源文件描述 + + **表2** 打包所需要的资源文件描述 | 命令参数 | 对应的资源文件 | 说明 | 是否可缺省 | | -------- | -------- | -------- | -------- | diff --git a/zh-cn/device-dev/subsystems/subsys-boot-init-deviceInfo.md b/zh-cn/device-dev/subsystems/subsys-boot-init-deviceInfo.md index 8fbaac350ee73750bc2dba8ed5f85336354f3166..5c57a90b23c64d46ec5cecd8565c0dc89efa15d0 100644 --- a/zh-cn/device-dev/subsystems/subsys-boot-init-deviceInfo.md +++ b/zh-cn/device-dev/subsystems/subsys-boot-init-deviceInfo.md @@ -35,7 +35,7 @@ - 适配说明: - OHOS 固定值参数由OHOS系统填充,厂商不能也不需适配,目前这部分参数主要定义在/base/startup/init/services/etc/param/ohos_const/ohos.para文件中。 + OHOS 固定值参数由OHOS系统填充,厂商不能也不需适配,目前这部分参数主要定义在`/base/startup/init/services/etc/param/ohos_const/ohos.para`文件中。 ### 厂商固定值参数的适配: @@ -63,18 +63,18 @@ 由各产品根据自身情况在vendor目录下适配。 - (1)L2以RK3568为例,在/vendor/hihope/rk3568/etc/para/hardware_rk3568.para中适配,并安装到指定目录。 + - 标准系统以RK3568为例,在`/vendor/hihope/rk3568/etc/para/hardware_rk3568.para`中适配,并安装到指定目录。 - ``` - ohos_prebuilt_etc("para_for_chip_prod") { - source = "./para/hardware_rk3568.para" - install_images = [ chip_prod_base_dir ] - relative_install_dir = "para" - part_name = "product_rk3568" - } - ``` + ``` + ohos_prebuilt_etc("para_for_chip_prod") { + source = "./para/hardware_rk3568.para" + install_images = [ chip_prod_base_dir ] + relative_install_dir = "para" + part_name = "product_rk3568" + } + ``` - (2)L0与L1 在产品对应的 hals/utils/sys_param/vendor.para文件中配置。例如: + - 轻量系统与小型系统在产品对应的`hals/utils/sys_param/vendor.para`文件中配置。例如: ``` const.product.manufacturer=Talkweb @@ -97,62 +97,63 @@ ### 厂商动态参数的适配 -- 厂商动态值参数,目前有三种获取形式:cmdline 读取,编译宏定义,在BUILD.gn中定义。 - - 1、cmdline 中读取的值有:ohos.boot.hardware, ohos.boot.bootslots, ohos.boot.sn等,其中ohos.boot.sn的获取略有不同,具体如下: - - (1)L2 Serial从参数ohos.boot.sn读取,ohos.boot.sn 参数值的获取方式:首先从cmdline (由uboot生成)获取,如果获取到的是sn值则直接读取,若获取的是文件路径,则从文件中读取;当获取不到时从默认的Sn文件读取,默认文件为:/sys/block/mmcblk0/device/cid;/proc/bootdevice/cid。 - - (2)L0 和 L1的 Serial各产品在实现过程中可能有自己特殊的算法,因此我们支持在hals/utils/sys_param目录下hal_sys_param.c文件中通过HalGetSerial()接口自定算法来获取Serial。 - - 2、编译宏定义的形式获取参数,目前主要在L0 和 L1中用到,例如: - - ``` - defines = [ - "INCREMENTAL_VERSION=\"${ohos_version}\"", - "BUILD_TYPE=\"${ohos_build_type}\"", - "BUILD_USER=\"${ohos_build_user}\"", - "BUILD_TIME=\"${ohos_build_time}\"", - "BUILD_HOST=\"${ohos_build_host}\"", - "BUILD_ROOTHASH=\"${ohos_build_roothash}\"", - ] - ``` - - 3、在BUILD.gn中定义,可参考文件/base/startup/init/services/etc/BUILD.gn,例如: - - ``` - if (target_cpu == "arm64") { - extra_paras += [ "const.product.cpu.abilist=arm64-v8a" ] - } - if (build_variant == "user") { - extra_paras += [ - "const.secure=1", - "const.debuggable=0", - ] - } else if (build_variant == "root") { - extra_paras += [ - "const.secure=0", - "const.debuggable=1", - ] - } - if (device_type != "default") { - extra_paras += [ - "const.product.devicetype=${device_type}", - "const.build.characteristics=${device_type}", - ] - } - module_install_dir = "etc/param" - } - ``` +厂商动态值参数,目前有三种获取形式:cmdline读取,编译宏定义,在BUILD.gn中定义。 + +1. cmdline中读取的值有:ohos.boot.hardware、ohos.boot.bootslots、ohos.boot.sn等,其中ohos.boot.sn的获取略有不同,具体如下: + + - 标准系统的Serial从参数ohos.boot.sn读取。 + + ohos.boot.sn参数值的获取方式:首先从cmdline(由uboot生成)获取,如果获取到的是sn值则直接读取,若获取的是文件路径,则从文件中读取;当获取不到时从默认的Sn文件读取,默认文件为:`/sys/block/mmcblk0/device/cid;/proc/bootdevice/cid`。 + + - 轻量系统与小型系统的Serial各产品在实现过程中可能有自己特殊的算法,因此OpenHarmony支持在`hals/utils/sys_param`目录下hal_sys_param.c文件中通过HalGetSerial()接口自定算法来获取Serial。 + +2. 编译宏定义的形式获取参数,目前主要在轻量系统与小型系统中用到,例如: + + ``` + defines = [ + "INCREMENTAL_VERSION=\"${ohos_version}\"", + "BUILD_TYPE=\"${ohos_build_type}\"", + "BUILD_USER=\"${ohos_build_user}\"", + "BUILD_TIME=\"${ohos_build_time}\"", + "BUILD_HOST=\"${ohos_build_host}\"", + "BUILD_ROOTHASH=\"${ohos_build_roothash}\"", + ] + ``` +3. 在BUILD.gn中定义,可参考文件`/base/startup/init/services/etc/BUILD.gn`,例如: + + ``` + if (target_cpu == "arm64") { + extra_paras += [ "const.product.cpu.abilist=arm64-v8a" ] + } + if (build_variant == "user") { + extra_paras += [ + "const.secure=1", + "const.debuggable=0", + ] + } else if (build_variant == "root") { + extra_paras += [ + "const.secure=0", + "const.debuggable=1", + ] + } + if (device_type != "default") { + extra_paras += [ + "const.product.devicetype=${device_type}", + "const.build.characteristics=${device_type}", + ] + } + module_install_dir = "etc/param" + + ``` #### 特别说明: - (1) L1的产品需要在hals/utils/sys_param/BUILD.gn中添加vendor.para的编译,具体如下: +1. 小型系统的产品需要在`hals/utils/sys_param/BUILD.gn`中添加vendor.para的编译,具体如下: - ``` - copy("vendor.para") { - sources = [ "./vendor.para" ] - outputs = [ "$root_out_dir/vendor/etc/param/vendor.para" ] - } - ``` + ``` + copy("vendor.para") { + sources = [ "./vendor.para" ] + outputs = [ "$root_out_dir/vendor/etc/param/vendor.para" ] + } + ``` - (2) L0的由于没有文件系统,在编译时会把hal_sys_param.c和vendor.para文件转化为头文件,编译时直接编译到系统中。 \ No newline at end of file +2. 轻量系统的产品由于没有文件系统,在编译时会把hal_sys_param.c和vendor.para文件转化为头文件,编译时直接编译到系统中。 \ No newline at end of file diff --git a/zh-cn/device-dev/subsystems/subsys-boot-init-log.md b/zh-cn/device-dev/subsystems/subsys-boot-init-log.md index f7e67b7d31bee1e67f7957ca9182d6748528e7dc..91d8ef25150e0e98d6be31fe48723418aa72634f 100644 --- a/zh-cn/device-dev/subsystems/subsys-boot-init-log.md +++ b/zh-cn/device-dev/subsystems/subsys-boot-init-log.md @@ -5,15 +5,14 @@ - 基于日志可以定位故障问题,可以查看各子系统启动时长,命令执行时长等。 - 可以查看不同模块的日志tag,如param、uevent、module等。 - 输出关键阶段日志,如第一阶段启动日志、required partition设备节点、uevent创建日志、服务启动日志等。 -- 日志等级可控,根据需要输出不同级别日志,目前日志级别分为INIT_DEBUG, -INIT_INFO,INIT_WARN,INIT_ERROR,INIT_FATAL。 +- 日志等级可控,根据需要输出不同级别日志,目前日志级别分为INIT_DEBUG、INIT_INFO、INIT_WARN、INIT_ERROR、INIT_FATAL。 ### 基本概念 init日志根据OpenHarmony版本不同实现方式不同。 -- 对于OpenHarmony标准版本,init日志采用内核的dmesg log实现。 -- 对于OpenHarmony liteos L1版本init日志采用hilog接口实现。 -- 对于OpenHarmony liteos L0版本init日志采用printf接口实现。 +- 对于OpenHarmony标准系统版本,init日志采用内核的dmesg log实现。 +- 对于OpenHarmony LiteOS小型系统版本init日志采用hilog接口实现。 +- 对于OpenHarmony LiteOS轻量系统版本init日志采用printf接口实现。 ### 约束与限制 无 diff --git a/zh-cn/device-dev/subsystems/subsys-build-gn-hap-compilation-guide.md b/zh-cn/device-dev/subsystems/subsys-build-gn-hap-compilation-guide.md index 045a09c28d618d7b84963820dfdd08db709dd182..4308d54284d488b2d06ed6962a4cd33eebb70df4 100644 --- a/zh-cn/device-dev/subsystems/subsys-build-gn-hap-compilation-guide.md +++ b/zh-cn/device-dev/subsystems/subsys-build-gn-hap-compilation-guide.md @@ -27,8 +27,8 @@ | hap_profile | HAP的config.json,Stage模型对应module.json。 | | raw_assets | 原始assets,这些assets会直接拷贝到HAP的assets目录下。 | | resources | 资源文件,编译后放置在assets/entry/resources目录下 | -| js_assets | js资源,ace编译后放置在assets/js/default目录下。| -| ets_assets | ets资源,ace编译后放置在assets/js/default目录下 | +| js_assets | js资源,编译后放置在assets/js/default目录下。| +| ets_assets | ets资源,编译后放置在assets/js/default目录下 | | deps | 当前目标的依赖 | | shared_libraries | 当前目标依赖的native库 | | hap_name | HAP的名字,可选,默认为目标名 | @@ -55,7 +55,7 @@ | sources | HAP的AppScope中的资源resources,只在Stage模型下使用。| #### ohos_js_assets -js或ets代码,ace编译后放置在assets/js/default目录下,stage模型根据代码分别放置到js或ets目录。 +js或ets代码,编译后放置在assets/js/default目录下,stage模型根据代码分别放置到js或ets目录。 | 支持的变量 | 说明 | | --------- | ---- | diff --git a/zh-cn/device-dev/subsystems/subsys-remote-start.md b/zh-cn/device-dev/subsystems/subsys-remote-start.md deleted file mode 100755 index 0cf26f8b0538e29872aa139f5a22e63220384376..0000000000000000000000000000000000000000 --- a/zh-cn/device-dev/subsystems/subsys-remote-start.md +++ /dev/null @@ -1,83 +0,0 @@ -# 分布式远程启动 - - -## 概述 - -分布式任务调度模块,通过主从设备服务代理机制,在OpenHarmony操作系统上建立起分布式服务平台,支持主设备(搭载OpenHarmony的智慧屏设备)启动从设备(IP Camera、运动手表等小内存OpenHarmony设备)FA的能力。 - -以智慧屏节目开播提醒为例,智慧屏上在喜欢的节目菜单中,点击“开播后提醒我”按钮,等节目开播后,智慧屏会拉起运动手表上的节目开播提醒FA。通过该FA用户可以快速知道喜欢的节目已经开始,达到协同互助的作用。 - - -## 基本概念 - -- FA - Feature Ability代表有界面的Ability,用于与用户进行交互。 - -- 远程启动 - 即跨设备启动FA,与本地启动FA相对应。 - - -## 接口说明 - -智慧屏端分布式开放能力如下表,包含在AbilitySlice类中,具体的API接口详见OpenHarmony应用接入接口文档: - - **表1** 分布式远程启动FA的API接口功能介绍 - -| 接口名 | 描述 | -| -------- | -------- | -| void startAbility(Want want) | 远程启动FA,Want参数命名以实际开发平台API为准。 | - - **表2** 参数Want功能介绍 - -| 参数名 | 类型 | 说明 | -| -------- | -------- | -------- | -| want | ohos.aafwk.content.Want | 当开发者需要调用该接口启动远程FA时,需要显式指定待启动FA的设备id、bundleName和abilityName。 | - - -## 约束与限制 - -- 支持主设备侧远程启动从设备侧FA,不支持从设备远程启动主设备FA。 - -- 远程启动前必须确保OpenHarmony设备间分布式组网成功(需要在同一网段内,可互相ping通),否则无法远程启动。 - -- 当前只支持拥有共同公钥信息的主从设备间FA(即主从设备的FA使用相同华为证书)的拉起。 - - -## 开发步骤 - -智慧屏侧通过如下操作启动从设备侧FA,从设备侧FA默认已开发。 - -1. 打开DevEco Studio,完成智慧屏侧FA开发。 - -2. 获取目标在线从设备的设备ID。 - - ``` - // 引入设备选择头文件 - import ohos.distributedschedule.interwork.DeviceInfo; - import ohos.distributedschedule.interwork.DeviceManager; - - // 获取在线设备列表 - List deviceInfoListOnline = DeviceManager.getDmsDeviceList(DeviceInfo.FLAG_GET_ONLINE_DEVICE); - String remote_device_id; - if (deviceInfoListOnline.size() > 0) - { - remote_device_id = deviceInfoListOnline[0].GetDeviceId(); // 获取在线列表中第一台设备的设备ID - } - ``` - -3. 构造want,首先使用ElementName类表明需要启动的远端设备ID,包名,Ability类名,传入want中,然后设置want中的分布式标志位Want.FLAG_ABILITYSLICE_MULTI_DEVICE表示需要远程启动。 - - ``` - // 引入相关头文件 - import ohos.aafwk.ability.Ability; - import ohos.aafwk.content.Want; - import ohos.bundle.ElementName; - - // 启动远程设备FA - Want want = new Want(); // 封装启动远端FA的Want - // 使用步骤2中获取的设备ID,并指定FA信息 - ElementName name = new ElementName(remote_device_id, "com.huawei.remote_package_name", "remote_class_name"); - want.setElement(name); // 将待启动的FA信息添加到Want中 - want.setFlags(Want.FLAG_ABILITYSLICE_MULTI_DEVICE); // 设置分布式标记,若不设置将无法使用分布式能力 - startAbility(want); // 按照Want启动指定FA,Want参数命名以实际开发平台API为准 - ``` diff --git a/zh-cn/device-dev/website.md b/zh-cn/device-dev/website.md index f983353d1b543053876695ec44148d5a94e03c4c..82a8ab951709ab62808b4aace234ac657645b24d 100644 --- a/zh-cn/device-dev/website.md +++ b/zh-cn/device-dev/website.md @@ -393,7 +393,6 @@ - [HAP编译构建指导](subsystems/subsys-build-gn-hap-compilation-guide.md) - [常见问题](subsystems/subsys-build-FAQ.md) - [ArkCompiler](subsystems/subsys-arkcompiler-guide.md) - - [分布式远程启动](subsystems/subsys-remote-start.md) - 图形图像 - [图形图像概述](subsystems/subsys-graphics-overview.md) - [容器类组件开发指导](subsystems/subsys-graphics-container-guide.md) diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-arkui.md b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-arkui.md index e887116ce27d7c17e96a5ff24ecd51b18d394ac9..2c8bbcc8165d49a380417123daa80a430f926721 100644 --- a/zh-cn/release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-arkui.md +++ b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-arkui.md @@ -98,3 +98,98 @@ struct Child { 如果需要在父组件中修改子组件的`@LocalStorageLink`, `@LocalStorageProp`修饰的变量,则使用LocalStorage提供的API接口方法(比如set方法)赋值。 +## cl.arkui.3 PromptAction模块中,文本提示框toast的bottom属性含义变更。 + +文本提示框toast的bottom属性值的含义,从文本提示框上边沿到屏幕下边沿,变更为文本提示框下边沿到屏幕下边沿。 + +**示例:** + +```ts +import promptAction from '@ohos.promptAction'; +@Entry +@Component +struct Index { + build() { + Row() { + Button() + .onClick(() => { + try { + promptAction.showToast({ + message: 'Message Info', + duration: 2000 + }); + } catch (error) { + console.error(`showToast args error code is ${error.code}, message is ${error.message}`); + }; + }) + } + } +} +``` + +**变更影响** + +PromptAction模块中,文本提示框toast的bottom属性设置同样的数值,会由于编译器所使用的API版本是否为API version 10+而有所差异。 + +**关键的接口/组件变更** + +不涉及。 + +**适配指导** + +编译器采用API version 9或以往版本以保持之前的样式,或者采用API version 10及以上版本以采用新样式。 + +## cl.arkui.4 AlertDialog控件内容布局变更。 + +AlertDialog的内容属性部分会根据:1)有无标题title,2)是否为单行文本,条件不同而布局有所不同。 + +目前规格:仅无标题title的单行文本情况下为居中,其余情况文本左对齐。 + +**示例:** + +```ts +// xxx.ets +@Entry +@Component +struct AlertDialogExample { + build() { + Column({ space: 5 }) { + Button('one button dialog') + .onClick(() => { + AlertDialog.show( + { + title: 'title', + message: 'text'.repeat(20), + autoCancel: true, + alignment: DialogAlignment.Bottom, + offset: { dx: 0, dy: -20 }, + gridCount: 3, + confirm: { + value: 'button', + action: () => { + console.info('Button-clicking callback') + } + }, + cancel: () => { + console.info('Closed callbacks') + } + } + ) + }) + .backgroundColor(0x317aff) + }.width('100%').margin({ top: 5 }) + } +} +``` + +**变更影响** + +AlertDialog控件message属性对应的文本内容,布局效果变更。 + +**关键的接口/组件变更** + +不涉及。 + +**适配指导** + +无需主动适配,或者可以使用customDialog做相关实现。 diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-datashare.md b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-datashare.md new file mode 100644 index 0000000000000000000000000000000000000000..64a399d30f428d342fadf30bedf3955282c42466 --- /dev/null +++ b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-datashare.md @@ -0,0 +1,39 @@ +# 分布式数据管理子系统ChangeLog + +## cl.datashare.1 js-apis-data-dataShare API version 10开始托管数据PublishedItem中data的数据类型从Ashmem变更为ArrayBuffer + +**变更影响** + +PublishedItem中data的数据类型从Ashmem变更为ArrayBuffer + +## PublishedItem10+ + +指定发布的数据类型。 + +**系统能力:** SystemCapability.DistributedDataManager.DataShare.Consumer + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| key | string | 是 | 指定发布数据的键。 | +| data | string \| ArrayBuffer | 是 | 指定发布的数据。如果数据很大,请使用ArrayBuffer。 | +| subscriberId | string | 是 | 指定订阅者id。 | + +**适配指导** +示例代码如下: + +**示例:** + +```ts +let arrayBuffer = new ArrayBuffer(1); +let version = 1; +let data : Array = [{key:"key2", subscriberId:"11", data:arrayBuffer}]; +function publishCallback(err, result: Array) { + console.info("publishCallback " + JSON.stringify(result)); +} +try { + console.info("data length is:", data.length); + dataShareHelper.publish(data, "com.acts.ohos.data.datasharetest", version, publishCallback); +} catch (e) { + console.error("publish error " + JSON.stringify(e)); +} +``` \ No newline at end of file diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md new file mode 100644 index 0000000000000000000000000000000000000000..caade19501be86ec1eec565b49a799fa86d7dada --- /dev/null +++ b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md @@ -0,0 +1,147 @@ +# 文件子系统ChangeLog + +## cl.file.1 mediaLibrary相关接口兼容性变更 + +mediaLibrary部分接口兼容性变更。 + +**变更影响** + +[mediaLibrary](../../../application-dev/reference/apis/js-apis-medialibrary.md)部分接口兼容性变更。 +基于此前版本开发的应用,需注意接口的迭代更新。 + +**关键接口/组件变更** + +| 模块名 | 方法/属性/枚举/常量 | 变更类型 | +| ------------------------- | ------------------------------------------------------------ | -------- | +| medialibrary | **function** getFileAssets(options: MediaFetchOptions, callback: AsyncCallback<FetchFileResult>): void | 接口兼容性变更 | +| medialibrary | **function** getFileAssets(options: MediaFetchOptions): Promise<FetchFileResult> | 接口兼容性变更 | +| medialibrary | **function** createAsset(mediaType: MediaType, displayName: string, relativePath: string, callback: AsyncCallback<FileAsset>): void| 接口兼容性变更 | +| medialibrary | **function** createAsset(mediaType: MediaType, displayName: string, relativePath: string): Promise<FileAsset>| 接口兼容性变更 | +| medialibrary | **function** getAlbums(options: MediaFetchOptions, callback: AsyncCallback<Array<Album>>): void | 接口兼容性变更 | +| medialibrary | **function** getAlbums(options: MediaFetchOptions): Promise<Array<Album>> | 接口兼容性变更 | +| medialibrary | **function** FileAsset.commitModify(callback: AsyncCallback<void>): void | 接口兼容性变更 | +| medialibrary | **function** FileAsset.commitModify(): Promise<void> | 接口兼容性变更 | + +**适配指导** + +**getFileAssets接口获取文件资源兼容性影响:** + +在API version 10上,摒弃了物理目录作为相册的设计,采用了逻辑相册的设计,一个相册中可以添加多个文件,一个文件也可以在多个相册中呈现。新的设计将带来parent、albumId、albumUri和albumName属性使用上的不兼容,无法作为MediaFetchOptions的参数在getFileAssets接口中使用。下面示例代码为错误示例: + +1. 使用[getMediaLibrary](../../../application-dev/reference/apis/js-apis-medialibrary.md#medialibrarygetmedialibrary)接口获取媒体库实例。 +2. 创建检索条件[MediaFetchOptions](../../../application-dev/reference/apis/js-apis-medialibrary.md#mediafetchoptions7)。 +3. 调用[getFileAssets](../../../application-dev/reference/apis/js-apis-medialibrary.md#getfileassets7)接口获取文件资源。 + +**错误示例:** + +```js +import mediaLibrary from '@ohos.multimedia.mediaLibrary'; + +async function example() { + try { + let context = getContext(this); + let media = mediaLibrary.getMediaLibrary(context); + let fileKeyObj = mediaLibrary.FileKey; + let albumId = 1; + let getImageOp = { + selections: fileKeyObj.ALBUM_ID + '= ?', // 使用parent、albumId、albumUri和albumName属性查询均无法获取文件资源。 + selectionArgs: [albumId.toString()], + }; + const fetchFileResult = await media.getFileAssets(getImageOp); // 查询失败,获取的fetchFileResult为空。 + const fileAsset = await fetchFileResult.getFirstObject(); + console.info('mediaLibrary fileAsset displayName: ' + fileAsset.displayName); + } catch (err) { + console.error('mediaLibrary fail, err: ' + err); + } +} +``` + +推荐使用以下方式调用getFileAssets接口获取文件资源: + +**正确示例:** + +```js +import mediaLibrary from '@ohos.multimedia.mediaLibrary'; + +async function example() { + try { + let context = getContext(this); + let media = mediaLibrary.getMediaLibrary(context); + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], // 查询所有图片类型的文件。 + }; + const fetchFileResult = await media.getFileAssets(getImageOp); + const fileAsset = await fetchFileResult.getFirstObject(); + console.info('mediaLibrary fileAsset displayName: ' + fileAsset.displayName); + } catch (err) { + console.error('mediaLibrary fail, err: ' + err); + } +} +``` + +**createAsset接口创建相册兼容性影响:** + +由于API version 10的SDK上relativePath和相册没有关联关系,文件创建成功后,relativePath的最后一级目录不会作为相册呈现。 + +**getAlbums接口获取相册兼容性影响:** + +由于API version 10的SDK上relativePath和相册没有关联关系,在使用getAlbums时不支持relativePath作为查询条件,并且ALBUM_NAME参数只能使用"Camera"和"Screenshots"。下面示例代码为错误示例: + +1. 使用[getMediaLibrary](../../../application-dev/reference/apis/js-apis-medialibrary.md#medialibrarygetmedialibrary)接口获取媒体库实例。 +2. 创建相册检索条件[MediaFetchOptions](../../../application-dev/reference/apis/js-apis-medialibrary.md#mediafetchoptions7)。 +3. 调用[getAlbums](../../../application-dev/reference/apis/js-apis-medialibrary.md#getalbums7)接口获取相册。 + +**错误示例:** + +```js +import mediaLibrary from '@ohos.multimedia.mediaLibrary'; + +async function example() { + try { + let context = getContext(this); + let media = mediaLibrary.getMediaLibrary(context); + let AlbumNoArgsfetchOp = { + selections: mediaLibrary.FileKey.ALBUM_NAME + ' = ?', + selectionArgs: ['新建相册1'], // 获取albumName为新建相册1的相册。 + }; + const albumList = await media.getAlbums(AlbumNoArgsfetchOp); // 查询失败,获取的fetchFileResult为空。 + for (let i = 0; i < albumList.length; i++) { + console.info('mediaLibrary album albumName: ' + albumList[i].albumName); + } + } catch (err) { + console.error('mediaLibrary fail, err: ' + err); + } +} +``` + +使用如下示例代码可以获取Camera和Screenshots相册。 + +**正确示例:** + +```js +import mediaLibrary from '@ohos.multimedia.mediaLibrary'; + +async function example() { + try { + let context = getContext(this); + let media = mediaLibrary.getMediaLibrary(context); + let AlbumNoArgsfetchOp = { + selections: mediaLibrary.FileKey.ALBUM_NAME + ' = ? OR ' + mediaLibrary.FileKey.ALBUM_NAME + ' = ?', + selectionArgs: ['Camera', 'Screenshots'], // 获取相机相册和截屏录屏相册。 + }; + const albumList = await media.getAlbums(AlbumNoArgsfetchOp); + for (let i = 0; i < albumList.length; i++) { + console.info('mediaLibrary album albumName: ' + albumList[i].albumName); + } + } catch (err) { + console.error('mediaLibrary fail, err: ' + err); + } +} +``` + +**FileAsset.commitModify接口获取相册兼容性影响:** + +在API version 10的SDK上去掉了针对audio无意义的orientation属性,在使用commitModify接口时将无法对audio资源的orientation属性进行修改。