diff --git a/CODEOWNERS b/CODEOWNERS index 638941c1a2a1765ad2a55dd81cf65ca72dce37be..d6a982c6e1feb8a49e4510906ad057354f734a42 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -135,7 +135,7 @@ zh-cn/application-dev/IDL/ @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingz zh-cn/application-dev/device-usage-statistics/ @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001 zh-cn/application-dev/ui/ @HelloCrease @huaweimaxuchu @tomatodevboy @niulihua zh-cn/application-dev/notification/ @RayShih @jayleehw @li-weifeng2 @currydavids -zh-cn/application-dev/windowmanager/ @ge-yafang @zhangqiang183 @zhouyaoying @zxg-gitee +zh-cn/application-dev/windowmanager/ @ge-yafang @zhangqiang183 @zhouyaoying @zxg-gitee @nobuggers zh-cn/application-dev/webgl/ @zengyawen @zhangqiang183 @wind_zj @zxg-gitee zh-cn/application-dev/media/audio-overview.md @zengyawen @liuyuehua1 @saga2020 @currydavids zh-cn/application-dev/media/audio-playback.md @zengyawen @liuyuehua1 @saga2020 @currydavids @@ -186,8 +186,9 @@ zh-cn/application-dev/dfx/errormanager-guidelines.md @littlejerry1 @ccllee @chen zh-cn/application-dev/dfx/errormanager-guidelines.md @littlejerry1 @ccllee @chengxingzhen @RayShih zh-cn/application-dev/key-features/multi-device-app-dev/ @lingminghw @crazyracing0726 zh-cn/application-dev/database/ @ge-yafang @feng-aiwen @gong-a-shi @logic42 -zh-cn/application-dev/napi/native-window-guidelines.md @ge-yafang @zhangqiang183 @zhouyaoying @zxg-gitee +zh-cn/application-dev/napi/native-window-guidelines.md @ge-yafang @zhangqiang183 @zhouyaoying @zxg-gitee @nobuggers zh-cn/application-dev/napi/mindspore-lite-guidelines.md @ge-yafang @grbuzhidao @jianghui58 @auraxu +zh-cn/application-dev/napi/mindspore-lite-offline-model-guidelines.md @ge-yafang @grbuzhidao @jianghui58 @auraxu zh-cn/application-dev/napi/rawfile_guidelines.md @ningningW zh-cn/application-dev/background-agent-scheduled-reminder/ @RayShih zh-cn/application-dev/background-task-management/ @ningningW @wangwenli_wolf @tangtiantian2021 @nan-xiansen @@ -274,9 +275,9 @@ zh-cn/application-dev/reference/apis/js-apis-application-shellCmdResult.md @litt zh-cn/application-dev/reference/apis/js-apis-application-StartOptions.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-application-Want.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen -zh-cn/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee -zh-cn/application-dev/application-models/windowextensionability.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee -zh-cn/application-dev/reference/apis/js-apis-inner-application-windowExtensionContext.md @ge-yafang @zhouyaoying @zxg-gitee +zh-cn/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee @nobuggers +zh-cn/application-dev/application-models/windowextensionability.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee @nobuggers +zh-cn/application-dev/reference/apis/js-apis-inner-application-windowExtensionContext.md @ge-yafang @zhouyaoying @zxg-gitee @nobuggers zh-cn/application-dev/reference/apis/js-apis-appmanager.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-arraylist.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-audio.md @liuyuehua1 @zengyawen @magekkkk @currydavids @@ -321,6 +322,8 @@ zh-cn/application-dev/reference/apis/js-apis-data-DataShareResultSet.md @feng-ai zh-cn/application-dev/reference/apis/js-apis-data-distributedobject.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 zh-cn/application-dev/reference/apis/js-apis-data-preferences.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 zh-cn/application-dev/reference/apis/js-apis-data-rdb.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 +zh-cn/application-dev/reference/apis/js-apis-data-udmf.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 +zh-cn/application-dev/reference/apis/js-apis-data-cloudData.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 zh-cn/application-dev/reference/apis/js-apis-data-relationStore.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 zh-cn/application-dev/reference/apis/js-apis-data-resultset.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 zh-cn/application-dev/reference/apis/js-apis-data-storage.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 @@ -331,7 +334,7 @@ zh-cn/application-dev/reference/apis/js-apis-deque.md @gongjunsong @ge-yafang @f zh-cn/application-dev/reference/apis/js-apis-device-info.md @mupceet @zengyawen @handyohos @nan-xiansen zh-cn/application-dev/reference/apis/js-apis-device-manager.md @intermilano @RayShih @william-ligang @liuhonggang123 zh-cn/application-dev/reference/apis/js-apis-deviceUsageStatistics.md @shuaytao @RayShih @wangzhen107 @inter515 -zh-cn/application-dev/reference/apis/js-apis-display.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee +zh-cn/application-dev/reference/apis/js-apis-display.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee @nobuggers zh-cn/application-dev/reference/apis/js-apis-distributed-account.md @nianCode @zengyawen @JiDong-CS @murphy1984 zh-cn/application-dev/reference/apis/js-apis-distributed-data.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 zh-cn/application-dev/reference/apis/js-apis-distributedMissionManager.md @chenmingJay @ningningW @nan-xiansen @iceice1001 @@ -415,9 +418,8 @@ zh-cn/application-dev/reference/apis/js-apis-resource-manager.md @Buda-Liu @ning zh-cn/application-dev/reference/apis/js-apis-router.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-rpc.md @xuepianpian @RayShih @zhaopeng_gitee @vagrant_world zh-cn/application-dev/reference/apis/js-apis-runninglock.md @aqxyjay @zengyawen @aqxyjay @alien0208 - -zh-cn/application-dev/reference/apis/js-apis-screen.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee -zh-cn/application-dev/reference/apis/js-apis-screenshot.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee +zh-cn/application-dev/reference/apis/js-apis-screen.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee @nobuggers +zh-cn/application-dev/reference/apis/js-apis-screenshot.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee @nobuggers zh-cn/application-dev/reference/apis/js-apis-securityLabel.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-sensor.md @hellohyh001 @ningningW @butterls @star-wind-snow-and-rain zh-cn/application-dev/reference/apis/js-apis-service-extension-ability.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen @@ -458,6 +460,8 @@ zh-cn/application-dev/reference/apis/js-apis-testRunner.md @inter515 @littlejerr zh-cn/application-dev/reference/apis/js-apis-thermal.md @aqxyjay @zengyawen @aqxyjay @alien0208 zh-cn/application-dev/reference/apis/js-apis-timer.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-touchevent.md @mayunteng_1 @ningningW @cococoler @alien0208 +zh-cn/application-dev/reference/apis/js-apis-shortKey.md @mayunteng_1 @ningningW @cococoler @alien0208 +zh-cn/application-dev/reference/apis/js-apis-devicestatus-cooperate.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-treemap.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-treeset.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-uitest.md @inter515 @ningningW @inter515 @jiyong @@ -473,17 +477,19 @@ zh-cn/application-dev/reference/apis/js-apis-vector.md @gongjunsong @ge-yafang @ zh-cn/application-dev/reference/apis/js-apis-vibrator.md @hellohyh001 @ningningW @butterls @star-wind-snow-and-rain zh-cn/application-dev/reference/apis/js-apis-volumemanager.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-wallpaper.md @feng-aiwen @ningningW @wangzhangjun @murphy1984 +zh-cn/application-dev/reference/apis/js-apis-screen-lock.md @feng-aiwen @ningningW @wangzhangjun @murphy1984 zh-cn/application-dev/reference/apis/js-apis-wantAgent.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-webgl.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-webgl2.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-webSocket.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-wifi.md @cheng_guohong @RayShih @cheng_guohong @quanli125 zh-cn/application-dev/reference/apis/js-apis-wifiext.md @cheng_guohong @RayShih @cheng_guohong @quanli125 -zh-cn/application-dev/reference/apis/js-apis-window.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee +zh-cn/application-dev/reference/apis/js-apis-window.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee @nobuggers zh-cn/application-dev/reference/apis/js-apis-windowAnimationManager.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-worker.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-taskpool.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-workScheduler.md @chenmingJay @ningningW @nan-xiansen @iceice1001 +zh-cn/application-dev/reference/apis/js-apis-inner-application-WorkSchedulerExtensionContext.md @chenmingJay @ningningW @nan-xiansen @iceice1001 zh-cn/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md @chenmingJay @ningningW @nan-xiansen @iceice1001 zh-cn/application-dev/reference/apis/js-apis-xml.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-zlib.md @shuaytao @RayShih @wangzhen107 @inter515 @@ -529,6 +535,7 @@ zh-cn/application-dev/reference/apis/js-apis-curve.md @huaweimaxuchu @HelloCreas zh-cn/application-dev/reference/apis/js-apis-defaultAppManager.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-distributedBundle.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-distributedKVStore.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 +zh-cn/application-dev/reference/apis/js-apis-enterprise-applicationManager.md @liuzuming @ningningW @yangqing3 zh-cn/application-dev/reference/apis/js-apis-enterprise-accountManager.md @liuzuming @ningningW @yangqing3 zh-cn/application-dev/reference/apis/js-apis-enterprise-adminManager.md @liuzuming @ningningW @yangqing3 zh-cn/application-dev/reference/apis/js-apis-enterprise-bundleManager.md @liuzuming @ningningW @yangqing3 @@ -551,8 +558,10 @@ zh-cn/application-dev/reference/apis/js-apis-net-sharing.md @zhang-hai-feng @zen zh-cn/application-dev/reference/apis/js-apis-nfctech.md @cheng_guohong @RayShih @cheng_guohong @quanli125 zh-cn/application-dev/reference/apis/js-apis-promptAction.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md @chenmingJay @ningningW @nan-xiansen @iceice1001 +zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceStandby.md @chenmingJay @ningningW @nan-xiansen @iceice1001 zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @chenmingJay @ningningW @nan-xiansen @iceice1001 zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md @chenmingJay @ningningW @nan-xiansen @iceice1001 +zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceStandby.md @chenmingJay @ningningW @nan-xiansen @iceice1001 zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md @chenmingJay @ningningW @nan-xiansen @iceice1001 zh-cn/application-dev/reference/apis/js-apis-stationary.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-system-capability.md taiyipei taiyipei BlackStone @@ -607,6 +616,7 @@ zh-cn/application-dev/reference/errorcodes/errorcode-request.md @ningningW zh-cn/application-dev/reference/errorcodes/errorcode-resource-manager.md @ningningW zh-cn/application-dev/reference/errorcodes/errorcode-router.md @HelloCrease zh-cn/application-dev/reference/errorcodes/errorcode-rpc.md @RayShih +zh-cn/application-dev/reference/errorcodes/errorcode-screenlock.md @ningningW zh-cn/application-dev/reference/errorcodes/errorcode-runninglock.md @zengyawen zh-cn/application-dev/reference/errorcodes/errorcode-sensor.md @ningningW zh-cn/application-dev/reference/errorcodes/errorcode-system-parameterV9.md @zengyawen diff --git a/en/application-dev/device-usage-statistics/device-usage-statistics-use-guide.md b/en/application-dev/device-usage-statistics/device-usage-statistics-use-guide.md index 82027e91a9c15b1fd1b62a8c5ef4cddc2f9c0ef3..067f372d7e27e568d3208f651b57132ecc3edd72 100644 --- a/en/application-dev/device-usage-statistics/device-usage-statistics-use-guide.md +++ b/en/application-dev/device-usage-statistics/device-usage-statistics-use-guide.md @@ -1,4 +1,4 @@ -# Device Usage Statistics Development (API Version 9) +# Device Usage Statistics Development ## When to Use @@ -38,7 +38,7 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; ## How to Develop 1. Before obtaining the device usage statistics, check whether the **ohos.permission.BUNDLE_ACTIVE_INFO** permission is configured. For details about how to configure a permission, see [Declaring Permissions](../security/accesstoken-guidelines.md). - + 2. Query events of all applications based on the specified start time and end time. This requires the **ohos.permission.BUNDLE_ACTIVE_INFO** permission to be configured. ```js diff --git a/en/application-dev/napi/Readme-EN.md b/en/application-dev/napi/Readme-EN.md index 1295e0798c8a2e98beace89c016828eac79d5a5a..2b1f8639a152589b76f44af97f9812a1a5711d23 100644 --- a/en/application-dev/napi/Readme-EN.md +++ b/en/application-dev/napi/Readme-EN.md @@ -1,7 +1,7 @@ # Native APIs - [Introduction to Native APIs](introduction.md) -- [Using N-APIs in Application Projects](napi-guidelines.md) +- [Using Native APIs in Application Projects](napi-guidelines.md) - [Drawing Development](drawing-guidelines.md) - [Raw File Development](rawfile-guidelines.md) - [Native Window Development](native-window-guidelines.md) diff --git a/en/application-dev/napi/drawing-guidelines.md b/en/application-dev/napi/drawing-guidelines.md index 22d85aec0fe405e47cd92abeafa94ba5e7b7ed5f..c341703ff86d6d0e3c6a34e8270e934b33a15d3a 100644 --- a/en/application-dev/napi/drawing-guidelines.md +++ b/en/application-dev/napi/drawing-guidelines.md @@ -128,10 +128,7 @@ The following steps describe how to use the canvas and brush of the Native Drawi ```c++ // Obtain the pixel address after drawing. The memory to which the address points contains the pixel data of the drawing on the canvas. void* bitmapAddr = OH_Drawing_BitmapGetPixels(cBitmap); - auto ret = memcpy_s(addr, addrSize, bitmapAddr, addrSize); - if (ret != EOK) { - LOGI("memcpy_s failed"); - } + std::copy(addr, addr + addrSize, static_cast(bitmapAddr)); // Destroy the canvas object. OH_Drawing_CanvasDestroy(cCanvas); // Destroy the bitmap object. diff --git a/en/application-dev/napi/napi-guidelines.md b/en/application-dev/napi/napi-guidelines.md index a12e23d9f48492911dff8476a1e5301736704d85..54ebab553f18ecaf21aae4e52b5a95e4bdfe1192 100644 --- a/en/application-dev/napi/napi-guidelines.md +++ b/en/application-dev/napi/napi-guidelines.md @@ -1,4 +1,4 @@ -# Using N-APIs in Application Projects +# Using Native APIs in Application Projects In OpenHarmony, you can use the N-APIs in C APIs to implement interaction between ArkTS/TS/JS and C/C++. The N-API names are the same as those in the third-party **Node.js**. Currently, OpenHarmony supports some N-APIs. For details about the APIs supported, see [arkui_napi](https://gitee.com/openharmony/arkui_napi/blob/master/libnapi.ndk.json). diff --git a/en/application-dev/quick-start/arkts-create-custom-components.md b/en/application-dev/quick-start/arkts-create-custom-components.md index b094ff46868af53f56627b1cfe2c5f297284f938..cb9da51e22baae00117cd269a6f95b74606b5979 100644 --- a/en/application-dev/quick-start/arkts-create-custom-components.md +++ b/en/application-dev/quick-start/arkts-create-custom-components.md @@ -1,7 +1,7 @@ # Creating a Custom Component -In ArkUI, components are what's displayed on the UI. They can be classified as built-in components – those directly provided by ArkUI framework, and custom components – those defined by developers. Defining the entire application UI with just built-in components would lead to a monolithic design, low code maintainability, and poor execution performance. A good UI is the result of a well-thought-out development process, with such factors as code reusability, separation of service logic from the UI, and version evolution carefully considered. Creating custom components that encapsulate the UI and some business logic is a critical step in this process. +In ArkUI, components are what's displayed on the UI. They can be classified as built-in components – those directly provided by the ArkUI framework, and custom components – those defined by developers. Defining the entire application UI with just built-in components would lead to a monolithic design, low code maintainability, and poor execution performance. A good UI is the result of a well-thought-out development process, with such factors as code reusability, separation of service logic from the UI, and version evolution carefully considered. Creating custom components that encapsulate the UI and some business logic is a critical step in this process. The custom component has the following features: diff --git a/en/application-dev/quick-start/cross-app-hsp.md b/en/application-dev/quick-start/cross-app-hsp.md index 4d4115490d7060843fe008cda7281fcc2a003ada..5c1e703b13730a207eac774bf1fa1b9c0b455bc1 100644 --- a/en/application-dev/quick-start/cross-app-hsp.md +++ b/en/application-dev/quick-start/cross-app-hsp.md @@ -29,7 +29,9 @@ liba │ └── module.json5 └── oh-package.json5 ``` -Below is an example of the **index.ets** file content: +In the entry file **index.ets**, declare the APIs to be exposed. + +Below is an example: ```ts // liba/src/main/ets/index.ets @@ -168,7 +170,7 @@ struct Index { } ``` -## Inter-Application HSP Distribution +## Inter-Application HSP Distribution (for System Applications Only) Inter-application HSPs are not completely integrated into an application. They are distributed by being preset in the system version or installed with an application on the device. To be specific: 1. Some frequently-used inter-application HSPs are preset in the system version. 2. When a user downloads an application from the application market, if the application market detects that the application depends on one or more inter-application HSPs and any of these HSPs are not installed on the target device, it will download the application as well as the missing HSPs for the user. In this way, the application can use the features shared through the HSPs properly. diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index f9a6af9e1de4ac19c1623914fcd7e6a62c41a3fd..8b122dde9179dc70c4caba012a1c23b5cc8d3919 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -210,6 +210,9 @@ - [@ohos.multimedia.camera (Camera Management)](js-apis-camera.md) - [@ohos.multimedia.image (Image Processing)](js-apis-image.md) - [@ohos.multimedia.media (Media)](js-apis-media.md) + - [@ohos.multimedia.systemSoundManager (System Sound Management)](js-apis-systemSoundManager.md) + - multimedia + - [ringtonePlayer (Ringtone Player)](js-apis-inner-multimedia-ringtonePlayer.md) - Resource Manager - [@ohos.i18n (Internationalization)](js-apis-i18n.md) @@ -238,6 +241,7 @@ - [PermissionRequestResult](js-apis-permissionrequestresult.md) - Data Management + - [@ohos.data.cloudData (Device-Cloud Synergy)](js-apis-data-cloudData.md) - [@ohos.data.dataAbility (DataAbility Predicates)](js-apis-data-ability.md) - [@ohos.data.dataShare (DataShare)](js-apis-data-dataShare.md) - [@ohos.data.dataSharePredicates (DataShare Predicates)](js-apis-data-dataSharePredicates.md) @@ -319,6 +323,7 @@ - [@ohos.InputMethodExtensionAbility (InputMethodExtensionAbility)](js-apis-inputmethod-extension-ability.md) - [@ohos.InputMethodExtensionContext (InputMethodExtensionContext)](js-apis-inputmethod-extension-context.md) - [@ohos.InputMethodSubtype (Input Method Subtype)](js-apis-inputmethod-subtype.md) + - [@ohos.logLibrary (Log Library)](js-apis-loglibrary.md) - [@ohos.pasteboard (Pasteboard)](js-apis-pasteboard.md) - [@ohos.screenLock (Screenlock)](js-apis-screen-lock.md) - [@ohos.systemDateTime (System Time and Time Zone)](js-apis-system-date-time.md) diff --git a/en/application-dev/reference/apis/commonEventManager-definitions.md b/en/application-dev/reference/apis/commonEventManager-definitions.md index ba5ebf915c918fff4774a4db95e858d00be591d3..05f158ad540403b78c11b77bd4f9ca45e6ea651f 100644 --- a/en/application-dev/reference/apis/commonEventManager-definitions.md +++ b/en/application-dev/reference/apis/commonEventManager-definitions.md @@ -5,13 +5,11 @@ For details about the definition of a system common event, see [Support in @ohos **System capability**: SystemCapability.Notification.CommonEvent -## COMMON_EVENT_BOOT_COMPLETED -Indicates that the user has finished booting and the system has been loaded. -- Value: **usual.event.BOOT_COMPLETED** -- Required subscriber permissions: ohos.permission.RECEIVER_STARTUP_COMPLETED +## [COMMON_EVENT_BOOT_COMPLETED](./common_event/commonEvent-ability.md) +Indicates that the user has finished the boot process. ## COMMON_EVENT_LOCKED_BOOT_COMPLETED -(Reserved, not supported yet) Indicates that the user has finished booting and the system has been loaded but the screen is still locked. +(Reserved, not supported yet) Indicates that the user has finished the boot process but the screen is still locked. - Value: **usual.event.LOCKED_BOOT_COMPLETED** - Required subscriber permissions: ohos.permission.RECEIVER_STARTUP_COMPLETED @@ -40,31 +38,26 @@ Indicates that the device is connected to an external power supply. - Value: **usual.event.POWER_CONNECTED** - Required subscriber permissions: none - ## COMMON_EVENT_POWER_DISCONNECTED Indicates that the device is disconnected from the external power supply. - Value: **usual.event.POWER_DISCONNECTED** - Required subscriber permissions: none - ## COMMON_EVENT_SCREEN_OFF Indicates that the device screen is off and the device is in sleep mode. - Value: **usual.event.SCREEN_OFF** - Required subscriber permissions: none - ## COMMON_EVENT_SCREEN_ON Indicates that the device screen is on and the device is in interactive state. - Value: **usual.event.SCREEN_ON** - Required subscriber permissions: none - ## COMMON_EVENT_THERMAL_LEVEL_CHANGED8+ Indicates that the device's thermal level has changed. - Value: **usual.event.THERMAL_LEVEL_CHANGED** - Required subscriber permissions: none - ## COMMON_EVENT_USER_PRESENT(deprecated) (Reserved, not supported yet) Indicates that the user unlocks the device. - Value: **usual.event.USER_PRESENT** @@ -78,43 +71,36 @@ Indicates that the system time has changed as time ticks by. - Value: **usual.event.TIME_TICK** - Required subscriber permissions: none - ## COMMON_EVENT_TIME_CHANGED Indicates that the system time is set. - Value: **usual.event.TIME_CHANGED** - Required subscriber permissions: none - ## COMMON_EVENT_DATE_CHANGED (Reserved, not supported yet) Indicates that the system date has changed. - Value: **usual.event.DATE_CHANGED** - Required subscriber permissions: none - ## COMMON_EVENT_TIMEZONE_CHANGED Indicates that the system time zone has changed. - Value: **usual.event.TIMEZONE_CHANGED** - Required subscriber permissions: none - ## COMMON_EVENT_CLOSE_SYSTEM_DIALOGS (Reserved, not supported yet) Indicates that the user closes a temporary system dialog box. - Value: **usual.event.CLOSE_SYSTEM_DIALOGS** - Required subscriber permissions: none - ## COMMON_EVENT_PACKAGE_ADDED Indicates that a new application package has been installed on the device. - Value: **usual.event.PACKAGE_ADDED** - Required subscriber permissions: none - ## COMMON_EVENT_PACKAGE_REPLACED (Reserved, not supported yet) Indicates that a later version of an installed application package has replaced the previous one on the device. - Value: **usual.event.PACKAGE_REPLACED** - Required subscriber permissions: none - ## COMMON_EVENT_MY_PACKAGE_REPLACED (Reserved, not supported yet) Indicates that a later version of your application package has replaced the previous one. - Value: **usual.event.MY_PACKAGE_REPLACED** @@ -125,85 +111,67 @@ Indicates that an installed application has been uninstalled from the device wit - Value: **usual.event.PACKAGE_REMOVED** - Required subscriber permissions: none - ## COMMON_EVENT_BUNDLE_REMOVED (Reserved, not supported yet) Indicates that an installed bundle has been uninstalled from the device with the application data retained. - Value: **usual.event.BUNDLE_REMOVED** - Required subscriber permissions: none - ## COMMON_EVENT_PACKAGE_FULLY_REMOVED (Reserved, not supported yet) Indicates that an installed application, including both the application data and code, has been completely uninstalled from the device. - Value: **usual.event.PACKAGE_FULLY_REMOVED** - Required subscriber permissions: none - ## COMMON_EVENT_PACKAGE_CHANGED Indicates that an application package has been changed (for example, an ability in the package has been enabled or disabled). - Value: **usual.event.PACKAGE_CHANGED** - Required subscriber permissions: none - -## COMMON_EVENT_PACKAGE_RESTARTED +## [COMMON_EVENT_PACKAGE_RESTARTED](./common_event/commonEvent-ability.md) Indicates that the user closed all processes of the application and restarted the application. -- Value: **usual.event.PACKAGE_RESTARTED** -- Required subscriber permissions: none - -## COMMON_EVENT_PACKAGE_DATA_CLEARED +## [COMMON_EVENT_PACKAGE_DATA_CLEARED](./common_event/commonEvent-ability.md) Indicates that the user cleared the application package data. -- Value: **usual.event.PACKAGE_DATA_CLEARED** -- Required subscriber permissions: none - ## COMMON_EVENT_PACKAGE_CACHE_CLEARED9+ Indicates that the user cleared the application package cache. - Value: **usual.event.PACKAGE_CACHE_CLEARED** - Required subscriber permissions: none - ## COMMON_EVENT_PACKAGES_SUSPENDED (Reserved, not supported yet) Indicates that application HAP files are suspended. - Value: **usual.event.PACKAGES_SUSPENDED** - Required subscriber permissions: none - ## COMMON_EVENT_PACKAGES_UNSUSPENDED (Reserved, not supported yet) Indicates that application HAP files are not suspended (restored from the suspended state). - Value: **usual.event.PACKAGES_UNSUSPENDED** - Required subscriber permissions: none - ## COMMON_EVENT_MY_PACKAGE_SUSPENDED Indicates that an application HAP file is suspended. - Value: **usual.event.MY_PACKAGE_SUSPENDED** - Required subscriber permissions: none - ## COMMON_EVENT_MY_PACKAGE_UNSUSPENDED Indicates that an application HAP file is not suspended. - Value: **usual.event.MY_PACKAGE_UNSUSPENDED** - Required subscriber permissions: none - ## COMMON_EVENT_UID_REMOVED (Reserved, not supported yet) Indicates that a user ID has been removed from the system. - Value: **usual.event.UID_REMOVED** - Required subscriber permissions: none - ## COMMON_EVENT_PACKAGE_FIRST_LAUNCH (Reserved, not supported yet) Indicates that an installed application is started for the first time. - Value: **usual.event.PACKAGE_FIRST_LAUNCH** - Required subscriber permissions: none - ## COMMON_EVENT_PACKAGE_NEEDS_VERIFICATION (Reserved, not supported yet) Indicates that an application requires system verification. - Value: **usual.event.PACKAGE_NEEDS_VERIFICATION** - Required subscriber permissions: none - ## COMMON_EVENT_PACKAGE_VERIFIED (Reserved, not supported yet) Indicates that an application has been verified by the system. - Value: **usual.event.PACKAGE_VERIFIED** @@ -215,91 +183,76 @@ Indicates that an application HAP file is not suspended. - Value: **usual.event.EXTERNAL_APPLICATIONS_AVAILABLE** - Required subscriber permissions: none - ## COMMON_EVENT_EXTERNAL_APPLICATIONS_UNAVAILABLE (Reserved, not supported yet) Indicates that applications installed on the external storage are not available for the system. - Value: **usual.event.EXTERNAL_APPLICATIONS_UNAVAILABLE** - Required subscriber permissions: none - ## COMMON_EVENT_CONFIGURATION_CHANGED (Reserved, not supported yet) Indicates that the device state (for example, orientation and locale) has changed. - Value: **usual.event.CONFIGURATION_CHANGED** - Required subscriber permissions: none - ## COMMON_EVENT_LOCALE_CHANGED (Reserved, not supported yet) Indicates that the device locale has changed. - Value: **usual.event.LOCALE_CHANGED** - Required subscriber permissions: none - ## COMMON_EVENT_MANAGE_PACKAGE_STORAGE (Reserved, not supported yet) Indicates that the device storage is insufficient. - Value: **usual.event.MANAGE_PACKAGE_STORAGE** - Required subscriber permissions: none - ## COMMON_EVENT_DRIVE_MODE (Reserved, not supported yet) Indicates that the system is in driving mode. - Value: **common.event.DRIVE_MODE** - Required subscriber permissions: none - ## COMMON_EVENT_HOME_MODE (Reserved, not supported yet) Indicates that the system is in home mode. - Value: **common.event.HOME_MODE** - Required subscriber permissions: none - ## COMMON_EVENT_OFFICE_MODE (Reserved, not supported yet) Indicates that the system is in office mode. - Value: **common.event.OFFICE_MODE** - Required subscriber permissions: none - ## COMMON_EVENT_USER_STARTED (Reserved, not supported yet) Indicates that the user has been started. - Value: **usual.event.USER_STARTED** - Required subscriber permissions: none - ## COMMON_EVENT_USER_BACKGROUND (Reserved, not supported yet) Indicates that the user has been brought to the background. - Value: **usual.event.USER_BACKGROUND** - Required subscriber permissions: none - ## COMMON_EVENT_USER_FOREGROUND (Reserved, not supported yet) Indicates that the user has been brought to the foreground. - Value: **usual.event.USER_FOREGROUND** - Required subscriber permissions: none - ## COMMON_EVENT_USER_SWITCHED Indicates that user switching is in progress. - Value: **usual.event.USER_SWITCHED** - Required subscriber permissions: ohos.permission.MANAGE_LOCAL_ACCOUNTS - ## COMMON_EVENT_USER_STARTING (Reserved, not supported yet) Indicates that the user is being started. - Value: **usual.event.USER_STARTING** - Required subscriber permissions: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS - ## COMMON_EVENT_USER_UNLOCKED (Reserved, not supported yet) Indicates that the credential-encrypted storage has been unlocked for the current user after the device is restarted. - Value: **usual.event.USER_UNLOCKED** - Required subscriber permissions: none - ## COMMON_EVENT_USER_STOPPING (Reserved, not supported yet) Indicates that the user is going to be stopped. - Value: **usual.event.USER_STOPPING** - Required subscriber permissions: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS - ## COMMON_EVENT_USER_STOPPED (Reserved, not supported yet) Indicates that the user has been stopped. - Value: **usual.event.USER_STOPPED** @@ -665,11 +618,15 @@ Indicates that the system charging type has changed. This event is available onl - Value: **usual.event.CHARGE_TYPE_CHANGED** - Required subscriber permissions: none -## COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED +## [COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED](./common_event/commonEvent-resourceschedule.md) (Reserved, not supported yet) Indicates that the system idle mode has changed. - Value: **usual.event.DEVICE_IDLE_MODE_CHANGED** - Required subscriber permissions: none +## [COMMON_EVENT_DEVICE_IDLE_EXEMPTION_LIST_UPDATED10+](./common_event/commonEvent-resourceschedule.md) +Indicates that the exemption list for resource usage restrictions has been updated in idle mode. This event is for system applications only. +- Value: **usual.event.DEVICE_IDLE_EXEMPTION_LIST_UPDATED** +- Required subscriber permissions: none ## COMMON_EVENT_POWER_SAVE_MODE_CHANGED Indicates that the system power saving mode has changed. @@ -766,61 +723,51 @@ Indicates that a user has been removed from the system. - Value: **common.event.IVI_VOLTAGE_RECOVERY** - Required subscriber permissions: none - ## COMMON_EVENT_IVI_TEMPERATURE_RECOVERY (Reserved, not supported yet) Indicates that the temperature of the IVI system is restored to normal. - Value: **common.event.IVI_TEMPERATURE_RECOVERY** - Required subscriber permissions: none - ## COMMON_EVENT_IVI_ACTIVE (Reserved, not supported yet) Indicates that the battery service of the IVI system is active. - Value: **common.event.IVI_ACTIVE** - Required subscriber permissions: none - ## COMMON_EVENT_USB_STATE9+ Indicates that the USB device state has changed. -- Value: **usual.event.hardware.usb.action.USB_STATE** -- Required subscriber permissions: none +For details, see [Common Events of the USB Subsystem](common_event/commonEvent-usb.md). ## COMMON_EVENT_USB_PORT_CHANGED9+ Indicates that the USB port state of the device has changed. -- Value: **usual.event.hardware.usb.action.USB_PORT_CHANGED** -- Required subscriber permissions: none +For details, see [Common Events of the USB Subsystem](common_event/commonEvent-usb.md). ## COMMON_EVENT_USB_DEVICE_ATTACHED Indicates that a USB device has been attached to the device functioning as a USB host. -- Value: **usual.event.hardware.usb.action.USB_DEVICE_ATTACHED** -- Required subscriber permissions: none +For details, see [Common Events of the USB Subsystem](common_event/commonEvent-usb.md). ## COMMON_EVENT_USB_DEVICE_DETACHED Indicates that a USB device has been detached from the device functioning as a USB host. -- Value: **usual.event.hardware.usb.action.USB_DEVICE_DETACHED** -- Required subscriber permissions: none +For details, see [Common Events of the USB Subsystem](common_event/commonEvent-usb.md). ## COMMON_EVENT_USB_ACCESSORY_ATTACHED (Reserved, not supported yet) Indicates that a USB accessory was attached. -- Value: **usual.event.hardware.usb.action.USB_ACCESSORY_ATTACHED** -- Required subscriber permissions: none +For details, see [Common Events of the USB Subsystem](common_event/commonEvent-usb.md). ## COMMON_EVENT_USB_ACCESSORY_DETACHED (Reserved, not supported yet) Indicates that a USB accessory was detached. -- Value: **usual.event.data.DISK_MOUNTED** -- Required subscriber permissions: none +For details, see [Common Events of the USB Subsystem](common_event/commonEvent-usb.md). ## COMMON_EVENT_DISK_REMOVED (Reserved, not supported yet) Indicates that an external storage device was removed. - Value: **usual.event.data.DISK_BAD_REMOVAL** - Required subscriber permissions: ohos.permission.STORAGE_MANAGER - ## COMMON_EVENT_DISK_UNMOUNTED (Reserved, not supported yet) Indicates that an external storage device was unmounted. - Value: **usual.event.data.DISK_UNMOUNTABLE** @@ -838,92 +785,77 @@ Indicates that a USB device has been detached from the device functioning as a U - Value: usual.event.data.DISK_REMOVED - Required subscriber permissions: ohos.permission.STORAGE_MANAGER - ## COMMON_EVENT_DISK_UNMOUNTABLE (Reserved, not supported yet) Indicates that an external storage device is unmountable when the card is inserted. - Value: **usual.event.data.DISK_UNMOUNTED** - Required subscriber permissions: ohos.permission.STORAGE_MANAGER - ## COMMON_EVENT_DISK_EJECT (Reserved, not supported yet) Indicates that an external storage device was ejected (at the software level). - Value: **usual.event.data.DISK_EJECT** - Required subscriber permissions: ohos.permission.STORAGE_MANAGER - ## COMMON_EVENT_VOLUME_REMOVED9+ Indicates that an external storage device was removed. - Value: **usual.event.data.VOLUME_REMOVED** - Required subscriber permissions: ohos.permission.STORAGE_MANAGER - ## COMMON_EVENT_VOLUME_UNMOUNTED9+ Indicates that an external storage device was unmounted. - Value: **usual.event.data.VOLUME_UNMOUNTED** - Required subscriber permissions: ohos.permission.STORAGE_MANAGER - ## COMMON_EVENT_VOLUME_MOUNTED9+ Indicates that an external storage device was mounted. - Value: **usual.event.data.VOLUME_MOUNTED** - Required subscriber permissions: ohos.permission.STORAGE_MANAGER - ## COMMON_EVENT_VOLUME_BAD_REMOVAL9+ Indicates that an external storage device was removed without being unmounted. - Value: **usual.event.data.VOLUME_BAD_REMOVAL** - Required subscriber permissions: ohos.permission.STORAGE_MANAGER - ## COMMON_EVENT_VOLUME_EJECT9+ Indicates that an external storage device was ejected (at the software level). - Value: usual.event.data.VOLUME_EJECT - Required subscriber permissions: ohos.permission.STORAGE_MANAGER - ## COMMON_EVENT_VISIBLE_ACCOUNTS_UPDATED (Reserved, not supported yet) Indicates that the account visibility changed. - Value: **usual.event.data.VISIBLE_ACCOUNTS_UPDATED** - Required subscriber permissions: ohos.permission.GET_APP_ACCOUNTS - ## COMMON_EVENT_ACCOUNT_DELETED (Reserved, not supported yet) Indicates that an account was deleted. - Value: **usual.event.data.ACCOUNT_DELETED** - Required subscriber permissions: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS - ## COMMON_EVENT_FOUNDATION_READY (Reserved, not supported yet) Indicates that the foundation is ready. - Value: **usual.event.data.FOUNDATION_READY** - Required subscriber permissions: ohos.permission.RECEIVER_STARTUP_COMPLETED - ## COMMON_EVENT_AIRPLANE_MODE_CHANGED Indicates that the airplane mode of the device has changed. - Value: **usual.event.AIRPLANE_MODE** - Required subscriber permissions: none - ## COMMON_EVENT_SPLIT_SCREEN Indicates that the screen has been split. - Value: **usual.event.SPLIT_SCREEN** - Required subscriber permissions: ohos.permission.RECEIVER_SPLIT_SCREEN - ## COMMON_EVENT_SLOT_CHANGE9+ Indicates that the notification slot has been updated. - Value: **usual.event.SLOT_CHANGE** - Required subscriber permissions: ohos.permission.NOTIFICATION_CONTROLLER - ## COMMON_EVENT_SPN_INFO_CHANGED9+ Indicates that the SPN displayed has been updated. - Value: **usual.event.SPN_INFO_CHANGED** - Required subscriber permissions: none - -## COMMON_EVENT_QUICK_FIX_APPLY_RESULT9+ +## [COMMON_EVENT_QUICK_FIX_APPLY_RESULT9+](./common_event/commonEvent-ability.md) Indicates the result of applying a quick fix to the application. - Value: **usual.event.QUICK_FIX_APPLY_RESULT** - Required subscriber permissions: none @@ -1049,3 +981,6 @@ Indicates that the screen is unlocked. - Value: **usual.event.SCREEN_UNLOCKED** - Required subscriber permissions: none +## [COMMON_EVENT_QUICK_FIX_REVOKE_RESULT10+](./common_event/commonEvent-ability.md#common_event_quick_fix_revoke_result10) + +ָIndicates the result of revoking a quick fix to the application. \ No newline at end of file diff --git a/en/application-dev/reference/apis/common_event/Readme-EN.md b/en/application-dev/reference/apis/common_event/Readme-EN.md new file mode 100644 index 0000000000000000000000000000000000000000..9c61482c2e615aa50161c5482c8c46bb91027d1a --- /dev/null +++ b/en/application-dev/reference/apis/common_event/Readme-EN.md @@ -0,0 +1,8 @@ +# Common Events + +- [Common Events of the Ability Subsystem](commonEvent-ability.md) +- [Common Events of the Bundle Management Subsystem](commonEvent-bundleManager.md) +- [Common Events of the Notification Service](commonEvent-ans.md) +- [Common Events of the Resource Scheduling Subsystem](commonEvent-resourceschedule.md) +- [Common Events of the Telephony Subsystem](commonEvent-telephony.md) +- [Common Events of the USB Subsystem](commonEvent-usb.md) diff --git a/en/application-dev/reference/apis/common_event/commonEvent-ability.md b/en/application-dev/reference/apis/common_event/commonEvent-ability.md new file mode 100644 index 0000000000000000000000000000000000000000..e19380c4e089bcfe94eacdb0f04ad234e1d657f0 --- /dev/null +++ b/en/application-dev/reference/apis/common_event/commonEvent-ability.md @@ -0,0 +1,47 @@ +# Common Events of the Ability Subsystem +This document lists the common system events provided by the Ability subsystem to applications. + +## COMMON_EVENT_BOOT_COMPLETED + +Indicates that the user has finished the boot process. + +- Constant value: "usual.event.BOOT_COMPLETED" +- Required subscriber permissions: ohos.permission.RECEIVER_STARTUP_COMPLETED + +When the specified user finishes the boot process on the device, the event notification service is triggered to publish this event. + +## COMMON_EVENT_PACKAGE_RESTARTED + +Indicates that the user has restarted the application package and killed all its processes. + +- Constant value: "usual.event.PACKAGE_RESTARTED" +- Required subscriber permissions: none + +When the specified user restarts the application and kills all its processes, the event notification service is triggered to publish this event. + +## COMMON_EVENT_PACKAGE_DATA_CLEARED + +Indicates that the user cleared the application package data. + +- Constant value: "usual.event.PACKAGE_DATA_CLEARED" +- Required subscriber permissions: none + +When the specified user clears the application package data on the device, the event notification service is triggered to publish this event. + +## COMMON_EVENT_QUICK_FIX_APPLY_RESULT9+ + +Indicates the result of applying a quick fix to the application. + +- Constant value: "usual.event.QUICK_FIX_APPLY_RESULT" +- Required subscriber permissions: none + +When the specified user applies a quick fix to the application on the device, the event notification service is triggered to publish this event. + +## COMMON_EVENT_QUICK_FIX_REVOKE_RESULT10+ + +Indicates the result of revoking a quick fix to the application. + +- Constant value: "usual.event.QUICK_FIX_REVOKE_RESULT" +- Required subscriber permissions: none + +When a quick fix to the application is revoked on the device, the event notification service is triggered to publish this event. diff --git a/en/application-dev/reference/apis/common_event/commonEvent-resourceschedule.md b/en/application-dev/reference/apis/common_event/commonEvent-resourceschedule.md new file mode 100644 index 0000000000000000000000000000000000000000..41e7e2adae16d45e83fc527010939bdb5cfe119c --- /dev/null +++ b/en/application-dev/reference/apis/common_event/commonEvent-resourceschedule.md @@ -0,0 +1,24 @@ +# Common Events of the Resource Scheduling Subsystem +This document lists the common system events provided by the resource scheduling subsystem to applications. Applications can use [APIs](../js-apis-commonEventManager.md) to subscribe to common system events. + +## COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED +Indicates that the system idle mode has changed. + +- Constant value: "usual.event.DEVICE_IDLE_MODE_CHANGED" +- Required subscriber permissions: none + +When the user does not use the device for the specified period of time and the screen is turned off, the system delays the CPU and network access by background applications, and the event notification service is triggered to publish this event. + +APIs related to this event: **deviceStandby**. + +## COMMON_EVENT_DEVICE_IDLE_EXEMPTION_LIST_UPDATED +Indicates that the exemption list for resource usage restrictions has been updated in idle mode. + +- Constant value: "usual.event.DEVICE_IDLE_EXEMPTION_LIST_UPDATED" +- Required subscriber permissions: none + +When the exemption list for resource usage restrictions is updated, the event notification service is triggered to publish this event. +Resources include application network access, Timer usage, and WorkScheduler task usage. +System applications can call JavaScript APIs to apply for removing resource usage restrictions. + +APIs related to this event: **deviceStandby**. diff --git a/en/application-dev/reference/apis/common_event/commonEvent-usb.md b/en/application-dev/reference/apis/common_event/commonEvent-usb.md new file mode 100644 index 0000000000000000000000000000000000000000..4a42b32faee0ee46fe7c24f49db8c5c13a69cb54 --- /dev/null +++ b/en/application-dev/reference/apis/common_event/commonEvent-usb.md @@ -0,0 +1,57 @@ +# Common Events of the USB Subsystem +This document lists the common system events provided by the USB subsystem to applications. Applications can use [APIs](../js-apis-commonEventManager.md) to subscribe to common system events. + +## COMMON_EVENT_USB_STATE +Indicates that the USB device state has changed. + +- Constant value: "usual.event.hardware.usb.action.USB_STATE" +- Required subscriber permissions: none + +When a USB device is connected to or disconnected from the device, the event notification service is triggered to publish this event. + +## COMMON_EVENT_USB_PORT_CHANGED + +Indicates that the USB port state of the device has changed. + +- Constant value: "usual.event.hardware.usb.action.USB_PORT_CHANGED" +- Required subscriber permissions: none + +When the USB port status changes, the event notification service is triggered to publish this event. + +APIs related to this event: **dataRole** parameter in [setPortRoles](../js-apis-usbManager.md#usbsetportroles). + +## COMMON_EVENT_USB_DEVICE_ATTACHED + +Indicates that a USB device has been attached to the device functioning as a USB host. + +- Constant value: "usual.event.hardware.usb.action.USB_DEVICE_ATTACHED" +- Required subscriber permissions: none + +When a USB device is attached, the event notification service is triggered to publish this event. + +APIs related to this event: [USBDevice](../js-apis-usbManager.md#usbdevice). + +## COMMON_EVENT_USB_DEVICE_DETACHED + +Indicates that a USB device has been detached from the device functioning as a USB host. + +- Constant value: "usual.event.hardware.usb.action.USB_DEVICE_DETACHED" +- Required subscriber permissions: none + +When a USB device is deattached, the event notification service is triggered to publish this event. + +APIs related to this event: [USBDevice](../js-apis-usbManager.md#usbdevice). + +## COMMON_EVENT_USB_ACCESSORY_ATTACHED + +(Reserved, not supported yet) Indicates that a USB accessory was attached. + +- Constant value: "usual.event.hardware.usb.action.USB_ACCESSORY_ATTACHED" +- Required subscriber permissions: none + +## COMMON_EVENT_USB_ACCESSORY_DETACHED + +(Reserved, not supported yet) Indicates that a USB accessory was detached. + +- Constant value: "usual.event.data.DISK_MOUNTED" +- Required subscriber permissions: none diff --git a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md index 86b80960d6de170eb7def9e9bfcc88aa8913c7ad..ffedb677c4743434e3c860a6d56b7af5d19be500 100644 --- a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md +++ b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md @@ -64,7 +64,7 @@ For details about the error codes, see [Application Access Control Error Codes]( | ID| Error Message| | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 or the permissionName exceeds 256 bytes. | +| 12100001 | The parameter is invalid. The tokenID is 0, or the permissionName exceeds 256 bytes. | **Example** @@ -74,7 +74,7 @@ import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. try { - atManager.checkAccessToken(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS").then((data) => { + atManager.checkAccessToken(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS').then((data) => { console.log(`checkAccessToken success, data->${JSON.stringify(data)}`); }).catch((err) => { console.log(`checkAccessToken fail, err->${JSON.stringify(err)}`); @@ -111,14 +111,14 @@ For details about the error codes, see [Application Access Control Error Codes]( | ID| Error Message| | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 or the permissionName exceeds 256 bytes. | +| 12100001 | The parameter is invalid. The tokenID is 0, or the permissionName exceeds 256 bytes. | **Example** ```js let atManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. -let data = atManager.verifyAccessTokenSync(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); +let data = atManager.verifyAccessTokenSync(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS'); console.log(`data->${JSON.stringify(data)}`); ``` @@ -154,7 +154,7 @@ For details about the error codes, see [Application Access Control Error Codes]( | ID| Error Message| | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0, the permissionName is greater than 256 bytes, or the flags value is invalid. | +| 12100001 | The parameter is invalid. The tokenID is 0, the permissionName exceeds 256 bytes, or the flags value is invalid. | | 12100002 | The specified tokenID does not exist. | | 12100003 | The specified permission does not exist. | | 12100006 | The application specified by the tokenID is not allowed to be granted with the specified permission. Either the application is a sandbox or the tokenID is from a remote device. | @@ -169,7 +169,7 @@ let atManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. let permissionFlags = 1; try { - atManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlags).then(() => { + atManager.grantUserGrantedPermission(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS', permissionFlags).then(() => { console.log('grantUserGrantedPermission success'); }).catch((err) => { console.log(`grantUserGrantedPermission fail, err->${JSON.stringify(err)}`); @@ -221,7 +221,7 @@ let atManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. let permissionFlags = 1; try { - atManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlags, (err, data) => { + atManager.grantUserGrantedPermission(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS', permissionFlags, (err, data) => { if (err) { console.log(`grantUserGrantedPermission fail, err->${JSON.stringify(err)}`); } else { @@ -280,7 +280,7 @@ let atManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. let permissionFlags = 1; try { - atManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlags).then(() => { + atManager.revokeUserGrantedPermission(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS', permissionFlags).then(() => { console.log('revokeUserGrantedPermission success'); }).catch((err) => { console.log(`revokeUserGrantedPermission fail, err->${JSON.stringify(err)}`); @@ -332,7 +332,7 @@ let atManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. let permissionFlags = 1; try { - atManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlags, (err, data) => { + atManager.revokeUserGrantedPermission(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS', permissionFlags, (err, data) => { if (err) { console.log(`revokeUserGrantedPermission fail, err->${JSON.stringify(err)}`); } else { @@ -375,7 +375,7 @@ For details about the error codes, see [Application Access Control Error Codes]( | ID| Error Message| | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 or the permissionName exceeds 256 bytes. | +| 12100001 | The parameter is invalid. The tokenID is 0, or the permissionName exceeds 256 bytes. | | 12100002 | The specified tokenID does not exist. | | 12100003 | The specified permission does not exist. | | 12100006 | The operation is not allowed. Either the application is a sandbox or the tokenID is from a remote device. | @@ -389,7 +389,7 @@ import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. try { - atManager.getPermissionFlags(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS").then((data) => { + atManager.getPermissionFlags(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS').then((data) => { console.log(`getPermissionFlags success, data->${JSON.stringify(data)}`); }).catch((err) => { console.log(`getPermissionFlags fail, err->${JSON.stringify(err)}`); @@ -443,7 +443,7 @@ Subscribes to permission state changes of the specified applications and permiss | ------------------ | --------------------- | ---- | ------------------------------------------------------------ | | type | string | Yes | Event type to subscribe to. The value is **'permissionStateChange'**, which indicates the permission grant state change. | | tokenIDList | Array<number> | Yes | Token IDs of the applications to observe. If this parameter is left empty, the permission grant state changes of all applications are observed. | -| permissionList | Array<Permissions> | Yes | Permissions to observe. If this parameter is left empty, the grant state changes of all permissions are observed. | +| permissionList | Array<Permissions> | Yes | List of permission names. If this parameter is left empty, the grant state changes of all permissions are subscribed to. | | callback | Callback<[PermissionStateChangeInfo](#permissionstatechangeinfo9)> | Yes| Callback invoked to return the permission grant state change.| **Error codes** @@ -452,7 +452,7 @@ For details about the error codes, see [Application Access Control Error Codes]( | ID| Error Message| | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 or the permissionName exceeds 256 bytes. | +| 12100001 | The parameter is invalid. The tokenID is 0, or the permissionName exceeds 256 bytes. | | 12100004 | The interface is called repeatedly with the same input. | | 12100005 | The registration time has exceeded the limitation. | | 12100007 | Service is abnormal. | @@ -461,16 +461,16 @@ For details about the error codes, see [Application Access Control Error Codes]( **Example** ```js -import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl'; +import {Permissions} from '@ohos.abilityAccessCtrl'; import bundleManager from '@ohos.bundle.bundleManager'; let atManager = abilityAccessCtrl.createAtManager(); let appInfo = bundleManager.getApplicationInfoSync('com.example.myapplication', 0, 100); let tokenIDList: Array = [appInfo.accessTokenId]; -let permissionList: Array = ["ohos.permission.DISTRIBUTED_DATASYNC"]; +let permissionList: Array = ['ohos.permission.DISTRIBUTED_DATASYNC']; try { atManager.on('permissionStateChange', tokenIDList, permissionList, (data) => { - console.debug("receive permission state change, data:" + JSON.stringify(data)); + console.debug('receive permission state change, data:' + JSON.stringify(data)); }); } catch(err) { console.log(`catch err->${JSON.stringify(err)}`); @@ -505,20 +505,20 @@ For details about the error codes, see [Application Access Control Error Codes]( | ID| Error Message| | -------- | -------- | | 12100001 | The parameter is invalid. The tokenIDs or permissionNames in the list are all invalid. | -| 12100004 | The interface is not used together with "on". | +| 12100004 | The interface is not used together with 'on'. | | 12100007 | Service is abnormal. | | 12100008 | Out of memory. | **Example** ```js -import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl'; +import {Permissions} from '@ohos.abilityAccessCtrl'; import bundleManager from '@ohos.bundle.bundleManager'; let atManager = abilityAccessCtrl.createAtManager(); let appInfo = bundleManager.getApplicationInfoSync('com.example.myapplication', 0, 100); let tokenIDList: Array = [appInfo.accessTokenId]; -let permissionList: Array = ["ohos.permission.DISTRIBUTED_DATASYNC"]; +let permissionList: Array = ['ohos.permission.DISTRIBUTED_DATASYNC']; try { atManager.off('permissionStateChange', tokenIDList, permissionList); } catch(err) { @@ -558,7 +558,7 @@ import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. -let promise = atManager.verifyAccessToken(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); +let promise = atManager.verifyAccessToken(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS'); promise.then(data => { console.log(`promise: data->${JSON.stringify(data)}`); }); @@ -599,10 +599,10 @@ For details about the error codes, see [Application Access Control Error Codes]( import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); try { - atManager.requestPermissionsFromUser(this.context, ["ohos.permission.CAMERA"], (err, data)=>{ - console.info("data:" + JSON.stringify(data)); - console.info("data permissions:" + data.permissions); - console.info("data authResults:" + data.authResults); + atManager.requestPermissionsFromUser(this.context, ['ohos.permission.CAMERA'], (err, data)=>{ + console.info('data:' + JSON.stringify(data)); + console.info('data permissions:' + data.permissions); + console.info('data authResults:' + data.authResults); }); } catch(err) { console.log(`catch err->${JSON.stringify(err)}`); @@ -650,12 +650,12 @@ For details about the error codes, see [Application Access Control Error Codes]( import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); try { - atManager.requestPermissionsFromUser(this.context, ["ohos.permission.CAMERA"]).then((data) => { - console.info("data:" + JSON.stringify(data)); - console.info("data permissions:" + data.permissions); - console.info("data authResults:" + data.authResults); + atManager.requestPermissionsFromUser(this.context, ['ohos.permission.CAMERA']).then((data) => { + console.info('data:' + JSON.stringify(data)); + console.info('data permissions:' + data.permissions); + console.info('data authResults:' + data.authResults); }).catch((err) => { - console.info("data:" + JSON.stringify(err)); + console.info('data:' + JSON.stringify(err)); }) } catch(err) { console.log(`catch err->${JSON.stringify(err)}`); @@ -694,7 +694,7 @@ import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. -let promise = atManager.verifyAccessToken(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); +let promise = atManager.verifyAccessToken(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS'); promise.then(data => { console.log(`promise: data->${JSON.stringify(data)}`); }); @@ -727,14 +727,14 @@ For details about the error codes, see [Application Access Control Error Codes]( | ID| Error Message| | -------- | -------- | -| 12100001 | The parameter is invalid. The tokenID is 0 or the permissionName exceeds 256 bytes. | +| 12100001 | The parameter is invalid. The tokenID is 0, or the permissionName exceeds 256 bytes. | **Example** ```js let atManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. -let data = atManager.checkAccessTokenSync(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); +let data = atManager.checkAccessTokenSync(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS'); console.log(`data->${JSON.stringify(data)}`); ``` diff --git a/en/application-dev/reference/apis/js-apis-accessibility-config.md b/en/application-dev/reference/apis/js-apis-accessibility-config.md index 673d820d17407a35991da01b0b25ee48cd51c7eb..09fb6c49bf265b0a4ef22ddd38dc46370097304d 100644 --- a/en/application-dev/reference/apis/js-apis-accessibility-config.md +++ b/en/application-dev/reference/apis/js-apis-accessibility-config.md @@ -247,7 +247,7 @@ Cancels the listener for changes in the list of enabled accessibility extension | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Listening type. The value is fixed at **'enabledAccessibilityExtensionListChange'**, indicating listening for changes in the list of enabled accessibility extension abilities.| -| callback | Callback<void> | No| Callback invoked when the list of enabled accessibility extension abilities changes.| +| callback | Callback<void> | No| Callback for the event.| **Example** @@ -425,7 +425,7 @@ Cancels the listener for attribute changes. This API uses an asynchronous callba | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | Callback<T> | No| Callback invoked when the list of enabled accessibility extension abilities changes.| +| callback | Callback<T> | No| Callback for the event.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-accessibility.md b/en/application-dev/reference/apis/js-apis-accessibility.md index 0b00bbfdf4c7c50ae3ffbd0d0fd1cc6effdb2f7d..2f92eaaf3052bd34f76baefc6a04de7a8d59b4a4 100644 --- a/en/application-dev/reference/apis/js-apis-accessibility.md +++ b/en/application-dev/reference/apis/js-apis-accessibility.md @@ -18,9 +18,9 @@ Enumerates the states of an accessibility application. **System capability**: SystemCapability.BarrierFree.Accessibility.Core -| Name| Description| -| -------- | -------- | -| enable | The accessibility application is enabled.| +| Name | Description | +| ------- | -------- | +| enable | The accessibility application is enabled.| | disable | The accessibility application is disabled.| | install | The accessibility application has been installed.| @@ -30,13 +30,13 @@ Enumerates the types of accessibility applications. **System capability**: SystemCapability.BarrierFree.Accessibility.Core -| Name| Description| -| -------- | -------- | -| audible | The accessibility application provides audible feedback.| -| generic | The accessibility application provides generic feedback.| -| haptic | The accessibility application provides haptic feedback.| -| spoken | The accessibility application provides spoken feedback.| -| visual | The accessibility application provides visual feedback.| +| Name | Description | +| ---------------- | --------- | +| audible | The accessibility application provides audible feedback.| +| generic | The accessibility application provides generic feedback.| +| haptic | The accessibility application provides haptic feedback.| +| spoken | The accessibility application provides spoken feedback.| +| visual | The accessibility application provides visual feedback.| | all9+ | All the preceding types.| ## AccessibilityAbilityInfo @@ -47,16 +47,16 @@ Provides information about an accessibility application. ### Attributes -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| id | string | Yes| No| Ability ID.| -| name | string | Yes| No| Ability name.| -| bundleName | string | Yes| No| Bundle name.| -| targetBundleNames9+ | Array<string> | Yes| No| Name of the target bundle.| -| abilityTypes | Array<[AbilityType](#abilitytype)> | Yes| No| Accessibility application type.| -| capabilities | Array<[Capability](#capability)> | Yes| No| Capabilities list of the accessibility application.| -| description | string | Yes| No| Description of the accessibility application.| -| eventTypes | Array<[EventType](#eventtype)> | Yes| No| List of events that the accessibility application focuses on.| +| Name | Type | Readable | Writable | Description | +| ------------------------------ | ---------------------------------------- | ---- | ---- | ---------------- | +| id | string | Yes | No | Ability ID.| +| name | string | Yes | No | Ability name. | +| bundleName | string | Yes | No | Bundle name. | +| targetBundleNames9+ | Array<string> | Yes | No | Name of the target bundle. | +| abilityTypes | Array<[AbilityType](#abilitytype)> | Yes | No | Accessibility application type. | +| capabilities | Array<[Capability](#capability)> | Yes | No | Capabilities list of the accessibility application. | +| description | string | Yes | No | Description of the accessibility application. | +| eventTypes | Array<[EventType](#eventtype)> | Yes | No | List of events that the accessibility application focuses on. | ## Action @@ -64,24 +64,24 @@ Describes the target action supported by an accessibility application. **System capability**: SystemCapability.BarrierFree.Accessibility.Core -| Name| Description| -| -------- | -------- | -| click | Clicking.| -| longClick | Long pressing.| -| scrollForward | Scrolling forward. Not supported currently. | -| scrollBackward | Scrolling backward. Not supported currently. | -| focus | Obtaining focus. Not supported currently. | -| clearFocus | Clearing focus. Not supported currently. | -| clearSelection | Clearing selection. Not supported currently. | -| accessibilityFocus | Obtaining the accessibility focus. | -| clearAccessibilityFocus | Clearing the accessibility focus. | -| cut | Cut. Not supported currently. | -| copy | Copy. Not supported currently. | -| paste | Paste. Not supported currently. | -| select | Select. Not supported currently. | -| setText | Setting the text. Not supported currently. | -| delete | Delete. Not supported currently. | -| setSelection | Setting the selection. Not supported currently. | +| Name | Description | +| ----------------------- | ------------------ | +| click | Clicking. | +| longClick | Long pressing. | +| scrollForward | Scrolling forward. Not supported currently.| +| scrollBackward | Scrolling backward. Not supported currently.| +| focus | Obtaining focus. Not supported currently.| +| clearFocus | Clearing focus. Not supported currently.| +| clearSelection | Clearing selection. Not supported currently.| +| accessibilityFocus | Obtaining the accessibility focus. | +| clearAccessibilityFocus | Clearing the accessibility focus. | +| cut | Cut. Not supported currently. | +| copy | Copy. Not supported currently. | +| paste | Paste. Not supported currently. | +| select | Select. Not supported currently. | +| setText | Setting the text. Not supported currently.| +| delete | Delete. Not supported currently. | +| setSelection | Setting the selection. Not supported currently. | ## Capability @@ -89,13 +89,13 @@ Enumerates the capabilities of an accessibility application. **System capability**: SystemCapability.BarrierFree.Accessibility.Core -| Name| Description| -| -------- | -------- | -| retrieve | Capability to retrieve the window content.| -| touchGuide | Capability of touch guide mode.| -| keyEventObserver | Capability to filter key events.| -| zoom | Capability to control the display zoom level. Not supported currently. | -| gesture | Capability to perform gesture actions.| +| Name | Description | +| ---------------- | --------------------- | +| retrieve | Capability to retrieve the window content. | +| touchGuide | Capability of touch guide mode. | +| keyEventObserver | Capability to filter key events. | +| zoom | Capability to control the display zoom level. Not supported currently.| +| gesture | Capability to perform gesture actions. | ## CaptionsFontEdgeType8+ @@ -103,12 +103,12 @@ Enumerates the font edge types of captions. **System capability**: SystemCapability.BarrierFree.Accessibility.Hearing -| Name| Description| -| -------- | -------- | -| none | No effect.| -| raised | Raised effect.| -| depressed | Depressed effect.| -| uniform | Uniform effect.| +| Name | Description | +| ---------- | ----- | +| none | No effect. | +| raised | Raised effect.| +| depressed | Depressed effect.| +| uniform | Uniform effect.| | dropShadow | Drop shadow effect.| ## CaptionsFontFamily8+ @@ -117,16 +117,16 @@ Enumerates the font families of captions. **System capability**: SystemCapability.BarrierFree.Accessibility.Hearing -| Name| Description| -| -------- | -------- | -| default | Default font family.| -| monospacedSerif | Monospaced Serif fonts, which use the same width for each character.| -| serif | Serif fonts.| +| Name | Description | +| ------------------- | ----------------- | +| default | Default font family. | +| monospacedSerif | Monospaced Serif fonts, which use the same width for each character. | +| serif | Serif fonts. | | monospacedSansSerif | Monospaced Sans Serif fonts, which use the same width for each character.| -| sansSerif | Sans Serif fonts.| -| casual | Casual fonts.| -| cursive | Cursive fonts.| -| smallCapitals | Small caps fonts.| +| sansSerif | Sans Serif fonts. | +| casual | Casual fonts. | +| cursive | Cursive fonts. | +| smallCapitals | Small caps fonts. | ## CaptionsStyle8+ @@ -134,14 +134,14 @@ Describes the style of captions. **System capability**: SystemCapability.BarrierFree.Accessibility.Hearing -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| fontFamily | [CaptionsFontFamily](#captionsfontfamily8) | Yes| No| Font family of captions.| -| fontScale | number | Yes| No| Font scale of captions.| -| fontColor | number \| string | Yes| No| Font color of captions.| -| fontEdgeType | [CaptionsFontEdgeType](#captionsfontedgetype8) | Yes| No| Font edge type of captions.| -| backgroundColor | number \| string | Yes| No| Background color of captions.| -| windowColor | number \| string | Yes| No| Window color of captions.| +| Name | Type | Readable | Writable | Description | +| --------------- | ---------------------------------------- | ---- | ---- | ----------- | +| fontFamily | [CaptionsFontFamily](#captionsfontfamily8) | Yes | No | Font family of captions. | +| fontScale | number | Yes | No | Font scale of captions.| +| fontColor | number \| string | Yes | No | Font color of captions. | +| fontEdgeType | [CaptionsFontEdgeType](#captionsfontedgetype8) | Yes | No | Font edge type of captions. | +| backgroundColor | number \| string | Yes | No | Background color of captions. | +| windowColor | number \| string | Yes | No | Window color of captions. | ## CaptionsManager8+ @@ -151,10 +151,10 @@ Implements configuration management for captions. Before calling any API of **Ca ### Attributes -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| enabled | boolean | Yes| No| Whether to enable captions configuration.| -| style | [CaptionsStyle](#captionsstyle8) | Yes| No| Style of captions.| +| Name | Type | Readable | Writable | Description | +| ------- | -------------------------------- | ---- | ---- | ----------- | +| enabled | boolean | Yes | No | Whether to enable captions configuration.| +| style | [CaptionsStyle](#captionsstyle8) | Yes | No | Style of captions. | ### on('enableChange') @@ -164,10 +164,10 @@ Enables listening for the enabled status changes of captions configuration. This **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the event to listen for, which is set to **'enableChange'** in this API.| -| callback | Callback<boolean> | Yes| Callback invoked when the enabled status of captions configuration changes.| +| Name | Type | Mandatory | Description | +| -------- | ----------------------- | ---- | --------------------------------------- | +| type | string | Yes | Type of the event to listen for, which is set to **'enableChange'** in this API.| +| callback | Callback<boolean> | Yes | Callback invoked when the enabled status of captions configuration changes. | **Example** @@ -190,10 +190,10 @@ Enables listening for captions style changes. This API uses an asynchronous call **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the event to listen for, which is set to **'styleChange'** in this API.| -| callback | Callback<[CaptionsStyle](#captionsstyle8)> | Yes| Callback invoked when the style of captions changes.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------- | +| type | string | Yes | Type of the event to listen for, which is set to **'styleChange'** in this API.| +| callback | Callback<[CaptionsStyle](#captionsstyle8)> | Yes | Callback invoked when the style of captions changes. | **Example** @@ -218,10 +218,10 @@ Disables listening for the enabled status changes of captions configuration. Thi **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the event to listen for, which is set to **'enableChange'** in this API.| -| callback | Callback<boolean> | No| Callback invoked when the enabled status of captions configuration changes.| +| Name | Type | Mandatory | Description | +| -------- | ----------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Type of the event to listen for, which is set to **'enableChange'** in this API.| +| callback | Callback<boolean> | No | Callback for the event. | **Example** @@ -244,10 +244,10 @@ Disables listening for captions style changes. This API uses an asynchronous cal **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the event to listen for, which is set to **'styleChange'** in this API.| -| callback | Callback<[CaptionsStyle](#captionsstyle8)> | No| Callback invoked when the style of captions changes.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------------------ | +| type | string | Yes | Type of the event to listen for, which is set to **'styleChange'** in this API.| +| callback | Callback<[CaptionsStyle](#captionsstyle8)> | No | Callback for the event. | **Example** @@ -272,22 +272,22 @@ Describes a GUI change event. ### Attributes -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| type | [EventType](#eventtype) | Yes| Yes| Accessibility event type.| -| windowUpdateType | [WindowUpdateType](#windowupdatetype) | Yes| Yes| Window update type.| -| bundleName | string | Yes| Yes| Target application name.| -| componentType | string | Yes| Yes| Type of the event source component, for example, button or chart.| -| pageId | number | Yes| Yes| Page ID of the event source.| -| description | string | Yes| Yes| Event description. Not supported currently. | -| triggerAction | [Action](#action) | Yes| Yes| Action that triggers the event.| -| textMoveUnit | [TextMoveUnit](#textmoveunit) | Yes| Yes| Text movement unit. Not supported currently. | -| contents | Array<string> | Yes| Yes| Array of contents.| -| lastContent | string | Yes| Yes| Latest content.| -| beginIndex | number | Yes| Yes| Sequence number of the first item displayed on the page. Not supported currently. | -| currentIndex | number | Yes| Yes| Sequence number of the current item. Not supported currently. | -| endIndex | number | Yes| Yes| Sequence number of the last item displayed on the page. Not supported currently. | -| itemCount | number | Yes| Yes| Total number of items. Not supported currently. | +| Name | Type | Readable | Writable | Description | +| ---------------- | ------------------------------------- | ---- | ---- | --------------------- | +| type | [EventType](#eventtype) | Yes | Yes | Accessibility event type. | +| windowUpdateType | [WindowUpdateType](#windowupdatetype) | Yes | Yes | Window update type. | +| bundleName | string | Yes | Yes | Target application name. | +| componentType | string | Yes | Yes | Type of the event source component, for example, button or chart. | +| pageId | number | Yes | Yes | Page ID of the event source. | +| description | string | Yes | Yes | Event description. Not supported currently. | +| triggerAction | [Action](#action) | Yes | Yes | Action that triggers the event. | +| textMoveUnit | [TextMoveUnit](#textmoveunit) | Yes | Yes | Text movement unit. Not supported currently. | +| contents | Array<string> | Yes | Yes | Array of contents. | +| lastContent | string | Yes | Yes | Latest content. | +| beginIndex | number | Yes | Yes | Sequence number of the first item displayed on the page. Not supported currently.| +| currentIndex | number | Yes | Yes | Sequence number of the current item. Not supported currently. | +| endIndex | number | Yes | Yes | Sequence number of the last item displayed on the page. Not supported currently.| +| itemCount | number | Yes | Yes | Total number of items. Not supported currently. | ### constructor @@ -299,9 +299,9 @@ Implements a constructor. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| jsonObject | string | Yes| JSON string required for creating an object.| +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | -------------------- | +| jsonObject | string | Yes | JSON string required for creating an object.| **Example** @@ -319,19 +319,19 @@ Enumerates accessibility event types. **System capability**: SystemCapability.BarrierFree.Accessibility.Core -| Name| Description| -| -------- | -------- | -| click | Event of clicking a component.| -| longClick | Event of long-pressing a component.| -| select | Event of selecting a component. Not supported currently. | -| focus | Event indicating that the component obtains the focus. Not supported currently. | -| textUpdate | Event indicating that the component text has been updated. Not supported currently. | -| hoverEnter | Event indicating that the hover enters a component. Not supported currently. | -| hoverExit | Event indicating that the hover exits a component. Not supported currently. | -| scroll | Event of the scroll view. Not supported currently. | -| textSelectionUpdate | Event indicating that the selected text has been updated. Not supported currently. | -| accessibilityFocus | Event indicating that the accessibility focus has been obtained.| -| accessibilityFocusClear | Event indicating that the accessibility focus has been cleared.| +| Name | Description | +| ----------------------- | ---------------------- | +| click | Event of clicking a component. | +| longClick | Event of long-pressing a component. | +| select | Event of selecting a component. Not supported currently. | +| focus | Event indicating that the component obtains the focus. Not supported currently. | +| textUpdate | Event indicating that the component text has been updated. Not supported currently.| +| hoverEnter | Event indicating that the hover enters a component. Not supported currently. | +| hoverExit | Event indicating that the hover exits a component. Not supported currently. | +| scroll | Event of the scroll view. Not supported currently. | +| textSelectionUpdate | Event indicating that the selected text has been updated. Not supported currently.| +| accessibilityFocus | Event indicating that the accessibility focus has been obtained. | +| accessibilityFocusClear | Event indicating that the accessibility focus has been cleared. | ## TextMoveUnit @@ -339,12 +339,12 @@ Enumerates the movement units for traversing the node text. **System capability**: SystemCapability.BarrierFree.Accessibility.Core -| Name| Description| -| -------- | -------- | -| char | The movement unit for traversing the node text is by character.| -| word | The movement unit for traversing the node text is by word.| -| line | The movement unit for traversing the node text is by line.| -| page | The movement unit for traversing the node text is by page.| +| Name | Description | +| --------- | --------------- | +| char | The movement unit for traversing the node text is by character.| +| word | The movement unit for traversing the node text is by word. | +| line | The movement unit for traversing the node text is by line. | +| page | The movement unit for traversing the node text is by page. | | paragraph | The movement unit for traversing the node text is by paragraph.| ## WindowUpdateType @@ -353,13 +353,13 @@ Enumerates window update types. **System capability**: SystemCapability.BarrierFree.Accessibility.Core -| Name| Description| -| -------- | -------- | -| add | Window adding.| -| remove | Window deletion.| -| bounds | Window boundary change.| +| Name | Description | +| ------ | ------------------ | +| add | Window adding. | +| remove | Window deletion. | +| bounds | Window boundary change. | | active | Window activity change.| -| focus | Window focus change.| +| focus | Window focus change. | ## accessibility.getAbilityLists(deprecated) @@ -370,21 +370,21 @@ Obtains the accessibility application list. This API uses a promise to return th > **NOTE** > > This API is supported since API version 7 and deprecated since API version 9. -> You are advised to use [getAccessibilityExtensionList()](#accessibilitygetaccessibilityextensionlist9). +> You are advised to use[getAccessibilityExtensionList()](#accessibilitygetaccessibilityextensionlist9). **System capability**: SystemCapability.BarrierFree.Accessibility.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| abilityType | [AbilityType](#abilitytype) | Yes| Accessibility application type.| -| stateType | [AbilityState](#abilitystate) | Yes| Accessibility application status.| +| Name | Type | Mandatory | Description | +| ----------- | ----------------------------- | ---- | -------- | +| abilityType | [AbilityType](#abilitytype) | Yes | Accessibility application type.| +| stateType | [AbilityState](#abilitystate) | Yes | Accessibility application status.| **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ---------------------------------------- | --------------------- | | Promise<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Promise used to return the accessibility application list.| **Example** @@ -426,11 +426,11 @@ Obtains the accessibility application list. This API uses an asynchronous callba **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| abilityType | [AbilityType](#abilitytype) | Yes| Accessibility application type.| -| stateType | [AbilityState](#abilitystate) | Yes| Accessibility application status.| -| callback | AsyncCallback<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Yes| Callback used to return the accessibility application list.| +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | ---------------- | +| abilityType | [AbilityType](#abilitytype) | Yes | Accessibility application type. | +| stateType | [AbilityState](#abilitystate) | Yes | Accessibility application status. | +| callback | AsyncCallback<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Yes | Callback used to return the accessibility application list.| **Example** @@ -470,15 +470,15 @@ Obtains the accessibility application list. This API uses a promise to return th **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| abilityType | [AbilityType](#abilitytype) | Yes| Accessibility application type.| -| stateType | [AbilityState](#abilitystate) | Yes| Accessibility application status.| +| Name | Type | Mandatory | Description | +| ----------- | ----------------------------- | ---- | -------- | +| abilityType | [AbilityType](#abilitytype) | Yes | Accessibility application type.| +| stateType | [AbilityState](#abilitystate) | Yes | Accessibility application status.| **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ---------------------------------------- | --------------------- | | Promise<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Promise used to return the accessibility application list.| **Example** @@ -515,11 +515,11 @@ Obtains the accessibility application list. This API uses an asynchronous callba **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| abilityType | [AbilityType](#abilitytype) | Yes| Accessibility application type.| -| stateType | [AbilityState](#abilitystate) | Yes| Accessibility application status.| -| callback | AsyncCallback<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Yes| Callback used to return the accessibility application list.| +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | ---------------- | +| abilityType | [AbilityType](#abilitytype) | Yes | Accessibility application type. | +| stateType | [AbilityState](#abilitystate) | Yes | Accessibility application status. | +| callback | AsyncCallback<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Yes | Callback used to return the accessibility application list.| **Example** @@ -557,8 +557,8 @@ Obtains a **CaptionsManager** instance. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------------------------------------ | ---------- | | [CaptionsManager](#captionsmanager8) | Captions configuration.| **Example** @@ -577,10 +577,10 @@ Enables listening for the enabled status changes of the accessibility applicatio **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the event to listen for, which is set to **'accessibilityStateChange'** in this API.| -| callback | Callback<boolean> | Yes| Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ----------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Type of the event to listen for, which is set to **'accessibilityStateChange'** in this API.| +| callback | Callback<boolean> | Yes | Callback used to return the result. | **Example** @@ -604,10 +604,10 @@ Enables listening for the enabled status changes of the touch guide mode. This A **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the event to listen for, which is set to **'touchGuideStateChange'** in this API.| -| callback | Callback<boolean> | Yes| Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ----------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Type of the event to listen for, which is set to **'touchGuideStateChange'** in this API.| +| callback | Callback<boolean> | Yes | Callback used to return the result. | **Example** @@ -631,10 +631,10 @@ Disables listening for the enabled status changes of the accessibility applicati **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | No| Type of the event to listen for, which is set to **'accessibilityStateChange'** in this API.| -| callback | Callback<boolean> | No| Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ----------------------- | ---- | ---------------------------------------- | +| type | string | No | Type of the event to listen for, which is set to **'accessibilityStateChange'** in this API.| +| callback | Callback<boolean> | No | Callback for the event. | **Example** @@ -658,10 +658,10 @@ Disables listening for the enabled status changes of the touch guide mode. This **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | No| Type of the event to listen for, which is set to **'touchGuideStateChange'** in this API.| -| callback | Callback<boolean> | No| Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ----------------------- | ---- | ---------------------------------------- | +| type | string | No | Type of the event to listen for, which is set to **'touchGuideStateChange'** in this API.| +| callback | Callback<boolean> | No | Callback for the event. | **Example** @@ -685,8 +685,8 @@ Checks whether accessibility is enabled. This API uses a promise to return the r **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ---------------------- | ---------------------------------------- | | Promise<boolean> | Promise used to return the result. Returns **true** if accessibility is enabled; returns **false** otherwise.| **Example** @@ -709,9 +709,9 @@ Checks whether accessibility is enabled. This API uses an asynchronous callback **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. Returns **true** if accessibility is enabled; returns **false** otherwise.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------- | ---- | ----------------------------------- | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. Returns **true** if accessibility is enabled; returns **false** otherwise.| **Example** @@ -735,8 +735,8 @@ Checks whether touch guide mode is enabled. This API uses a promise to return th **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ---------------------- | ---------------------------------------- | | Promise<boolean> | Promise used to return the result. Returns **true** if touch guide mode is enabled; returns **false** otherwise.| **Example** @@ -759,9 +759,9 @@ Checks whether touch guide mode is enabled. This API uses an asynchronous callba **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. Returns **true** if touch guide mode is enabled; returns **false** otherwise.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------- | ---- | ------------------------------------- | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. Returns **true** if touch guide mode is enabled; returns **false** otherwise.| **Example** @@ -790,14 +790,14 @@ Sends an accessibility event. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| event | [EventInfo](#eventinfo) | Yes| Accessibility event.| +| Name | Type | Mandatory | Description | +| ----- | ----------------------- | ---- | -------- | +| event | [EventInfo](#eventinfo) | Yes | Accessibility event.| **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------------------- | ---------------- | | Promise<void> | Promise that returns no value.| **Example** @@ -830,10 +830,10 @@ Sends an accessibility event. This API uses an asynchronous callback to return t **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| event | [EventInfo](#eventinfo) | Yes| Accessibility event.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation fails, **error** that contains data is returned. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ---------------------------------------- | +| event | [EventInfo](#eventinfo) | Yes | Accessibility event. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation fails, **error** that contains data is returned.| **Example** @@ -862,14 +862,14 @@ Sends an accessibility event. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| event | [EventInfo](#eventinfo) | Yes| Accessibility event.| +| Name | Type | Mandatory | Description | +| ----- | ----------------------- | ---- | -------- | +| event | [EventInfo](#eventinfo) | Yes | Accessibility event.| **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------------------- | ---------------- | | Promise<void> | Promise that returns no value.| **Example** @@ -901,10 +901,10 @@ Sends an accessibility event. This API uses an asynchronous callback to return t **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| event | [EventInfo](#eventinfo) | Yes| Accessibility event.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation fails, **error** that contains data is returned. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ---------------------------------------- | +| event | [EventInfo](#eventinfo) | Yes | Accessibility event. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation fails, **error** that contains data is returned.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-app-ability-appManager.md b/en/application-dev/reference/apis/js-apis-app-ability-appManager.md index 6be97f26f89b5bf8750a30555200d518990c709f..9fa26885cc9f8ab20b8c5a1dc17ee4be054195ad 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-appManager.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-appManager.md @@ -22,9 +22,9 @@ Checks whether this application is undergoing a stability test. This API uses an **Parameters** -| Type| Description| -| -------- | -------- | -|AsyncCallback<boolean> |Callback used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is undergoing a stability test, and **false** means the opposite.| + | Type| Description| + | -------- | -------- | + |AsyncCallback<boolean> |Callback used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is undergoing a stability test, and **false** means the opposite.| **Error codes** @@ -59,9 +59,9 @@ Checks whether this application is undergoing a stability test. This API uses a **Return value** -| Type| Description| -| -------- | -------- | -| Promise<boolean> | Promise used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is undergoing a stability test, and **false** means the opposite.| + | Type| Description| + | -------- | -------- | + | Promise<boolean> | Promise used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is undergoing a stability test, and **false** means the opposite.| **Error codes** @@ -94,9 +94,9 @@ Checks whether this application is running on a RAM constrained device. This API **Return value** -| Type| Description| -| -------- | -------- | -| Promise<boolean> | Promise used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is running on a RAM constrained device, and **false** means the opposite.| + | Type| Description| + | -------- | -------- | + | Promise<boolean> | Promise used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is running on a RAM constrained device, and **false** means the opposite.| **Error codes** @@ -128,9 +128,9 @@ Checks whether this application is running on a RAM constrained device. This API **Parameters** -| Type| Description| -| -------- | -------- | -| AsyncCallback<boolean> |Callback used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is running on a RAM constrained device, and **false** means the opposite.| + | Type| Description| + | -------- | -------- | + | AsyncCallback<boolean> |Callback used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is running on a RAM constrained device, and **false** means the opposite.| **Error codes** @@ -164,9 +164,9 @@ Obtains the memory size of this application. This API uses a promise to return t **Return value** -| Type| Description| -| -------- | -------- | -| Promise<number> | Promise used to return the API call result and the memory size. You can perform error handling or custom processing in this callback.| + | Type| Description| + | -------- | -------- | + | Promise<number> | Promise used to return the API call result and the memory size. You can perform error handling or custom processing in this callback.| **Error codes** @@ -198,9 +198,9 @@ Obtains the memory size of this application. This API uses an asynchronous callb **Parameters** -| Type| Description| -| -------- | -------- | -|AsyncCallback<number> |Callback used to return the API call result and the memory size. You can perform error handling or custom processing in this callback.| + | Type| Description| + | -------- | -------- | + |AsyncCallback<number> |Callback used to return the API call result and the memory size. You can perform error handling or custom processing in this callback.| **Error codes** @@ -298,6 +298,82 @@ appManager.getRunningProcessInformation((err, data) => { }); ``` +## appManager.isSharedBundleRunning + +isSharedBundleRunning(bundleName: string, versionCode: number): Promise\; + +Checks whether the shared library is in use. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| bundleName | string | Yes | Bundle name of the shared library.| +| versionCode | number | Yes | Version number of the shared library. | + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\ | Promise used to return the result. The value **true** means that the shared library is in use, and **false** means the opposite.| + +**Example** + +```ts +import appManager from '@ohos.app.ability.appManager'; + +appManager.isSharedBundleRunning(bundleName, versionCode).then((data) => { + console.log('The shared bundle running is: ${JSON.stringify(data)}'); +}).catch((error) => { + console.error('error: ${JSON.stringify(error)}'); +}); +``` + +## appManager.isSharedBundleRunning + +isSharedBundleRunning(bundleName: string, versionCode: number, callback: AsyncCallback\): void; + +Checks whether the shared library is in use. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| bundleName | string | Yes | Bundle name of the shared library.| +| versionCode | number | Yes | Version number of the shared library. | + +**Return value** + +| Type| Description| +| -------- | -------- | +|AsyncCallback\> | Callback used to return the result. The value **true** means that the shared library is in use, and **false** means the opposite.| + +**Example** + +```ts +import appManager from '@ohos.app.ability.appManager'; + +appManager.isSharedBundleRunning(bundleName, versionCode, (err, data) => { + if (err) { + console.error('err: ${JSON.stringify(err)}'); + } else { + console.log('The shared bundle running is: ${JSON.stringify(data)}'); + } +}); +``` + ## appManager.on on(type: 'applicationState', observer: ApplicationStateObserver): number; @@ -641,7 +717,7 @@ Obtains applications that are running in the foreground. This API uses a promise | Type| Description| | -------- | -------- | -| Promise\> | Promise used to return an array holding the application state data. | +| Promise\> | Promise used to return an array holding the application state data.| **Error codes** @@ -731,11 +807,11 @@ Kills a process by bundle name and account ID. This API uses an asynchronous cal **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| bundleName | string | Yes| Bundle name.| -| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| callback | AsyncCallback\ | Yes| Callback used to return the API call result. You can perform error handling or custom processing in this callback.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | bundleName | string | Yes| Bundle name.| + | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| + | callback | AsyncCallback\ | Yes| Callback used to return the API call result. You can perform error handling or custom processing in this callback.| **Error codes** diff --git a/en/application-dev/reference/apis/js-apis-appAccount.md b/en/application-dev/reference/apis/js-apis-appAccount.md index 307b991bc1f5725cd7dffd73bc93ced1541ab004..6bb26ca37ab1d320d904cdaa17c5a100291f322c 100644 --- a/en/application-dev/reference/apis/js-apis-appAccount.md +++ b/en/application-dev/reference/apis/js-apis-appAccount.md @@ -65,11 +65,11 @@ Creates an app account. This API uses an asynchronous callback to return the res ```js try { - appAccountManager.createAccount("WangWu", (err) => { - console.log("createAccount err: " + JSON.stringify(err)); + appAccountManager.createAccount('WangWu', (err) => { + console.log('createAccount err: ' + JSON.stringify(err)); }); } catch (err) { - console.log("createAccount err: " + JSON.stringify(err)); + console.log('createAccount err: ' + JSON.stringify(err)); } ``` @@ -103,19 +103,19 @@ Creates an app account with custom data. This API uses an asynchronous callback ```js let options = { customData: { - "age": "10" + 'age': '10' } } try { - appAccountManager.createAccount("LiSi", options, (err) => { + appAccountManager.createAccount('LiSi', options, (err) => { if (err) { - console.log("createAccount failed, error: " + JSON.stringify(err)); + console.log('createAccount failed, error: ' + JSON.stringify(err)); } else { - console.log("createAccount successfully"); + console.log('createAccount successfully'); } }); } catch(err) { - console.log("createAccount exception: " + JSON.stringify(err)); + console.log('createAccount exception: ' + JSON.stringify(err)); } ``` @@ -132,7 +132,7 @@ Creates an app account with custom data. This API uses a promise to return the r | Name | Type | Mandatory | Description | | --------- | ------ | ---- | ---------------------------------------- | | name | string | Yes | Name of the app account to create. | -| options | [CreateAccountOptions](#createaccountoptions9) | No | Options for creating the app account. You can customize data based on service requirements, but do not add sensitive data (such as passwords and tokens). This parameter can be left empty.| +| options | [CreateAccountOptions](#createaccountoptions9) | No | Options for creating the app account. You can customize data based on service requirements, but do not add sensitive data (such as passwords and tokens).
By default, no value is passed, which means no additional information needs to be added for the account.| **Return value** @@ -154,17 +154,17 @@ Creates an app account with custom data. This API uses a promise to return the r ```js let options = { customData: { - "age": "10" + 'age': '10' } } try { - appAccountManager.createAccount("LiSi", options).then(() => { - console.log("createAccount successfully"); + appAccountManager.createAccount('LiSi', options).then(() => { + console.log('createAccount successfully'); }).catch((err) => { - console.log("createAccount failed, error: " + JSON.stringify(err)); + console.log('createAccount failed, error: ' + JSON.stringify(err)); }); } catch(err) { - console.log("createAccount exception: " + JSON.stringify(err)); + console.log('createAccount exception: ' + JSON.stringify(err)); } ``` @@ -198,8 +198,8 @@ Creates an app account implicitly based on the specified account owner. This API ```js function onResultCallback(code, result) { - console.log("resultCode: " + code); - console.log("result: " + JSON.stringify(result)); + console.log('resultCode: ' + code); + console.log('result: ' + JSON.stringify(result)); } function onRequestRedirectedCallback(request) { @@ -210,19 +210,19 @@ Creates an app account implicitly based on the specified account owner. This API entities: ['entity.system.default'], } this.context.startAbility(wantInfo).then(() => { - console.log("startAbility successfully"); + console.log('startAbility successfully'); }).catch((err) => { - console.log("startAbility err: " + JSON.stringify(err)); + console.log('startAbility err: ' + JSON.stringify(err)); }) } try { - appAccountManager.createAccountImplicitly("com.example.accountjsdemo", { + appAccountManager.createAccountImplicitly('com.example.accountjsdemo', { onResult: onResultCallback, onRequestRedirected: onRequestRedirectedCallback }); } catch (err) { - console.log("createAccountImplicitly exception: " + JSON.stringify(err)); + console.log('createAccountImplicitly exception: ' + JSON.stringify(err)); } ``` @@ -257,8 +257,8 @@ Creates an app account implicitly based on the specified account owner and optio ```js function onResultCallback(code, result) { - console.log("resultCode: " + code); - console.log("result: " + JSON.stringify(result)); + console.log('resultCode: ' + code); + console.log('result: ' + JSON.stringify(result)); } function onRequestRedirectedCallback(request) { @@ -269,23 +269,23 @@ Creates an app account implicitly based on the specified account owner and optio entities: ['entity.system.default'], } this.context.startAbility(wantInfo).then(() => { - console.log("startAbility successfully"); + console.log('startAbility successfully'); }).catch((err) => { - console.log("startAbility err: " + JSON.stringify(err)); + console.log('startAbility err: ' + JSON.stringify(err)); }) } let options = { - authType: "getSocialData", - requiredLabels: [ "student" ] + authType: 'getSocialData', + requiredLabels: [ 'student' ] }; try { - appAccountManager.createAccountImplicitly("com.example.accountjsdemo", options, { + appAccountManager.createAccountImplicitly('com.example.accountjsdemo', options, { onResult: onResultCallback, onRequestRedirected: onRequestRedirectedCallback }); } catch (err) { - console.log("createAccountImplicitly exception: " + JSON.stringify(err)); + console.log('createAccountImplicitly exception: ' + JSON.stringify(err)); } ``` @@ -316,15 +316,15 @@ Removes an app account. This API uses an asynchronous callback to return the res ```js try { - appAccountManager.removeAccount("ZhaoLiu", (err) => { + appAccountManager.removeAccount('ZhaoLiu', (err) => { if (err) { - console.log("removeAccount failed, error: " + JSON.stringify(err)); + console.log('removeAccount failed, error: ' + JSON.stringify(err)); } else { - console.log("removeAccount successfully"); + console.log('removeAccount successfully'); } }); } catch(err) { - console.log("removeAccount exception: " + JSON.stringify(err)); + console.log('removeAccount exception: ' + JSON.stringify(err)); } ``` @@ -360,13 +360,13 @@ Removes an app account. This API uses a promise to return the result. ```js try { - appAccountManager.removeAccount("Lisi").then(() => { - console.log("removeAccount successfully"); + appAccountManager.removeAccount('Lisi').then(() => { + console.log('removeAccount successfully'); }).catch((err) => { - console.log("removeAccount failed, error: " + JSON.stringify(err)); + console.log('removeAccount failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log("removeAccount exception: " + JSON.stringify(err)); + console.log('removeAccount exception: ' + JSON.stringify(err)); } ``` @@ -400,15 +400,15 @@ Sets the access to the data of an account for an app. This API uses an asynchron ```js try { - appAccountManager.setAppAccess("ZhangSan", "com.example.accountjsdemo", true, (err) => { + appAccountManager.setAppAccess('ZhangSan', 'com.example.accountjsdemo', true, (err) => { if (err) { - console.log("setAppAccess failed: " + JSON.stringify(err)); + console.log('setAppAccess failed: ' + JSON.stringify(err)); } else { - console.log("setAppAccess successfully"); + console.log('setAppAccess successfully'); } }); } catch (err) { - console.log("setAppAccess exception: " + JSON.stringify(err)); + console.log('setAppAccess exception: ' + JSON.stringify(err)); } ``` @@ -447,13 +447,13 @@ Sets the access to the data of an account for an app. This API uses a promise to ```js try { - appAccountManager.setAppAccess("ZhangSan", "com.example.accountjsdemo", true).then(() => { - console.log("setAppAccess successfully"); + appAccountManager.setAppAccess('ZhangSan', 'com.example.accountjsdemo', true).then(() => { + console.log('setAppAccess successfully'); }).catch((err) => { - console.log("setAppAccess failed: " + JSON.stringify(err)); + console.log('setAppAccess failed: ' + JSON.stringify(err)); }); } catch (err) { - console.log("setAppAccess exception: " + JSON.stringify(err)); + console.log('setAppAccess exception: ' + JSON.stringify(err)); } ``` @@ -485,15 +485,15 @@ Checks whether an app can access the data of an account. This API uses an asynch ```js try { - appAccountManager.checkAppAccess("ZhangSan", "com.example.accountjsdemo", (err, isAccessible) => { + appAccountManager.checkAppAccess('ZhangSan', 'com.example.accountjsdemo', (err, isAccessible) => { if (err) { - console.log("checkAppAccess failed, error: " + JSON.stringify(err)); + console.log('checkAppAccess failed, error: ' + JSON.stringify(err)); } else { - console.log("checkAppAccess successfully"); + console.log('checkAppAccess successfully'); } }); } catch (err) { - console.log("checkAppAccess exception: " + JSON.stringify(err)); + console.log('checkAppAccess exception: ' + JSON.stringify(err)); } ``` @@ -530,13 +530,13 @@ Checks whether an app can access the data of an account. This API uses a promise ```js try { - appAccountManager.checkAppAccess("ZhangSan", "com.example.accountjsdemo").then((isAccessible) => { - console.log("checkAppAccess successfully, isAccessible: " + isAccessible); + appAccountManager.checkAppAccess('ZhangSan', 'com.example.accountjsdemo').then((isAccessible) => { + console.log('checkAppAccess successfully, isAccessible: ' + isAccessible); }).catch((err) => { - console.log("checkAppAccess failed, error: " + JSON.stringify(err)); + console.log('checkAppAccess failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log("checkAppAccess exception: " + JSON.stringify(err)); + console.log('checkAppAccess exception: ' + JSON.stringify(err)); } ``` @@ -570,11 +570,11 @@ Sets data synchronization for an app account. This API uses an asynchronous call ```js try { - appAccountManager.setDataSyncEnabled("ZhangSan", true, (err) => { - console.log("setDataSyncEnabled err: " + JSON.stringify(err)); + appAccountManager.setDataSyncEnabled('ZhangSan', true, (err) => { + console.log('setDataSyncEnabled err: ' + JSON.stringify(err)); }); } catch (err) { - console.log("setDataSyncEnabled err: " + JSON.stringify(err)); + console.log('setDataSyncEnabled err: ' + JSON.stringify(err)); } ``` @@ -613,13 +613,13 @@ Sets data synchronization for an app account. This API uses a promise to return ```js try { - appAccountManager .setDataSyncEnabled("ZhangSan", true).then(() => { + appAccountManager .setDataSyncEnabled('ZhangSan', true).then(() => { console.log('setDataSyncEnabled Success'); }).catch((err) => { - console.log("setDataSyncEnabled err: " + JSON.stringify(err)); + console.log('setDataSyncEnabled err: ' + JSON.stringify(err)); }); } catch (err) { - console.log("setDataSyncEnabled err: " + JSON.stringify(err)); + console.log('setDataSyncEnabled err: ' + JSON.stringify(err)); } ``` @@ -652,15 +652,15 @@ Checks whether data synchronization is enabled for an app account. This API uses ```js try { - appAccountManager.checkDataSyncEnabled("ZhangSan", (err, isEnabled) => { + appAccountManager.checkDataSyncEnabled('ZhangSan', (err, isEnabled) => { if (err) { - console.log("checkDataSyncEnabled failed, err: " + JSON.stringify(err)); + console.log('checkDataSyncEnabled failed, err: ' + JSON.stringify(err)); } else { console.log('checkDataSyncEnabled successfully, isEnabled: ' + isEnabled); } }); } catch (err) { - console.log("checkDataSyncEnabled err: " + JSON.stringify(err)); + console.log('checkDataSyncEnabled err: ' + JSON.stringify(err)); } ``` @@ -698,13 +698,13 @@ Checks whether data synchronization is enabled for an app account. This API uses ```js try { - appAccountManager.checkDataSyncEnabled("ZhangSan").then((isEnabled) => { - console.log("checkDataSyncEnabled successfully, isEnabled: " + isEnabled); + appAccountManager.checkDataSyncEnabled('ZhangSan').then((isEnabled) => { + console.log('checkDataSyncEnabled successfully, isEnabled: ' + isEnabled); }).catch((err) => { - console.log("checkDataSyncEnabled failed, err: " + JSON.stringify(err)); + console.log('checkDataSyncEnabled failed, err: ' + JSON.stringify(err)); }); } catch (err) { - console.log("checkDataSyncEnabled err: " + JSON.stringify(err)); + console.log('checkDataSyncEnabled err: ' + JSON.stringify(err)); } ``` @@ -737,15 +737,15 @@ Sets a credential for an app account. This API uses an asynchronous callback to ```js try { - appAccountManager.setCredential("ZhangSan", "PIN_SIX", "xxxxxx", (err) => { + appAccountManager.setCredential('ZhangSan', 'PIN_SIX', 'xxxxxx', (err) => { if (err) { - console.log("setCredential failed, error: " + JSON.stringify(err)); + console.log('setCredential failed, error: ' + JSON.stringify(err)); } else { - console.log("setCredential successfully"); + console.log('setCredential successfully'); } }); } catch (err) { - console.log("setCredential exception: " + JSON.stringify(err)); + console.log('setCredential exception: ' + JSON.stringify(err)); } ``` @@ -783,13 +783,13 @@ Sets a credential for an app account. This API uses a promise to return the resu ```js try { - appAccountManager.setCredential("ZhangSan", "PIN_SIX", "xxxxxx").then(() => { - console.log("setCredential successfully"); + appAccountManager.setCredential('ZhangSan', 'PIN_SIX', 'xxxxxx').then(() => { + console.log('setCredential successfully'); }).catch((err) => { - console.log("setCredential failed, error: " + JSON.stringify(err)); + console.log('setCredential failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log("setCredential exception: " + JSON.stringify(err)); + console.log('setCredential exception: ' + JSON.stringify(err)); } ``` @@ -822,15 +822,15 @@ Obtains the credential of an app account. This API uses an asynchronous callback ```js try { - appAccountManager.getCredential("ZhangSan", "PIN_SIX", (err, result) => { + appAccountManager.getCredential('ZhangSan', 'PIN_SIX', (err, result) => { if (err) { - console.log("getCredential failed, error: " + JSON.stringify(err)); + console.log('getCredential failed, error: ' + JSON.stringify(err)); } else { console.log('getCredential successfully, result: ' + result); } }); } catch (err) { - console.log("getCredential err: " + JSON.stringify(err)); + console.log('getCredential err: ' + JSON.stringify(err)); } ``` @@ -868,13 +868,13 @@ Obtains the credential of an app account. This API uses a promise to return the ```js try { - appAccountManager.getCredential("ZhangSan", "PIN_SIX").then((credential) => { - console.log("getCredential successfully, credential: " + credential); + appAccountManager.getCredential('ZhangSan', 'PIN_SIX').then((credential) => { + console.log('getCredential successfully, credential: ' + credential); }).catch((err) => { - console.log("getCredential failed, error: " + JSON.stringify(err)); + console.log('getCredential failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log("getCredential exception: " + JSON.stringify(err)); + console.log('getCredential exception: ' + JSON.stringify(err)); } ``` @@ -908,15 +908,15 @@ Sets custom data for an app account. This API uses an asynchronous callback to r ```js try { - appAccountManager.setCustomData("ZhangSan", "age", "12", (err) => { + appAccountManager.setCustomData('ZhangSan', 'age', '12', (err) => { if (err) { - console.log("setCustomData failed, error: " + JSON.stringify(err)); + console.log('setCustomData failed, error: ' + JSON.stringify(err)); } else { - console.log("setCustomData successfully"); + console.log('setCustomData successfully'); } }); } catch (err) { - console.log("setCustomData exception: " + JSON.stringify(err)); + console.log('setCustomData exception: ' + JSON.stringify(err)); } ``` @@ -955,13 +955,13 @@ Sets custom data for an app account. This API uses a promise to return the resul ```js try { - appAccountManager.setCustomData("ZhangSan", "age", "12").then(() => { - console.log("setCustomData successfully"); + appAccountManager.setCustomData('ZhangSan', 'age', '12').then(() => { + console.log('setCustomData successfully'); }).catch((err) => { - console.log("setCustomData failed, error: " + JSON.stringify(err)); + console.log('setCustomData failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log("setCustomData exception: " + JSON.stringify(err)); + console.log('setCustomData exception: ' + JSON.stringify(err)); } ``` @@ -994,15 +994,15 @@ Obtains the custom data of an app account based on the specified key. This API u ```js try { - appAccountManager.getCustomData("ZhangSan", "age", (err, data) => { + appAccountManager.getCustomData('ZhangSan', 'age', (err, data) => { if (err) { console.log('getCustomData failed, error: ' + err); } else { - console.log("getCustomData successfully, data: " + data); + console.log('getCustomData successfully, data: ' + data); } }); } catch (err) { - console.log("getCustomData exception: " + JSON.stringify(err)); + console.log('getCustomData exception: ' + JSON.stringify(err)); } ``` @@ -1040,13 +1040,13 @@ Obtains the custom data of an app account based on the specified key. This API u ```js try { - appAccountManager.getCustomData("ZhangSan", "age").then((data) => { - console.log("getCustomData successfully, data: " + data); + appAccountManager.getCustomData('ZhangSan', 'age').then((data) => { + console.log('getCustomData successfully, data: ' + data); }).catch((err) => { - console.log("getCustomData failed, error: " + JSON.stringify(err)); + console.log('getCustomData failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log("getCustomData exception: " + JSON.stringify(err)); + console.log('getCustomData exception: ' + JSON.stringify(err)); } ``` @@ -1084,10 +1084,10 @@ Obtains the custom data of an app account based on the specified key. The API re ```js try { - let value = appAccountManager.getCustomDataSync("ZhangSan", "age"); - console.info("getCustomDataSync successfully, vaue:" + value); + let value = appAccountManager.getCustomDataSync('ZhangSan', 'age'); + console.info('getCustomDataSync successfully, vaue: ' + value); } catch (err) { - console.error("getCustomDataSync failed, error: " + JSON.stringify(err)); + console.error('getCustomDataSync failed, error: ' + JSON.stringify(err)); } ``` @@ -1117,13 +1117,13 @@ Obtains information about all accessible app accounts. This API uses an asynchro try { appAccountManager.getAllAccounts((err, data) => { if (err) { - console.debug("getAllAccounts failed, error:" + JSON.stringify(err)); + console.debug('getAllAccounts failed, error: ' + JSON.stringify(err)); } else { - console.debug("getAllAccounts successfully"); + console.debug('getAllAccounts successfully'); } }); } catch (err) { - console.debug("getAllAccounts exception: " + JSON.stringify(err)); + console.debug('getAllAccounts exception: ' + JSON.stringify(err)); } ``` @@ -1152,12 +1152,12 @@ Obtains information about all accessible app accounts. This API uses a promise t ```js try { appAccountManager.getAllAccounts().then((data) => { - console.debug("getAllAccounts successfully"); + console.debug('getAllAccounts successfully'); }).catch((err) => { - console.debug("getAllAccounts failed, error:" + JSON.stringify(err)); + console.debug('getAllAccounts failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.debug("getAllAccounts exception: " + JSON.stringify(err)); + console.debug('getAllAccounts exception: ' + JSON.stringify(err)); } ``` @@ -1188,15 +1188,15 @@ Obtains the app accounts that can be accessed by the invoker based on the app ac ```js try { - appAccountManager.getAccountsByOwner("com.example.accountjsdemo2", (err, data) => { + appAccountManager.getAccountsByOwner('com.example.accountjsdemo2', (err, data) => { if (err) { - console.debug("getAccountsByOwner failed, error:" + JSON.stringify(err)); + console.debug('getAccountsByOwner failed, error:' + JSON.stringify(err)); } else { - console.debug("getAccountsByOwner successfully, data:" + JSON.stringify(data)); + console.debug('getAccountsByOwner successfully, data:' + JSON.stringify(data)); } }); } catch (err) { - console.debug("getAccountsByOwner exception:" + JSON.stringify(err)); + console.debug('getAccountsByOwner exception:' + JSON.stringify(err)); } ``` @@ -1232,13 +1232,13 @@ Obtains the app accounts that can be accessed by the invoker based on the app ac ```js try { - appAccountManager.getAccountsByOwner("com.example.accountjsdemo2").then((data) => { - console.debug("getAccountsByOwner successfully, data:" + JSON.stringify(data)); + appAccountManager.getAccountsByOwner('com.example.accountjsdemo2').then((data) => { + console.debug('getAccountsByOwner successfully, data: ' + JSON.stringify(data)); }).catch((err) => { - console.debug("getAccountsByOwner failed, error:" + JSON.stringify(err)); + console.debug('getAccountsByOwner failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.debug("getAccountsByOwner exception:" + JSON.stringify(err)); + console.debug('getAccountsByOwner exception: ' + JSON.stringify(err)); } ``` @@ -1256,7 +1256,7 @@ Subscribes to account information changes of apps. | -------- | ---------------------------------------- | ---- | ------------------------------ | | type | 'accountChange' | Yes | Event type to subscribe to. The value is **'accountChange'**. An event will be reported when the account information of the target app changes.| | owners | Array<string> | Yes | App bundle names of the account. | -| callback | Callback<Array<[AppAccountInfo](#appaccountinfo)>> | Yes | Callback invoked to return a list of app accounts whose information is changed. | +| callback | Callback<Array<[AppAccountInfo](#appaccountinfo)>> | Yes | Callback registered to return the list of changed app accounts. | **Error codes** @@ -1270,12 +1270,12 @@ Subscribes to account information changes of apps. ```js function changeOnCallback(data){ - console.log("receive change data:" + JSON.stringify(data)); + console.log('receive change data:' + JSON.stringify(data)); } try{ - appAccountManager.on("accountChange", ["com.example.actsaccounttest"], changeOnCallback); + appAccountManager.on('accountChange', ['com.example.actsaccounttest'], changeOnCallback); } catch(err) { - console.error("on accountChange failed, error:" + JSON.stringify(err)); + console.error('on accountChange failed, error:' + JSON.stringify(err)); } ``` @@ -1292,7 +1292,7 @@ Unsubscribes from account information changes. | Name | Type | Mandatory | Description | | -------- | -------------------------------- | ---- | ------------ | | type | 'accountChange' | Yes | Event type to unsubscribe from. The value is **'accountChange'**. | -| callback | Callback<Array<[AppAccountInfo](#appaccountinfo)>> | No | Callback to unregister.| +| callback | Callback<Array<[AppAccountInfo](#appaccountinfo)>> | No | Callback to unregister. By default, no value is passed, which means to unregister all callbacks for the specified event.| **Error codes** @@ -1305,18 +1305,18 @@ Unsubscribes from account information changes. ```js function changeOnCallback(data) { - console.log("receive change data:" + JSON.stringify(data)); + console.log('receive change data:' + JSON.stringify(data)); } try{ - appAccountManager.on("accountChange", ["com.example.actsaccounttest"], changeOnCallback); + appAccountManager.on('accountChange', ['com.example.actsaccounttest'], changeOnCallback); } catch(err) { - console.error("on accountChange failed, error:" + JSON.stringify(err)); + console.error('on accountChange failed, error:' + JSON.stringify(err)); } try{ appAccountManager.off('accountChange', changeOnCallback); } catch(err){ - console.error("off accountChange failed, error:" + JSON.stringify(err)); + console.error('off accountChange failed, error:' + JSON.stringify(err)); } ``` @@ -1354,8 +1354,8 @@ Authenticates an app account. This API uses an asynchronous callback to return t function onResultCallback(code, authResult) { - console.log("resultCode: " + code); - console.log("authResult: " + JSON.stringify(authResult)); + console.log('resultCode: ' + code); + console.log('authResult: ' + JSON.stringify(authResult)); } function onRequestRedirectedCallback(request) { @@ -1366,19 +1366,19 @@ Authenticates an app account. This API uses an asynchronous callback to return t entities: ['entity.system.default'], } this.context.startAbility(wantInfo).then(() => { - console.log("startAbility successfully"); + console.log('startAbility successfully'); }).catch((err) => { - console.log("startAbility err: " + JSON.stringify(err)); + console.log('startAbility err: ' + JSON.stringify(err)); }) } try { - appAccountManager.auth("LiSi", "com.example.accountjsdemo", "getSocialData", { + appAccountManager.auth('LiSi', 'com.example.accountjsdemo', 'getSocialData', { onResult: onResultCallback, onRequestRedirected: onRequestRedirectedCallback }); } catch (err) { - console.log("auth exception: " + JSON.stringify(err)); + console.log('auth exception: ' + JSON.stringify(err)); } ``` @@ -1417,8 +1417,8 @@ Authenticates an app account with customized options. This API uses an asynchron function onResultCallback(code, authResult) { - console.log("resultCode: " + code); - console.log("authResult: " + JSON.stringify(authResult)); + console.log('resultCode: ' + code); + console.log('authResult: ' + JSON.stringify(authResult)); } function onRequestRedirectedCallback(request) { @@ -1429,22 +1429,22 @@ Authenticates an app account with customized options. This API uses an asynchron entities: ['entity.system.default'], } this.context.startAbility(wantInfo).then(() => { - console.log("startAbility successfully"); + console.log('startAbility successfully'); }).catch((err) => { - console.log("startAbility err: " + JSON.stringify(err)); + console.log('startAbility err: ' + JSON.stringify(err)); }) } let options = { - "password": "xxxx", + 'password': 'xxxx', }; try { - appAccountManager.auth("LiSi", "com.example.accountjsdemo", "getSocialData", options, { + appAccountManager.auth('LiSi', 'com.example.accountjsdemo', 'getSocialData', options, { onResult: onResultCallback, onRequestRedirected: onRequestRedirectedCallback }); } catch (err) { - console.log("auth exception: " + JSON.stringify(err)); + console.log('auth exception: ' + JSON.stringify(err)); } ``` @@ -1478,15 +1478,15 @@ Obtains the authorization token of the specified authentication type for an app ```js try { - appAccountManager.getAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", (err, token) => { + appAccountManager.getAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData', (err, token) => { if (err) { - console.log("getAuthToken failed, error: " + JSON.stringify(err)); + console.log('getAuthToken failed, error: ' + JSON.stringify(err)); } else { - console.log("getAuthToken successfully, token: " + token); + console.log('getAuthToken successfully, token: ' + token); } }); } catch (err) { - console.log("getAuthToken exception: " + JSON.stringify(err)); + console.log('getAuthToken exception: ' + JSON.stringify(err)); } ``` @@ -1525,13 +1525,13 @@ Obtains the authorization token of the specified authentication type for an app ```js try { - appAccountManager.getAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData").then((token) => { - console.log("getAuthToken successfully, token: " + token); + appAccountManager.getAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData').then((token) => { + console.log('getAuthToken successfully, token: ' + token); }).catch((err) => { - console.log("getAuthToken failed, error: " + JSON.stringify(err)); + console.log('getAuthToken failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log("getAuthToken exception: " + JSON.stringify(err)); + console.log('getAuthToken exception: ' + JSON.stringify(err)); } ``` @@ -1565,11 +1565,11 @@ Sets an authorization token of the specific authentication type for an app accou ```js try { - appAccountManager.setAuthToken("LiSi", "getSocialData", "xxxx", (err) => { + appAccountManager.setAuthToken('LiSi', 'getSocialData', 'xxxx', (err) => { if (err) { - console.log("setAuthToken failed, error: " + JSON.stringify(err)); + console.log('setAuthToken failed, error: ' + JSON.stringify(err)); } else { - console.log("setAuthToken successfully"); + console.log('setAuthToken successfully'); } }); } catch (err) { @@ -1612,13 +1612,13 @@ Sets an authorization token of the specific authentication type for an app accou ```js try { - appAccountManager.setAuthToken("LiSi", "getSocialData", "xxxx").then(() => { - console.log("setAuthToken successfully"); + appAccountManager.setAuthToken('LiSi', 'getSocialData', 'xxxx').then(() => { + console.log('setAuthToken successfully'); }).catch((err) => { - console.log("setAuthToken failed, error: " + JSON.stringify(err)); + console.log('setAuthToken failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log("setAuthToken exception: " + JSON.stringify(err)); + console.log('setAuthToken exception: ' + JSON.stringify(err)); } ``` @@ -1653,11 +1653,11 @@ Deletes the authorization token of the specified authentication type for an app ```js try { - appAccountManager.deleteAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", "xxxxx", (err) => { + appAccountManager.deleteAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData', 'xxxxx', (err) => { if (err) { console.log('deleteAuthToken failed, error: ' + JSON.stringify(err)); } else { - console.log("deleteAuthToken successfully"); + console.log('deleteAuthToken successfully'); } }); } catch (err) { @@ -1701,8 +1701,8 @@ Deletes the authorization token of the specified authentication type for an app ```js try { - appAccountManager.deleteAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", "xxxxx").then(() => { - console.log("deleteAuthToken successfully"); + appAccountManager.deleteAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData', 'xxxxx').then(() => { + console.log('deleteAuthToken successfully'); }).catch((err) => { console.log('deleteAuthToken failed, error: ' + JSON.stringify(err)); }); @@ -1744,15 +1744,15 @@ Sets the visibility of an authorization token to an app. This API uses an asynch ```js try { - appAccountManager.setAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", true, (err) => { + appAccountManager.setAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo', true, (err) => { if (err) { - console.log("setAuthTokenVisibility failed, error: " + JSON.stringify(err)); + console.log('setAuthTokenVisibility failed, error: ' + JSON.stringify(err)); } else { - console.log("setAuthTokenVisibility successfully"); + console.log('setAuthTokenVisibility successfully'); } }); } catch (err) { - console.log("setAuthTokenVisibility exception: " + JSON.stringify(err)); + console.log('setAuthTokenVisibility exception: ' + JSON.stringify(err)); } ``` @@ -1794,13 +1794,13 @@ Sets the visibility of an authorization token to an app. This API uses a promise ```js try { - appAccountManager.setAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", true).then(() => { - console.log("setAuthTokenVisibility successfully"); + appAccountManager.setAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo', true).then(() => { + console.log('setAuthTokenVisibility successfully'); }).catch((err) => { - console.log("setAuthTokenVisibility failed, error: " + JSON.stringify(err)); + console.log('setAuthTokenVisibility failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log("setAuthTokenVisibility exception: " + JSON.stringify(err)); + console.log('setAuthTokenVisibility exception: ' + JSON.stringify(err)); } ``` @@ -1834,15 +1834,15 @@ Checks the visibility of an authorization token of the specified authentication ```js try { - appAccountManager.checkAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", (err, isVisible) => { + appAccountManager.checkAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo', (err, isVisible) => { if (err) { - console.log("checkAuthTokenVisibility failed, error: " + JSON.stringify(err)); + console.log('checkAuthTokenVisibility failed, error: ' + JSON.stringify(err)); } else { - console.log("checkAuthTokenVisibility successfully, isVisible: " + isVisible); + console.log('checkAuthTokenVisibility successfully, isVisible: ' + isVisible); } }); } catch (err) { - console.log("checkAuthTokenVisibility exception: " + JSON.stringify(err)); + console.log('checkAuthTokenVisibility exception: ' + JSON.stringify(err)); } ``` @@ -1881,13 +1881,13 @@ Checks the visibility of an authorization token of the specified authentication ```js try { - appAccountManager.checkAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo").then((isVisible) => { - console.log("checkAuthTokenVisibility successfully, isVisible: " + isVisible); + appAccountManager.checkAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo').then((isVisible) => { + console.log('checkAuthTokenVisibility successfully, isVisible: ' + isVisible); }).catch((err) => { - console.log("checkAuthTokenVisibility failed, error: " + JSON.stringify(err)); + console.log('checkAuthTokenVisibility failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log("checkAuthTokenVisibility exception: " + JSON.stringify(err)); + console.log('checkAuthTokenVisibility exception: ' + JSON.stringify(err)); } ``` @@ -1919,15 +1919,15 @@ Obtains all tokens visible to the invoker for an app account. This API uses an a ```js try { - appAccountManager.getAllAuthTokens("LiSi", "com.example.accountjsdemo", (err, tokenArr) => { + appAccountManager.getAllAuthTokens('LiSi', 'com.example.accountjsdemo', (err, tokenArr) => { if (err) { - console.log("getAllAuthTokens failed, error: " + JSON.stringify(err)); + console.log('getAllAuthTokens failed, error: ' + JSON.stringify(err)); } else { console.log('getAllAuthTokens successfully, tokenArr: ' + tokenArr); } }); } catch (err) { - console.log("getAllAuthTokens exception: " + JSON.stringify(err)); + console.log('getAllAuthTokens exception: ' + JSON.stringify(err)); } ``` @@ -1964,13 +1964,13 @@ Obtains all tokens visible to the invoker for an app account. This API uses a pr ```js try { - appAccountManager.getAllAuthTokens("LiSi", "com.example.accountjsdemo").then((tokenArr) => { + appAccountManager.getAllAuthTokens('LiSi', 'com.example.accountjsdemo').then((tokenArr) => { console.log('getAllAuthTokens successfully, tokenArr: ' + JSON.stringify(tokenArr)); }).catch((err) => { - console.log("getAllAuthTokens failed, error: " + JSON.stringify(err)); + console.log('getAllAuthTokens failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log("getAllAuthTokens exception: " + JSON.stringify(err)); + console.log('getAllAuthTokens exception: ' + JSON.stringify(err)); } ``` @@ -2003,11 +2003,11 @@ Obtains the authorization list of the specified authentication type for an app a ```js try { - appAccountManager.getAuthList("com.example.accountjsdemo", "getSocialData", (err, authList) => { + appAccountManager.getAuthList('LiSi', 'getSocialData', (err, authList) => { if (err) { - console.log("getAuthList failed, error: " + JSON.stringify(err)); + console.log('getAuthList failed, error: ' + JSON.stringify(err)); } else { - console.log("getAuthList successfully, authList: " + authList); + console.log('getAuthList successfully, authList: ' + authList); } }); } catch (err) { @@ -2049,13 +2049,13 @@ Obtains the authorization list of the specified authentication type for an app a ```js try { - appAccountManager.getAuthList("com.example.accountjsdemo", "getSocialData").then((authList) => { - console.log("getAuthList successfully, authList: " + authList); + appAccountManager.getAuthList('LiSi', 'getSocialData').then((authList) => { + console.log('getAuthList successfully, authList: ' + authList); }).catch((err) => { - console.log("getAuthList failed, error: " + JSON.stringify(err)); + console.log('getAuthList failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log("getAuthList exception: " + JSON.stringify(err)); + console.log('getAuthList exception: ' + JSON.stringify(err)); } ``` @@ -2063,7 +2063,7 @@ Obtains the authorization list of the specified authentication type for an app a getAuthCallback(sessionId: string, callback: AsyncCallback<AuthCallback>): void -Obtains the authenticator callback for the authentication session. This API uses an asynchronous callback to return the result. +Obtains the authenticator callback for an authentication session. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -2093,23 +2093,23 @@ Obtains the authenticator callback for the authentication session. This API uses try { appAccountManager.getAuthCallback(sessionId, (err, callback) => { if (err != null) { - console.log("getAuthCallback err: " + JSON.stringify(err)); + console.log('getAuthCallback err: ' + JSON.stringify(err)); return; } var result = { accountInfo: { - name: "Lisi", - owner: "com.example.accountjsdemo", + name: 'Lisi', + owner: 'com.example.accountjsdemo', }, tokenInfo: { - token: "xxxxxx", - authType: "getSocialData" + token: 'xxxxxx', + authType: 'getSocialData' } }; callback.onResult(0, result); }); } catch (err) { - console.log("getAuthCallback exception: " + JSON.stringify(err)); + console.log('getAuthCallback exception: ' + JSON.stringify(err)); } } } @@ -2119,7 +2119,7 @@ Obtains the authenticator callback for the authentication session. This API uses getAuthCallback(sessionId: string): Promise<AuthCallback> -Obtains the authenticator callback for the authentication session. This API uses a promise to return the result. +Obtains the authenticator callback for an authentication session. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -2155,20 +2155,20 @@ Obtains the authenticator callback for the authentication session. This API uses appAccountManager.getAuthCallback(sessionId).then((callback) => { var result = { accountInfo: { - name: "Lisi", - owner: "com.example.accountjsdemo", + name: 'Lisi', + owner: 'com.example.accountjsdemo', }, tokenInfo: { - token: "xxxxxx", - authType: "getSocialData" + token: 'xxxxxx', + authType: 'getSocialData' } }; callback.onResult(0, result); }).catch((err) => { - console.log("getAuthCallback err: " + JSON.stringify(err)); + console.log('getAuthCallback err: ' + JSON.stringify(err)); }); } catch (err) { - console.log("getAuthCallback exception: " + JSON.stringify(err)); + console.log('getAuthCallback exception: ' + JSON.stringify(err)); } } } @@ -2201,15 +2201,15 @@ Obtains the authenticator information of an app. This API uses an asynchronous c ```js try { - appAccountManager.queryAuthenticatorInfo("com.example.accountjsdemo", (err, info) => { + appAccountManager.queryAuthenticatorInfo('com.example.accountjsdemo', (err, info) => { if (err) { - console.log("queryAuthenticatorInfo failed, error: " + JSON.stringify(err)); + console.log('queryAuthenticatorInfo failed, error: ' + JSON.stringify(err)); } else { console.log('queryAuthenticatorInfo successfully, info: ' + JSON.stringify(info)); } }); } catch (err) { - console.log("queryAuthenticatorInfo exception: " + JSON.stringify(err)); + console.log('queryAuthenticatorInfo exception: ' + JSON.stringify(err)); } ``` @@ -2245,13 +2245,13 @@ Obtains the authenticator information of an app. This API uses a promise to retu ```js try { - appAccountManager.queryAuthenticatorInfo("com.example.accountjsdemo").then((info) => { - console.log("queryAuthenticatorInfo successfully, info: " + JSON.stringify(info)); + appAccountManager.queryAuthenticatorInfo('com.example.accountjsdemo').then((info) => { + console.log('queryAuthenticatorInfo successfully, info: ' + JSON.stringify(info)); }).catch((err) => { - console.log("queryAuthenticatorInfo failed, error: " + JSON.stringify(err)); + console.log('queryAuthenticatorInfo failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log("queryAuthenticatorInfo exception: " + JSON.stringify(err)); + console.log('queryAuthenticatorInfo exception: ' + JSON.stringify(err)); } ``` @@ -2286,17 +2286,17 @@ Checks whether an app account has specific labels. This API uses an asynchronous **Example** ```js - let labels = ["student"]; + let labels = ['student']; try { - appAccountManager.checkAccountLabels("zhangsan", "com.example.accountjsdemo", labels, (err, hasAllLabels) => { + appAccountManager.checkAccountLabels('zhangsan', 'com.example.accountjsdemo', labels, (err, hasAllLabels) => { if (err) { - console.log("checkAccountLabels failed, error: " + JSON.stringify(err)); + console.log('checkAccountLabels failed, error: ' + JSON.stringify(err)); } else { - console.log("checkAccountLabels successfully, hasAllLabels: " + hasAllLabels); + console.log('checkAccountLabels successfully, hasAllLabels: ' + hasAllLabels); } }); } catch (err) { - console.log("checkAccountLabels exception: " + JSON.stringify(err)); + console.log('checkAccountLabels exception: ' + JSON.stringify(err)); } ``` @@ -2336,15 +2336,15 @@ Checks whether an app account has specific labels. This API uses a promise to re **Example** ```js - let labels = ["student"]; + let labels = ['student']; try { - appAccountManager.checkAccountLabels("zhangsan", "com.example.accountjsdemo", labels).then((hasAllLabels) => { + appAccountManager.checkAccountLabels('zhangsan', 'com.example.accountjsdemo', labels).then((hasAllLabels) => { console.log('checkAccountLabels successfully: ' + hasAllLabels); }).catch((err) => { - console.log("checkAccountLabels failed, error: " + JSON.stringify(err)); + console.log('checkAccountLabels failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log("checkAccountLabels exception: " + JSON.stringify(err)); + console.log('checkAccountLabels exception: ' + JSON.stringify(err)); } ``` @@ -2377,15 +2377,15 @@ Deletes the credential of the specified type from an app account. This API uses ```js try { - appAccountManager.deleteCredential("zhangsan", "PIN_SIX", (err) => { + appAccountManager.deleteCredential('zhangsan', 'PIN_SIX', (err) => { if (err) { - console.log("deleteCredential failed, error: " + JSON.stringify(err)); + console.log('deleteCredential failed, error: ' + JSON.stringify(err)); } else { - console.log("deleteCredential successfully"); + console.log('deleteCredential successfully'); } }); } catch (err) { - console.log("deleteCredential exception: " + JSON.stringify(err)); + console.log('deleteCredential exception: ' + JSON.stringify(err)); } ``` @@ -2423,13 +2423,13 @@ Deletes the credential of the specified type from an app account. This API uses ```js try { - appAccountManager.deleteCredential("zhangsan", "PIN_SIX").then(() => { - console.log("deleteCredential successfully"); + appAccountManager.deleteCredential('zhangsan', 'PIN_SIX').then(() => { + console.log('deleteCredential successfully'); }).catch((err) => { - console.log("deleteCredential failed, error: " + JSON.stringify(err)); + console.log('deleteCredential failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log("deleteCredential exception: " + JSON.stringify(err)); + console.log('deleteCredential exception: ' + JSON.stringify(err)); } ``` @@ -2461,19 +2461,19 @@ Selects the accounts that can be accessed by the invoker based on the options. T ```js let options = { - allowedOwners: [ "com.example.accountjsdemo" ], - requiredLabels: [ "student" ] + allowedOwners: [ 'com.example.accountjsdemo' ], + requiredLabels: [ 'student' ] }; try { appAccountManager.selectAccountsByOptions(options, (err, accountArr) => { if (err) { - console.log("selectAccountsByOptions failed, error: " + JSON.stringify(err)); + console.log('selectAccountsByOptions failed, error: ' + JSON.stringify(err)); } else { - console.log("selectAccountsByOptions successfully, accountArr: " + JSON.stringify(accountArr)); + console.log('selectAccountsByOptions successfully, accountArr: ' + JSON.stringify(accountArr)); } }); } catch (err) { - console.log("selectAccountsByOptions exception: " + JSON.stringify(err)); + console.log('selectAccountsByOptions exception: ' + JSON.stringify(err)); } ``` @@ -2510,16 +2510,16 @@ Selects the accounts that can be accessed by the invoker based on the options. T ```js let options = { - allowedOwners: ["com.example.accountjsdemo"] + allowedOwners: ['com.example.accountjsdemo'] }; try { appAccountManager.selectAccountsByOptions(options).then((accountArr) => { - console.log("selectAccountsByOptions successfully, accountArr: " + JSON.stringify(accountArr)); + console.log('selectAccountsByOptions successfully, accountArr: ' + JSON.stringify(accountArr)); }).catch((err) => { - console.log("selectAccountsByOptions failed, error: " + JSON.stringify(err)); + console.log('selectAccountsByOptions failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log("selectAccountsByOptions exception: " + JSON.stringify(err)); + console.log('selectAccountsByOptions exception: ' + JSON.stringify(err)); } ``` @@ -2554,17 +2554,17 @@ Verifies the credential of an app account. This API uses an asynchronous callbac ```js try { - appAccountManager.verifyCredential("zhangsan", "com.example.accountjsdemo", { + appAccountManager.verifyCredential('zhangsan', 'com.example.accountjsdemo', { onResult: (resultCode, result) => { - console.log("verifyCredential onResult, resultCode:" + JSON.stringify(resultCode)); - console.log("verifyCredential onResult, result:" + JSON.stringify(result)); + console.log('verifyCredential onResult, resultCode: ' + JSON.stringify(resultCode)); + console.log('verifyCredential onResult, result: ' + JSON.stringify(result)); }, onRequestRedirected: (request) => { - console.log("verifyCredential onRequestRedirected, request:" + JSON.stringify(request)); + console.log('verifyCredential onRequestRedirected, request: ' + JSON.stringify(request)); } }); } catch (err) { - console.log("verifyCredential err: " + JSON.stringify(err)); + console.log('verifyCredential err: ' + JSON.stringify(err)); } ``` @@ -2600,21 +2600,21 @@ Verifies the user credential. This API uses an asynchronous callback to return t ```js let options = { - credentialType: "pin", - credential: "123456" + credentialType: 'pin', + credential: '123456' }; try { - appAccountManager.verifyCredential("zhangsan", "com.example.accountjsdemo", options, { + appAccountManager.verifyCredential('zhangsan', 'com.example.accountjsdemo', options, { onResult: (resultCode, result) => { - console.log("verifyCredential onResult, resultCode:" + JSON.stringify(resultCode)); - console.log("verifyCredential onResult, result:" + JSON.stringify(result)); + console.log('verifyCredential onResult, resultCode: ' + JSON.stringify(resultCode)); + console.log('verifyCredential onResult, result: ' + JSON.stringify(result)); }, onRequestRedirected: (request) => { - console.log("verifyCredential onRequestRedirected, request:" + JSON.stringify(request)); + console.log('verifyCredential onRequestRedirected, request: ' + JSON.stringify(request)); } }); } catch (err) { - console.log("verifyCredential err: " + JSON.stringify(err)); + console.log('verifyCredential err: ' + JSON.stringify(err)); } ``` @@ -2647,17 +2647,17 @@ Sets the authenticator attributes of an app. This API uses an asynchronous callb ```js try { - appAccountManager.setAuthenticatorProperties("com.example.accountjsdemo", { + appAccountManager.setAuthenticatorProperties('com.example.accountjsdemo', { onResult: (resultCode, result) => { - console.log("setAuthenticatorProperties onResult, resultCode:" + JSON.stringify(resultCode)); - console.log("setAuthenticatorProperties onResult, result:" + JSON.stringify(result)); + console.log('setAuthenticatorProperties onResult, resultCode: ' + JSON.stringify(resultCode)); + console.log('setAuthenticatorProperties onResult, result: ' + JSON.stringify(result)); }, onRequestRedirected: (request) => { - console.log("setAuthenticatorProperties onRequestRedirected, request:" + JSON.stringify(request)); + console.log('setAuthenticatorProperties onRequestRedirected, request: ' + JSON.stringify(request)); } }); } catch (err) { - console.log("setAuthenticatorProperties err: " + JSON.stringify(err)); + console.log('setAuthenticatorProperties err: ' + JSON.stringify(err)); } ``` @@ -2691,20 +2691,20 @@ Set authenticator properties. This API uses an asynchronous callback to return t ```js let options = { - properties: {"prop1": "value1"} + properties: {'prop1': 'value1'} }; try { - appAccountManager.setAuthenticatorProperties("com.example.accountjsdemo", options, { + appAccountManager.setAuthenticatorProperties('com.example.accountjsdemo', options, { onResult: (resultCode, result) => { - console.log("setAuthenticatorProperties onResult, resultCode:" + JSON.stringify(resultCode)); - console.log("setAuthenticatorProperties onResult, result:" + JSON.stringify(result)); + console.log('setAuthenticatorProperties onResult, resultCode: ' + JSON.stringify(resultCode)); + console.log('setAuthenticatorProperties onResult, result: ' + JSON.stringify(result)); }, onRequestRedirected: (request) => { - console.log("setAuthenticatorProperties onRequestRedirected, request:" + JSON.stringify(request)); + console.log('setAuthenticatorProperties onRequestRedirected, request: ' + JSON.stringify(request)); } }); } catch (err) { - console.log("setAuthenticatorProperties err: " + JSON.stringify(err)); + console.log('setAuthenticatorProperties err: ' + JSON.stringify(err)); } ``` @@ -2732,8 +2732,8 @@ Adds an app account. This API uses an asynchronous callback to return the result **Example** ```js - appAccountManager.addAccount("WangWu", (err) => { - console.log("addAccount err: " + JSON.stringify(err)); + appAccountManager.addAccount('WangWu', (err) => { + console.log('addAccount err: ' + JSON.stringify(err)); }); ``` @@ -2744,7 +2744,6 @@ addAccount(name: string, extraInfo: string, callback: AsyncCallback<void>) Adds an app account name and additional information. This API uses an asynchronous callback to return the result. > **NOTE** -> > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [createAccount](#createaccount9-1). **System capability**: SystemCapability.Account.AppAccount @@ -2760,8 +2759,8 @@ Adds an app account name and additional information. This API uses an asynchrono **Example** ```js - appAccountManager.addAccount("LiSi", "token101", (err) => { - console.log("addAccount err: " + JSON.stringify(err)); + appAccountManager.addAccount('LiSi', 'token101', (err) => { + console.log('addAccount err: ' + JSON.stringify(err)); }); ``` @@ -2771,8 +2770,7 @@ addAccount(name: string, extraInfo?: string): Promise<void> Adds an app account name and additional information. This API uses an asynchronous callback to return the result. This API uses a promise to return the result. -> **NOTE** -> +> **NOTE** > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [createAccount](#createaccount9-2). **System capability**: SystemCapability.Account.AppAccount @@ -2782,7 +2780,7 @@ Adds an app account name and additional information. This API uses an asynchrono | Name | Type | Mandatory | Description | | --------- | ------ | ---- | ---------------------------------------- | | name | string | Yes | Name of the target app account. | -| extraInfo | string | No | Additional information (information that can be converted to the string type). It cannot contain sensitive information, such as the app account password and token.| +| extraInfo | string | No | Additional information (information that can be converted to the string type).
The additional information cannot be sensitive information (such as the password and token) of the app account.
By default, no value is passed, which means no additional information needs to be added for the account.| **Return value** @@ -2793,10 +2791,10 @@ Adds an app account name and additional information. This API uses an asynchrono **Example** ```js - appAccountManager.addAccount("LiSi", "token101").then(()=> { + appAccountManager.addAccount('LiSi', 'token101').then(()=> { console.log('addAccount Success'); }).catch((err) => { - console.log("addAccount err: " + JSON.stringify(err)); + console.log('addAccount err: ' + JSON.stringify(err)); }); ``` @@ -2827,8 +2825,8 @@ Adds an app account implicitly based on the specified owner. This API uses an as function onResultCallback(code, result) { - console.log("resultCode: " + code); - console.log("result: " + JSON.stringify(result)); + console.log('resultCode: ' + code); + console.log('result: ' + JSON.stringify(result)); } function onRequestRedirectedCallback(request) { @@ -2839,13 +2837,13 @@ Adds an app account implicitly based on the specified owner. This API uses an as entities: ['entity.system.default'], } this.context.startAbility(wantInfo).then(() => { - console.log("startAbility successfully"); + console.log('startAbility successfully'); }).catch((err) => { - console.log("startAbility err: " + JSON.stringify(err)); + console.log('startAbility err: ' + JSON.stringify(err)); }) } - appAccountManager.addAccountImplicitly("com.example.accountjsdemo", "getSocialData", {}, { + appAccountManager.addAccountImplicitly('com.example.accountjsdemo', 'getSocialData', {}, { onResult: onResultCallback, onRequestRedirected: onRequestRedirectedCallback }); @@ -2873,8 +2871,8 @@ Deletes an app account. This API uses an asynchronous callback to return the res **Example** ```js - appAccountManager.deleteAccount("ZhaoLiu", (err) => { - console.log("deleteAccount err: " + JSON.stringify(err)); + appAccountManager.deleteAccount('ZhaoLiu', (err) => { + console.log('deleteAccount err: ' + JSON.stringify(err)); }); ``` @@ -2905,10 +2903,10 @@ Deletes an app account. This API uses a promise to return the result. **Example** ```js - appAccountManager.deleteAccount("ZhaoLiu").then(() => { + appAccountManager.deleteAccount('ZhaoLiu').then(() => { console.log('deleteAccount Success'); }).catch((err) => { - console.log("deleteAccount err: " + JSON.stringify(err)); + console.log('deleteAccount err: ' + JSON.stringify(err)); }); ``` ### disableAppAccess(deprecated) @@ -2934,8 +2932,8 @@ Disables an app account from accessing an app. This API uses an asynchronous cal **Example** ```js - appAccountManager.disableAppAccess("ZhangSan", "com.example.accountjsdemo", (err) => { - console.log("disableAppAccess err: " + JSON.stringify(err)); + appAccountManager.disableAppAccess('ZhangSan', 'com.example.accountjsdemo', (err) => { + console.log('disableAppAccess err: ' + JSON.stringify(err)); }); ``` @@ -2967,10 +2965,10 @@ Disables an app account from accessing an app. This API uses a promise to return **Example** ```js - appAccountManager.disableAppAccess("ZhangSan", "com.example.accountjsdemo").then(() => { + appAccountManager.disableAppAccess('ZhangSan', 'com.example.accountjsdemo').then(() => { console.log('disableAppAccess Success'); }).catch((err) => { - console.log("disableAppAccess err: " + JSON.stringify(err)); + console.log('disableAppAccess err: ' + JSON.stringify(err)); }); ``` @@ -2997,8 +2995,8 @@ Enables an app account to access an app. This API uses an asynchronous callback **Example** ```js - appAccountManager.enableAppAccess("ZhangSan", "com.example.accountjsdemo", (err) => { - console.log("enableAppAccess: " + JSON.stringify(err)); + appAccountManager.enableAppAccess('ZhangSan', 'com.example.accountjsdemo', (err) => { + console.log('enableAppAccess: ' + JSON.stringify(err)); }); ``` @@ -3030,10 +3028,10 @@ Enables an app account to access an app. This API uses a promise to return the r **Example** ```js - appAccountManager.enableAppAccess("ZhangSan", "com.example.accountjsdemo").then(() => { + appAccountManager.enableAppAccess('ZhangSan', 'com.example.accountjsdemo').then(() => { console.log('enableAppAccess Success'); }).catch((err) => { - console.log("enableAppAccess err: " + JSON.stringify(err)); + console.log('enableAppAccess err: ' + JSON.stringify(err)); }); ``` @@ -3061,8 +3059,8 @@ Checks whether data synchronization is enabled for an app account. This API uses **Example** ```js - appAccountManager.checkAppAccountSyncEnable("ZhangSan", (err, result) => { - console.log("checkAppAccountSyncEnable err: " + JSON.stringify(err)); + appAccountManager.checkAppAccountSyncEnable('ZhangSan', (err, result) => { + console.log('checkAppAccountSyncEnable err: ' + JSON.stringify(err)); console.log('checkAppAccountSyncEnable result: ' + result); }); ``` @@ -3096,10 +3094,10 @@ Checks whether data synchronization is enabled for an app account. This API uses **Example** ```js - appAccountManager.checkAppAccountSyncEnable("ZhangSan").then((data) => { + appAccountManager.checkAppAccountSyncEnable('ZhangSan').then((data) => { console.log('checkAppAccountSyncEnable, result: ' + data); }).catch((err) => { - console.log("checkAppAccountSyncEnable err: " + JSON.stringify(err)); + console.log('checkAppAccountSyncEnable err: ' + JSON.stringify(err)); }); ``` @@ -3127,8 +3125,8 @@ Set credentials for an app account. This API uses an asynchronous callback to re **Example** ```js - appAccountManager.setAccountCredential("ZhangSan", "credentialType001", "credential001", (err) => { - console.log("setAccountCredential err: " + JSON.stringify(err)); + appAccountManager.setAccountCredential('ZhangSan', 'credentialType001', 'credential001', (err) => { + console.log('setAccountCredential err: ' + JSON.stringify(err)); }); ``` @@ -3161,10 +3159,10 @@ Set credentials for an app account. This API uses a promise to return the result **Example** ```js - appAccountManager.setAccountCredential("ZhangSan", "credentialType001", "credential001").then(() => { + appAccountManager.setAccountCredential('ZhangSan', 'credentialType001', 'credential001').then(() => { console.log('setAccountCredential Success'); }).catch((err) => { - console.log("setAccountCredential err: " + JSON.stringify(err)); + console.log('setAccountCredential err: ' + JSON.stringify(err)); }); ``` @@ -3192,8 +3190,8 @@ Sets additional information for an app account. This API uses an asynchronous ca **Example** ```js - appAccountManager.setAccountExtraInfo("ZhangSan", "Tk002", (err) => { - console.log("setAccountExtraInfo err: " + JSON.stringify(err)); + appAccountManager.setAccountExtraInfo('ZhangSan', 'Tk002', (err) => { + console.log('setAccountExtraInfo err: ' + JSON.stringify(err)); }); ``` @@ -3226,10 +3224,10 @@ Sets additional information for an app account. This API uses a promise to retur **Example** ```js - appAccountManager.setAccountExtraInfo("ZhangSan", "Tk002").then(() => { + appAccountManager.setAccountExtraInfo('ZhangSan', 'Tk002').then(() => { console.log('setAccountExtraInfo Success'); }).catch((err) => { - console.log("setAccountExtraInfo err: " + JSON.stringify(err)); + console.log('setAccountExtraInfo err: ' + JSON.stringify(err)); }); ``` @@ -3258,8 +3256,8 @@ Sets data synchronization for an app account. This API uses an asynchronous call **Example** ```js - appAccountManager.setAppAccountSyncEnable("ZhangSan", true, (err) => { - console.log("setAppAccountSyncEnable err: " + JSON.stringify(err)); + appAccountManager.setAppAccountSyncEnable('ZhangSan', true, (err) => { + console.log('setAppAccountSyncEnable err: ' + JSON.stringify(err)); }); ``` @@ -3293,10 +3291,10 @@ Sets data synchronization for an app account. This API uses a promise to return **Example** ```js - appAccountManager .setAppAccountSyncEnable("ZhangSan", true).then(() => { + appAccountManager .setAppAccountSyncEnable('ZhangSan', true).then(() => { console.log('setAppAccountSyncEnable Success'); }).catch((err) => { - console.log("setAppAccountSyncEnable err: " + JSON.stringify(err)); + console.log('setAppAccountSyncEnable err: ' + JSON.stringify(err)); }); ``` @@ -3325,8 +3323,8 @@ Sets data to be associated with an app account. This API uses an asynchronous ca **Example** ```js - appAccountManager.setAssociatedData("ZhangSan", "k001", "v001", (err) => { - console.log("setAssociatedData err: " + JSON.stringify(err)); + appAccountManager.setAssociatedData('ZhangSan', 'k001', 'v001', (err) => { + console.log('setAssociatedData err: ' + JSON.stringify(err)); }); ``` @@ -3360,10 +3358,10 @@ Sets data to be associated with an app account. This API uses a promise to retur **Example** ```js - appAccountManager.setAssociatedData("ZhangSan", "k001", "v001").then(() => { + appAccountManager.setAssociatedData('ZhangSan', 'k001', 'v001').then(() => { console.log('setAssociatedData Success'); }).catch((err) => { - console.log("setAssociatedData err: " + JSON.stringify(err)); + console.log('setAssociatedData err: ' + JSON.stringify(err)); }); ``` @@ -3391,8 +3389,8 @@ Obtains information about all accessible app accounts. This API uses an asynchro ```js appAccountManager.getAllAccessibleAccounts((err, data)=>{ - console.debug("getAllAccessibleAccounts err:" + JSON.stringify(err)); - console.debug("getAllAccessibleAccounts data:" + JSON.stringify(data)); + console.debug('getAllAccessibleAccounts err: ' + JSON.stringify(err)); + console.debug('getAllAccessibleAccounts data: ' + JSON.stringify(data)); }); ``` @@ -3422,7 +3420,7 @@ Obtains information about all accessible app accounts. This API uses a promise t appAccountManager.getAllAccessibleAccounts().then((data) => { console.log('getAllAccessibleAccounts: ' + data); }).catch((err) => { - console.log("getAllAccessibleAccounts err: " + JSON.stringify(err)); + console.log('getAllAccessibleAccounts err: ' + JSON.stringify(err)); }); ``` @@ -3450,10 +3448,10 @@ Obtains the app accounts that can be accessed by the invoker based on the app ac **Example** ```js - const selfBundle = "com.example.actsgetallaaccounts"; + const selfBundle = 'com.example.actsgetallaaccounts'; appAccountManager.getAllAccounts(selfBundle, (err, data)=>{ - console.debug("getAllAccounts err:" + JSON.stringify(err)); - console.debug("getAllAccounts data:" + JSON.stringify(data)); + console.debug('getAllAccounts err: ' + JSON.stringify(err)); + console.debug('getAllAccounts data:' + JSON.stringify(data)); }); ``` @@ -3486,11 +3484,11 @@ Obtains the app accounts that can be accessed by the invoker based on the app ac **Example** ```js - const selfBundle = "com.example.actsgetallaaccounts"; + const selfBundle = 'com.example.actsgetallaaccounts'; appAccountManager.getAllAccounts(selfBundle).then((data) => { console.log('getAllAccounts: ' + data); }).catch((err) => { - console.log("getAllAccounts err: " + JSON.stringify(err)); + console.log('getAllAccounts err: ' + JSON.stringify(err)); }); ``` @@ -3517,8 +3515,8 @@ Obtains the credential of an app account. This API uses an asynchronous callback **Example** ```js - appAccountManager.getAccountCredential("ZhangSan", "credentialType001", (err, result) => { - console.log("getAccountCredential err: " + JSON.stringify(err)); + appAccountManager.getAccountCredential('ZhangSan', 'credentialType001', (err, result) => { + console.log('getAccountCredential err: ' + JSON.stringify(err)); console.log('getAccountCredential result: ' + result); }); ``` @@ -3551,10 +3549,10 @@ Obtains the credential of an app account. This API uses a promise to return the **Example** ```js - appAccountManager.getAccountCredential("ZhangSan", "credentialType001").then((data) => { + appAccountManager.getAccountCredential('ZhangSan', 'credentialType001').then((data) => { console.log('getAccountCredential, result: ' + data); }).catch((err) => { - console.log("getAccountCredential err: " + JSON.stringify(err)); + console.log('getAccountCredential err: ' + JSON.stringify(err)); }); ``` @@ -3580,8 +3578,8 @@ Obtains additional information of an app account. Additional information refers **Example** ```js - appAccountManager.getAccountExtraInfo("ZhangSan", (err, result) => { - console.log("getAccountExtraInfo err: " + JSON.stringify(err)); + appAccountManager.getAccountExtraInfo('ZhangSan', (err, result) => { + console.log('getAccountExtraInfo err: ' + JSON.stringify(err)); console.log('getAccountExtraInfo result: ' + result); }); ``` @@ -3613,10 +3611,10 @@ Obtains additional information of an app account. Additional information refers **Example** ```js - appAccountManager.getAccountExtraInfo("ZhangSan").then((data) => { + appAccountManager.getAccountExtraInfo('ZhangSan').then((data) => { console.log('getAccountExtraInfo, result: ' + data); }).catch((err) => { - console.log("getAccountExtraInfo err: " + JSON.stringify(err)); + console.log('getAccountExtraInfo err: ' + JSON.stringify(err)); }); ``` @@ -3643,8 +3641,8 @@ Obtains data associated with an app account. This API uses an asynchronous callb **Example** ```js - appAccountManager.getAssociatedData("ZhangSan", "k001", (err, result) => { - console.log("getAssociatedData err: " + JSON.stringify(err)); + appAccountManager.getAssociatedData('ZhangSan', 'k001', (err, result) => { + console.log('getAssociatedData err: ' + JSON.stringify(err)); console.log('getAssociatedData result: ' + result); }); ``` @@ -3677,10 +3675,10 @@ Obtains data associated with an app account. This API uses a promise to return t **Example** ```js - appAccountManager.getAssociatedData("ZhangSan", "k001").then((data) => { + appAccountManager.getAssociatedData('ZhangSan', 'k001').then((data) => { console.log('getAssociatedData: ' + data); }).catch((err) => { - console.log("getAssociatedData err: " + JSON.stringify(err)); + console.log('getAssociatedData err: ' + JSON.stringify(err)); }); ``` @@ -3702,19 +3700,19 @@ Subscribes to account information changes of apps. | -------- | ---------------------------------------- | ---- | ------------------------------ | | type | 'change' | Yes | Event type to subscribe to. The value is **'change'**. An event will be reported when the account information changes.| | owners | Array<string> | Yes | App bundle names of the account. | -| callback | Callback<Array<[AppAccountInfo](#appaccountinfo)>> | Yes | Callback invoked to return the account changes. | +| callback | Callback<Array<[AppAccountInfo](#appaccountinfo)>> | Yes | Callback registered to return the list of changed app accounts. | **Example** ```js function changeOnCallback(data){ - console.debug("receive change data:" + JSON.stringify(data)); + console.debug('receive change data:' + JSON.stringify(data)); } try{ - appAccountManager.on('change', ["com.example.actsaccounttest"], changeOnCallback); + appAccountManager.on('change', ['com.example.actsaccounttest'], changeOnCallback); } catch(err){ - console.error("on accountOnOffDemo err:" + JSON.stringify(err)); + console.error('on accountOnOffDemo err:' + JSON.stringify(err)); } ``` @@ -3735,22 +3733,22 @@ Unsubscribes from account information changes. | Name | Type | Mandatory | Description | | -------- | -------------------------------- | ---- | ------------ | | type | 'change' | Yes | Event type to unsubscribe from. The value is **'change'**, which indicates the account change event. | -| callback | Callback<Array<[AppAccountInfo](#appaccountinfo)>> | No | Callback to unregister.| +| callback | Callback<Array<[AppAccountInfo](#appaccountinfo)>> | No | Callback to unregister. By default, no value is passed, which means to unregister all callbacks for the specified event.| **Example** ```js function changeOnCallback(data){ - console.debug("receive change data:" + JSON.stringify(data)); + console.debug('receive change data: ' + JSON.stringify(data)); appAccountManager.off('change', function(){ - console.debug("off finish"); + console.debug('off finish'); }) } try{ - appAccountManager.on('change', ["com.example.actsaccounttest"], changeOnCallback); + appAccountManager.on('change', ['com.example.actsaccounttest'], changeOnCallback); } catch(err){ - console.error("on accountOnOffDemo err:" + JSON.stringify(err)); + console.error('on accountOnOffDemo err: ' + JSON.stringify(err)); } ``` @@ -3780,8 +3778,8 @@ Authenticates an app account with customized options. This API uses an asynchron ```js function onResultCallback(code, result) { - console.log("resultCode: " + code); - console.log("result: " + JSON.stringify(result)); + console.log('resultCode: ' + code); + console.log('result: ' + JSON.stringify(result)); } function onRequestRedirectedCallback(request) { @@ -3792,13 +3790,13 @@ Authenticates an app account with customized options. This API uses an asynchron entities: ['entity.system.default'], } this.context.startAbility(wantInfo).then(() => { - console.log("startAbility successfully"); + console.log('startAbility successfully'); }).catch((err) => { - console.log("startAbility err: " + JSON.stringify(err)); + console.log('startAbility err: ' + JSON.stringify(err)); }) } - appAccountManager.authenticate("LiSi", "com.example.accountjsdemo", "getSocialData", {}, { + appAccountManager.authenticate('LiSi', 'com.example.accountjsdemo', 'getSocialData', {}, { onResult: onResultCallback, onRequestRedirected: onRequestRedirectedCallback }); @@ -3828,7 +3826,7 @@ Obtains the authorization token of the specified authentication type for an app **Example** ```js - appAccountManager.getOAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", (err, data) => { + appAccountManager.getOAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData', (err, data) => { console.log('getOAuthToken err: ' + JSON.stringify(err)); console.log('getOAuthToken token: ' + data); }); @@ -3863,10 +3861,10 @@ Obtains the authorization token of the specified authentication type for an app **Example** ```js - appAccountManager.getOAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData").then((data) => { + appAccountManager.getOAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData').then((data) => { console.log('getOAuthToken token: ' + data); }).catch((err) => { - console.log("getOAuthToken err: " + JSON.stringify(err)); + console.log('getOAuthToken err: ' + JSON.stringify(err)); }); ``` @@ -3894,7 +3892,7 @@ Sets an authorization token of the specific authentication type for an app accou **Example** ```js - appAccountManager.setOAuthToken("LiSi", "getSocialData", "xxxx", (err) => { + appAccountManager.setOAuthToken('LiSi', 'getSocialData', 'xxxx', (err) => { console.log('setOAuthToken err: ' + JSON.stringify(err)); }); ``` @@ -3928,7 +3926,7 @@ Sets an authorization token of the specific authentication type for an app accou **Example** ```js - appAccountManager.setOAuthToken("LiSi", "getSocialData", "xxxx").then(() => { + appAccountManager.setOAuthToken('LiSi', 'getSocialData', 'xxxx').then(() => { console.log('setOAuthToken successfully'); }).catch((err) => { console.log('setOAuthToken err: ' + JSON.stringify(err)); @@ -3960,7 +3958,7 @@ Deletes the authorization token of the specified authentication type for an app **Example** ```js - appAccountManager.deleteOAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", "xxxxx", (err) => { + appAccountManager.deleteOAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData', 'xxxxx', (err) => { console.log('deleteOAuthToken err: ' + JSON.stringify(err)); }); ``` @@ -3995,10 +3993,10 @@ Deletes the authorization token of the specified authentication type for an app **Example** ```js - appAccountManager.deleteOAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", "xxxxx").then(() => { + appAccountManager.deleteOAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData', 'xxxxx').then(() => { console.log('deleteOAuthToken successfully'); }).catch((err) => { - console.log("deleteOAuthToken err: " + JSON.stringify(err)); + console.log('deleteOAuthToken err: ' + JSON.stringify(err)); }); ``` @@ -4027,7 +4025,7 @@ Sets the visibility of an authorization token to an app. This API uses an asynch **Example** ```js - appAccountManager.setOAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", true, (err) => { + appAccountManager.setOAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo', true, (err) => { console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err)); }); ``` @@ -4062,7 +4060,7 @@ Sets the visibility of an authorization token to an app. This API uses a promise **Example** ```js - appAccountManager.setOAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", true).then(() => { + appAccountManager.setOAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo', true).then(() => { console.log('setOAuthTokenVisibility successfully'); }).catch((err) => { console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err)); @@ -4093,7 +4091,7 @@ Checks the visibility of an authorization token of the specified authentication **Example** ```js - appAccountManager.checkOAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", (err, data) => { + appAccountManager.checkOAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo', (err, data) => { console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err)); console.log('checkOAuthTokenVisibility isVisible: ' + data); }); @@ -4128,7 +4126,7 @@ Checks the visibility of an authorization token of the specified authentication **Example** ```js - appAccountManager.checkOAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo").then((data) => { + appAccountManager.checkOAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo').then((data) => { console.log('checkOAuthTokenVisibility isVisible: ' + data); }).catch((err) => { console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err)); @@ -4158,8 +4156,8 @@ Obtains all tokens visible to the invoker for an app account. This API uses an a **Example** ```js - appAccountManager.getAllOAuthTokens("LiSi", "com.example.accountjsdemo", (err, data) => { - console.log("getAllOAuthTokens err: " + JSON.stringify(err)); + appAccountManager.getAllOAuthTokens('LiSi', 'com.example.accountjsdemo', (err, data) => { + console.log('getAllOAuthTokens err: ' + JSON.stringify(err)); console.log('getAllOAuthTokens data: ' + JSON.stringify(data)); }); ``` @@ -4192,10 +4190,10 @@ Obtains all tokens visible to the invoker for an app account. This API uses a pr **Example** ```js - appAccountManager.getAllOAuthTokens("LiSi", "com.example.accountjsdemo").then((data) => { + appAccountManager.getAllOAuthTokens('LiSi', 'com.example.accountjsdemo').then((data) => { console.log('getAllOAuthTokens data: ' + JSON.stringify(data)); }).catch((err) => { - console.log("getAllOAuthTokens err: " + JSON.stringify(err)); + console.log('getAllOAuthTokens err: ' + JSON.stringify(err)); }); ``` @@ -4222,7 +4220,7 @@ Obtains the authorization list of the specified authentication type for an app a **Example** ```js - appAccountManager.getOAuthList("com.example.accountjsdemo", "getSocialData", (err, data) => { + appAccountManager.getOAuthList('LiSi', 'getSocialData', (err, data) => { console.log('getOAuthList err: ' + JSON.stringify(err)); console.log('getOAuthList data: ' + JSON.stringify(data)); }); @@ -4256,10 +4254,10 @@ Obtains the authorization list of the specified authentication type for an app a **Example** ```js - appAccountManager.getOAuthList("com.example.accountjsdemo", "getSocialData").then((data) => { + appAccountManager.getOAuthList('LiSi', 'getSocialData').then((data) => { console.log('getOAuthList data: ' + JSON.stringify(data)); }).catch((err) => { - console.log("getOAuthList err: " + JSON.stringify(err)); + console.log('getOAuthList err: ' + JSON.stringify(err)); }); ``` @@ -4292,13 +4290,13 @@ Obtains the authenticator callback for an authentication session. This API uses var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; appAccountManager.getAuthenticatorCallback(sessionId, (err, callback) => { if (err.code != account_appAccount.ResultCode.SUCCESS) { - console.log("getAuthenticatorCallback err: " + JSON.stringify(err)); + console.log('getAuthenticatorCallback err: ' + JSON.stringify(err)); return; } - var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi", - [account_appAccount.Constants.KEY_OWNER]: "com.example.accountjsdemo", - [account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData", - [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; + var result = {[account_appAccount.Constants.KEY_NAME]: 'LiSi', + [account_appAccount.Constants.KEY_OWNER]: 'com.example.accountjsdemo', + [account_appAccount.Constants.KEY_AUTH_TYPE]: 'getSocialData', + [account_appAccount.Constants.KEY_TOKEN]: 'xxxxxx'}; callback.onResult(account_appAccount.ResultCode.SUCCESS, result); }); } @@ -4338,13 +4336,13 @@ Obtains the authenticator callback for an authentication session. This API uses onCreate(want, param) { var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => { - var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi", - [account_appAccount.Constants.KEY_OWNER]: "com.example.accountjsdemo", - [account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData", - [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; + var result = {[account_appAccount.Constants.KEY_NAME]: 'LiSi', + [account_appAccount.Constants.KEY_OWNER]: 'com.example.accountjsdemo', + [account_appAccount.Constants.KEY_AUTH_TYPE]: 'getSocialData', + [account_appAccount.Constants.KEY_TOKEN]: 'xxxxxx'}; callback.onResult(account_appAccount.ResultCode.SUCCESS, result); }).catch((err) => { - console.log("getAuthenticatorCallback err: " + JSON.stringify(err)); + console.log('getAuthenticatorCallback err: ' + JSON.stringify(err)); }); } } @@ -4372,8 +4370,8 @@ Obtains the authenticator information of an app. This API uses an asynchronous c **Example** ```js - appAccountManager.getAuthenticatorInfo("com.example.accountjsdemo", (err, data) => { - console.log("getAuthenticatorInfo err: " + JSON.stringify(err)); + appAccountManager.getAuthenticatorInfo('com.example.accountjsdemo', (err, data) => { + console.log('getAuthenticatorInfo err: ' + JSON.stringify(err)); console.log('getAuthenticatorInfo data: ' + JSON.stringify(data)); }); ``` @@ -4405,10 +4403,10 @@ Obtains the authenticator information of an app. This API uses a promise to retu **Example** ```js - appAccountManager.getAuthenticatorInfo("com.example.accountjsdemo").then((data) => { + appAccountManager.getAuthenticatorInfo('com.example.accountjsdemo').then((data) => { console.log('getAuthenticatorInfo: ' + JSON.stringify(data)); }).catch((err) => { - console.log("getAuthenticatorInfo err: " + JSON.stringify(err)); + console.log('getAuthenticatorInfo err: ' + JSON.stringify(err)); }); ``` @@ -4433,7 +4431,7 @@ Defines authorization token information. | -------------------- | -------------- | ----- | ---------------- | | authType9+ | string | Yes | Authentication type. | | token9+ | string | Yes | Value of the authorization token. | -| account9+ | [AppAccountInfo](#appaccountinfo) | No | Account information of the authorization token.| +| account9+ | [AppAccountInfo](#appaccountinfo) | No | Information about the account to which the token belongs. By default, no value is passed.| ## OAuthTokenInfo(deprecated) @@ -4449,7 +4447,7 @@ Defines authorization token information. | -------------------- | -------------- | ----- | ---------------- | | authType | string | Yes | Authentication type. | | token | string | Yes | Value of the authorization token. | -| account9+ | [AppAccountInfo](#appaccountinfo) | No | Account information of the authorization token.| +| account9+ | [AppAccountInfo](#appaccountinfo) | No | Information about the account to which the token belongs. By default, no value is passed.| ## AuthenticatorInfo8+ @@ -4471,8 +4469,8 @@ Defines the authentication result. | Name | Type | Mandatory | Description | | ------- | ------ | ---- | ---------- | -| account | [AppAccountInfo](#appaccountinfo) | No | Account information of the authorization token.| -| tokenInfo | [AuthTokenInfo](#authtokeninfo9) | No | Token information. | +| account | [AppAccountInfo](#appaccountinfo) | No | Information about the account to which the token belongs. By default, no value is passed.| +| tokenInfo | [AuthTokenInfo](#authtokeninfo9) | No | Token information. By default, no value is passed. | ## CreateAccountOptions9+ @@ -4482,7 +4480,7 @@ Defines the options for creating an app account. | Name | Type | Mandatory | Description | | ------- | ------ | ---- | ---------- | -| customData | {[key: string]: string} | No | Custom data.| +| customData | {[key: string]: string} | No | Custom data. By default, no value is passed.| ## CreateAccountImplicitlyOptions9+ @@ -4492,9 +4490,9 @@ Defines the options for implicitly creating an app account. | Name | Type | Mandatory | Description | | ------- | ------ | ---- | ---------- | -| requiredLabels | Array<string> | No | Labels required.| -| authType | string | No | Authentication type.| -| parameters | {[key: string]: Object} | No | Customized parameters.| +| requiredLabels | Array<string> | No | Required labels. By default, no value is passed.| +| authType | string | No | Authentication type. By default, no value is passed.| +| parameters | {[key: string]: Object} | No | Custom parameter object. By default, no value is passed.| ## SelectAccountsOptions9+ Defines the options for selecting accounts. @@ -4503,9 +4501,9 @@ Defines the options for selecting accounts. | Name | Type | Mandatory | Description | | --------------- | --------------------------- | ----- | ------------------- | -| allowedAccounts | Array<[AppAccountInfo](#appaccountinfo)> | No | Allowed accounts. | -| allowedOwners | Array<string> | No | Allowed account owners.| -| requiredLabels | Array<string> | No | Labels required for the authenticator. | +| allowedAccounts | Array<[AppAccountInfo](#appaccountinfo)> | No | Array of allowed accounts. By default, no value is passed. | +| allowedOwners | Array<string> | No | Array of the owners of the allowed accounts. By default, no value is passed.| +| requiredLabels | Array<string> | No | Labels of the authenticator. By default, no value is passed. | ## VerifyCredentialOptions9+ @@ -4515,9 +4513,9 @@ Represents the options for verifying the user credential. | Name | Type | Mandatory | Description | | -------------- | ---------------------- | ----- | -------------- | -| credentialType | string | No | Type of the credential to verify. | -| credential | string | No | Credential value. | -| parameters | {[key: string]: Object} | No | Customized parameters.| +| credentialType | string | No | Credential type. By default, no value is passed. | +| credential | string | No | Credential value. By default, no value is passed. | +| parameters | {[key: string]: Object} | No | Custom parameter object. By default, no value is passed.| ## SetPropertiesOptions9+ @@ -4528,8 +4526,8 @@ Represents the options for setting authenticator properties. | Name | Type | Mandatory | Description | | ---------- | ---------------------- | ----- | -------------- | -| properties | {[key: string]: Object} | No | Authenticator properties. | -| parameters | {[key: string]: Object} | No | Customized parameters.| +| properties | {[key: string]: Object} | No | Property object. By default, no value is passed. | +| parameters | {[key: string]: Object} | No | Custom parameter object. By default, no value is passed.| ## Constants8+ @@ -4539,23 +4537,23 @@ Enumerates the constants. | Name | Value | Description | | -------------------------------- | ---------------------- | ----------------------- | -| ACTION_ADD_ACCOUNT_IMPLICITLY(deprecated) | "addAccountImplicitly" | Operation of adding an account implicitly. | -| ACTION_AUTHENTICATE(deprecated) | "authenticate" | Authentication operation. | -| ACTION_CREATE_ACCOUNT_IMPLICITLY9+ | "createAccountImplicitly" | Operation of creating an account implicitly. | -| ACTION_AUTH9+ | "auth" | Authentication operation. | -| ACTION_VERIFY_CREDENTIAL9+ | "verifyCredential" | Operation of verifying credentials. | -| ACTION_SET_AUTHENTICATOR_PROPERTIES9+ | "setAuthenticatorProperties" | Operation of setting authenticator properties. | -| KEY_NAME | "name" | Name of the app account. | -| KEY_OWNER | "owner" | Owner of the app account.| -| KEY_TOKEN | "token" | Token. | -| KEY_ACTION | "action" | Operation. | -| KEY_AUTH_TYPE | "authType" | Authentication type. | -| KEY_SESSION_ID | "sessionId" | Session ID. | -| KEY_CALLER_PID | "callerPid" | PID of the caller. | -| KEY_CALLER_UID | "callerUid" | UID of the caller. | -| KEY_CALLER_BUNDLE_NAME | "callerBundleName" | Bundle name of the caller. | -| KEY_REQUIRED_LABELS9+ | "requiredLabels" | Required labels. | -| KEY_BOOLEAN_RESULT9+ | "booleanResult" | Return value of the Boolean type. | +| ACTION_ADD_ACCOUNT_IMPLICITLY(deprecated) | 'addAccountImplicitly' | Operation of adding an account implicitly. | +| ACTION_AUTHENTICATE(deprecated) | 'authenticate' | Authentication operation. | +| ACTION_CREATE_ACCOUNT_IMPLICITLY9+ | 'createAccountImplicitly' | Operation of creating an account implicitly. | +| ACTION_AUTH9+ | 'auth' | Authentication operation. | +| ACTION_VERIFY_CREDENTIAL9+ | 'verifyCredential' | Operation of verifying credentials. | +| ACTION_SET_AUTHENTICATOR_PROPERTIES9+ | 'setAuthenticatorProperties' | Operation of setting authenticator properties. | +| KEY_NAME | 'name' | Name of the app account. | +| KEY_OWNER | 'owner' | Owner of the app account.| +| KEY_TOKEN | 'token' | Token. | +| KEY_ACTION | 'action' | Operation. | +| KEY_AUTH_TYPE | 'authType' | Authentication type. | +| KEY_SESSION_ID | 'sessionId' | Session ID. | +| KEY_CALLER_PID | 'callerPid' | PID of the caller. | +| KEY_CALLER_UID | 'callerUid' | UID of the caller. | +| KEY_CALLER_BUNDLE_NAME | 'callerBundleName' | Bundle name of the caller. | +| KEY_REQUIRED_LABELS9+ | 'requiredLabels' | Required labels. | +| KEY_BOOLEAN_RESULT9+ | 'booleanResult' | Return value of the Boolean type. | ## ResultCode(deprecated) @@ -4606,27 +4604,27 @@ Called to return the result of an authentication request. | Name | Type | Mandatory | Description | | ------ | -------------------- | ---- | ------ | | code | number | Yes | Authentication result code.| -| result | [AuthResult](#authresult9) | No | Authentication result. | +| result | [AuthResult](#authresult9) | No | Authentication result. By default, no value is passed, which means the authentication result is not received. | **Example** ```js let appAccountManager = account_appAccount.createAppAccountManager(); - var sessionId = "1234"; + var sessionId = '1234'; appAccountManager.getAuthCallback(sessionId).then((callback) => { var result = { accountInfo: { - name: "Lisi", - owner: "com.example.accountjsdemo", + name: 'Lisi', + owner: 'com.example.accountjsdemo', }, tokenInfo: { - token: "xxxxxx", - authType: "getSocialData" + token: 'xxxxxx', + authType: 'getSocialData' } }; callback.onResult(account_appAccount.ResultCode.SUCCESS, result); }).catch((err) => { - console.log("getAuthCallback err: " + JSON.stringify(err)); + console.log('getAuthCallback err: ' + JSON.stringify(err)); }); ``` @@ -4650,20 +4648,20 @@ Called to redirect a request. class MyAuthenticator extends account_appAccount.Authenticator { createAccountImplicitly(options, callback) { callback.onRequestRedirected({ - bundleName: "com.example.accountjsdemo", - abilityName: "com.example.accountjsdemo.LoginAbility", + bundleName: 'com.example.accountjsdemo', + abilityName: 'com.example.accountjsdemo.LoginAbility', }); } auth(name, authType, options, callback) { var result = { accountInfo: { - name: "Lisi", - owner: "com.example.accountjsdemo", + name: 'Lisi', + owner: 'com.example.accountjsdemo', }, tokenInfo: { - token: "xxxxxx", - authType: "getSocialData" + token: 'xxxxxx', + authType: 'getSocialData' } }; callback.onResult(account_appAccount.ResultCode.SUCCESS, result); @@ -4683,11 +4681,11 @@ Called to continue to process the request. ```js let appAccountManager = account_appAccount.createAppAccountManager(); - var sessionId = "1234"; + var sessionId = '1234'; appAccountManager.getAuthCallback(sessionId).then((callback) => { callback.onRequestContinued(); }).catch((err) => { - console.log("getAuthCallback err: " + JSON.stringify(err)); + console.log('getAuthCallback err: ' + JSON.stringify(err)); }); ``` @@ -4718,15 +4716,15 @@ Called to return the result of an authentication request. ```js let appAccountManager = account_appAccount.createAppAccountManager(); - var sessionId = "1234"; + var sessionId = '1234'; appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => { - var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi", - [account_appAccount.Constants.KEY_OWNER]: "com.example.accountjsdemo", - [account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData", - [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; + var result = {[account_appAccount.Constants.KEY_NAME]: 'LiSi', + [account_appAccount.Constants.KEY_OWNER]: 'com.example.accountjsdemo', + [account_appAccount.Constants.KEY_AUTH_TYPE]: 'getSocialData', + [account_appAccount.Constants.KEY_TOKEN]: 'xxxxxx'}; callback.onResult(account_appAccount.ResultCode.SUCCESS, result); }).catch((err) => { - console.log("getAuthenticatorCallback err: " + JSON.stringify(err)); + console.log('getAuthenticatorCallback err: ' + JSON.stringify(err)); }); ``` @@ -4750,15 +4748,15 @@ Called to redirect a request. class MyAuthenticator extends account_appAccount.Authenticator { addAccountImplicitly(authType, callerBundleName, options, callback) { callback.onRequestRedirected({ - bundleName: "com.example.accountjsdemo", - abilityName: "com.example.accountjsdemo.LoginAbility", + bundleName: 'com.example.accountjsdemo', + abilityName: 'com.example.accountjsdemo.LoginAbility', }); } authenticate(name, authType, callerBundleName, options, callback) { var result = {[account_appAccount.Constants.KEY_NAME]: name, [account_appAccount.Constants.KEY_AUTH_TYPE]: authType, - [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; + [account_appAccount.Constants.KEY_TOKEN]: 'xxxxxx'}; callback.onResult(account_appAccount.ResultCode.SUCCESS, result); } } @@ -4776,11 +4774,11 @@ Called to continue to process the request. ```js let appAccountManager = account_appAccount.createAppAccountManager(); - var sessionId = "1234"; + var sessionId = '1234'; appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => { callback.onRequestContinued(); }).catch((err) => { - console.log("getAuthenticatorCallback err: " + JSON.stringify(err)); + console.log('getAuthenticatorCallback err: ' + JSON.stringify(err)); }); ``` @@ -4940,22 +4938,22 @@ Obtains the remote object of an authenticator. This API cannot be overloaded. class MyAuthenticator extends account_appAccount.Authenticator { addAccountImplicitly(authType, callerBundleName, options, callback) { callback.onRequestRedirected({ - bundleName: "com.example.accountjsdemo", - abilityName: "com.example.accountjsdemo.LoginAbility", + bundleName: 'com.example.accountjsdemo', + abilityName: 'com.example.accountjsdemo.LoginAbility', }); } authenticate(name, authType, callerBundleName, options, callback) { var result = {[account_appAccount.Constants.KEY_NAME]: name, [account_appAccount.Constants.KEY_AUTH_TYPE]: authType, - [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; + [account_appAccount.Constants.KEY_TOKEN]: 'xxxxxx'}; callback.onResult(account_appAccount.ResultCode.SUCCESS, result); } verifyCredential(name, options, callback) { callback.onRequestRedirected({ - bundleName: "com.example.accountjsdemo", - abilityName: "com.example.accountjsdemo.VerifyAbility", + bundleName: 'com.example.accountjsdemo', + abilityName: 'com.example.accountjsdemo.VerifyAbility', parameters: { name: name } 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 f8bbe2212f0b6b9ae41183bfce2ae7c03a726d99..b6a2b41d6c9b9ed05603c68f94d8f53426570414 100644 --- a/en/application-dev/reference/apis/js-apis-arkui-componentSnapshot.md +++ b/en/application-dev/reference/apis/js-apis-arkui-componentSnapshot.md @@ -116,8 +116,8 @@ struct SnapshotExample { Image(this.pixmap) .width(300).height(300) // ...Component - // ...Components - // ...Components + // ...Component + // ...Component Button("click to generate UI snapshot") .onClick(() => { componentSnapshot.get("root") diff --git a/en/application-dev/reference/apis/js-apis-camera.md b/en/application-dev/reference/apis/js-apis-camera.md index b8d4e4b54a0d34826962b8d3d66b5e7f1b30be13..c86b21c5f8c541e29b38eeb38cb25edfc13bfc14 100644 --- a/en/application-dev/reference/apis/js-apis-camera.md +++ b/en/application-dev/reference/apis/js-apis-camera.md @@ -2,8 +2,7 @@ > **NOTE** > -> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> - The APIs provided by this module are system APIs. +> 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 @@ -110,17 +109,18 @@ Enumerates the camera error codes, which are returned when an API call is incorr **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| ------------------------- | ---- | ------------ | -| INVALID_ARGUMENT | 7400101 | A parameter is missing or the parameter type is incorrect. | -| OPERATION_NOT_ALLOWED | 7400102 | The operation is not allowed. | -| SESSION_NOT_CONFIG | 7400103 | The session is not configured. | -| SESSION_NOT_RUNNING | 7400104 | The session is not running. | -| SESSION_CONFIG_LOCKED | 7400105 | The session configuration is locked. | -| DEVICE_SETTING_LOCKED | 7400106 | The device setting is locked. | -| CONFILICT_CAMERA | 7400107 | The device is already started. | -| DEVICE_DISABLED | 7400108 | The camera is disabled for security reasons. | -| SERVICE_FATAL_ERROR | 7400201 | An error occurs in the camera service. | +| Name | Value | Description | +| ------------------------- | ---- | ------------ | +| INVALID_ARGUMENT | 7400101 | A parameter is missing or the parameter type is incorrect. | +| OPERATION_NOT_ALLOWED | 7400102 | The operation is not allowed. | +| SESSION_NOT_CONFIG | 7400103 | The session is not configured. | +| SESSION_NOT_RUNNING | 7400104 | The session is not running. | +| SESSION_CONFIG_LOCKED | 7400105 | The session configuration is locked. | +| DEVICE_SETTING_LOCKED | 7400106 | The device setting is locked. | +| CONFLICT_CAMERA | 7400107 | The device is already started. | +| DEVICE_DISABLED | 7400108 | The camera is disabled for security reasons. | +| DEVICE_PREEMPTED | 7400109 | The camera is preempted. | +| SERVICE_FATAL_ERROR | 7400201 | An error occurs in the camera service. | ## CameraManager @@ -203,7 +203,7 @@ isCameraMuteSupported(): boolean Checks whether the camera can be muted. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -225,7 +225,7 @@ muteCamera(mute: boolean): void Mutes or unmutes the camera. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -562,7 +562,7 @@ on(type: 'cameraMute', callback: AsyncCallback\): void Listens for camera mute status changes. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -630,6 +630,20 @@ Enumerates the camera connection types. | CAMERA_CONNECTION_USB_PLUGIN | 1 | Camera connected using USB.| | CAMERA_CONNECTION_REMOTE | 2 | Remote camera.| +## HostDeviceType + +Enumerates the remote camera types. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Value | Description | +| ---------------------------- | ---- | ------------- | +| UNKNOWN_TYPE | 0 | Unknown type. | +| PHONE | 0x0E | Camera of a smartphone.| +| TABLET | 0x11 | Camera of a tablet.| + ## CameraDevice Defines the camera device information. @@ -642,6 +656,8 @@ Defines the camera device information. | cameraPosition | [CameraPosition](#cameraposition) | Yes | Camera position. | | cameraType | [CameraType](#cameratype) | Yes | Camera type. | | connectionType | [ConnectionType](#connectiontype) | Yes | Camera connection type.| +| hostDeviceName | string | Yes | Name of the remote device.
**System API**: This is a system API.| +| hostDeviceType | [hostDeviceType](#hostdevicetype) | Yes | Type of the remote device.
**System API**: This is a system API.| ## Size @@ -1754,7 +1770,7 @@ Before the setting, you are advised to use **[getExposureBiasRange](#getexposure | Name | Type | Mandatory| Description | | -------- | -------------------------------| ---- | ------------------- | -| exposureBias | number | Yes | EV. The supported EV range can be obtained by calling **getExposureBiasRange**. If calling the API fails, an error code defined in [CameraErrorCode](#cameraerrorcode) will be returned. If the value passed is not within the supported range, the nearest critical point is used.| +| exposureBias | number | Yes | EV. The supported EV range can be obtained by calling **getExposureBiasRange**. If the value passed is not within the supported range, the nearest critical point is used. There is a step for EV. For example, if the step is 0.5 and this parameter is set to 1.2, the EV that takes effect is 1.0. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned. | **Error codes** @@ -1788,7 +1804,7 @@ Obtains the exposure value in use. | Type | Description | | ---------- | ----------------------------- | -| number | Exposure value obtained. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| +| number | Exposure value obtained. There is a step for EV. For example, if the step is 0.5 and this parameter is set to 1.2, the EV that takes effect is 1.0. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned. | **Error codes** diff --git a/en/application-dev/reference/apis/js-apis-data-cloudData.md b/en/application-dev/reference/apis/js-apis-data-cloudData.md new file mode 100644 index 0000000000000000000000000000000000000000..38c6d65e42ea6c2665f33812d94b7093432af401 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-data-cloudData.md @@ -0,0 +1,348 @@ +# @ohos.data.cloudData (Device-Cloud Synergy) + +The **cloudData** module provides the capability of synchronizing the structured data (in RDB stores) between the device and cloud. The cloud serves as the central node of data. The devices synchronize data with the data in the cloud to implement cloud data backup and data consistency between the devices with the same account. + +This module provides the following common functions: + +- [Config](#config): provides methods for configuring device-cloud synergy, including enabling and disabling cloud synchronization, clearing data, and notifying data changes. + +> **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 cloudData from '@ohos.data.cloudData'; +``` + +## Action + +Enumerates the actions for clearing the cloud information about the local data. + +**System API**: This is a system API. + +**System capability**: SystemCapability.DistributedDataManager.CloudSync.Config + +| Name | Description | +| --------- | ---------------------------- | +| CLEAR_CLOUD_INFO | Clear the cloud ID information.| +| CLEAR_CLOUD_DATA_AND_INFO |Clear all cloud data, including cloud ID information and data downloaded from the cloud (excluding the data modified or generated locally). | + +## Config + +Provides methods for configuring device-cloud synergy, including enabling and disabling cloud synchronization, clearing data, and notifying data changes. + +### enableCloud + +static enableCloud(accountId: string, switches: {[bundleName: string]: boolean}, callback: AsyncCallback<void>):void + +Enables device-cloud synergy. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.CLOUDDATA_CONFIG + +**System capability**: SystemCapability.DistributedDataManager.CloudSync.Config + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------- | ---- | ------------------------------------------------------------ | +| accountId | string | Yes | ID of the target cloud. | +| switches | {[bundleName: string]: boolean} | Yes | Device-cloud synergy switches for applications. The value **true** means to enable the device-cloud synergy; the value **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Example** + +```js +let account = 'test_id'; +let switches = { 'test_bundleName1': true, 'test_bundleName2': false }; +try { + cloudData.Config.enableCloud(account, switches, function (err) { + if (err === undefined) { + console.info('Succeeded in enabling cloud'); + } else { + console.error(`Failed to enable.Code: ${err.code}, message: ${err.message}`); + } + }); +} catch (error) { + console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`); +} +``` + +### enableCloud + +static enableCloud(accountId: string, switches: {[bundleName: string]: boolean}): Promise<void> + +Enables device-cloud synergy. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.CLOUDDATA_CONFIG + +**System capability**: SystemCapability.DistributedDataManager.CloudSync.Config + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------- | ---- | ------------------------------------------------------------ | +| accountId | string | Yes | ID of the target cloud. | +| switches | {[bundleName: string]: boolean} | Yes | Device-cloud synergy switches for applications. The value **true** means to enable the device-cloud synergy; the value **false** means the opposite.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let account = 'test_id'; +let switches = { 'test_bundleName1': true, 'test_bundleName2': false }; +try { + cloudData.Config.enableCloud(account, switches).then(() => { + console.info('Succeeded in enabling cloud'); + }).catch((err) => { + console.error(`Failed to enable.Code: ${err.code}, message: ${err.message}`); + }); +} catch (error) { + console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`); +} +``` + +### disableCloud + +static disableCloud(accountId: string, callback: AsyncCallback<void>):void + +Disables device-cloud synergy. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.CLOUDDATA_CONFIG + +**System capability**: SystemCapability.DistributedDataManager.CloudSync.Config + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------- | ---- | ---------------- | +| accountId | string | Yes | ID of the target cloud.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Example** + +```js +let account = 'test_id'; +try { + cloudData.Config.disableCloud(account, function (err) { + if (err === undefined) { + console.info('Succeeded in disabling cloud'); + } else { + console.error(`Failed to disableCloud. Code: ${err.code}, message: ${err.message}`); + } + }); +} catch (error) { + console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`); +} +``` + +### disableCloud + +static disableCloud(accountId: string): Promise<void> + +Disables device-cloud synergy. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.CLOUDDATA_CONFIG + +**System capability**: SystemCapability.DistributedDataManager.CloudSync.Config + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ---------------- | +| accountId | string | Yes | ID of the target cloud.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let account = 'test_id'; +try { + cloudData.Config.disableCloud(account).then(() => { + console.info('Succeeded in disabling cloud'); + }).catch((err) => { + console.error(`Failed to disableCloud. Code: ${err.code}, message: ${err.message}`); + }); +} catch (error) { + console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`); +} +``` + +### changeAppCloudSwitch + +static changeAppCloudSwitch(accountId: string,bundleName:string,status:boolean, callback: AsyncCallback<void>):void + +Changes the device-cloud synergy switch for an application. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.CLOUDDATA_CONFIG + +**System capability**: SystemCapability.DistributedDataManager.CloudSync.Config + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------- | ---- | ---------------------------- | +| accountId | string | Yes | ID of the target cloud.| +| bundleName| string | Yes | Name of the target application.| +| status | boolean | Yes | Setting of the device-cloud synergy switch for the application. The value **true** means to enable the device-cloud synergy; the value **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Example** + +```js +let account = 'test_id'; +let bundleName = 'test_bundleName'; +try { + cloudData.Config.changeAppCloudSwitch(account, bundleName, true, function (err) { + if (err === undefined) { + console.info('Succeeded in changing App cloud switch'); + } else { + console.error(`Failed to change App cloud switch. Code: ${err.code}, message: ${err.message}`); + } + }); +} catch (error) { + console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`); +} +``` + +### changeAppCloudSwitch + +static changeAppCloudSwitch(accountId: string,bundleName:string,status:boolean): Promise<void> + +Changes the device-cloud synergy switch for an application. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.CLOUDDATA_CONFIG + +**System capability**: SystemCapability.DistributedDataManager.CloudSync.Config + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------- | ---- | ---------------------------- | +| accountId | string | Yes | ID of the target cloud.| +| bundleName| string | Yes | Name of the target application.| +| status | boolean | Yes | Setting of the device-cloud synergy switch for the application. The value **true** means to enable the device-cloud synergy; the value **false** means the opposite.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let account = 'test_id'; +let bundleName = 'test_bundleName'; +try { + cloudData.Config.changeAppCloudSwitch(account, bundleName, true).then(() => { + console.info('Succeeded in changing App cloud switch'); + }).catch((err) => { + console.error(`Failed to change App cloud switch. Code is ${err.code}, message is ${err.message}`); + }); +} catch (error) { + console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`); +} +``` + +### notifyDataChange + +static notifyDataChange(accountId: string,bundleName:string, callback: AsyncCallback<void>):void + +Notifies the data changes in the cloud. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.CLOUDDATA_CONFIG + +**System capability**: SystemCapability.DistributedDataManager.CloudSync.Server + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------- | ---- | ---------------- | +| accountId | string | Yes | ID of the target cloud.| +| bundleName | string | Yes | Name of the target application. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Example** + +```js +let account = 'test_id'; +let bundleName = 'test_bundleName'; +try { + cloudData.Config.notifyDataChange(account, bundleName, function (err) { + if (err === undefined) { + console.info('Succeeded in notifying the change of data'); + } else { + console.error(`Failed to notify the change of data. Code: ${err.code}, message: ${err.message}`); + } + }); +} catch (error) { + console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`); +} +``` + +### notifyDataChange + +static notifyDataChange(accountId: string,bundleName:string): Promise<void> + +Notifies the data changes in the cloud. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.CLOUDDATA_CONFIG + +**System capability**: SystemCapability.DistributedDataManager.CloudSync.Server + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | ---------------- | +| accountId | string | Yes | ID of the target cloud.| +| bundleName | string | Yes | Name of the target application. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let account = 'test_id'; +let bundleName = 'test_bundleName'; +try { + cloudData.Config.notifyDataChange(account, bundleName).then(() => { + console.info('Succeeded in notifying the change of data'); + }).catch((err) => { + console.error(`Failed to notify the change of data. Code: ${err.code}, message: ${err.message}`); + }); +} catch (error) { + console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md b/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md index 78d896c54a2f1c1674825ddaff66088634129596..6f63bb98574f0499ea47acb1f9ff0e04fff65f34 100644 --- a/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md +++ b/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md @@ -1,4 +1,4 @@ -# @ohos.data.dataSharePredicates (DataShare Predicates) +# @ohos.data.dataSharePredicates (Data Share Predicates) You can use **DataSharePredicates** to specify conditions for [updating](js-apis-data-dataShare.md#update), [deleting](js-apis-data-dataShare.md#delete), and [querying](js-apis-data-dataShare.md#query) data when **DataShare** is used to manage data. @@ -18,13 +18,13 @@ import dataSharePredicates from '@ohos.data.dataSharePredicates'; ``` ## DataSharePredicates -Provides methods for setting different **DataSharePredicates** objects. +Provides methods for setting different **DataSharePredicates** objects. This type is not multi-thread safe. If a **DataSharePredicates** instance is operated by multiple threads at the same time in an application, use a lock for the instance. ### equalTo equalTo(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to search for the data that is equal to the specified value. +Sets a **DataSharePredicates** object to match the data that is equal to the specified value. Currently, only the relational database (RDB) and key-value database (KVDB, schema) support this **DataSharePredicates** object. @@ -54,10 +54,11 @@ predicates.equalTo("NAME", "Rose") notEqualTo(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to search for the data that is not equal to the specified value. +Sets a **DataSharePredicates** object to match the data that is not equal to the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** @@ -88,6 +89,7 @@ Adds a left parenthesis to this **DataSharePredicates**. Currently, only the RDB supports this **DataSharePredicates** object. +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Return value** @@ -116,6 +118,7 @@ Adds a right parenthesis to this **DataSharePredicates** object. Currently, only the RDB supports this **DataSharePredicates** object. +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Return value** @@ -144,6 +147,7 @@ Adds the OR condition to this **DataSharePredicates** object. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Return value** @@ -190,10 +194,11 @@ predicates.equalTo("NAME", "lisi") contains(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to search for the data that contains the specified value. +Sets a **DataSharePredicates** object to match the data that contains the specified value. Currently, only the RDB supports this **DataSharePredicates** object. +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** @@ -220,10 +225,11 @@ predicates.contains("NAME", "os") beginsWith(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to search for the data that begins with the specified value. +Sets a **DataSharePredicates** object to match the data that begins with the specified value. Currently, only the RDB supports this **DataSharePredicates** object. +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** @@ -250,10 +256,11 @@ predicates.beginsWith("NAME", "os") endsWith(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to search for the data that ends with the specified value. +Sets a **DataSharePredicates** object to match the data that ends with the specified value. Currently, only the RDB supports this **DataSharePredicates** object. +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** @@ -280,10 +287,11 @@ predicates.endsWith("NAME", "os") isNull(field: string): DataSharePredicates -Sets a **DataSharePredicates** object to search for the data whose value is null. +Sets a **DataSharePredicates** object to match the data whose value is null. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** @@ -309,10 +317,11 @@ predicates.isNull("NAME") isNotNull(field: string): DataSharePredicates -Sets a **DataSharePredicates** object to search for the data whose value is not null. +Sets a **DataSharePredicates** object to match the data whose value is not null. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** @@ -338,10 +347,11 @@ predicates.isNotNull("NAME") like(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to search for the data that matches the specified wildcard expression. +Sets a **DataSharePredicates** object to match the data that matches the specified wildcard expression. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** @@ -368,10 +378,11 @@ predicates.like("NAME", "%os%") unlike(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to search for the data that does not match the specified wildcard expression. +Sets a **DataSharePredicates** object to match the data that does not match the specified wildcard expression. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** @@ -398,10 +409,11 @@ predicates.unlike("NAME", "%os%") glob(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to search for the data that matches the specified wildcard expression. +Sets a **DataSharePredicates** object to match the data that matches the specified wildcard expression. Currently, only the RDB supports this **DataSharePredicates** object. +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** @@ -428,10 +440,11 @@ predicates.glob("NAME", "?h*g") between(field: string, low: ValueType, high: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to search for the data that is within the specified range, including the start and end values. +Sets a **DataSharePredicates** object to match the data that is within the specified range, including the start and end values. Currently, only the RDB supports this **DataSharePredicates** object. +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** @@ -459,10 +472,11 @@ predicates.between("AGE", 10, 50) notBetween(field: string, low: ValueType, high: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to search for the data that is out of the specified range, excluding the start and end values. +Sets a **DataSharePredicates** object to match the data that is out of the specified range, excluding the start and end values. Currently, only the RDB supports this **DataSharePredicates** object. +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** @@ -490,10 +504,11 @@ predicates.notBetween("AGE", 10, 50) greaterThan(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to search for the data that is greater than the specified value. +Sets a **DataSharePredicates** object to match the data that is greater than the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** @@ -520,10 +535,11 @@ predicates.greaterThan("AGE", 10) lessThan(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to search for the data that is less than the specified value. +Sets a **DataSharePredicates** object to match the data that is less than the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** @@ -550,10 +566,11 @@ predicates.lessThan("AGE", 50) greaterThanOrEqualTo(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to search for the data that is greater than or equal to the specified value. +Sets a **DataSharePredicates** object to match the data that is greater than or equal to the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** @@ -580,10 +597,11 @@ predicates.greaterThanOrEqualTo("AGE", 10) lessThanOrEqualTo(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to search for the data that is less than or equal to the specified value. +Sets a **DataSharePredicates** object to match the data that is less than or equal to the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** @@ -672,6 +690,7 @@ Sets a **DataSharePredicates** object to filter out duplicate data records. Currently, only the RDB supports this **DataSharePredicates** object. +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Return value** @@ -725,6 +744,7 @@ Sets a **DataSharePredicates** object group the records according to the specifi Currently, only the RDB supports this **DataSharePredicates** object. +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** @@ -754,6 +774,7 @@ Sets a **DataSharePredicates** object to list data by the specified index. Currently, only the RDB supports this **DataSharePredicates** object. +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** @@ -779,7 +800,7 @@ predicates.indexedBy("SALARY_INDEX") in(field: string, value: Array<ValueType>): DataSharePredicates -Sets a **DataSharePredicates** object to search for the data that is within the specified value. +Sets a **DataSharePredicates** object to match the data that is within the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -809,10 +830,11 @@ predicates.in("AGE", [18, 20]) notIn(field: string, value: Array<ValueType>): DataSharePredicates -Sets a **DataSharePredicates** object to search for the data that is not in the specified value. +Sets a **DataSharePredicates** object to match the data that is not in the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** @@ -839,10 +861,11 @@ predicates.notIn("NAME", ["Lisa", "Rose"]) prefixKey(prefix: string): DataSharePredicates -Sets a **DataSharePredicates** object to search for the data with the specified key prefix. +Sets a **DataSharePredicates** object to match the data with the specified key prefix. Currently, only the KVDB supports this **DataSharePredicates** object. +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** @@ -868,10 +891,11 @@ predicates.prefixKey("NAME") inKeys(keys: Array<string>): DataSharePredicates -Sets a **DataSharePredicates** object to search for the data whose keys are within the given range. +Sets a **DataSharePredicates** object to match the data whose keys are within the given range. Currently, only the KVDB supports this **DataSharePredicates** object. +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** diff --git a/en/application-dev/reference/apis/js-apis-data-distributedobject.md b/en/application-dev/reference/apis/js-apis-data-distributedobject.md index 978cbffcf74444d9c902a91d72017d316f5ae5e8..8892f9ff2538ad00cebda30ba7b80fa3abf31641 100644 --- a/en/application-dev/reference/apis/js-apis-data-distributedobject.md +++ b/en/application-dev/reference/apis/js-apis-data-distributedobject.md @@ -23,10 +23,10 @@ Creates a distributed data object. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| context | Context | Yes| Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| -| source | object | Yes| Attributes of the distributed data object.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | context | Context | Yes| Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| + | source | object | Yes| Attributes of the distributed data object.| **Return value** @@ -75,9 +75,9 @@ Creates a random session ID. **Return value** -| Type| Description| -| -------- | -------- | -| string | Session ID created.| + | Type| Description| + | -------- | -------- | + | string | Session ID created.| **Example** @@ -124,18 +124,18 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| sessionId | string | Yes| ID of a distributed data object on a trusted network.| -| callback | AsyncCallback<void> | Yes| Asynchronous callback invoked when the session ID is successfully set.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | sessionId | string | Yes| ID of a distributed data object on a trusted network.| + | callback | AsyncCallback<void> | Yes| Asynchronous callback invoked when the session ID is successfully set.| **Error codes** For details about the error codes, see [Distributed Data Object Error Codes](../errorcodes/errorcode-distributed-dataObject.md). -| ID| Error Message| -| -------- | -------- | -| 15400001 | Failed to create the in-memory database.| + | ID| Error Message| + | -------- | -------- | + | 15400001 | Create table failed.| **Example** @@ -158,17 +158,17 @@ Exits all joined sessions. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<void> | Yes| Asynchronous callback invoked when the distributed data object exits all joined sessions.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | Yes| Asynchronous callback invoked when the distributed data object exits all joined sessions.| **Error codes** For details about the error codes, see [Distributed Data Object Error Codes](../errorcodes/errorcode-distributed-dataObject.md). -| ID| Error Message| -| -------- | -------- | -| 15400001 | Failed to create the in-memory database.| + | ID| Error Message| + | -------- | -------- | + | 15400001 | Create table failed.| **Example** @@ -195,9 +195,9 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| **Return value** @@ -209,9 +209,9 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo For details about the error codes, see [Distributed Data Object Error Codes](../errorcodes/errorcode-distributed-dataObject.md). -| ID| Error Message| -| -------- | -------- | -| 15400001 | Failed to create the in-memory database.| + | ID| Error Message| + | -------- | -------- | + | 15400001 | Create table failed.| **Example** @@ -240,10 +240,10 @@ Subscribes to data changes of this distributed data object. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.| -| callback | Callback<{ sessionId: string, fields: Array<string> }> | Yes| Callback invoked to return the changes of the distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.| + | callback | Callback<{ sessionId: string, fields: Array<string> }> | Yes| Callback invoked to return the changes of the distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| **Example** @@ -269,10 +269,10 @@ Unsubscribes from the data changes of this distributed data object. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | | type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.| -| callback | Callback<{ sessionId: string, fields: Array<string> }> | No| Callback for data changes. If this parameter is not specified, all data change callbacks of this distributed data object will be unregistered.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| + | callback | Callback<{ sessionId: string, fields: Array<string> }> | No| Callback for data changes. If this parameter is not specified, all data change callbacks of this distributed data object will be unregistered.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| **Example** @@ -294,10 +294,10 @@ Subscribes to status changes of this distributed data object. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| -| callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback invoked to return the status change.
**sessionId** indicates the session ID of the distributed data object.
**networkId** indicates the object device ID, that is, **deviceId**.
**status** indicates the object status, which can be online or offline.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| + | callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback invoked to return the status change.
**sessionId** indicates the session ID of the distributed data object.
**networkId** indicates the object device ID, that is, **deviceId**.
**status** indicates the object status, which can be online or offline.| **Example** @@ -318,10 +318,10 @@ Unsubscribes from the status change of this distributed data object. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | | type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| -| callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback for status changes. If this parameter is not specified, all status change callbacks of this distributed data object will be unsubscribed from.
**sessionId** indicates the session ID of the distributed data object.
**deviceId** indicates the device ID of the distributed data object.
**status** indicates the object status, which can be online or offline.| + | callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback for status changes. If this parameter is not specified, all status change callbacks of this distributed data object will be unsubscribed from.
**sessionId** indicates the session ID of the distributed data object.
**deviceId** indicates the device ID of the distributed data object.
**status** indicates the object status, which can be online or offline.| **Example** @@ -354,10 +354,10 @@ The saved data will be released in the following cases: **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates the local device.| -| callback | AsyncCallback<[SaveSuccessResponse](#savesuccessresponse9)> | Yes| Callback invoked to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates the local device.| + | callback | AsyncCallback<[SaveSuccessResponse](#savesuccessresponse9)> | Yes| Callback invoked to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| **Example** @@ -394,15 +394,15 @@ The saved data will be released in the following cases: **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| deviceId | string | Yes| ID of the device where the data is saved. The default value is **local**, which indicates the local device. | + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | deviceId | string | Yes| ID of the device where the data is saved. The default value is **local**, which indicates the local device. | **Return value** -| Type| Description| -| -------- | -------- | -| Promise<[SaveSuccessResponse](#savesuccessresponse9)> | Promise used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| + | Type| Description| + | -------- | -------- | + | Promise<[SaveSuccessResponse](#savesuccessresponse9)> | Promise used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| **Example** @@ -423,7 +423,7 @@ g_object.save("local").then((result) => { revokeSave(callback: AsyncCallback<RevokeSaveSuccessResponse>): void -Revokes the saving operation of this distributed data object. This API uses an asynchronous callback to return the result. +Revokes the data of this distributed data object saved. This API uses an asynchronous callback to return the result. If the object is saved on the local device, the data saved on all trusted devices will be deleted. If the object is stored on another device, the data on the local device will be deleted. @@ -432,9 +432,9 @@ If the object is stored on another device, the data on the local device will be **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | Yes| Callback invoked to return **RevokeSaveSuccessResponse**, which contains the session ID.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | Yes| Callback invoked to return **RevokeSaveSuccessResponse**, which contains the session ID.| **Example** @@ -468,7 +468,7 @@ g_object.revokeSave((err, result) => { revokeSave(): Promise<RevokeSaveSuccessResponse> -Revokes the saving operation of this distributed data object. This API uses a promise to return the result. +Revokes the data of this distributed data object saved. This API uses a promise to return the result. If the object is saved on the local device, the data saved on all trusted devices will be deleted. If the object is stored on another device, the data on the local device will be deleted. @@ -477,9 +477,9 @@ If the object is stored on another device, the data on the local device will be **Return value** -| Type| Description| -| -------- | -------- | -| Promise<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | Promise used to return **RevokeSaveSuccessResponse**, which contains the session ID.| + | Type| Description| + | -------- | -------- | + | Promise<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | Promise used to return **RevokeSaveSuccessResponse**, which contains the session ID.| **Example** @@ -520,9 +520,9 @@ Creates a distributed data object. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| source | object | Yes| Attributes of the distributed data object.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | source | object | Yes| Attributes of the distributed data object.| **Return value** @@ -558,15 +558,15 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the session ID is set successfully;
returns **false** otherwise. | + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the session ID is set successfully;
returns **false** otherwise. | **Example** @@ -593,10 +593,10 @@ Subscribes to data changes of this distributed data object. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.| -| callback | Callback<{ sessionId: string, fields: Array<string> }> | Yes| Callback invoked to return the changes of the distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.| + | callback | Callback<{ sessionId: string, fields: Array<string> }> | Yes| Callback invoked to return the changes of the distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| **Example** @@ -628,10 +628,10 @@ Unsubscribes from the data changes of this distributed data object. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | | type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.| -| callback | Callback<{ sessionId: string, fields: Array<string> }> | No| Callback for data changes. If this parameter is not specified, all data change callbacks of this distributed data object will be unregistered.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| + | callback | Callback<{ sessionId: string, fields: Array<string> }> | No| Callback for data changes. If this parameter is not specified, all data change callbacks of this distributed data object will be unregistered.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| **Example** @@ -659,10 +659,10 @@ Subscribes to status changes of this distributed data object. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| -| callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback invoked to return the status change.
**sessionId** indicates the session ID of the distributed data object.
**networkId** indicates the object device ID, that is, **deviceId**.
**status** indicates the object status, which can be online or offline.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| + | callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback invoked to return the status change.
**sessionId** indicates the session ID of the distributed data object.
**networkId** indicates the object device ID, that is, **deviceId**.
**status** indicates the object status, which can be online or offline.| **Example** @@ -689,8 +689,8 @@ Unsubscribes from the status change of this distributed data object. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | | type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| | callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback for status changes. If this parameter is not specified, all status change callbacks of this distributed data object will be unregistered.
**sessionId** indicates the session ID of the distributed data object.
**deviceId** indicates the device ID of the distributed data object.
**status** indicates the object status, which can be online or offline.| diff --git a/en/application-dev/reference/apis/js-apis-data-preferences.md b/en/application-dev/reference/apis/js-apis-data-preferences.md index 156078c63ad8f33a7747e493948f59d511a1c791..7ee96b8c97e6d294255a541fce2c392b04fc310f 100644 --- a/en/application-dev/reference/apis/js-apis-data-preferences.md +++ b/en/application-dev/reference/apis/js-apis-data-preferences.md @@ -185,7 +185,7 @@ For details about the error codes, see [User Preference Error Codes](../errorcod | ID| Error Message | | -------- | ------------------------------| -| 15500010 | Failed to delete the preferences. | +| 15500010 | Failed to delete preferences file. | **Example** @@ -197,7 +197,7 @@ import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); try { - data_preferences.deletePreferences(context, 'mystore', function (err, val) { + data_preferences.deletePreferences(context, 'mystore', function (err) { if (err) { console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message); return; @@ -217,7 +217,7 @@ import UIAbility from '@ohos.app.ability.UIAbility'; class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { try { - data_preferences.deletePreferences(this.context, 'mystore', function (err, val) { + data_preferences.deletePreferences(this.context, 'mystore', function (err) { if (err) { console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message); return; @@ -262,7 +262,7 @@ For details about the error codes, see [User Preference Error Codes](../errorcod | ID| Error Message | | -------- | ------------------------------| -| 15500010 | Failed to delete the preferences. | +| 15500010 | Failed to delete preferences file. | **Example** @@ -334,7 +334,7 @@ import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); try { - data_preferences.removePreferencesFromCache(context, 'mystore', function (err, val) { + data_preferences.removePreferencesFromCache(context, 'mystore', function (err) { if (err) { console.info("Failed to remove the preferences. code =" + err.code + ", message =" + err.message); return; @@ -354,7 +354,7 @@ import UIAbility from '@ohos.app.ability.UIAbility'; class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { try { - data_preferences.removePreferencesFromCache(this.context, 'mystore', function (err, val) { + data_preferences.removePreferencesFromCache(this.context, 'mystore', function (err) { if (err) { console.info("Failed to remove the preferences. code =" + err.code + ", message =" + err.message); return; diff --git a/en/application-dev/reference/apis/js-apis-data-relationalStore.md b/en/application-dev/reference/apis/js-apis-data-relationalStore.md index 3e7e078f595f8468bf78cc953f5267c5515360a2..126dff90c4a6d06dfe675668409cf4d4d9573fa6 100644 --- a/en/application-dev/reference/apis/js-apis-data-relationalStore.md +++ b/en/application-dev/reference/apis/js-apis-data-relationalStore.md @@ -38,10 +38,11 @@ Obtains an RDB store. This API uses an asynchronous callback to return the resul For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). -| **ID**| **Error Message** | -| ------------ | ----------------------- | -| 14800010 | If failed delete database by invalid database name. | -| 14800011 | If failed open database by database corrupted. | +| **ID**| **Error Message** | +| ------------ | ----------------------------------------------------------- | +| 14800010 | Failed to open or delete database by invalid database path. | +| 14800011 | Failed to open database by database corrupted. | +| 14800000 | Inner error. | **Example** @@ -64,7 +65,7 @@ const STORE_CONFIG = { relationalStore.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { store = rdbStore; if (err) { - console.error(`Get RdbStore failed, err: ${err}`); + console.error(`Get RdbStore failed, code is ${err.code},message is ${err.message}`); return; } console.info(`Get RdbStore successfully.`); @@ -87,7 +88,7 @@ class EntryAbility extends UIAbility { relationalStore.getRdbStore(this.context, STORE_CONFIG, function (err, rdbStore) { store = rdbStore; if (err) { - console.error(`Get RdbStore failed, err: ${err}`); + console.error(`Get RdbStore failed, code is ${err.code},message is ${err.message}`); return; } console.info(`Get RdbStore successfully.`); @@ -121,10 +122,11 @@ Obtains an RDB store. This API uses a promise to return the result. You can set For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). -| **ID**| **Error Message** | -| ------------ | ----------------------- | -| 14800010 | If failed delete database by invalid database name. | -| 14800011 | If failed open database by database corrupted. | +| **ID**| **Error Message** | +| ------------ | ----------------------------------------------------------- | +| 14800010 | Failed to open or delete database by invalid database path. | +| 14800011 | Failed to open database by database corrupted. | +| 14800000 | Inner error. | **Example** @@ -148,7 +150,7 @@ promise.then(async (rdbStore) => { store = rdbStore; console.info(`Get RdbStore successfully.`); }).catch((err) => { - console.error(`Get RdbStore failed, err: ${err}`); + console.error(`Get RdbStore failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -170,7 +172,7 @@ class EntryAbility extends UIAbility { store = rdbStore; console.info(`Get RdbStore successfully.`) }).catch((err) => { - console.error(`Get RdbStore failed, err: ${err}`); + console.error(`Get RdbStore failed, code is ${err.code},message is ${err.message}`); }) } } @@ -196,9 +198,10 @@ Deletes an RDB store. This API uses an asynchronous callback to return the resul For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). -| **ID**| **Error Message** | -| ------------ | ----------------------- | -| 14800010 | If failed delete database by invalid database name. | +| **ID**| **Error Message** | +| ------------ | ----------------------------------------------------------- | +| 14800010 | Failed to open or delete database by invalid database path. | +| 14800000 | Inner error. | **Example** @@ -212,7 +215,7 @@ let context = featureAbility.getContext() relationalStore.deleteRdbStore(context, "RdbTest.db", function (err) { if (err) { - console.error(`Delete RdbStore failed, err: ${err}`); + console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`); return; } console.info(`Delete RdbStore successfully.`); @@ -228,7 +231,7 @@ class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ relationalStore.deleteRdbStore(this.context, "RdbTest.db", function (err) { if (err) { - console.error(`Delete RdbStore failed, err: ${err}`); + console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`); return; } console.info(`Delete RdbStore successfully.`); @@ -262,9 +265,10 @@ Deletes an RDB store. This API uses a promise to return the result. For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). -| **ID**| **Error Message** | -| ------------ | ----------------------- | -| 14800010 | If failed delete database by invalid database name. | +| **ID**| **Error Message** | +| ------------ | ----------------------------------------------------------- | +| 14800010 | Failed to open or delete database by invalid database path. | +| 14800000 | Inner error. | **Example** @@ -280,7 +284,7 @@ let promise = relationalStore.deleteRdbStore(context, "RdbTest.db"); promise.then(()=>{ console.info(`Delete RdbStore successfully.`); }).catch((err) => { - console.error(`Delete RdbStore failed, err: ${err}`); + console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -295,7 +299,7 @@ class EntryAbility extends UIAbility { promise.then(()=>{ console.info(`Delete RdbStore successfully.`); }).catch((err) => { - console.error(`Delete RdbStore failed, err: ${err}`); + console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`); }) } } @@ -311,7 +315,7 @@ Defines the RDB store configuration. | ------------- | ------------- | ---- | --------------------------------------------------------- | | name | string | Yes | Database file name. | | securityLevel | [SecurityLevel](#securitylevel) | Yes | Security level of the RDB store. | -| encrypt | boolean | No | Whether to encrypt the RDB store.
The value **true** means to encrypt the RDB store;
the value **false** means the opposite.| +| encrypt | boolean | No | Whether to encrypt the RDB store.
The value **true** means to encrypt the RDB store;
the value **false** (default) means the opposite.| ## SecurityLevel @@ -319,7 +323,7 @@ Enumerates the RDB store security levels. > **NOTE** > -> To perform data synchronization operations, the RDB store security level must be lower than or equal to that of the peer device. For details, see the [Cross-Device Data Synchronization Mechanism](../../database/sync-app-data-across-devices-overview.md#cross-device-data-synchronization-mechanism). +> To perform data synchronization operations, the RDB store security level must be lower than or equal to that of the peer device. For details, see the [Cross-Device Data Synchronization Mechanism]( ../../database/sync-app-data-across-devices-overview.md#cross-device-data-synchronization-mechanism). **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -344,7 +348,7 @@ Defines the data types allowed. ## ValuesBucket -Defines the types of the key and value in a KV pair. +Defines the types of the key and value in a KV pair. This type is not multi-thread safe. If a **ValuesBucket** instance is operated by multiple threads at the same time in an application, use a lock for the instance. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -374,6 +378,7 @@ Defines the subscription type. | Name | Value | Description | | --------------------- | ---- | ------------------ | | SUBSCRIBE_TYPE_REMOTE | 0 | Subscribe to remote data changes.| +| SUBSCRIBE_TYPE_CLOUD10+ | 1 | Subscribe to cloud data changes.| ## ConflictResolution10+ @@ -392,7 +397,7 @@ Defines the resolution to use when **insert()** and **update()** conflict. ## RdbPredicates -Defines the predicates for an RDB store. This class determines whether the conditional expression for the RDB store is true or false. +Defines the predicates for an RDB store. This class determines whether the conditional expression for the RDB store is true or false. This type is not multi-thread safe. If an **RdbPredicates** instance is operated by multiple threads at the same time in an application, use a lock for the instance. ### constructor @@ -1289,9 +1294,10 @@ Inserts a row of data into a table. This API uses an asynchronous callback to re For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). -| **ID**| **Error Message** | -| ------------ | ----------------------- | -| 14800047 | The WAL file size exceeds the default limit.| +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | **Example** @@ -1304,7 +1310,7 @@ const valueBucket = { }; store.insert("EMPLOYEE", valueBucket, function (err, rowId) { if (err) { - console.error(`Insert is failed, err: ${err}`); + console.error(`Insert is failed, code is ${err.code},message is ${err.message}`); return; } console.info(`Insert is successful, rowId = ${rowId}`); @@ -1332,9 +1338,10 @@ Inserts a row of data into a table. This API uses an asynchronous callback to re For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). -| **ID**| **Error Message** | -| ------------ | ----------------------- | -| 14800047 | The WAL file size exceeds the default limit.| +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | **Example** @@ -1347,7 +1354,7 @@ const valueBucket = { }; store.insert("EMPLOYEE", valueBucket, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE, function (err, rowId) { if (err) { - console.error(`Insert is failed, err: ${err}`); + console.error(`Insert is failed, code is ${err.code},message is ${err.message}`); return; } console.info(`Insert is successful, rowId = ${rowId}`); @@ -1379,9 +1386,10 @@ Inserts a row of data into a table. This API uses a promise to return the result For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). -| **ID**| **Error Message** | -| ------------ | ----------------------- | -| 14800047 | The WAL file size exceeds the default limit.| +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | **Example** @@ -1396,7 +1404,7 @@ let promise = store.insert("EMPLOYEE", valueBucket); promise.then((rowId) => { console.info(`Insert is successful, rowId = ${rowId}`); }).catch((err) => { - console.error(`Insert is failed, err: ${err}`); + console.error(`Insert is failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -1426,9 +1434,10 @@ Inserts a row of data into a table. This API uses a promise to return the result For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). -| **ID**| **Error Message** | -| ------------ | ----------------------- | -| 14800047 | The WAL file size exceeds the default limit.| +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | **Example** @@ -1443,7 +1452,7 @@ let promise = store.insert("EMPLOYEE", valueBucket, relationalStore.ConflictReso promise.then((rowId) => { console.info(`Insert is successful, rowId = ${rowId}`); }).catch((err) => { - console.error(`Insert is failed, err: ${err}`); + console.error(`Insert is failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -1467,9 +1476,10 @@ Batch inserts data into a table. This API uses an asynchronous callback to retur For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). -| **ID**| **Error Message** | -| ------------ | ----------------------- | -| 14800047 | The WAL file size exceeds the default limit.| +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | **Example** @@ -1496,7 +1506,7 @@ const valueBucket3 = { let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); store.batchInsert("EMPLOYEE", valueBuckets, function(err, insertNum) { if (err) { - console.error(`batchInsert is failed, err: ${err}`); + console.error(`batchInsert is failed, code is ${err.code},message is ${err.message}`); return; } console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`); @@ -1528,9 +1538,10 @@ Batch inserts data into a table. This API uses a promise to return the result. For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). -| **ID**| **Error Message** | -| ------------ | ----------------------- | -| 14800047 | The WAL file size exceeds the default limit.| +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | **Example** @@ -1559,7 +1570,7 @@ let promise = store.batchInsert("EMPLOYEE", valueBuckets); promise.then((insertNum) => { console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`); }).catch((err) => { - console.error(`batchInsert is failed, err: ${err}`); + console.error(`batchInsert is failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -1583,9 +1594,10 @@ Updates data in the RDB store based on the specified **RdbPredicates** object. T For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). -| **ID**| **Error Message** | -| ------------ | ----------------------- | -| 14800047 | The WAL file size exceeds the default limit.| +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | **Example** @@ -1600,7 +1612,7 @@ let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa"); store.update(valueBucket, predicates, function (err, rows) { if (err) { - console.error(`Updated failed, err: ${err}`); + console.error(`Updated failed, code is ${err.code},message is ${err.message}`); return; } console.info(`Updated row count: ${rows}`); @@ -1628,9 +1640,10 @@ Updates data in the RDB store based on the specified **RdbPredicates** object. T For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). -| **ID**| **Error Message** | -| ------------ | ----------------------- | -| 14800047 | The WAL file size exceeds the default limit.| +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | **Example** @@ -1645,7 +1658,7 @@ let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa"); store.update(valueBucket, predicates, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE, function (err, rows) { if (err) { - console.error(`Updated failed, err: ${err}`); + console.error(`Updated failed, code is ${err.code},message is ${err.message}`); return; } console.info(`Updated row count: ${rows}`); @@ -1677,9 +1690,10 @@ Updates data based on the specified **RdbPredicates** object. This API uses a pr For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). -| **ID**| **Error Message** | -| ------------ | ----------------------- | -| 14800047 | The WAL file size exceeds the default limit.| +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | **Example** @@ -1696,7 +1710,7 @@ let promise = store.update(valueBucket, predicates); promise.then(async (rows) => { console.info(`Updated row count: ${rows}`); }).catch((err) => { - console.error(`Updated failed, err: ${err}`); + console.error(`Updated failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -1726,9 +1740,10 @@ Updates data based on the specified **RdbPredicates** object. This API uses a pr For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). -| **ID**| **Error Message** | -| ------------ | ----------------------- | -| 14800047 | The WAL file size exceeds the default limit.| +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | **Example** @@ -1745,7 +1760,7 @@ let promise = store.update(valueBucket, predicates, relationalStore.ConflictReso promise.then(async (rows) => { console.info(`Updated row count: ${rows}`); }).catch((err) => { - console.error(`Updated failed, err: ${err}`); + console.error(`Updated failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -1757,6 +1772,8 @@ Updates data based on the specified **DataSharePredicates** object. This API use **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core +**Model restriction**: This API can be used only in the stage model. + **System API**: This is a system API. **Parameters** @@ -1772,9 +1789,10 @@ Updates data based on the specified **DataSharePredicates** object. This API use For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). -| **ID**| **Error Message** | -| ------------ | ----------------------- | -| 14800047 | The WAL file size exceeds the default limit.| +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | **Example** @@ -1790,7 +1808,7 @@ let predicates = new dataSharePredicates.DataSharePredicates(); predicates.equalTo("NAME", "Lisa"); store.update("EMPLOYEE", valueBucket, predicates, function (err, rows) { if (err) { - console.error(`Updated failed, err: ${err}`); + console.error(`Updated failed, code is ${err.code},message is ${err.message}`); return; } console.info(`Updated row count: ${rows}`); @@ -1805,6 +1823,8 @@ Updates data based on the specified **DataSharePredicates** object. This API use **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core +**Model restriction**: This API can be used only in the stage model. + **System API**: This is a system API. **Parameters** @@ -1825,9 +1845,10 @@ Updates data based on the specified **DataSharePredicates** object. This API use For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). -| **ID**| **Error Message** | -| ------------ | ----------------------- | -| 14800047 | The WAL file size exceeds the default limit.| +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | **Example** @@ -1845,7 +1866,7 @@ let promise = store.update("EMPLOYEE", valueBucket, predicates); promise.then(async (rows) => { console.info(`Updated row count: ${rows}`); }).catch((err) => { - console.error(`Updated failed, err: ${err}`); + console.error(`Updated failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -1868,9 +1889,10 @@ Deletes data from the RDB store based on the specified **RdbPredicates** object. For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). -| **ID**| **Error Message** | -| ------------ | ----------------------- | -| 14800047 | The WAL file size exceeds the default limit.| +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | **Example** @@ -1879,7 +1901,7 @@ let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa"); store.delete(predicates, function (err, rows) { if (err) { - console.error(`Delete failed, err: ${err}`); + console.error(`Delete failed, code is ${err.code},message is ${err.message}`); return; } console.info(`Delete rows: ${rows}`); @@ -1910,9 +1932,10 @@ Deletes data from the RDB store based on the specified **RdbPredicates** object. For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). -| **ID**| **Error Message** | -| ------------ | ----------------------- | -| 14800047 | The WAL file size exceeds the default limit.| +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | **Example** @@ -1923,7 +1946,7 @@ let promise = store.delete(predicates); promise.then((rows) => { console.info(`Delete rows: ${rows}`); }).catch((err) => { - console.error(`Delete failed, err: ${err}`); + console.error(`Delete failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -1935,6 +1958,8 @@ Deletes data from the RDB store based on the specified **DataSharePredicates** o **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core +**Model restriction**: This API can be used only in the stage model. + **System API**: This is a system API. **Parameters** @@ -1949,9 +1974,10 @@ Deletes data from the RDB store based on the specified **DataSharePredicates** o For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). -| **ID**| **Error Message** | -| ------------ | ----------------------- | -| 14800047 | The WAL file size exceeds the default limit.| +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | **Example** @@ -1961,7 +1987,7 @@ let predicates = new dataSharePredicates.DataSharePredicates(); predicates.equalTo("NAME", "Lisa"); store.delete("EMPLOYEE", predicates, function (err, rows) { if (err) { - console.error(`Delete failed, err: ${err}`); + console.error(`Delete failed, code is ${err.code},message is ${err.message}`); return; } console.info(`Delete rows: ${rows}`); @@ -1976,6 +2002,8 @@ Deletes data from the RDB store based on the specified **DataSharePredicates** o **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core +**Model restriction**: This API can be used only in the stage model. + **System API**: This is a system API. **Parameters** @@ -1995,9 +2023,10 @@ Deletes data from the RDB store based on the specified **DataSharePredicates** o For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). -| **ID**| **Error Message** | -| ------------ | ----------------------- | -| 14800047 | The WAL file size exceeds the default limit.| +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | **Example** @@ -2009,7 +2038,7 @@ let promise = store.delete("EMPLOYEE", predicates); promise.then((rows) => { console.info(`Delete rows: ${rows}`); }).catch((err) => { - console.error(`Delete failed, err: ${err}`); + console.error(`Delete failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -2029,6 +2058,14 @@ Queries data from the RDB store based on specified conditions. This API uses an | columns | Array<string> | Yes | Columns to query. If this parameter is not specified, the query applies to all columns. | | callback | AsyncCallback<[ResultSet](#resultset)> | Yes | Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + **Example** ```js @@ -2036,7 +2073,7 @@ let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Rose"); store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { if (err) { - console.error(`Query failed, err: ${err}`); + console.error(`Query failed, code is ${err.code},message is ${err.message}`); return; } console.info(`ResultSet column names: ${resultSet.columnNames}`); @@ -2059,6 +2096,14 @@ Queries data from the RDB store based on specified conditions. This API uses a p | predicates | [RdbPredicates](#rdbpredicates) | Yes | Query conditions specified by the **RdbPredicates** object. | | columns | Array<string> | No | Columns to query. If this parameter is not specified, the query applies to all columns.| +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + **Return value** | Type | Description | @@ -2075,7 +2120,7 @@ promise.then((resultSet) => { console.info(`ResultSet column names: ${resultSet.columnNames}`); console.info(`ResultSet column count: ${resultSet.columnCount}`); }).catch((err) => { - console.error(`Query failed, err: ${err}`); + console.error(`Query failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -2087,6 +2132,8 @@ Queries data from the RDB store based on specified conditions. This API uses an **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core +**Model restriction**: This API can be used only in the stage model. + **System API**: This is a system API. **Parameters** @@ -2098,6 +2145,14 @@ Queries data from the RDB store based on specified conditions. This API uses an | columns | Array<string> | Yes | Columns to query. If this parameter is not specified, the query applies to all columns. | | callback | AsyncCallback<[ResultSet](#resultset)> | Yes | Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + **Example** ```js @@ -2106,7 +2161,7 @@ let predicates = new dataSharePredicates.DataSharePredicates(); predicates.equalTo("NAME", "Rose"); store.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { if (err) { - console.error(`Query failed, err: ${err}`); + console.error(`Query failed, code is ${err.code},message is ${err.message}`); return; } console.info(`ResultSet column names: ${resultSet.columnNames}`); @@ -2122,6 +2177,8 @@ Queries data from the RDB store based on specified conditions. This API uses a p **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core +**Model restriction**: This API can be used only in the stage model. + **System API**: This is a system API. **Parameters** @@ -2138,6 +2195,14 @@ Queries data from the RDB store based on specified conditions. This API uses a p | ------------------------------------------------------- | -------------------------------------------------- | | Promise<[ResultSet](#resultset)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + **Example** ```js @@ -2149,7 +2214,7 @@ promise.then((resultSet) => { console.info(`ResultSet column names: ${resultSet.columnNames}`); console.info(`ResultSet column count: ${resultSet.columnCount}`); }).catch((err) => { - console.error(`Query failed, err: ${err}`); + console.error(`Query failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -2175,6 +2240,14 @@ Queries data from the RDB store of a remote device based on specified conditions | columns | Array<string> | Yes | Columns to query. If this parameter is not specified, the query applies to all columns. | | callback | AsyncCallback<[ResultSet](#resultset)> | Yes | Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + **Example** ```js @@ -2197,7 +2270,7 @@ predicates.greaterThan("id", 0); store.remoteQuery(deviceId, "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function(err, resultSet) { if (err) { - console.error(`Failed to remoteQuery, err: ${err}`); + console.error(`Failed to remoteQuery, code is ${err.code},message is ${err.message}`); return; } console.info(`ResultSet column names: ${resultSet.columnNames}`); @@ -2233,6 +2306,14 @@ Queries data from the RDB store of a remote device based on specified conditions | ------------------------------------------------------------ | -------------------------------------------------- | | Promise<[ResultSet](#resultset)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + **Example** ```js @@ -2257,7 +2338,7 @@ promise.then((resultSet) => { console.info(`ResultSet column names: ${resultSet.columnNames}`); console.info(`ResultSet column count: ${resultSet.columnCount}`); }).catch((err) => { - console.error(`Failed to remoteQuery, err: ${err}`); + console.error(`Failed to remoteQuery, code is ${err.code},message is ${err.message}`); }) ``` @@ -2277,12 +2358,20 @@ Queries data using the specified SQL statement. This API uses an asynchronous ca | bindArgs | Array<[ValueType](#valuetype)> | Yes | Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, the value of this parameter must be an empty array.| | callback | AsyncCallback<[ResultSet](#resultset)> | Yes | Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned. | +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + **Example** ```js store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo'], function (err, resultSet) { if (err) { - console.error(`Query failed, err: ${err}`); + console.error(`Query failed, code is ${err.code},message is ${err.message}`); return; } console.info(`ResultSet column names: ${resultSet.columnNames}`); @@ -2311,6 +2400,14 @@ Queries data using the specified SQL statement. This API uses a promise to retur | ------------------------------------------------------- | -------------------------------------------------- | | Promise<[ResultSet](#resultset)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + **Example** ```js @@ -2319,7 +2416,7 @@ promise.then((resultSet) => { console.info(`ResultSet column names: ${resultSet.columnNames}`); console.info(`ResultSet column count: ${resultSet.columnCount}`); }).catch((err) => { - console.error(`Query failed, err: ${err}`); + console.error(`Query failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -2343,9 +2440,10 @@ Executes an SQL statement that contains specified arguments but returns no value For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). -| **ID**| **Error Message** | -| ------------ | ----------------------- | -| 14800047 | The WAL file size exceeds the default limit.| +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | **Example** @@ -2353,7 +2451,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode const SQL_DELETE_TABLE = "DELETE FROM test WHERE name = ?" store.executeSql(SQL_DELETE_TABLE, ['zhangsan'], function(err) { if (err) { - console.error(`ExecuteSql failed, err: ${err}`); + console.error(`ExecuteSql failed, code is ${err.code},message is ${err.message}`); return; } console.info(`Delete table done.`); @@ -2385,9 +2483,10 @@ Executes an SQL statement that contains specified arguments but returns no value For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). -| **ID**| **Error Message** | -| ------------ | ----------------------- | -| 14800047 | The WAL file size exceeds the default limit.| +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | **Example** @@ -2397,7 +2496,7 @@ let promise = store.executeSql(SQL_DELETE_TABLE); promise.then(() => { console.info(`Delete table done.`); }).catch((err) => { - console.error(`ExecuteSql failed, err: ${err}`); + console.error(`ExecuteSql failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -2413,9 +2512,10 @@ Starts the transaction before executing an SQL statement. For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). -| **ID**| **Error Message** | -| ------------ | ----------------------- | -| 14800047 | The WAL file size exceeds the default limit.| +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | **Example** @@ -2428,7 +2528,7 @@ const STORE_CONFIG = { }; relationalStore.getRdbStore(context, STORE_CONFIG, async function (err, store) { if (err) { - console.error(`GetRdbStore failed, err: ${err}`); + console.error(`GetRdbStore failed, code is ${err.code},message is ${err.message}`); return; } store.beginTransaction(); @@ -2462,7 +2562,7 @@ const STORE_CONFIG = { }; relationalStore.getRdbStore(context, STORE_CONFIG, async function (err, store) { if (err) { - console.error(`GetRdbStore failed, err: ${err}`); + console.error(`GetRdbStore failed, code is ${err.code},message is ${err.message}`); return; } store.beginTransaction(); @@ -2496,7 +2596,7 @@ const STORE_CONFIG = { }; relationalStore.getRdbStore(context, STORE_CONFIG, async function (err, store) { if (err) { - console.error(`GetRdbStore failed, err: ${err}`); + console.error(`GetRdbStore failed, code is ${err.code},message is ${err.message}`); return; } try { @@ -2511,7 +2611,7 @@ relationalStore.getRdbStore(context, STORE_CONFIG, async function (err, store) { await store.insert("test", valueBucket); store.commit(); } catch (err) { - console.error(`Transaction failed, err: ${err}`); + console.error(`Transaction failed, code is ${err.code},message is ${err.message}`); store.rollBack(); } }) @@ -2532,12 +2632,20 @@ Backs up an RDB store. This API uses an asynchronous callback to return the resu | destName | string | Yes | Name of the RDB store backup file.| | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + **Example** ```js store.backup("dbBackup.db", function(err) { if (err) { - console.error(`Backup failed, err: ${err}`); + console.error(`Backup failed, code is ${err.code},message is ${err.message}`); return; } console.info(`Backup success.`); @@ -2564,6 +2672,14 @@ Backs up an RDB store. This API uses a promise to return the result. | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + **Example** ```js @@ -2571,7 +2687,7 @@ let promiseBackup = store.backup("dbBackup.db"); promiseBackup.then(()=>{ console.info(`Backup success.`); }).catch((err)=>{ - console.error(`Backup failed, err: ${err}`); + console.error(`Backup failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -2590,12 +2706,20 @@ Restores an RDB store from a backup file. This API uses an asynchronous callback | srcName | string | Yes | Name of the RDB store backup file.| | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + **Example** ```js store.restore("dbBackup.db", function(err) { if (err) { - console.error(`Restore failed, err: ${err}`); + console.error(`Restore failed, code is ${err.code},message is ${err.message}`); return; } console.info(`Restore success.`); @@ -2622,6 +2746,14 @@ Restores an RDB store from a backup file. This API uses a promise to return the | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + **Example** ```js @@ -2629,7 +2761,7 @@ let promiseRestore = store.restore("dbBackup.db"); promiseRestore.then(()=>{ console.info(`Restore success.`); }).catch((err)=>{ - console.error(`Restore failed, err: ${err}`); + console.error(`Restore failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -2650,12 +2782,20 @@ Sets distributed tables. This API uses an asynchronous callback to return the re | tables | Array<string> | Yes | Names of the distributed tables to set.| | callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + **Example** ```js store.setDistributedTables(["EMPLOYEE"], function (err) { if (err) { - console.error(`SetDistributedTables failed, err: ${err}`); + console.error(`SetDistributedTables failed, code is ${err.code},message is ${err.message}`); return; } console.info(`SetDistributedTables successfully.`); @@ -2684,6 +2824,14 @@ Sets distributed tables. This API uses a promise to return the result. | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + **Example** ```js @@ -2691,7 +2839,7 @@ let promise = store.setDistributedTables(["EMPLOYEE"]); promise.then(() => { console.info(`SetDistributedTables successfully.`); }).catch((err) => { - console.error(`SetDistributedTables failed, err: ${err}`); + console.error(`SetDistributedTables failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -2717,6 +2865,14 @@ Obtains the distributed table name of a remote device based on the local table n | table | string | Yes | Local table name of the remote device. | | callback | AsyncCallback<string> | Yes | Callback invoked to return the result. If the operation succeeds, the distributed table name of the remote device is returned.| +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + **Example** ```js @@ -2736,7 +2892,7 @@ deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) store.obtainDistributedTableName(deviceId, "EMPLOYEE", function (err, tableName) { if (err) { - console.error(`ObtainDistributedTableName failed, err: ${err}`); + console.error(`ObtainDistributedTableName failed, code is ${err.code},message is ${err.message}`); return; } console.info(`ObtainDistributedTableName successfully, tableName= ${tableName}`); @@ -2770,6 +2926,14 @@ Obtains the distributed table name of a remote device based on the local table n | --------------------- | ----------------------------------------------------- | | Promise<string> | Promise used to return the result. If the operation succeeds, the distributed table name of the remote device is returned.| +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + **Example** ```js @@ -2791,7 +2955,7 @@ let promise = store.obtainDistributedTableName(deviceId, "EMPLOYEE"); promise.then((tableName) => { console.info(`ObtainDistributedTableName successfully, tableName= ${tableName}`); }).catch((err) => { - console.error(`ObtainDistributedTableName failed, err: ${err}`); + console.error(`ObtainDistributedTableName failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -2813,6 +2977,14 @@ Synchronizes data between devices. This API uses an asynchronous callback to ret | predicates | [RdbPredicates](#rdbpredicates) | Yes | **RdbPredicates** object that specifies the data and devices to synchronize. | | callback | AsyncCallback<Array<[string, number]>> | Yes | Callback invoked to send the synchronization result to the caller.
**string** indicates the device ID.
**number** indicates the synchronization status of that device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. | +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + **Example** ```js @@ -2836,7 +3008,7 @@ let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); predicates.inDevices(deviceIds); store.sync(relationalStore.SyncMode.SYNC_MODE_PUSH, predicates, function (err, result) { if (err) { - console.error(`Sync failed, err: ${err}`); + console.error(`Sync failed, code is ${err.code},message is ${err.message}`); return; } console.info(`Sync done.`); @@ -2869,6 +3041,14 @@ Synchronizes data between devices. This API uses a promise to return the result. | -------------------------------------------- | ------------------------------------------------------------ | | Promise<Array<[string, number]>> | Promise used to send the synchronization result.
**string** indicates the device ID.
**number** indicates the synchronization status of that device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. | +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + **Example** ```js @@ -2897,7 +3077,7 @@ promise.then((result) =>{ console.info(`device= ${result[i][0]}, status= ${result[i][1]}`); } }).catch((err) => { - console.error(`Sync failed, err: ${err}`); + console.error(`Sync failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -2915,7 +3095,7 @@ Registers an observer for this RDB store. When the data in the RDB store changes | -------- | ----------------------------------- | ---- | ------------------------------------------- | | event | string | Yes | Event to observe. The value is **dataChange**, which indicates a data change event. | | type | [SubscribeType](#subscribetype) | Yes | Subscription type to register.| -| observer | Callback<Array<string>> | Yes | Callback invoked to return the data change event. | +| observer | Callback<Array<string>> | Yes | Callback invoked to return the data change event. **Array** indicates the IDs of the peer devices whose data in the database is changed.| **Example** @@ -2928,7 +3108,7 @@ function storeObserver(devices) { try { store.on('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver); } catch (err) { - console.error(`Register observer failed, err: ${err}`); + console.error(`Register observer failed, code is ${err.code},message is ${err.message}`); } ``` @@ -2944,9 +3124,9 @@ Unregisters the observer of the specified type from the RDB store. This API uses | Name | Type | Mandatory| Description | | -------- | ---------------------------------- | ---- | ------------------------------------------ | -| event | string | Yes | Event type. The value is **dataChange**, which indicates a data change event. | -| type | [SubscribeType](#subscribetype) | Yes | Subscription type to unregister. | -| observer | Callback<Array<string>> | Yes | Callback for the data change event. | +| event | string | Yes | Event type. The value is **dataChange**, which indicates a data change event. | +| type | [SubscribeType](#subscribetype) | Yes | Subscription type to unregister. | +| observer | Callback<Array<string>> | Yes | Callback for the data change event. **Array** indicates the IDs of the peer devices whose data in the database is changed.| **Example** @@ -2959,7 +3139,7 @@ function storeObserver(devices) { try { store.off('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver); } catch (err) { - console.error(`Unregister observer failed, err: ${err}`); + console.error(`Unregister observer failed, code is ${err.code},message is ${err.message}`); } ``` @@ -3099,7 +3279,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode | **ID**| **Error Message** | | ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | +| 14800012 | The result set is empty or the specified location is invalid. | **Example** @@ -3110,7 +3290,7 @@ promise.then((resultSet) => { resultSet.goTo(1); resultSet.close(); }).catch((err) => { - console.error(`query failed, err: ${err}`); + console.error(`query failed, code is ${err.code},message is ${err.message}`); }); ``` @@ -3140,7 +3320,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode | **ID**| **Error Message** | | ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | +| 14800012 | The result set is empty or the specified location is invalid. | **Example** @@ -3151,7 +3331,7 @@ promise.then((resultSet) => { resultSet.goToRow(5); resultSet.close(); }).catch((err) => { - console.error(`query failed, err: ${err}`); + console.error(`query failed, code is ${err.code},message is ${err.message}`); }); ``` @@ -3176,7 +3356,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode | **ID**| **Error Message** | | ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | +| 14800012 | The result set is empty or the specified location is invalid. | **Example** @@ -3187,7 +3367,7 @@ promise.then((resultSet) => { resultSet.goToFirstRow(); resultSet.close(); }).catch((err) => { - console.error(`query failed, err: ${err}`); + console.error(`query failed, code is ${err.code},message is ${err.message}`); }); ``` @@ -3211,7 +3391,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode | **ID**| **Error Message** | | ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | +| 14800012 | The result set is empty or the specified location is invalid. | **Example** @@ -3222,7 +3402,7 @@ promise.then((resultSet) => { resultSet.goToLastRow(); resultSet.close(); }).catch((err) => { - console.error(`query failed, err: ${err}`); + console.error(`query failed, code is ${err.code},message is ${err.message}`); }); ``` @@ -3246,7 +3426,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode | **ID**| **Error Message** | | ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | +| 14800012 | The result set is empty or the specified location is invalid. | **Example** @@ -3257,7 +3437,7 @@ promise.then((resultSet) => { resultSet.goToNextRow(); resultSet.close(); }).catch((err) => { - console.error(`query failed, err: ${err}`); + console.error(`query failed, code is ${err.code},message is ${err.message}`); }); ``` @@ -3281,7 +3461,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode | **ID**| **Error Message** | | ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | +| 14800012 | The result set is empty or the specified location is invalid. | **Example** @@ -3292,7 +3472,7 @@ promise.then((resultSet) => { resultSet.goToPreviousRow(); resultSet.close(); }).catch((err) => { - console.error(`query failed, err: ${err}`); + console.error(`query failed, code is ${err.code},message is ${err.message}`); }); ``` @@ -3316,6 +3496,14 @@ Obtains the value in the form of a byte array based on the specified column and | ---------- | -------------------------------- | | Uint8Array | Value obtained.| +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + **Example** ```js @@ -3342,6 +3530,14 @@ Obtains the value in the form of a string based on the specified column and the | ------ | ---------------------------- | | string | String obtained.| +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + **Example** ```js @@ -3366,7 +3562,15 @@ Obtains the value of the Long type based on the specified column and the current | Type | Description | | ------ | ------------------------------------------------------------ | -| number | Value obtained.
The value range supported by this API is **Number.MIN_SAFE_INTEGER** to **Number.MAX_SAFE_INTEGER**. If the value is out of this range, use [getDouble](#getdouble).| +| number | Value obtained.
The value range supported by API is **Number.MIN_SAFE_INTEGER** to **Number.MAX_SAFE_INTEGER**. If the value is out of this range, use [getDouble](#getdouble).| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | **Example** @@ -3394,6 +3598,14 @@ Obtains the value of the double type based on the specified column and the curre | ------ | ---------------------------- | | number | Value obtained.| +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + **Example** ```js @@ -3450,7 +3662,7 @@ let promiseClose = store.query(predicatesClose, ["ID", "NAME", "AGE", "SALARY", promiseClose.then((resultSet) => { resultSet.close(); }).catch((err) => { - console.error(`resultset close failed, err: ${err}`); + console.error(`resultset close failed, code is ${err.code},message is ${err.message}`); }); ``` @@ -3460,6 +3672,4 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode | **ID**| **Error Message** | | ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - - +| 14800012 | The result set is empty or the specified location is invalid. | diff --git a/en/application-dev/reference/apis/js-apis-data-valuesBucket.md b/en/application-dev/reference/apis/js-apis-data-valuesBucket.md index 009ff71b091c7d91a92d92364450316e3aeecfa2..ee21647ac71dacf7afa8240d2aa93e2ea65967f4 100644 --- a/en/application-dev/reference/apis/js-apis-data-valuesBucket.md +++ b/en/application-dev/reference/apis/js-apis-data-valuesBucket.md @@ -1,4 +1,4 @@ -# @ohos.data.ValuesBucket (Value Bucket) +# @ohos.data.ValuesBucket (Data Set) The **ValueBucket** module holds data in key-value (KV) pairs. You can use it to insert data into a database. @@ -6,7 +6,6 @@ The **ValueBucket** module holds data in key-value (KV) pairs. You can use it to > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > -> The APIs provided by this module are system APIs. ## Modules to Import @@ -30,7 +29,7 @@ Enumerates the value types allowed by the database. ## ValuesBucket -Defines the types of the key and value in a KV pair. +Defines the types of the key and value in a KV pair. This type is not multi-thread safe. If a **ValuesBucket** instance is operated by multiple threads at the same time in an application, use a lock for the instance. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core diff --git a/en/application-dev/reference/apis/js-apis-distributed-account.md b/en/application-dev/reference/apis/js-apis-distributed-account.md index 0ec67bc229c124cdf36a289e7321acaa9c2fcd43..5ea4792ec68bf59975274abd5cb7e0a58f8c1188 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-account.md +++ b/en/application-dev/reference/apis/js-apis-distributed-account.md @@ -62,12 +62,14 @@ Obtains distributed account information. This API uses an asynchronous callback const accountAbility = account_distributedAccount.getDistributedAccountAbility(); try { accountAbility.getOsAccountDistributedInfo((err, data) => { - console.log("getOsAccountDistributedInfo err: " + JSON.stringify(err)); - console.log('Query account info name: ' + data.name); - console.log('Query account info id: ' + data.id); + if (err) { + console.log('getOsAccountDistributedInfo exception: ' + JSON.stringify(err)); + } else { + console.log('distributed information: ' + JSON.stringify(data)); + } }); - } catch (e) { - console.log("getOsAccountDistributedInfo exception: " + JSON.stringify(e)); + } catch (err) { + console.log('getOsAccountDistributedInfo exception: ' + JSON.stringify(err)); } ``` @@ -98,15 +100,96 @@ Obtains distributed account information. This API uses a promise to return the r const accountAbility = account_distributedAccount.getDistributedAccountAbility(); try { accountAbility.getOsAccountDistributedInfo().then((data) => { - console.log('Query account info name: ' + data.name); - console.log('Query account info id: ' + data.id); + console.log('distributed information: ' + JSON.stringify(data)); }).catch((err) => { - console.log("getOsAccountDistributedInfo err: " + JSON.stringify(err)); + console.log('getOsAccountDistributedInfo exception: ' + JSON.stringify(err)); }); - } catch (e) { - console.log("getOsAccountDistributedInfo exception: " + JSON.stringify(e)); + } catch (err) { + console.log('getOsAccountDistributedInfo exception: ' + JSON.stringify(err)); } ``` + +### getOsAccountDistributedInfoByLocalId10+ + +getOsAccountDistributedInfoByLocalId(localId: number, callback: AsyncCallback<DistributedInfo>): void + +Obtains distributed information about an OS account. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | localId | number | Yes| ID of the target OS account.| + | callback | AsyncCallback<[DistributedInfo](#distributedinfo)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the distributed account information obtained. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message| +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300003 | Account not found. | + +**Example** + ```js + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + try { + accountAbility.getOsAccountDistributedInfoByLocalId(100, (err, data) => { + if (err) { + console.log('getOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); + } else { + console.log('distributed information: ' + JSON.stringify(data)); + } + }); + } catch (err) { + console.log('getOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); + } + ``` + +### getOsAccountDistributedInfoByLocalId10+ + +getOsAccountDistributedInfoByLocalId(localId: number): Promise<DistributedInfo> + +Obtains distributed information about an OS account. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[DistributedInfo](#distributedinfo)> | Promise used to return the distributed account information obtained.| + +**Error codes** + +| ID| Error Message| +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300003 | Account not found. | + +**Example** + ```js + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + try { + accountAbility.getOsAccountDistributedInfoByLocalId(100).then((data) => { + console.log('distributed information: ' + JSON.stringify(data)); + }).catch((err) => { + console.log('getOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); + }); + } catch (err) { + console.log('getOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); + } + ``` + ### queryOsAccountDistributedInfo(deprecated) queryOsAccountDistributedInfo(callback: AsyncCallback<DistributedInfo>): void @@ -130,9 +213,11 @@ Obtains distributed account information. This API uses an asynchronous callback ```js const accountAbility = account_distributedAccount.getDistributedAccountAbility(); accountAbility.queryOsAccountDistributedInfo((err, data) => { - console.log("queryOsAccountDistributedInfo err: " + JSON.stringify(err)); - console.log('Query account info name: ' + data.name); - console.log('Query account info id: ' + data.id); + if (err) { + console.log('queryOsAccountDistributedInfo exception: ' + JSON.stringify(err)); + } else { + console.log('distributed information: ' + JSON.stringify(data)); + } }); ``` @@ -160,10 +245,9 @@ Obtains distributed account information. This API uses a promise to return the r ```js const accountAbility = account_distributedAccount.getDistributedAccountAbility(); accountAbility.queryOsAccountDistributedInfo().then((data) => { - console.log('Query account info name: ' + data.name); - console.log('Query account info id: ' + data.id); + console.log('distributed information: ' + JSON.stringify(data)); }).catch((err) => { - console.log("queryOsAccountDistributedInfoerr: " + JSON.stringify(err)); + console.log('queryOsAccountDistributedInfo exception: ' + JSON.stringify(err)); }); ``` @@ -198,10 +282,14 @@ Sets the distributed account information. This API uses an asynchronous callback let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; try { accountAbility.setOsAccountDistributedInfo(accountInfo, (err) => { - console.log("setOsAccountDistributedInfo err: " + JSON.stringify(err)); + if (err) { + console.log('setOsAccountDistributedInfo exception: ' + JSON.stringify(err)); + } else { + console.log('setOsAccountDistributedInfo successfully'); + } }); - } catch (e) { - console.log("setOsAccountDistributedInfo exception: " + JSON.stringify(e)); + } catch (err) { + console.log('setOsAccountDistributedInfo exception: ' + JSON.stringify(err)); } ``` @@ -241,14 +329,109 @@ Sets the distributed account information. This API uses a promise to return the let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; try { accountAbility.setOsAccountDistributedInfo(accountInfo).then(() => { - console.log('setOsAccountDistributedInfo Success'); + console.log('setOsAccountDistributedInfo successfully'); }).catch((err) => { - console.log("setOsAccountDistributedInfo err: " + JSON.stringify(err)); + console.log('setOsAccountDistributedInfo exception: ' + JSON.stringify(err)); }); - } catch (e) { - console.log("setOsAccountDistributedInfo exception: " + JSON.stringify(e)); + } catch (err) { + console.log('setOsAccountDistributedInfo exception: ' + JSON.stringify(err)); } ``` +### setOsAccountDistributedInfoByLocalId10+ + +setOsAccountDistributedInfoByLocalId(localId: number, distributedInfo: DistributedInfo, callback: AsyncCallback<void>): void + +Sets the distributed information for an OS account. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | localId | number | Yes| ID of the target OS account.| + | accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information to set.| + | callback | AsyncCallback<void> | Yes| Callback invoked to return the result. If the distributed information is set successfully, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message| +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid distributedInfo. | +| 12300003 | Account identified by localId or by distributedInfo not found. | +| 12300008 | Restricted OS account. | + +**Example** + ```js + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; + try { + accountAbility.setOsAccountDistributedInfoByLocalId(100, accountInfo, (err) => { + if (err) { + console.log('setOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); + } else { + console.log('setOsAccountDistributedInfoByLocalId successfully'); + } + }); + } catch (err) { + console.log('setOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); + } + ``` + +### setOsAccountDistributedInfoByLocalId10+ + +setOsAccountDistributedInfoByLocalId(localId: number, distributedInfo: DistributedInfo): Promise<void> + +Sets the distributed information for an OS account. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | localId | number | Yes| ID of the target OS account.| + | distributedInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information to set.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message| +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid distributedInfo. | +| 12300003 | Account identified by localId or by distributedInfo not found. | +| 12300008 | Restricted OS account. | + +**Example** + ```js + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; + try { + accountAbility.setOsAccountDistributedInfoByLocalId(100, accountInfo).then(() => { + console.log('setOsAccountDistributedInfoByLocalId successfully'); + }).catch((err) => { + console.log('setOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); + }); + } catch (err) { + console.log('setOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); + } + ``` + ### updateOsAccountDistributedInfo(deprecated) updateOsAccountDistributedInfo(accountInfo: DistributedInfo, callback: AsyncCallback<void>): void @@ -275,7 +458,11 @@ Updates the distributed account information. This API uses an asynchronous callb const accountAbility = account_distributedAccount.getDistributedAccountAbility(); let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; accountAbility.updateOsAccountDistributedInfo(accountInfo, (err) => { - console.log("queryOsAccountDistributedInfo err: " + JSON.stringify(err)); + if (err) { + console.log('queryOsAccountDistributedInfo exception: ' + JSON.stringify(err)); + } else { + console.log('queryOsAccountDistributedInfo successfully'); + } }); ``` @@ -308,22 +495,34 @@ Updates the distributed account information. This API uses a promise to return t const accountAbility = account_distributedAccount.getDistributedAccountAbility(); let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; accountAbility.updateOsAccountDistributedInfo(accountInfo).then(() => { - console.log('updateOsAccountDistributedInfo Success'); + console.log('updateOsAccountDistributedInfo successfully'); }).catch((err) => { - console.log("updateOsAccountDistributedInfo err: " + JSON.stringify(err)); + console.log('updateOsAccountDistributedInfo exception: ' + JSON.stringify(err)); }); ``` ## DistributedInfo -Defines distributed OS account information. +Defines the distributed information about an OS account. + +**System capability**: SystemCapability.Account.OsAccount + +| Name| Type| Read-only| Mandatory| Description| +| -------- | -------- | -------- |-------- | -------- | +| name | string | No|Yes| Name of the distributed account. It must be a non-null string.| +| id | string | No|Yes| UID of the distributed account. It must be a non-null string.| +| event | string | No|Yes| Login state of the distributed account. The state can be login, logout, token invalid, or logoff, which correspond to the following strings respectively:
- Ohos.account.event.LOGIN
- Ohos.account.event.LOGOUT
- Ohos.account.event.TOKEN_INVALID
- Ohos.account.event.LOGOFF | +| nickname9+ | string | No|No| Nickname of the distributed account. By default, no value is passed.| +| avatar9+ | string | No|No| Avatar of the distributed account. By default, no value is passed.| +| status10+ | [DistributedAccountStatus](#distributedaccountstatus10) | Yes|No| Status of the distributed account. The value is of the enumerated type. The default status is unlogged.| +| scalableData8+ | object | No|No| Extended information about the distributed account, passed in key-value (KV) pairs based on service requirements. By default, no value is passed.| + +## DistributedAccountStatus10+ + +Enumerates the statuses of a distributed account. **System capability**: SystemCapability.Account.OsAccount -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| name | string | Yes| Name of the distributed account. It must be a non-null string.| -| id | string | Yes| UID of the distributed account. It must be a non-null string.| -| event | string | Yes| Login state of the distributed account. The state can be login, logout, token invalid, or logoff, which correspond to the following strings respectively:
- Ohos.account.event.LOGIN
- Ohos.account.event.LOGOUT
- Ohos.account.event.TOKEN_INVALID
- Ohos.account.event.LOGOFF | -| nickname9+ | string | No| Nickname of the distributed account. It must be a non-null string.| -| avatar9+ | string | No| Avatar of the distributed account. It must be a non-null string.| -| scalableData8+ | object | No| Extended information about the distributed account, passed in key-value (KV) pairs.
**NOTE**
This parameter is reserved and not used in the setters and getters.| +| Name | Value| Description | +| ---- | ------ | ----------- | +| NOT_LOGGED_IN | 0 | The account has not logged in.| +| LOGGED_IN | 1 | The account has logged in.| diff --git a/en/application-dev/reference/apis/js-apis-distributed-data.md b/en/application-dev/reference/apis/js-apis-distributed-data.md index cd25c298b90c6f59cba4e2d86f79650991eb7ab8..51c73ee6de1bf48c0417819f6bc9cdd8222981f4 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-data.md +++ b/en/application-dev/reference/apis/js-apis-distributed-data.md @@ -3768,7 +3768,7 @@ sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void Synchronizes the KV store manually. > **NOTE** > -> The value of **deviceIds** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceIds** is the **networkId** in [DeviceInfo](js-apis-device-manager.md#deviceinfo), which is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -3778,9 +3778,9 @@ Synchronizes the KV store manually. | Name | Type | Mandatory| Description | | --------- | --------------------- | ---- | ---------------------------------------------- | -| deviceIds | string[] | Yes | List of IDs of the devices in the same networking environment to be synchronized.| +| deviceIds | string[] | Yes | List of **networkId**s of the devices in the same networking environment to be synchronized.| | mode | [SyncMode](#syncmode) | Yes | Synchronization mode. | -| delayMs | number | No | Allowed synchronization delay time, in ms. | +| delayMs | number | No | Delay time allowed, in milliseconds. The default value is **0**. | **Example** @@ -3799,7 +3799,7 @@ deviceManager.createDeviceManager('bundleName', (err, value) => { if (devManager != null) { var devices = devManager.getTrustedDeviceListSync(); for (var i = 0; i < devices.length; i++) { - deviceIds[i] = devices[i].deviceId; + deviceIds[i] = devices[i].networkId; } } try { @@ -5246,7 +5246,7 @@ Synchronizes the KV store manually. > **NOTE** > -> The value of **deviceIds** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceIds** is the **networkId** in [DeviceInfo](js-apis-device-manager.md#deviceinfo), which is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -5256,7 +5256,7 @@ Synchronizes the KV store manually. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| deviceIds |string[] | Yes |IDs of the devices to be synchronized.| +| deviceIds |string[] | Yes |**networkId**s of the devices to be synchronized.| | mode |[SyncMode](#syncmode) | Yes |Synchronization mode. | | delayMs |number | No |Allowed synchronization delay time, in ms. The default value is **0**. | @@ -5277,7 +5277,7 @@ deviceManager.createDeviceManager('bundleName', (err, value) => { if (devManager != null) { var devices = devManager.getTrustedDeviceListSync(); for (var i = 0; i < devices.length; i++) { - deviceIds[i] = devices[i].deviceId; + deviceIds[i] = devices[i].networkId; } } try { diff --git a/en/application-dev/reference/apis/js-apis-distributedKVStore.md b/en/application-dev/reference/apis/js-apis-distributedKVStore.md index 117afe8d4f70bb034add259da1a09d3b58b680ba..3d2441aa70b66ffb01e9bc19eb0f38156f912e50 100644 --- a/en/application-dev/reference/apis/js-apis-distributedKVStore.md +++ b/en/application-dev/reference/apis/js-apis-distributedKVStore.md @@ -127,7 +127,7 @@ Enumerates the distributed KV store types. | Name | Description | | -------------------- | ------------------------------------------------------------ | -| DEVICE_COLLABORATION | Device KV store.
The device KV store manages data by device, which eliminates conflicts. Data can be queried by device.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore | +| DEVICE_COLLABORATION | Device KV store.
The device KV store manages data by device, which eliminates conflicts. Data can be queried by device.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore| | SINGLE_VERSION | Single KV store.
The single KV store does not differentiate data by device. If entries with the same key are modified on different devices, the value will be overwritten.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | ## SecurityLevel @@ -457,7 +457,7 @@ try { kvStore = store; kvStore = null; store = null; - kvManager.closeKVStore('appId', 'storeId', function (err, data) { + kvManager.closeKVStore('appId', 'storeId', function (err) { if (err != undefined) { console.error(`Failed to close KVStore.code is ${err.code},message is ${err.message}`); return; @@ -568,7 +568,7 @@ try { kvStore = store; kvStore = null; store = null; - kvManager.deleteKVStore('appId', 'storeId', function (err, data) { + kvManager.deleteKVStore('appId', 'storeId', function (err) { if (err != undefined) { console.error(`Failed to delete KVStore.code is ${err.code},message is ${err.message}`); return; @@ -2128,7 +2128,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err) { if (err != undefined) { console.error(`Failed to put.code is ${err.code},message is ${err.message}`); return; @@ -2182,8 +2182,8 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { - console.info(`Succeeded in putting.data=${data}`); + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(() => { + console.info(`Succeeded in putting data`); }).catch((err) => { console.error(`Failed to put.code is ${err.code},message is ${err.message}`); }); @@ -2239,7 +2239,7 @@ try { entries.push(entry); } console.info(`entries: ${entries}`); - kvStore.putBatch(entries, async function (err, data) { + kvStore.putBatch(entries, async function (err) { if (err != undefined) { console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`); return; @@ -2311,7 +2311,7 @@ try { entries.push(entry); } console.info(`entries: ${entries}`); - kvStore.putBatch(entries).then(async (entries) => { + kvStore.putBatch(entries).then(async () => { console.info('Succeeded in putting Batch'); kvStore.getEntries('batch_test_string_key').then((entries) => { console.info('Succeeded in getting Entries'); @@ -2372,7 +2372,7 @@ try { v8Arr.push(vb1); v8Arr.push(vb2); v8Arr.push(vb3); - kvStore.putBatch(v8Arr, async function (err, data) { + kvStore.putBatch(v8Arr, async function (err) { if (err != undefined) { console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); return; @@ -2434,7 +2434,7 @@ try { v8Arr.push(vb1); v8Arr.push(vb2); v8Arr.push(vb3); - kvStore.putBatch(v8Arr).then(async (data) => { + kvStore.putBatch(v8Arr).then(async () => { console.info(`Succeeded in putting patch`); }).catch((err) => { console.error(`putBatch fail.code is ${err.code},message is ${err.message}`); @@ -2480,13 +2480,13 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err) { if (err != undefined) { console.error(`Failed to put.code is ${err.code},message is ${err.message}`); return; } console.info('Succeeded in putting'); - kvStore.delete(KEY_TEST_STRING_ELEMENT, function (err, data) { + kvStore.delete(KEY_TEST_STRING_ELEMENT, function (err) { if (err != undefined) { console.error(`Failed to delete.code is ${err.code},message is ${err.message}`); return; @@ -2540,9 +2540,9 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { - console.info(`Succeeded in putting: ${data}`); - kvStore.delete(KEY_TEST_STRING_ELEMENT).then((data) => { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(() => { + console.info(`Succeeded in putting data`); + kvStore.delete(KEY_TEST_STRING_ELEMENT).then(() => { console.info('Succeeded in deleting'); }).catch((err) => { console.error(`Failed to delete.code is ${err.code},message is ${err.message}`); @@ -2595,13 +2595,13 @@ try { let predicates = new dataSharePredicates.DataSharePredicates(); let arr = ["name"]; predicates.inKeys(arr); - kvStore.put("name", "bob", function (err, data) { + kvStore.put("name", "bob", function (err) { if (err != undefined) { console.error(`Failed to put.code is ${err.code},message is ${err.message}`); return; } console.info("Succeeded in putting"); - kvStore.delete(predicates, function (err, data) { + kvStore.delete(predicates, function (err) { if (err == undefined) { console.info('Succeeded in deleting'); } else { @@ -2660,9 +2660,9 @@ try { let predicates = new dataSharePredicates.DataSharePredicates(); let arr = ["name"]; predicates.inKeys(arr); - kvStore.put("name", "bob").then((data) => { - console.info(`Succeeded in putting: ${data}`); - kvStore.delete(predicates).then((data) => { + kvStore.put("name", "bob").then(() => { + console.info(`Succeeded in putting data`); + kvStore.delete(predicates).then(() => { console.info('Succeeded in deleting'); }).catch((err) => { console.error(`Failed to delete.code is ${err.code},message is ${err.message}`); @@ -2724,13 +2724,13 @@ try { keys.push(key + i); } console.info(`entries: ${entries}`); - kvStore.putBatch(entries, async function (err, data) { + kvStore.putBatch(entries, async function (err) { if (err != undefined) { console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`); return; } console.info('Succeeded in putting Batch'); - kvStore.deleteBatch(keys, async function (err, data) { + kvStore.deleteBatch(keys, async function (err) { if (err != undefined) { console.error(`Failed to delete Batch.code is ${err.code},message is ${err.message}`); return; @@ -2797,9 +2797,9 @@ try { keys.push(key + i); } console.info(`entries: ${entries}`); - kvStore.putBatch(entries).then(async (data) => { + kvStore.putBatch(entries).then(async () => { console.info('Succeeded in putting Batch'); - kvStore.deleteBatch(keys).then((err) => { + kvStore.deleteBatch(keys).then(() => { console.info('Succeeded in deleting Batch'); }).catch((err) => { console.error(`Failed to delete Batch.code is ${err.code},message is ${err.message}`); @@ -2845,10 +2845,10 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err, data) { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err) { console.info('Succeeded in putting data'); const deviceid = 'no_exist_device_id'; - kvStore.removeDeviceData(deviceid, async function (err, data) { + kvStore.removeDeviceData(deviceid, async function (err) { if (err == undefined) { console.info('succeeded in removing device data'); } else { @@ -2902,13 +2902,13 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((err) => { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(() => { console.info('Succeeded in putting data'); }).catch((err) => { console.error(`Failed to put data.code is ${err.code},message is ${err.message} `); }); const deviceid = 'no_exist_device_id'; - kvStore.removeDeviceData(deviceid).then((err) => { + kvStore.removeDeviceData(deviceid).then(() => { console.info('succeeded in removing device data'); }).catch((err) => { console.error(`Failed to remove device data.code is ${err.code},message is ${err.message} `); @@ -2954,7 +2954,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err) { if (err != undefined) { console.error(`Failed to put.code is ${err.code},message is ${err.message}`); return; @@ -3009,8 +3009,8 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { - console.info(`Succeeded in putting data.data=${data}`); + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(() => { + console.info(`Succeeded in putting data`); kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { console.info(`Succeeded in getting data.data=${data}`); }).catch((err) => { @@ -3065,7 +3065,7 @@ try { entries.push(entry); } console.info(`entries: ${entries}`); - kvStore.putBatch(entries, async function (err, data) { + kvStore.putBatch(entries, async function (err) { if (err != undefined) { console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`); return; @@ -3132,7 +3132,7 @@ try { entries.push(entry); } console.info(`entries: ${entries}`); - kvStore.putBatch(entries).then(async (entries) => { + kvStore.putBatch(entries).then(async () => { console.info('Succeeded in putting Batch'); kvStore.getEntries('batch_test_string_key').then((entries) => { console.info('Succeeded in getting Entries'); @@ -3190,7 +3190,7 @@ try { entries.push(entry); } console.info(`entries: {entries}`); - kvStore.putBatch(entries, async function (err, data) { + kvStore.putBatch(entries, async function (err) { console.info('Succeeded in putting Batch'); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); @@ -3256,7 +3256,7 @@ try { entries.push(entry); } console.info(`entries: {entries}`); - kvStore.putBatch(entries).then(async (err) => { + kvStore.putBatch(entries).then(async () => { console.info('Succeeded in putting Batch'); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); @@ -3317,7 +3317,7 @@ try { } entries.push(entry); } - kvStore.putBatch(entries, async function (err, data) { + kvStore.putBatch(entries, async function (err) { if (err != undefined) { console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); return; @@ -3330,7 +3330,7 @@ try { } console.info('Succeeded in getting result set'); resultSet = result; - kvStore.closeResultSet(resultSet, function (err, data) { + kvStore.closeResultSet(resultSet, function (err) { if (err != undefined) { console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); return; @@ -3391,7 +3391,7 @@ try { } entries.push(entry); } - kvStore.putBatch(entries).then(async (err) => { + kvStore.putBatch(entries).then(async () => { console.info('Succeeded in putting batch'); }).catch((err) => { console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); @@ -3402,7 +3402,7 @@ try { }).catch((err) => { console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); }); - kvStore.closeResultSet(resultSet).then((err) => { + kvStore.closeResultSet(resultSet).then(() => { console.info('Succeeded in closing result set'); }).catch((err) => { console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); @@ -3454,7 +3454,7 @@ try { } entries.push(entry); } - kvStore.putBatch(entries, async function (err, data) { + kvStore.putBatch(entries, async function (err) { if (err != undefined) { console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); return; @@ -3522,7 +3522,7 @@ try { } entries.push(entry); } - kvStore.putBatch(entries).then(async (err) => { + kvStore.putBatch(entries).then(async () => { console.info('Succeeded in putting batch'); }).catch((err) => { console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); @@ -3583,7 +3583,7 @@ try { } console.info('Succeeded in getting result set'); resultSet = result; - kvStore.closeResultSet(resultSet, function (err, data) { + kvStore.closeResultSet(resultSet, function (err) { if (err != undefined) { console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); return; @@ -3643,7 +3643,7 @@ try { }).catch((err) => { console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); }); - kvStore.closeResultSet(resultSet).then((err) => { + kvStore.closeResultSet(resultSet).then(() => { console.info('Succeeded in closing result set'); }).catch((err) => { console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); @@ -3673,7 +3673,7 @@ Closes the **KVStoreResultSet** object returned by [SingleKvStore.getResultSet]( ```js try { let resultSet = null; - kvStore.closeResultSet(resultSet, function (err, data) { + kvStore.closeResultSet(resultSet, function (err) { if (err == undefined) { console.info('Succeeded in closing result set'); } else { @@ -3760,7 +3760,7 @@ try { } entries.push(entry); } - kvStore.putBatch(entries, async function (err, data) { + kvStore.putBatch(entries, async function (err) { console.info('Succeeded in putting batch'); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); @@ -3822,7 +3822,7 @@ try { } entries.push(entry); } - kvStore.putBatch(entries).then(async (err) => { + kvStore.putBatch(entries).then(async () => { console.info('Succeeded in putting batch'); }).catch((err) => { console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); @@ -3867,11 +3867,11 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ```js let file = "BK001"; try { - kvStore.backup(file, (err, data) => { + kvStore.backup(file, function(err) => { if (err) { console.error(`Failed to backup.code is ${err.code},message is ${err.message} `); } else { - console.info(`Succeeded in backupping data.data=${data}`); + console.info(`Succeeded in backupping data`); } }); } catch (e) { @@ -3912,8 +3912,8 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ```js let file = "BK001"; try { - kvStore.backup(file).then((data) => { - console.info(`Succeeded in backupping data.data=${data}`); + kvStore.backup(file).then(() => { + console.info(`Succeeded in backupping data`); }).catch((err) => { console.error(`Failed to backup.code is ${err.code},message is ${err.message}`); }); @@ -3950,11 +3950,11 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ```js let file = "BK001"; try { - kvStore.restore(file, (err, data) => { + kvStore.restore(file, (err) => { if (err) { console.error(`Failed to restore.code is ${err.code},message is ${err.message}`); } else { - console.info(`Succeeded in restoring data.data=${data}`); + console.info(`Succeeded in restoring data`); } }); } catch (e) { @@ -3995,8 +3995,8 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ```js let file = "BK001"; try { - kvStore.restore(file).then((data) => { - console.info(`Succeeded in restoring data.data=${data}`); + kvStore.restore(file).then(() => { + console.info(`Succeeded in restoring data`); }).catch((err) => { console.error(`Failed to restore.code is ${err.code},message is ${err.message}`); }); @@ -4124,7 +4124,7 @@ try { console.info(`startTransaction 0 ${data}`); count++; }); - kvStore.startTransaction(async function (err, data) { + kvStore.startTransaction(async function (err) { if (err != undefined) { console.error(`Failed to start Transaction.code is ${err.code},message is ${err.message}`); return; @@ -4132,7 +4132,7 @@ try { console.info('Succeeded in starting Transaction'); let entries = putBatchString(10, 'batch_test_string_key'); console.info(`entries: ${entries}`); - kvStore.putBatch(entries, async function (err, data) { + kvStore.putBatch(entries, async function (err) { if (err != undefined) { console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); return; @@ -4182,7 +4182,7 @@ try { console.info(`startTransaction 0 ${data}`); count++; }); - kvStore.startTransaction().then(async (err) => { + kvStore.startTransaction().then(async () => { console.info('Succeeded in starting Transaction'); }).catch((err) => { console.error(`Failed to start Transaction.code is ${err.code},message is ${err.message}`); @@ -4218,7 +4218,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ```js try { - kvStore.commit(function (err, data) { + kvStore.commit(function (err) { if (err == undefined) { console.info('Succeeded in committing'); } else { @@ -4256,7 +4256,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ```js try { - kvStore.commit().then(async (err) => { + kvStore.commit().then(async () => { console.info('Succeeded in committing'); }).catch((err) => { console.error(`Failed to commit.code is ${err.code},message is ${err.message}`); @@ -4292,7 +4292,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ```js try { - kvStore.rollback(function (err,data) { + kvStore.rollback(function (err) { if (err == undefined) { console.info('Succeeded in rolling back'); } else { @@ -4330,7 +4330,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ```js try { - kvStore.rollback().then(async (err) => { + kvStore.rollback().then(async () => { console.info('Succeeded in rolling back'); }).catch((err) => { console.error(`Failed to rollback.code is ${err.code},message is ${err.message}`); @@ -4359,7 +4359,7 @@ Sets data synchronization, which can be enabled or disabled. This API uses an as ```js try { - kvStore.enableSync(true, function (err, data) { + kvStore.enableSync(true, function (err) { if (err == undefined) { console.info('Succeeded in enabling sync'); } else { @@ -4395,7 +4395,7 @@ Sets data synchronization, which can be enabled or disabled. This API uses a pro ```js try { - kvStore.enableSync(true).then((err) => { + kvStore.enableSync(true).then(() => { console.info('Succeeded in enabling sync'); }).catch((err) => { console.error(`Failed to enable sync.code is ${err.code},message is ${err.message}`); @@ -4427,7 +4427,7 @@ Sets the data synchronization range. This API uses an asynchronous callback to r try { const localLabels = ['A', 'B']; const remoteSupportLabels = ['C', 'D']; - kvStore.setSyncRange(localLabels, remoteSupportLabels, function (err, data) { + kvStore.setSyncRange(localLabels, remoteSupportLabels, function (err) { if (err != undefined) { console.error(`Failed to set syncRange.code is ${err.code},message is ${err.message}`); return; @@ -4466,7 +4466,7 @@ Sets the data synchronization range. This API uses a promise to return the resul try { const localLabels = ['A', 'B']; const remoteSupportLabels = ['C', 'D']; - kvStore.setSyncRange(localLabels, remoteSupportLabels).then((err) => { + kvStore.setSyncRange(localLabels, remoteSupportLabels).then(() => { console.info('Succeeded in setting syncRange'); }).catch((err) => { console.error(`Failed to set syncRange.code is ${err.code},message is ${err.message}`); @@ -4496,7 +4496,7 @@ Sets the default delay allowed for KV store synchronization. This API uses an as ```js try { const defaultAllowedDelayMs = 500; - kvStore.setSyncParam(defaultAllowedDelayMs, function (err, data) { + kvStore.setSyncParam(defaultAllowedDelayMs, function (err) { if (err != undefined) { console.error(`Failed to set syncParam.code is ${err.code},message is ${err.message}`); return; @@ -4533,7 +4533,7 @@ Sets the default delay allowed for KV store synchronization. This API uses a pro ```js try { const defaultAllowedDelayMs = 500; - kvStore.setSyncParam(defaultAllowedDelayMs).then((err) => { + kvStore.setSyncParam(defaultAllowedDelayMs).then(() => { console.info('Succeeded in setting syncParam'); }).catch((err) => { console.error(`Failed to set syncParam.code is ${err.code},message is ${err.message}`); @@ -4550,7 +4550,7 @@ sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void Synchronizes the KV store manually. For details about the synchronization modes of KV stores, see [Cross-Device Synchronization of KV Stores](../../database/data-sync-of-kv-store.md). > **NOTE** > -> The value of **deviceIds** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceIds** is the **networkId** in [DeviceInfo](js-apis-device-manager.md#deviceinfo), which is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -4560,7 +4560,7 @@ Synchronizes the KV store manually. For details about the synchronization modes | Name | Type | Mandatory| Description | | --------- | --------------------- | ---- | ---------------------------------------------- | -| deviceIds | string[] | Yes | List of IDs of the devices in the same networking environment to be synchronized.| +| deviceIds | string[] | Yes | List of **networkId**s of the devices in the same networking environment to be synchronized.| | mode | [SyncMode](#syncmode) | Yes | Synchronization mode. | | delayMs | number | No | Allowed synchronization delay time, in ms. The default value is **0**. | @@ -4589,14 +4589,14 @@ deviceManager.createDeviceManager('bundleName', (err, value) => { if (devManager != null) { var devices = devManager.getTrustedDeviceListSync(); for (var i = 0; i < devices.length; i++) { - deviceIds[i] = devices[i].deviceId; + deviceIds[i] = devices[i].networkId; } } try { kvStore.on('syncComplete', function (data) { console.info('Sync dataChange'); }); - kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err, data) { + kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err) { if (err != undefined) { console.error(`Failed to sync.code is ${err.code},message is ${err.message}`); return; @@ -4619,7 +4619,7 @@ sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void Synchronizes the KV store manually. This API returns the result synchronously. For details about the synchronization modes of KV stores, see [Cross-Device Synchronization of KV Stores](../../database/data-sync-of-kv-store.md). > **NOTE** > -> The value of **deviceIds** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> **deviceIds** is the **networkId** in [DeviceInfo](js-apis-device-manager.md#deviceinfo), which is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -4629,7 +4629,7 @@ Synchronizes the KV store manually. This API returns the result synchronously. F | Name | Type | Mandatory| Description | | --------- | --------------------- | ---- | ---------------------------------------------- | -| deviceIds | string[] | Yes | List of IDs of the devices in the same networking environment to be synchronized.| +| deviceIds | string[] | Yes | List of **networkId**s of the devices in the same networking environment to be synchronized.| | mode | [SyncMode](#syncmode) | Yes | Synchronization mode. | | query | [Query](#query) | Yes | **Query** object to match. | | delayMs | number | No | Allowed synchronization delay time, in ms. The default value is **0**.| @@ -4659,14 +4659,14 @@ deviceManager.createDeviceManager('bundleName', (err, value) => { if (devManager != null) { var devices = devManager.getTrustedDeviceListSync(); for (var i = 0; i < devices.length; i++) { - deviceIds[i] = devices[i].deviceId; + deviceIds[i] = devices[i].networkId; } } try { kvStore.on('syncComplete', function (data) { console.info('Sync dataChange'); }); - kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err, data) { + kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err) { if (err != undefined) { console.error(`Failed to sync.code is ${err.code},message is ${err.message}`); return; @@ -4735,7 +4735,7 @@ Subscribes to synchronization complete events. | Name | Type | Mandatory| Description | | ------------ | --------------------------------------------- | ---- | ------------------------------------------------------ | | event | string | Yes | Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event.| -| syncCallback | Callback<Array<[string, number]>> | Yes | Callback invoked to return the synchronization complete event.| +| syncCallback | Callback<Array<[string, number]>> | Yes | Callback invoked to return the synchronization complete event. | **Example** @@ -4746,7 +4746,7 @@ try { kvStore.on('syncComplete', function (data) { console.info(`syncComplete ${data}`); }); - kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then((data) => { + kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then(() => { console.info('succeeded in putting'); }).catch((err) => { console.error(`Failed to put.code is ${err.code},message is ${err.message}`); @@ -4969,7 +4969,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err) { if (err != undefined) { console.error(`Failed to put.code is ${err.code},message is ${err.message}`); return; @@ -5024,8 +5024,8 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { - console.info(`Succeeded in putting data.data=${data}`); + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(() => { + console.info(`Succeeded in putting data`); kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { console.info(`Succeeded in getting data.data=${data}`); }).catch((err) => { @@ -5075,7 +5075,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err, data) { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err) { if (err != undefined) { console.error(`Failed to put.code is ${err.code},message is ${err.message}`); return; @@ -5135,7 +5135,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(async (data) => { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(async () => { console.info('Succeeded in putting'); kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => { console.info('Succeeded in getting'); @@ -5191,7 +5191,7 @@ try { entries.push(entry); } console.info(`entries: ${entries}`); - kvStore.putBatch(entries, async function (err, data) { + kvStore.putBatch(entries, async function (err) { if (err != undefined) { console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`); return; @@ -5258,7 +5258,7 @@ try { entries.push(entry); } console.info(`entries: ${entries}`); - kvStore.putBatch(entries).then(async (entries) => { + kvStore.putBatch(entries).then(async () => { console.info('Succeeded in putting Batch'); kvStore.getEntries('batch_test_string_key').then((entries) => { console.info('Succeeded in getting Entries'); @@ -5320,7 +5320,7 @@ try { entries.push(entry); } console.info(`entries : ${entries}`); - kvStore.putBatch(entries, async function (err, data) { + kvStore.putBatch(entries, async function (err) { if (err != undefined) { console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); return; @@ -5392,7 +5392,7 @@ try { entries.push(entry); } console.info(`entries: ${entries}`); - kvStore.putBatch(entries).then(async (err) => { + kvStore.putBatch(entries).then(async () => { console.info('Succeeded in putting batch'); kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entries) => { console.info('Succeeded in getting entries'); @@ -5453,7 +5453,7 @@ try { entries.push(entry); } console.info(`entries: {entries}`); - kvStore.putBatch(entries, async function (err, data) { + kvStore.putBatch(entries, async function (err) { console.info('Succeeded in putting Batch'); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); @@ -5519,7 +5519,7 @@ try { entries.push(entry); } console.info(`entries: {entries}`); - kvStore.putBatch(entries).then(async (err) => { + kvStore.putBatch(entries).then(async () => { console.info('Succeeded in putting Batch'); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); @@ -5584,7 +5584,7 @@ try { entries.push(entry); } console.info(`entries: ${entries}`); - kvStore.putBatch(entries, async function (err, data) { + kvStore.putBatch(entries, async function (err) { if (err != undefined) { console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); return; @@ -5661,7 +5661,7 @@ try { entries.push(entry); } console.info(`entries: ${entries}`); - kvStore.putBatch(entries).then(async (err) => { + kvStore.putBatch(entries).then(async () => { console.info('Succeeded in putting batch'); var query = new distributedKVStore.Query(); query.deviceId('localDeviceId'); @@ -5722,7 +5722,7 @@ try { } entries.push(entry); } - kvStore.putBatch(entries, async function (err, data) { + kvStore.putBatch(entries, async function (err) { if (err != undefined) { console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); return; @@ -5735,7 +5735,7 @@ try { } console.info('Succeeded in getting result set'); resultSet = result; - kvStore.closeResultSet(resultSet, function (err, data) { + kvStore.closeResultSet(resultSet, function (err) { if (err != undefined) { console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); return; @@ -5796,7 +5796,7 @@ try { } entries.push(entry); } - kvStore.putBatch(entries).then(async (err) => { + kvStore.putBatch(entries).then(async () => { console.info('Succeeded in putting batch'); }).catch((err) => { console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); @@ -5807,7 +5807,7 @@ try { }).catch((err) => { console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); }); - kvStore.closeResultSet(resultSet).then((err) => { + kvStore.closeResultSet(resultSet).then(() => { console.info('Succeeded in closing result set'); }).catch((err) => { console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); @@ -5859,7 +5859,7 @@ try { } console.info('Succeeded in getting resultSet'); resultSet = result; - kvStore.closeResultSet(resultSet, function (err, data) { + kvStore.closeResultSet(resultSet, function (err) { if (err != undefined) { console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`); return; @@ -5918,7 +5918,7 @@ try { }).catch((err) => { console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`); }); - kvStore.closeResultSet(resultSet).then((err) => { + kvStore.closeResultSet(resultSet).then(() => { console.info('Succeeded in closing resultSet'); }).catch((err) => { console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`); @@ -5975,7 +5975,7 @@ try { } entries.push(entry); } - kvStore.putBatch(entries, async function (err, data) { + kvStore.putBatch(entries, async function (err) { if (err != undefined) { console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); return; @@ -5990,7 +5990,7 @@ try { } console.info('Succeeded in getting resultSet'); resultSet = result; - kvStore.closeResultSet(resultSet, function (err, data) { + kvStore.closeResultSet(resultSet, function (err) { if (err != undefined) { console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`); return; @@ -6056,7 +6056,7 @@ try { } entries.push(entry); } - kvStore.putBatch(entries).then(async (err) => { + kvStore.putBatch(entries).then(async () => { console.info('Succeeded in putting batch'); }).catch((err) => { console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); @@ -6071,7 +6071,7 @@ try { }); query.deviceId('localDeviceId'); console.info("GetResultSet " + query.getSqlLike()); - kvStore.closeResultSet(resultSet).then((err) => { + kvStore.closeResultSet(resultSet).then(() => { console.info('Succeeded in closing resultSet'); }).catch((err) => { console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`); @@ -6129,7 +6129,7 @@ try { } entries.push(entry); } - kvStore.putBatch(entries).then(async (err) => { + kvStore.putBatch(entries).then(async () => { console.info('Succeeded in putting batch'); }).catch((err) => { console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); @@ -6194,7 +6194,7 @@ try { } entries.push(entry); } - kvStore.putBatch(entries, async function (err, data) { + kvStore.putBatch(entries, async function (err) { if (err != undefined) { console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); return; @@ -6209,7 +6209,7 @@ try { } console.info('Succeeded in getting resultSet'); resultSet = result; - kvStore.closeResultSet(resultSet, function (err, data) { + kvStore.closeResultSet(resultSet, function (err) { if (err != undefined) { console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`); return; @@ -6266,7 +6266,7 @@ try { } console.info('Succeeded in getting result set'); resultSet = result; - kvStore.closeResultSet(resultSet, function (err, data) { + kvStore.closeResultSet(resultSet, function (err) { if (err != undefined) { console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); return; @@ -6326,7 +6326,7 @@ try { }).catch((err) => { console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); }); - kvStore.closeResultSet(resultSet).then((err) => { + kvStore.closeResultSet(resultSet).then(() => { console.info('Succeeded in closing result set'); }).catch((err) => { console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); @@ -6384,7 +6384,7 @@ try { } console.info('Succeeded in getting result set'); resultSet = result; - kvStore.closeResultSet(resultSet, function (err, data) { + kvStore.closeResultSet(resultSet, function (err) { if (err != undefined) { console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); return; @@ -6449,7 +6449,7 @@ try { }).catch((err) => { console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); }); - kvStore.closeResultSet(resultSet).then((err) => { + kvStore.closeResultSet(resultSet).then(() => { console.info('Succeeded in closing result set'); }).catch((err) => { console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); @@ -6499,7 +6499,7 @@ try { } entries.push(entry); } - kvStore.putBatch(entries, async function (err, data) { + kvStore.putBatch(entries, async function (err) { console.info('Succeeded in putting batch'); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); @@ -6561,7 +6561,7 @@ try { } entries.push(entry); } - kvStore.putBatch(entries).then(async (err) => { + kvStore.putBatch(entries).then(async () => { console.info('Succeeded in putting batch'); }).catch((err) => { console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); @@ -6623,7 +6623,7 @@ try { } entries.push(entry); } - kvStore.putBatch(entries, async function (err, data) { + kvStore.putBatch(entries, async function (err) { if (err != undefined) { console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); return; @@ -6695,7 +6695,7 @@ try { } entries.push(entry); } - kvStore.putBatch(entries).then(async (err) => { + kvStore.putBatch(entries).then(async () => { console.info('Succeeded in putting batch'); }).catch((err) => { console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); diff --git a/en/application-dev/reference/apis/js-apis-huks.md b/en/application-dev/reference/apis/js-apis-huks.md index 085a1da52c3b233db29b04738eeea3bb8e532594..11c2f8d4ea97dbc0149b68b6eea7b873ba8eeefb 100644 --- a/en/application-dev/reference/apis/js-apis-huks.md +++ b/en/application-dev/reference/apis/js-apis-huks.md @@ -77,6 +77,25 @@ Generates a key. This API uses an asynchronous callback to return the result. | options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. The algorithm, key purpose, and key length are mandatory.| | callback | AsyncCallback\ | Yes | Callback invoked to return the result. If no error is captured, the key is successfully generated. In this case, the API does not return the key content because the key is always protected in a TEE. If an error is captured, an exception occurs in the generation process.| +**Error codes** + +For details about the error codes, see [HUKS Error Codes](../errorcodes/errorcode-huks.md). + +| ID| Error Message | +| -------- | ------------- | +| 401 | argument is invalid. | +| 801 | api is not supported. | +| 12000001 | algorithm mode is not supported. | +| 12000002 | algorithm param is missing. | +| 12000003 | algorithm param is invalid. | +| 12000004 | operating file failed. | +| 12000005 | IPC communication failed. | +| 12000006 | error occured in crypto engine. | +| 12000012 | external error. | +| 12000013 | queried credential does not exist. | +| 12000014 | memory is insufficient. | +| 12000015 | call service failed. | + **Example** ```js @@ -132,6 +151,25 @@ Generates a key. This API uses a promise to return the result. Because the key i | keyAlias | string | Yes | Alias of the key. | | options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. The algorithm, key purpose, and key length are mandatory.| +**Error codes** + +For details about the error codes, see [HUKS Error Codes](../errorcodes/errorcode-huks.md). + +| ID| Error Message | +| -------- | ------------- | +| 401 | argument is invalid. | +| 801 | api is not supported. | +| 12000001 | algorithm mode is not supported. | +| 12000002 | algorithm param is missing. | +| 12000003 | algorithm param is invalid. | +| 12000004 | operating file failed. | +| 12000005 | IPC communication failed. | +| 12000006 | error occured in crypto engine. | +| 12000012 | external error. | +| 12000013 | queried credential does not exist. | +| 12000014 | memory is insufficient. | +| 12000015 | call service failed. | + **Example** ```js @@ -188,6 +226,20 @@ Deletes a key. This API uses an asynchronous callback to return the result. | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | | callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| +**Error codes** + +For details about the error codes, see [HUKS Error Codes](../errorcodes/errorcode-huks.md). + +| ID| Error Message | +| -------- | ------------- | +| 401 | argument is invalid. | +| 801 | api is not supported. | +| 12000004 | operating file failed. | +| 12000005 | IPC communication failed. | +| 12000011 | queried entity does not exist. | +| 12000012 | external error. | +| 12000014 | memory is insufficient. | + **Example** ```js @@ -224,6 +276,20 @@ Deletes a key. This API uses a promise to return the result. | keyAlias | string | Yes | Key alias passed in when the key was generated.| | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | +**Error codes** + +For details about the error codes, see [HUKS Error Codes](../errorcodes/errorcode-huks.md). + +| ID| Error Message | +| -------- | ------------- | +| 401 | argument is invalid. | +| 801 | api is not supported. | +| 12000004 | operating file failed. | +| 12000005 | IPC communication failed. | +| 12000011 | queried entity does not exist. | +| 12000012 | external error. | +| 12000014 | memory is insufficient. | + **Example** ```js @@ -291,6 +357,26 @@ Imports a key in plaintext. This API uses an asynchronous callback to return the | options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import. The algorithm, key purpose, and key length are mandatory.| | callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| +**Error codes** + +For details about the error codes, see [HUKS Error Codes](../errorcodes/errorcode-huks.md). + +| ID| Error Message | +| -------- | ------------- | +| 401 | argument is invalid. | +| 801 | api is not supported. | +| 12000001 | algorithm mode is not supported. | +| 12000002 | algorithm param is missing. | +| 12000003 | algorithm param is invalid. | +| 12000004 | operating file failed. | +| 12000005 | IPC communication failed. | +| 12000006 | error occured in crypto engine. | +| 12000011 | queried entity does not exist. | +| 12000012 | external error. | +| 12000013 | queried credential does not exist. | +| 12000014 | memory is insufficient. | +| 12000015 | call service failed. | + **Example** ```js @@ -358,6 +444,26 @@ Imports a key in plaintext. This API uses a promise to return the result. | keyAlias | string | Yes | Alias of the key. | | options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import. The algorithm, key purpose, and key length are mandatory.| +**Error codes** + +For details about the error codes, see [HUKS Error Codes](../errorcodes/errorcode-huks.md). + +| ID| Error Message | +| -------- | ------------- | +| 401 | argument is invalid. | +| 801 | api is not supported. | +| 12000001 | algorithm mode is not supported. | +| 12000002 | algorithm param is missing. | +| 12000003 | algorithm param is invalid. | +| 12000004 | operating file failed. | +| 12000005 | IPC communication failed. | +| 12000006 | error occured in crypto engine. | +| 12000011 | queried entity does not exist. | +| 12000012 | external error. | +| 12000013 | queried credential does not exist. | +| 12000014 | memory is insufficient. | +| 12000015 | call service failed. | + **Example** ```js @@ -428,6 +534,25 @@ Obtains the certificate used to verify a key. This API uses an asynchronous call | options | [HuksOptions](#huksoptions) | Yes | Parameters and data required for obtaining the certificate. | | callback | AsyncCallback<[HuksReturnResult](#huksreturnresult9)> | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| +**Error codes** + +For details about the error codes, see [HUKS Error Codes](../errorcodes/errorcode-huks.md). + +| ID| Error Message | +| -------- | ------------- | +| 201 | check permission failed. | +| 401 | argument is invalid. | +| 801 | api is not supported. | +| 12000001 | algorithm mode is not supported. | +| 12000002 | algorithm param is missing. | +| 12000003 | algorithm param is invalid. | +| 12000004 | operating file failed. | +| 12000005 | IPC communication failed. | +| 12000006 | error occured in crypto engine. | +| 12000011 | queried entity does not exist. | +| 12000012 | external error. | +| 12000014 | memory is insufficient. | + **Example** ```js @@ -555,6 +680,25 @@ Obtains the certificate used to verify a key. This API uses a promise to return | ---------------------------------------------- | --------------------------------------------- | | Promise<[HuksReturnResult](#huksreturnresult9)> | Promise used to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| +**Error codes** + +For details about the error codes, see [HUKS Error Codes](../errorcodes/errorcode-huks.md). + +| ID| Error Message | +| -------- | ------------- | +| 201 | check permission failed. | +| 401 | argument is invalid. | +| 801 | api is not supported. | +| 12000001 | algorithm mode is not supported. | +| 12000002 | algorithm param is missing. | +| 12000003 | algorithm param is invalid. | +| 12000004 | operating file failed. | +| 12000005 | IPC communication failed. | +| 12000006 | error occured in crypto engine. | +| 12000011 | queried entity does not exist. | +| 12000012 | external error. | +| 12000014 | memory is insufficient. | + **Example** ```js @@ -678,6 +822,26 @@ Imports a wrapped key. This API uses an asynchronous callback to return the resu | options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import. The algorithm, key purpose, and key length are mandatory.| | callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| +**Error codes** + +For details about the error codes, see [HUKS Error Codes](../errorcodes/errorcode-huks.md). + +| ID| Error Message | +| -------- | ------------- | +| 401 | argument is invalid. | +| 801 | api is not supported. | +| 12000001 | algorithm mode is not supported. | +| 12000002 | algorithm param is missing. | +| 12000003 | algorithm param is invalid. | +| 12000004 | operating file failed. | +| 12000005 | IPC communication failed. | +| 12000006 | error occured in crypto engine. | +| 12000011 | queried entity does not exist. | +| 12000012 | external error. | +| 12000013 | queried credential does not exist. | +| 12000014 | memory is insufficient. | +| 12000015 | call service failed. | + **Example** ```js @@ -893,6 +1057,26 @@ Imports a wrapped key. This API uses a promise to return the result. | wrappingKeyAlias | string | Yes | Alias of the data used to unwrap the key imported. | | options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import. The algorithm, key purpose, and key length are mandatory.| +**Error codes** + +For details about the error codes, see [HUKS Error Codes](../errorcodes/errorcode-huks.md). + +| ID| Error Message | +| -------- | ------------- | +| 401 | argument is invalid. | +| 801 | api is not supported. | +| 12000001 | algorithm mode is not supported. | +| 12000002 | algorithm param is missing. | +| 12000003 | algorithm param is invalid. | +| 12000004 | operating file failed. | +| 12000005 | IPC communication failed. | +| 12000006 | error occured in crypto engine. | +| 12000011 | queried entity does not exist. | +| 12000012 | external error. | +| 12000013 | queried credential does not exist. | +| 12000014 | memory is insufficient. | +| 12000015 | call service failed. | + **Example** ```js @@ -928,6 +1112,24 @@ Exports a key. This API uses an asynchronous callback to return the result. | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | | callback | AsyncCallback<[HuksReturnResult](#huksreturnresult9)> | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned. **outData** contains the public key exported.| +**Error codes** + +For details about the error codes, see [HUKS Error Codes](../errorcodes/errorcode-huks.md). + +| ID| Error Message | +| -------- | ------------- | +| 401 | argument is invalid. | +| 801 | api is not supported. | +| 12000001 | algorithm mode is not supported. | +| 12000002 | algorithm param is missing. | +| 12000003 | algorithm param is invalid. | +| 12000004 | operating file failed. | +| 12000005 | IPC communication failed. | +| 12000006 | error occured in crypto engine. | +| 12000011 | queried entity does not exist. | +| 12000012 | external error. | +| 12000014 | memory is insufficient. | + **Example** ```js @@ -970,6 +1172,24 @@ Exports a key. This API uses a promise to return the result. | ---------------------------------------------- | ------------------------------------------------------------ | | Promise<[HuksReturnResult](#huksreturnresult9)> | Promise used to return the result. If the operation is successful, no **err** value is returned and **outData** contains the public key exported. If the operation fails, an error code is returned. | +**Error codes** + +For details about the error codes, see [HUKS Error Codes](../errorcodes/errorcode-huks.md). + +| ID| Error Message | +| -------- | ------------- | +| 401 | argument is invalid. | +| 801 | api is not supported. | +| 12000001 | algorithm mode is not supported. | +| 12000002 | algorithm param is missing. | +| 12000003 | algorithm param is invalid. | +| 12000004 | operating file failed. | +| 12000005 | IPC communication failed. | +| 12000006 | error occured in crypto engine. | +| 12000011 | queried entity does not exist. | +| 12000012 | external error. | +| 12000014 | memory is insufficient. | + **Example** ```js @@ -1007,6 +1227,24 @@ Obtains key properties. This API uses an asynchronous callback to return the res | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | | callback | AsyncCallback<[HuksReturnResult](#huksreturnresult9)> | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned and **properties** contains the parameters required for generating the key. If the operation fails, an error code is returned. | +**Error codes** + +For details about the error codes, see [HUKS Error Codes](../errorcodes/errorcode-huks.md). + +| ID| Error Message | +| -------- | ------------- | +| 401 | argument is invalid. | +| 801 | api is not supported. | +| 12000001 | algorithm mode is not supported. | +| 12000002 | algorithm param is missing. | +| 12000003 | algorithm param is invalid. | +| 12000004 | operating file failed. | +| 12000005 | IPC communication failed. | +| 12000006 | error occured in crypto engine. | +| 12000011 | queried entity does not exist. | +| 12000012 | external error. | +| 12000014 | memory is insufficient. | + **Example** ```js @@ -1049,6 +1287,24 @@ Obtains key properties. This API uses a promise to return the result. | ----------------------------------------------- | ------------------------------------------------------------ | | Promise\<[HuksReturnResult](#huksreturnresult9)> | Promise used to return the result. If the operation is successful, no **err** value is returned and **properties** contains the parameters required for generating the key. If the operation fails, an error code is returned. | +**Error codes** + +For details about the error codes, see [HUKS Error Codes](../errorcodes/errorcode-huks.md). + +| ID| Error Message | +| -------- | ------------- | +| 401 | argument is invalid. | +| 801 | api is not supported. | +| 12000001 | algorithm mode is not supported. | +| 12000002 | algorithm param is missing. | +| 12000003 | algorithm param is invalid. | +| 12000004 | operating file failed. | +| 12000005 | IPC communication failed. | +| 12000006 | error occured in crypto engine. | +| 12000011 | queried entity does not exist. | +| 12000012 | external error. | +| 12000014 | memory is insufficient. | + **Example** ```js @@ -1086,9 +1342,28 @@ Checks whether a key exists. This API uses an asynchronous callback to return th | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | | callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the key exists, **data** is **true**. If the key does not exist, **error** is the error code.| +**Error codes** + +For details about the error codes, see [HUKS Error Codes](../errorcodes/errorcode-huks.md). + +| ID| Error Message | +| -------- | ------------- | +| 401 | argument is invalid. | +| 801 | api is not supported. | +| 12000002 | algorithm param is missing. | +| 12000003 | algorithm param is invalid. | +| 12000004 | operating file failed. | +| 12000005 | IPC communication failed. | +| 12000006 | error occured in crypto engine. | +| 12000012 | external error. | +| 12000014 | memory is insufficient. | + **Example** ```js +import huks from '@ohos.security.huks'; +import promptAction from '@ohos.promptAction'; + /* Set options to emptyOptions. */ let keyAlias = 'keyAlias'; let emptyOptions = { @@ -1130,9 +1405,28 @@ Checks whether a key exists. This API uses a promise to return the result. | ----------------- | --------------------------------------- | | Promise\ | Promise used to return the result. If the key exists, then() performs subsequent operations. If the key does not exist, error() performs the related service operations.| +**Error codes** + +For details about the error codes, see [HUKS Error Codes](../errorcodes/errorcode-huks.md). + +| ID| Error Message | +| -------- | ------------- | +| 401 | argument is invalid. | +| 801 | api is not supported. | +| 12000002 | algorithm param is missing. | +| 12000003 | algorithm param is invalid. | +| 12000004 | operating file failed. | +| 12000005 | IPC communication failed. | +| 12000006 | error occured in crypto engine. | +| 12000012 | external error. | +| 12000014 | memory is insufficient. | + **Example** ```js +import huks from '@ohos.security.huks'; +import promptAction from '@ohos.promptAction'; + /* Set options to emptyOptions. */ let keyAlias = 'keyAlias'; let emptyOptions = { @@ -1167,6 +1461,25 @@ Initializes the data for a key operation. This API uses an asynchronous callback | options | [HuksOptions](#huksoptions) | Yes | Parameter set used for the **initSession** operation. | | callback | AsyncCallback\<[HuksSessionHandle](#hukssessionhandle9)> | Yes | Callback invoked to return a session handle for subsequent operations.| +**Error codes** + +For details about the error codes, see [HUKS Error Codes](../errorcodes/errorcode-huks.md). + +| ID| Error Message | +| -------- | ------------- | +| 401 | argument is invalid. | +| 801 | api is not supported. | +| 12000001 | algorithm mode is not supported. | +| 12000002 | algorithm param is missing. | +| 12000003 | algorithm param is invalid. | +| 12000004 | operating file failed. | +| 12000005 | IPC communication failed. | +| 12000006 | error occured in crypto engine. | +| 12000010 | the number of sessions has reached limit. | +| 12000011 | queried entity does not exist. | +| 12000012 | external error. | +| 12000014 | memory is insufficient. | + ## huks.initSession9+ initSession(keyAlias: string, options: HuksOptions) : Promise\ @@ -1188,6 +1501,25 @@ Initializes the data for a key operation. This API uses a promise to return the | ----------------------------------- | -------------------------------------------------- | | Promise\<[HuksSessionHandle](#hukssessionhandle9)> | Promise used to return a session handle for subsequent operations.| +**Error codes** + +For details about the error codes, see [HUKS Error Codes](../errorcodes/errorcode-huks.md). + +| ID| Error Message | +| -------- | ------------- | +| 401 | argument is invalid. | +| 801 | api is not supported. | +| 12000001 | algorithm mode is not supported. | +| 12000002 | algorithm param is missing. | +| 12000003 | algorithm param is invalid. | +| 12000004 | operating file failed. | +| 12000005 | IPC communication failed. | +| 12000006 | error occured in crypto engine. | +| 12000010 | the number of sessions has reached limit. | +| 12000011 | queried entity does not exist. | +| 12000012 | external error. | +| 12000014 | memory is insufficient. | + ## huks.updateSession9+ updateSession(handle: number, options: HuksOptions, callback: AsyncCallback\) : void @@ -1204,6 +1536,26 @@ Updates the key operation by segment. This API uses an asynchronous callback to | options | [HuksOptions](#huksoptions) | Yes | Parameter set used for the **updateSession** operation. | | callback | AsyncCallback<[HuksReturnResult](#huksreturnresult9)> | Yes | Callback invoked to return the **updateSession** operation result.| +**Error codes** + +For details about the error codes, see [HUKS Error Codes](../errorcodes/errorcode-huks.md). + +| ID| Error Message | +| -------- | ------------- | +| 401 | argument is invalid. | +| 801 | api is not supported. | +| 12000001 | algorithm mode is not supported. | +| 12000002 | algorithm param is missing. | +| 12000003 | algorithm param is invalid. | +| 12000004 | operating file failed. | +| 12000005 | IPC communication failed. | +| 12000006 | error occured in crypto engine. | +| 12000007 | this credential is already invalidated permanently. | +| 12000008 | verify authtoken failed. | +| 12000009 | authtoken is already timeout. | +| 12000011 | queried entity does not exist. | +| 12000012 | external error. | +| 12000014 | memory is insufficient. | ## huks.updateSession9+ @@ -1222,6 +1574,27 @@ Updates the key operation by segment. This API uses an asynchronous callback to | token | Uint8Array | Yes | Token of the **updateSession** operation. | | callback | AsyncCallback<[HuksReturnResult](#huksreturnresult9)> | Yes | Callback invoked to return the **updateSession** operation result.| +**Error codes** + +For details about the error codes, see [HUKS Error Codes](../errorcodes/errorcode-huks.md). + +| ID| Error Message | +| -------- | ------------- | +| 401 | argument is invalid. | +| 801 | api is not supported. | +| 12000001 | algorithm mode is not supported. | +| 12000002 | algorithm param is missing. | +| 12000003 | algorithm param is invalid. | +| 12000004 | operating file failed. | +| 12000005 | IPC communication failed. | +| 12000006 | error occured in crypto engine. | +| 12000007 | this credential is already invalidated permanently. | +| 12000008 | verify authtoken failed. | +| 12000009 | authtoken is already timeout. | +| 12000011 | queried entity does not exist. | +| 12000012 | external error. | +| 12000014 | memory is insufficient. | + ## huks.updateSession9+ updateSession(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\ @@ -1244,6 +1617,27 @@ Updates the key operation by segment. This API uses a promise to return the resu | ----------------------------------- | -------------------------------------------------- | | Promise<[HuksReturnResult](#huksreturnresult9)> | Promise used to return the **updateSession** operation result.| +**Error codes** + +For details about the error codes, see [HUKS Error Codes](../errorcodes/errorcode-huks.md). + +| ID| Error Message | +| -------- | ------------- | +| 401 | argument is invalid. | +| 801 | api is not supported. | +| 12000001 | algorithm mode is not supported. | +| 12000002 | algorithm param is missing. | +| 12000003 | algorithm param is invalid. | +| 12000004 | operating file failed. | +| 12000005 | IPC communication failed. | +| 12000006 | error occured in crypto engine. | +| 12000007 | this credential is already invalidated permanently. | +| 12000008 | verify authtoken failed. | +| 12000009 | authtoken is already timeout. | +| 12000011 | queried entity does not exist. | +| 12000012 | external error. | +| 12000014 | memory is insufficient. | + ## huks.finishSession9+ finishSession(handle: number, options: HuksOptions, callback: AsyncCallback\) : void @@ -1261,6 +1655,27 @@ Completes the key operation and releases resources. This API uses an asynchronou | token | Uint8Array | Yes | Token of the **finishSession** operation. | | callback | AsyncCallback<[HuksReturnResult](#huksreturnresult9)> | Yes | Callback invoked to return the **finishSession** operation result.| +**Error codes** + +For details about the error codes, see [HUKS Error Codes](../errorcodes/errorcode-huks.md). + +| ID| Error Message | +| -------- | ------------- | +| 401 | argument is invalid. | +| 801 | api is not supported. | +| 12000001 | algorithm mode is not supported. | +| 12000002 | algorithm param is missing. | +| 12000003 | algorithm param is invalid. | +| 12000004 | operating file failed. | +| 12000005 | IPC communication failed. | +| 12000006 | error occured in crypto engine. | +| 12000007 | this credential is already invalidated permanently. | +| 12000008 | verify authtoken failed. | +| 12000009 | authtoken is already timeout. | +| 12000011 | queried entity does not exist. | +| 12000012 | external error. | +| 12000014 | memory is insufficient. | + ## huks.finishSession9+ finishSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void @@ -1278,6 +1693,27 @@ Completes the key operation and releases resources. This API uses an asynchronou | token | Uint8Array | Yes | Token of the **finishSession** operation. | | callback | AsyncCallback\<[HuksReturnResult](#huksreturnresult9)> | Yes | Callback invoked to return the **finishSession** operation result.| +**Error codes** + +For details about the error codes, see [HUKS Error Codes](../errorcodes/errorcode-huks.md). + +| ID| Error Message | +| -------- | ------------- | +| 401 | argument is invalid. | +| 801 | api is not supported. | +| 12000001 | algorithm mode is not supported. | +| 12000002 | algorithm param is missing. | +| 12000003 | algorithm param is invalid. | +| 12000004 | operating file failed. | +| 12000005 | IPC communication failed. | +| 12000006 | error occured in crypto engine. | +| 12000007 | this credential is already invalidated permanently. | +| 12000008 | verify authtoken failed. | +| 12000009 | authtoken is already timeout. | +| 12000011 | queried entity does not exist. | +| 12000012 | external error. | +| 12000014 | memory is insufficient. | + ## huks.finishSession9+ finishSession(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\ @@ -1300,6 +1736,27 @@ Completes the key operation and releases resources. This API uses a promise to r | ----------------------------------- | -------------------------------------------------- | | Promise\<[HuksReturnResult](#huksreturnresult9)> | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [HUKS Error Codes](../errorcodes/errorcode-huks.md). + +| ID| Error Message | +| -------- | ------------- | +| 401 | argument is invalid. | +| 801 | api is not supported. | +| 12000001 | algorithm mode is not supported. | +| 12000002 | algorithm param is missing. | +| 12000003 | algorithm param is invalid. | +| 12000004 | operating file failed. | +| 12000005 | IPC communication failed. | +| 12000006 | error occured in crypto engine. | +| 12000007 | this credential is already invalidated permanently. | +| 12000008 | verify authtoken failed. | +| 12000009 | authtoken is already timeout. | +| 12000011 | queried entity does not exist. | +| 12000012 | external error. | +| 12000014 | memory is insufficient. | + ## huks.abortSession9+ abortSession(handle: number, options: HuksOptions, callback: AsyncCallback\) : void @@ -1316,6 +1773,20 @@ Aborts a key operation. This API uses an asynchronous callback to return the res | options | [HuksOptions](#huksoptions) | Yes | Parameter set used for the **abortSession** operation. | | callback | AsyncCallback\ | Yes | Callback that returns no value. | +**Error codes** + +For details about the error codes, see [HUKS Error Codes](../errorcodes/errorcode-huks.md). + +| ID| Error Message | +| -------- | ------------- | +| 401 | argument is invalid. | +| 801 | api is not supported. | +| 12000004 | operating file failed. | +| 12000005 | IPC communication failed. | +| 12000006 | error occured in crypto engine. | +| 12000012 | external error. | +| 12000014 | memory is insufficient. | + **Example** ```js @@ -1466,6 +1937,20 @@ Aborts a key operation. This API uses a promise to return the result. | ----------------------------------- | -------------------------------------------------- | | Promise\ | Promise used to return the **abortSession** operation result.| +**Error codes** + +For details about the error codes, see [HUKS Error Codes](../errorcodes/errorcode-huks.md). + +| ID| Error Message | +| -------- | ------------- | +| 401 | argument is invalid. | +| 801 | api is not supported. | +| 12000004 | operating file failed. | +| 12000005 | IPC communication failed. | +| 12000006 | error occured in crypto engine. | +| 12000012 | external error. | +| 12000014 | memory is insufficient. | + **Example** ```js @@ -1773,10 +2258,12 @@ Enumerates the key storage modes. **System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ----------------------- | ---- | ------------------------------ | -| HUKS_STORAGE_TEMP | 0 | The key is managed locally. | -| HUKS_STORAGE_PERSISTENT | 1 | The key is managed by the HUKS service.| +| 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.| ## HuksSendType @@ -1812,6 +2299,17 @@ Enumerates the types of keys to import. By default, a public key is imported. Th | HUKS_KEY_TYPE_PRIVATE_KEY | 1 | Private key | | HUKS_KEY_TYPE_KEY_PAIR | 2 | Public and private key pair| +## HuksRsaPssSaltLenType10+ + +Enumerates the **salt_len** types to set when PSS padding is used in RSA signing or signature verification. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------------------------ | ---- | ---------------------------- | +| HUKS_RSA_PSS_SALT_LEN_DIGEST10+ | 0 | **salt_len** is set to the digest length.| +| HUKS_RSA_PSS_SALT_LEN_MAX10+ | 1 | **salt_len** is set to the maximum length.| + ## HuksUserAuthType9+ Enumerates the user authentication types. @@ -1920,6 +2418,8 @@ Enumerates the tags used to invoke parameters. | 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. | @@ -1934,6 +2434,7 @@ Enumerates the tags used to invoke parameters. | 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. | diff --git a/en/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md index a3e98a1cebd86dc45ac0e09f17ca505543d52935..4f94686f60f8964beac0159a44a476c13904ce52 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md @@ -433,7 +433,7 @@ try { getWindows(callback: AsyncCallback\>): void; -Obtains the list of windows on a display. This API uses an asynchronous callback to return the result. +Obtains the list of windows on this display. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -610,7 +610,7 @@ Defines the accessibilityelement. Before calling APIs of **AccessibilityElement* **System capability**: SystemCapability.BarrierFree.Accessibility.Core -## attributeNames +### attributeNames attributeNames\(): Promise\>; @@ -636,7 +636,7 @@ rootElement.attributeNames().then((data) => { console.log('failed to get attribute names, because ${JSON.stringify(err)}'); }); ``` -## attributeNames +### attributeNames attributeNames\(callback: AsyncCallback\>): void; @@ -664,7 +664,7 @@ rootElement.attributeNames((err, data) => { console.info('get attribute names success'); }); ``` -## AccessibilityElement.attributeValue +### attributeValue attributeValue\(attributeName: T): Promise\; @@ -709,7 +709,7 @@ try { console.error('failed to get attribute value, because ${JSON.stringify(exception)}'); } ``` -## AccessibilityElement.attributeValue +### attributeValue attributeValue\(attributeName: T, callback: AsyncCallback\): void; @@ -752,7 +752,7 @@ try { console.error('failed to get attribute value, because ${JSON.stringify(exception)}'); } ``` -## actionNames +### actionNames actionNames(): Promise\>; @@ -778,7 +778,7 @@ rootElement.actionNames().then((data) => { console.error('failed to get action names because ${JSON.stringify(err)}'); }); ``` -## actionNames +### actionNames actionNames(callback: AsyncCallback\>): void; @@ -806,7 +806,7 @@ rootElement.actionNames((err, data) => { console.info('get action names success'); }); ``` -## performAction +### performAction performAction(actionName: string, parameters?: object): Promise\; @@ -818,8 +818,8 @@ Performs an action based on the specified action name. This API uses a promise t | Name | Type | Mandatory | Description | | ----------- | ---------------------------------------- | ---- | -------------- | -| actionName | string | Yes | Action name. For details, see [Action](./js-apis-accessibility.md#action). | -| parameters | object | No | Parameters required for performing the target action. Not supported currently. | +| actionName | string | Yes | Action name. For details, see [Action](./js-apis-accessibility.md#action). +| parameters | object | No | Parameters required for performing the target action. Empty by default. Not supported currently. | **Return value** @@ -849,7 +849,7 @@ try { console.error('failed to perform action, because ${JSON.stringify(exception)}'); } ``` -## performAction +### performAction performAction(actionName: string, callback: AsyncCallback\): void; @@ -861,7 +861,7 @@ Performs an action based on the specified action name. This API uses an asynchro | Name | Type | Mandatory | Description | | ----------- | ---------------------------------------- | ---- | -------------- | -| actionName | string | Yes | Action name. For details, see [Action](./js-apis-accessibility.md#action). | +| actionName | string | Yes | Action name. For details, see [Action](./js-apis-accessibility.md#action). | callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Error codes** @@ -888,7 +888,7 @@ try { console.error('failed to perform action, because ${JSON.stringify(exception)}'); } ``` -## performAction +### performAction performAction(actionName: string, parameters: object, callback: AsyncCallback\): void; @@ -901,7 +901,7 @@ Performs an action based on the specified action name. This API uses an asynchro | Name | Type | Mandatory | Description | | ---------- | ------------------------- | ---- | ---------------------------------------- | | actionName | string | Yes | Action name. For details, see [Action](./js-apis-accessibility.md#action).| -| parameters | object | Yes | Parameters required for performing the target action. Not supported currently. | +| parameters | object | Yes | Parameters required for performing the target action. Empty by default. Not supported currently. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** @@ -932,7 +932,7 @@ try { console.error('failed to perform action, because ${JSON.stringify(exception)}'); } ``` -## findElement('content') +### findElement('content') findElement(type: 'content', condition: string): Promise\>; @@ -971,7 +971,7 @@ try { console.error('failed to find element, because ${JSON.stringify(exception)}'); } ``` -## findElement('content') +### findElement('content') findElement(type: 'content', condition: string, callback: AsyncCallback\>): void; @@ -1007,7 +1007,7 @@ try { console.error('failed to find element, because ${JSON.stringify(exception)}'); } ``` -## findElement('focusType') +### findElement('focusType') findElement(type: 'focusType', condition: FocusType): Promise\; @@ -1046,7 +1046,7 @@ try { console.error('failed to find element, because ${JSON.stringify(exception)}'); } ``` -## findElement('focusType') +### findElement('focusType') findElement(type: 'focusType', condition: FocusType, callback: AsyncCallback\): void; @@ -1082,7 +1082,7 @@ try { console.error('failed to find element, because ${JSON.stringify(exception)}'); } ``` -## findElement('focusDirection') +### findElement('focusDirection') findElement(type: 'focusDirection', condition: FocusDirection): Promise\; @@ -1121,7 +1121,7 @@ try { console.error('failed to find element, because ${JSON.stringify(exception)}'); } ``` -## findElement('focusDirection') +### findElement('focusDirection') findElement(type: 'focusDirection', condition: FocusDirection, callback: AsyncCallback\): void; diff --git a/en/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md b/en/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md index 1e12c17c771021d8bd6dc8f0a38bde2de6d079fc..a36b30aa6ebeff234d11c1f928bbb688664e06bd 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md @@ -43,5 +43,5 @@ let applicationStateObserver = { console.log('onProcessStateChanged onProcessStateChanged: ${JSON.stringify(processData)}'); } }; -let observerCode = appManager.registerApplicationStateObserver(applicationStateObserver); +let observerCode = appManager.on('applicationState', applicationStateObserver); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-multimedia-ringtonePlayer.md b/en/application-dev/reference/apis/js-apis-inner-multimedia-ringtonePlayer.md new file mode 100644 index 0000000000000000000000000000000000000000..66aa7fbf4972c578b1dd544c18618defed8dedeb --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-multimedia-ringtonePlayer.md @@ -0,0 +1,471 @@ +# ringtonePlayer (Ringtone Player) + +The **ringtonePlayer** module provides APIs for playing, configuring, and obtaining system ringtones. + +This module must work with [@ohos.multimedia.systemSoundManager](js-apis-systemSoundManager.md) to manage system ringtones. + +> **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. +> +> The APIs provided by this module are system APIs. + +## Modules to Import + +```js +import systemSoundManager from '@ohos.multimedia.systemSoundManager'; +``` + +## RingtoneOptions + +Enumerates the ringtone parameters. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.SystemSound.Core + +| Name | Type |Mandatory | Description | +| --------- | -------------- | ---- | --------------------------------- | +| volume | number | Yes | Relative volume. The value ranges from 0.00 to 1.00. The value **1.00** indicates the maximum volume (100%).| +| loop | boolean | Yes | Whether to enable loop playback. The value **true** means to enable loop playback, and **false** means the opposite.| + +## RingtonePlayer + +Provides APIs for setting and obtaining system ringtone parameters as well as playing and stopping system ringtones. Before calling any API in **RingtonePlayer**, you must use [getSystemRingtonePlayer](js-apis-systemSoundManager.md#getsystemringtoneplayer) to create a **RingtonePlayer** instance. + +### Attributes + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.SystemSound.Core + +| Name | Type | Readable| Writable| Description | +| ----- | -------------------------- | ---- | ---- | ------------------ | +| state | [media.AVPlayerState](js-apis-media.md#avplayerstate9) | Yes | No | Audio renderer state.| + +**Example** + +```js +let state = systemRingtonePlayer.state; +``` + +### getTitle + +getTitle(callback: AsyncCallback<string>): void + +Obtains the title of a system ringtone. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.SystemSound.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -----------------------------------------| ---- | ------------------------- | +| callback | AsyncCallback<string> | Yes | Callback used to return the ringtone title obtained. | + +**Example** + +```js +systemRingtonePlayer.getTitle((err, value) => { + if (err) { + console.error(`Failed to get system ringtone title. ${err}`); + return; + } + console.info(`Callback invoked to indicate the value of the system ringtone title is obtained ${value}.`); +}); +``` + +### getTitle + +getTitle(): Promise<string> + +Obtains the title of a system ringtone. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.SystemSound.Core + +**Return value** + +| Type | Description | +| --------------------- | -------------------------------- | +| Promise<string> | Promise used to return the ringtone title obtained.| + +**Example** + +```js +systemRingtonePlayer.getTitle().then((value) => { + console.info(`Promise returned to indicate that the value of the system ringtone title is obtained ${value}.`); +}).catch ((err) => { + console.error(`Failed to get the system ringtone title ${err}`); +}); +``` + +### getAudioRendererInfo + +getAudioRendererInfo(callback: AsyncCallback<audio.AudioRendererInfo>): void + +Obtains the information about the audio renderer used by the ringtone. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.SystemSound.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -----------------------------------------| ---- | ------------------------- | +| callback | AsyncCallback<[audio.AudioRendererInfo](js-apis-audio.md#audiorendererinfo8)> | Yes| Callback used to return the audio renderer information obtained.| + +**Example** + +```js +import audio from '@ohos.multimedia.audio'; + +let audioRendererInfo: audio.AudioRendererInfo = null; + +systemRingtonePlayer.getAudioRendererInfo((err, value) => { + if (err) { + console.error(`Failed to get ringtone AudioRendererInfo. ${err}`); + return; + } + console.info(`Callback invoked to indicate the value of the ringtone AudioRendererInfo is obtained.`); + audioRendererInfo = value; +}); +``` + +### getAudioRendererInfo + +getAudioRendererInfo(): Promise<audio.AudioRendererInfo> + +Obtains the information about the audio renderer used by the ringtone. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.SystemSound.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------- | +| Promise<[audio.AudioRendererInfo](js-apis-audio.md#audiorendererinfo8)> | Promise used to return the audio renderer information obtained.| + +**Example** + +```js +import audio from '@ohos.multimedia.audio'; + +let audioRendererInfo: audio.AudioRendererInfo = null; + +systemRingtonePlayer.getAudioRendererInfo().then((value) => { + console.info(`Promise returned to indicate that the value of the ringtone AudioRendererInfo is obtained ${value}.`); + audioRendererInfo = value; +}).catch ((err) => { + console.error(`Failed to get the ringtone AudioRendererInfo ${err}`); +}); +``` + +### configure + +configure(options: RingtoneOptions, callback: AsyncCallback<void>): void + +Sets ringtone parameters. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.SystemSound.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -----------------------------------------| ---- | ------------------------- | +| options | [RingtoneOptions](#ringtoneoptions) | Yes | Ringtone parameters. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +let ringtoneOptions = {volume: 0.5, loop: true}; + +systemRingtonePlayer.configure(ringtoneOptions, (err) => { + if (err) { + console.error(`Failed to configure ringtone options. ${err}`); + return; + } + console.info(`Callback invoked to indicate a successful setting of ringtone options.`); +}); +``` + +### configure + +configure(options: RingtoneOptions): Promise<void> + +Sets ringtone parameters. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.SystemSound.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -----------------------------------------| ---- | ------------------------- | +| options | [RingtoneOptions](#ringtoneoptions) | Yes | Ringtone parameters. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let ringtoneOptions = {volume: 0.5, loop: true}; + +systemRingtonePlayer.configure(ringtoneOptions).then(() => { + console.info(`Promise returned to indicate a successful setting of ringtone options.`); +}).catch ((err) => { + console.error(`Failed to configure ringtone options. ${err}`); +}); +``` + +### start + +start(callback: AsyncCallback<void>): void + +Starts playing the ringtone. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.SystemSound.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -----------------------------------------| ---- | ------------------------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +systemRingtonePlayer.start((err) => { + if (err) { + console.error(`Failed to start playing ringtone. ${err}`); + return; + } + console.info(`Callback invoked to indicate a successful starting of ringtone.`); +}); +``` + +### start + +start(): Promise<void> + +Starts playing the ringtone. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.SystemSound.Core + +**Return value** + +| Type | Description | +| ------------------- | -------------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +systemRingtonePlayer.start().then(() => { + console.info(`Promise returned to indicate a successful starting of ringtone.`); +}).catch ((err) => { + console.error(`Failed to start playing ringtone. ${err}`); +}); +``` + +### stop + +stop(callback: AsyncCallback<void>): void + +Stops playing the ringtone. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.SystemSound.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -----------------------------------------| ---- | ------------------------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +systemRingtonePlayer.stop((err) => { + if (err) { + console.error(`Failed to stop playing ringtone. ${err}`); + return; + } + console.info(`Callback invoked to indicate a successful stopping of ringtone.`); +}); +``` + +### stop + +stop(): Promise<void> + +Stops playing the ringtone. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.SystemSound.Core + +**Return value** + +| Type | Description | +| ------------------- | -------------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +systemRingtonePlayer.stop().then(() => { + console.info(`Promise returned to indicate a successful stopping of ringtone.`); +}).catch ((err) => { + console.error(`Failed to stop playing ringtone. ${err}`); +}); +``` + +### release + +release(callback: AsyncCallback<void>): void + +Releases the ringtone player. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.SystemSound.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -----------------------------------------| ---- | ------------------------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +systemRingtonePlayer.release((err) => { + if (err) { + console.error(`Failed to release ringtone player. ${err}`); + return; + } + console.info(`Callback invoked to indicate a successful releasing of ringtone player.`); +}); +``` + +### release + +release(): Promise<void> + +Releases the ringtone player. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.SystemSound.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------- | +| Promise<void> | Promise used to return the result. | + +**Example** + +```js +systemRingtonePlayer.release().then(() => { + console.info(`Promise returned to indicate a successful releasing of ringtone player.`); +}).catch ((err) => { + console.error(`Failed to release ringtone player. ${err}`); +}); +``` + +### on('audioInterrupt') + +on(type: 'audioInterrupt', callback: Callback<audio.InterruptEvent>): void + +Subscribes to audio interruption events. This API uses a callback to obtain interrupt events. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.SystemSound.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------------------------------------------- | +| type | string | Yes | Event type. The value **'audioInterrupt'** means the audio interruption event, which is triggered when audio rendering is interrupted.| +| callback | Callback<[audio.InterruptEvent](js-apis-audio.md#interruptevent9)> | Yes | Callback used to return the audio interruption event. | + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 401 | if input parameter type or number mismatch | +| 6800101 | if input parameter value error | + +**Example** + +```js +import audio from '@ohos.multimedia.audio'; + +let isPlaying; // An identifier specifying whether rendering is in progress. +let isDucked; // An identifier specifying whether the audio volume is reduced. + +systemRingtonePlayer.on('audioInterrupt', async(interruptEvent) => { +if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { + // The system forcibly interrupts audio rendering. The application must update the status and displayed content accordingly. + switch (interruptEvent.hintType) { + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + // The audio stream has been paused and temporarily loses the focus. It will receive the interruptEvent corresponding to resume when it is able to regain the focus. + console.info('Force paused. Update playing status and stop writing'); + isPlaying = false; // A simplified processing indicating several operations for switching the application to the paused state. + break; + case audio.InterruptHint.INTERRUPT_HINT_STOP: + // The audio stream has been stopped and permanently loses the focus. The user must manually trigger the operation to resume rendering. + console.info('Force stopped. Update playing status and stop writing'); + isPlaying = false; // A simplified processing indicating several operations for switching the application to the paused state. + break; + case audio.InterruptHint.INTERRUPT_HINT_DUCK: + // The audio stream is rendered at a reduced volume. + console.info('Force ducked. Update volume status'); + isDucked = true; // A simplified processing indicating several operations for updating the volume status. + break; + case audio.InterruptHint.INTERRUPT_HINT_UNDUCK: + // The audio stream is rendered at the normal volume. + console.info('Force ducked. Update volume status'); + isDucked = false; // A simplified processing indicating several operations for updating the volume status. + break; + default: + break; + } +} else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { + // The application can choose to take action or ignore. + switch (interruptEvent.hintType) { + case audio.InterruptHint.INTERRUPT_HINT_RESUME: + // It is recommended that the application continue rendering. (The audio stream has been forcibly paused and temporarily lost the focus. It can resume rendering now.) + console.info('Resume force paused renderer or ignore'); + // To continue rendering, the application must perform the required operations. + break; + default: + break; + } +} +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-inputmethodengine.md b/en/application-dev/reference/apis/js-apis-inputmethodengine.md index 43b396fca5c68edbdda3b6146c9a42192421e1d0..1ab9aa0e1bae22a05750f20051029cf979db2ad1 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethodengine.md +++ b/en/application-dev/reference/apis/js-apis-inputmethodengine.md @@ -57,7 +57,9 @@ Provides the constant values of function keys, edit boxes, and the cursor. getInputMethodAbility(): InputMethodAbility Obtains an [InputMethodAbility](#inputmethodability) instance for the input method. + This API can be called only by an input method. + The input method can use the obtained instance to subscribe to a soft keyboard display/hide request event, create/destroy an input method panel, and the like. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -494,7 +496,7 @@ This API can be called only by an input method. Only one SOFT_KEYBOARD panel and | Name | Type | Mandatory| Description | | ------- | ----------- | ---- | ------------------------ | -| ctx | [BaseContext](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-inner-application-baseContext.md) | Yes | Context of the current input method.| +| ctx | [BaseContext](js-apis-inner-application-baseContext.md) | Yes | Context of the current input method.| | info | [PanelInfo](#panelinfo10) | Yes | Information about the input method panel.| | callback | AsyncCallback\<[Panel](#panel10)> | Yes | Callback used to return the result. If the operation is successful, the created input method panel is returned. | @@ -538,7 +540,7 @@ This API can be called only by an input method. Only one SOFT_KEYBOARD panel and | Name | Type | Mandatory| Description | | ------- | ----------- | ---- | ------------------------ | -| ctx | [BaseContext](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-inner-application-baseContext.md) | Yes | Context of the current input method.| +| ctx | [BaseContext](js-apis-inner-application-baseContext.md) | Yes | Context of the current input method.| | info | [PanelInfo](#panelinfo10) | Yes | Information about the input method panel.| **Return value** @@ -953,7 +955,7 @@ Loads content from a page linked to LocalStorage to this panel. This API uses an | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | -------- | | path | string | Yes | Path of the page from which the content will be loaded.| -| storage | [LocalStorage](../../quick-start/arkts-localstorage.md) | Yes | Storage unit that provides storage for mutable and immutable state variables in the application.| +| storage | [LocalStorage](../arkui-ts/ts-state-management.md#localstorage9) | Yes | Storage unit that provides storage for mutable and immutable state variables in the application.| | callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| **Example** @@ -987,7 +989,7 @@ Loads content from a page linked to LocalStorage to this panel. This API uses a | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | -------- | | path | string | Yes | Path of the page from which the content will be loaded.| -| storage | [LocalStorage](../../quick-start/arkts-localstorage.md) | Yes | Storage unit that provides storage for mutable and immutable state variables in the application.| +| storage | [LocalStorage](../arkui-ts/ts-state-management.md#localstorage9) | Yes | Storage unit that provides storage for mutable and immutable state variables in the application.| **Return value** @@ -1067,7 +1069,7 @@ The panel width cannot exceed the screen width, and the panel height cannot be h | Type | Description | | ------- | ------------------------------ | -| Promise | Promise that returns no value. | +| Promise\ | Promise that returns no value. | **Example** @@ -1139,7 +1141,7 @@ This API does not work on panels in the FLG_FIXED state. | Type | Description | | ------- | ------------------------------ | -| Promise | Promise that returns no value. | +| Promise\ | Promise that returns no value. | **Example** @@ -1558,7 +1560,7 @@ Sends the function key. This API uses a promise to return the result. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| action | number | Yes| Action of the function key.
**0**: invalid key.
**1**: confirm key (Enter key).| +| action | number | Yes| Action of the function key.
- **0**: invalid key.
- **1**: confirm key (Enter key).| **Return value** @@ -2521,8 +2523,8 @@ Describes the attribute of a key. | Name | Type| Readable| Writable| Description | | --------- | -------- | ---- | ---- | ------------ | -| keyCode | number | Yes | No | Key value.| -| keyAction | number | Yes | No | Key status.| +| keyCode | number | Yes | No | Key value. For detail, see [KeyCode](js-apis-keycode.md#keycode).| +| keyAction | number | Yes | No | Key event type.
- **2**: keydown event.
- **3**: keyup event.| ## PanelFlag10+ diff --git a/en/application-dev/reference/apis/js-apis-media.md b/en/application-dev/reference/apis/js-apis-media.md index 52178a666aa9ef29b878cd2b1978c3ab3ca3d163..7616a34520de90becc362cb12b6ba27ee8be0b49 100644 --- a/en/application-dev/reference/apis/js-apis-media.md +++ b/en/application-dev/reference/apis/js-apis-media.md @@ -310,18 +310,19 @@ Enumerates the media description keys. **System capability**: SystemCapability.Multimedia.Media.Core -| Name | Value | Description | -| ------------------------ | --------------- | ------------------------------------------------------------ | -| MD_KEY_TRACK_INDEX | 'track_index' | Track index, which is a number. | -| MD_KEY_TRACK_TYPE | 'track_type' | Track type, which is a number. For details, see [MediaType](#mediatype8).| -| MD_KEY_CODEC_MIME | 'codec_mime' | Codec MIME type, which is a string. | -| MD_KEY_DURATION | 'duration' | Media duration, which is a number, in units of ms. | -| MD_KEY_BITRATE | 'bitrate' | Bit rate, which is a number, in units of bit/s. | -| MD_KEY_WIDTH | 'width' | Video width, which is a number, in units of pixel. | -| MD_KEY_HEIGHT | 'height' | Video height, which is a number, in units of pixel. | -| MD_KEY_FRAME_RATE | 'frame_rate' | Video frame rate, which is a number, in units of 100 fps.| -| MD_KEY_AUD_CHANNEL_COUNT | 'channel_count' | Number of audio channels, which is a number. | -| MD_KEY_AUD_SAMPLE_RATE | 'sample_rate' | Sampling rate, which is a number, in units of Hz. | +| Name | Value | Description | +| ----------------------------- | --------------- | ------------------------------------------------------------ | +| MD_KEY_TRACK_INDEX | 'track_index' | Track index, which is a number. | +| MD_KEY_TRACK_TYPE | 'track_type' | Track type, which is a number. For details, see [MediaType](#mediatype8).| +| MD_KEY_CODEC_MIME | 'codec_mime' | Codec MIME type, which is a string. | +| MD_KEY_DURATION | 'duration' | Media duration, which is a number, in units of ms. | +| MD_KEY_BITRATE | 'bitrate' | Bit rate, which is a number, in units of bit/s. | +| MD_KEY_WIDTH | 'width' | Video width, which is a number, in units of pixel. | +| MD_KEY_HEIGHT | 'height' | Video height, which is a number, in units of pixel. | +| MD_KEY_FRAME_RATE | 'frame_rate' | Video frame rate, which is a number, in units of 100 fps.| +| MD_KEY_AUD_CHANNEL_COUNT | 'channel_count' | Number of audio channels, which is a number. | +| MD_KEY_AUD_SAMPLE_RATE | 'sample_rate' | Sampling rate, which is a number, in units of Hz. | +| MD_KEY_LANGUAGE10+ | "language" | Language, which is a string. | ## BufferingInfoType8+ @@ -359,17 +360,17 @@ For details about the audio and video playback demo, see [Audio Playback](../../ | Name | Type | Readable| Writable| Description | | --------------------------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | -| url9+ | string | Yes | Yes | URL of the media asset. It is a static attribute and can be set only when the AVPlayer is in the idle state.
The video formats MP4, MPEG-TS, WebM, and MKV are supported.
The audio formats M4A, AAC, MP3, OGG, and WAV are supported.
**Examples of supported URLs**:
1. FD: fd://xx
![](figures/en-us_image_url.png)
2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx| -| fdSrc9+ | [AVFileDescriptor](#avfiledescriptor9) | Yes | Yes | FD of the media asset. It is a static attribute and can be set only when the AVPlayer is in the idle state.
This attribute is required when media assets of an application are continuously stored in a file.
The video formats MP4, MPEG-TS, WebM, and MKV are supported.
The audio formats M4A, AAC, MP3, OGG, and WAV are supported.
**Example:**
Assume that a media file that stores continuous assets consists of the following:
Video 1 (address offset: 0, byte length: 100)
Video 2 (address offset: 101; byte length: 50)
Video 3 (address offset: 151, byte length: 150)
1. To play video 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }
2. To play video 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }
3. To play video 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }
To play an independent media file, use **src=fd://xx**.| -| dataSrc10+ | [AVDataSrcDescriptor](#avdatasrcdescriptor10) | Yes | Yes | Descriptor of a streaming media asset. It is a static attribute and can be set only when the AVPlayer is in the idle state.
Use scenario: An application starts playing a media file while the file is still being downloaded from the remote to the local host.
The video formats MP4, MPEG-TS, WebM, and MKV are supported.
The audio formats M4A, AAC, MP3, OGG, and WAV are supported.
**Example:**
A user is obtaining an audio and video file from a remote server and wants to play the downloaded file content. To implement this scenario, do as follows:
1. Obtain the total file size, in bytes. If the total size cannot be obtained, set **fileSize** to **-1**.
2. Implement the **func** callback to fill in data. If **fileSize** is **-1**, the format of **func** is **func(buffer: ArrayBuffer, length: number)**, and the AVPlayer obtains data in sequence; otherwise, the format is **func(buffer: ArrayBuffer, length: number, pos: number)**, and the AVPlayer seeks and obtains data in the required positions.
3. Set **AVDataSrcDescriptor {fileSize = size, callback = func}**.
**Notes:**
If the media file to play is in MP4/M4A format, ensure that the **moov** field (specifying the media information) is before the **mdat** field (specifying the media data) or the fields before the **moov** field is less than 10 MB. Otherwise, the parsing fails and the media file cannot be played.| +| url9+ | string | Yes | Yes | URL of the media asset. It is a static attribute and can be set only when the AVPlayer is in the idle state.
The video formats MP4, MPEG-TS, WebM, and MKV are supported.
The audio formats M4A, AAC, MP3, OGG, WAV, and FLAC are supported.
**Example of supported URLs**:
1. FD: fd://xx
![](figures/en-us_image_url.png)
2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx| +| fdSrc9+ | [AVFileDescriptor](#avfiledescriptor9) | Yes | Yes | FD of the media asset. It is a static attribute and can be set only when the AVPlayer is in the idle state.
This attribute is required when media assets of an application are continuously stored in a file.
The video formats MP4, MPEG-TS, WebM, and MKV are supported.
The audio formats M4A, AAC, MP3, OGG, WAV, and FLAC are supported.
**Example:**
Assume that a media file that stores continuous assets consists of the following:
Video 1 (address offset: 0, byte length: 100)
Video 2 (address offset: 101; byte length: 50)
Video 3 (address offset: 151, byte length: 150)
1. To play video 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }
2. To play video 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }
3. To play video 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }
To play an independent media file, use **src=fd://xx**.| +| dataSrc10+ | [AVDataSrcDescriptor](#avdatasrcdescriptor10) | Yes | Yes | Descriptor of a streaming media asset. It is a static attribute and can be set only when the AVPlayer is in the idle state.
Use scenario: An application starts playing a media file while the file is still being downloaded from the remote to the local host.
The video formats MP4, MPEG-TS, WebM, and MKV are supported.
The audio formats M4A, AAC, MP3, OGG, WAV, and FLAC are supported.
**Example:**
A user is obtaining an audio and video file from a remote server and wants to play the downloaded file content. To implement this scenario, do as follows:
1. Obtain the total file size, in bytes. If the total size cannot be obtained, set **fileSize** to **-1**.
2. Implement the **func** callback to fill in data. If **fileSize** is **-1**, the format of **func** is **func(buffer: ArrayBuffer, length: number)**, and the AVPlayer obtains data in sequence; otherwise, the format is **func(buffer: ArrayBuffer, length: number, pos: number)**, and the AVPlayer seeks and obtains data in the required positions.
3. Set **AVDataSrcDescriptor {fileSize = size, callback = func}**.
**Notes:**
If the media file to play is in MP4/M4A format, ensure that the **moov** field (specifying the media information) is before the **mdat** field (specifying the media data) or the fields before the **moov** field is less than 10 MB. Otherwise, the parsing fails and the media file cannot be played.| | surfaceId9+ | string | Yes | Yes | Video window ID. By default, there is no video window. It is a static attribute and can be set only when the AVPlayer is in the initialized state.
It is used to render the window for video playback and therefore is not required in audio-only playback scenarios.
**Example:**
[Create a surface ID through XComponent](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid).| -| loop9+ | boolean | Yes | Yes | Whether to loop playback. The value **true** means to loop playback, and **false** (default) means the opposite. It is a dynamic attribute
and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.
This setting is not supported in the live mode.| +| loop9+ | boolean | Yes | Yes | Whether to loop playback. The value **true** means to loop playback, and **false** (default) means the opposite. It is a dynamic attribute
and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.
This setting is not supported in live mode.| | videoScaleType9+ | [VideoScaleType](#videoscaletype9) | Yes | Yes | Video scaling type. The default value is **VIDEO_SCALE_TYPE_FIT_CROP**. It is a dynamic attribute
and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.| | audioInterruptMode9+ | [audio.InterruptMode](js-apis-audio.md#interruptmode9) | Yes | Yes | Audio interruption mode. The default value is **SHARE_MODE**. It is a dynamic attribute
and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.| | audioRendererInfo10+ | [audio.AudioRendererInfo](js-apis-audio.md#audiorendererinfo8) | Yes | Yes | Audio renderer information. The default value of **contentType** is **CONTENT_TYPE_MUSIC**, and the default value of **streamUsage** is **STREAM_USAGE_MEDIA**.
It can be set only when the AVPlayer is in the initialized state.| | state9+ | [AVPlayerState](#avplayerstate9) | Yes | No | AVPlayer state. It can be used as a query parameter when the AVPlayer is in any state. | -| currentTime9+ | number | Yes | No | Current video playback position, in ms. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.
The value **-1** indicates an invalid value.
In the live mode, **-1** is returned by default.| -| duration9+ | number | Yes | No | Video duration, in ms. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.
The value **-1** indicates an invalid value.
In live streaming scenarios, **-1** is returned by default.| +| currentTime9+ | number | Yes | No | Current video playback position, in ms. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.
The value **-1** indicates an invalid value.
In live mode, **-1** is returned by default.| +| duration9+ | number | Yes | No | Video duration, in ms. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.
The value **-1** indicates an invalid value.
In live mode, **-1** is returned by default.| | width9+ | number | Yes | No | Video width, in pixels. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.
The value **0** indicates an invalid value.| | height9+ | number | Yes | No | Video height, in pixels. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.
The value **0** indicates an invalid value.| @@ -907,7 +908,7 @@ avPlayer.release().then(() => { }) ``` -### getTrackDescription9+ +### getTrackDescription9+ getTrackDescription(callback: AsyncCallback\>): void @@ -999,12 +1000,130 @@ for (let i = 0; i < arrayDescription.length; i++) { } ``` +### selectTrack10+ + +selectTrack(index: number): void + +Selects an audio track. This API can be called only when the AVPlayer is in the prepared state. You can listen for the [trackChange event](#trackchange_on) to determine whether the API calling takes effect. + +**System capability**: SystemCapability.Multimedia.Media.AVPlayer + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| index | number | Yes | Track ID, which can be obtained by calling [getTrackDescription](#avplayer_gettrackdescription).| + +**Example** + +```js +let index = 2 +avPlayer.setBitrate(index) +``` + +### deselectTrack10+ + +deselectTrack(index: number): void + +Deselects an audio track. The default audio track will be used after the audio track is deselected. This API can be called only when the AVPlayer is in the prepared state. You can listen for the [trackChange event](#trackchange_on) to determine whether the API calling takes effect. + +**System capability**: SystemCapability.Multimedia.Media.AVPlayer + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| index | number | Yes | Track ID. You can obtain the ID of the current track by calling [getCurrentTrack](#avplayer_getcurrenttrack).| + +**Example** + +```js +let index = 2 +avPlayer.deselectTrack(index) +``` + +### getCurrentTrack10+ + +getCurrentTrack(trackType: MediaType, callback: AsyncCallback\): void + +Obtains the ID of the current track. This API uses an asynchronous callback to return the result. It can be called only when the AVPlayer is in the prepared, playing, paused, or completed state. + +**System capability**: SystemCapability.Multimedia.Media.AVPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ----------------------- | ---- | ------------------------------------------------------------ | +| trackType | [MediaType](#mediatype) | Yes | Enumerates the media types. | +| callback | AsyncCallback\ | Yes | Callback used to return the current track. If **-1** is returned, no track for the specified media type exists.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | + +**Example** + +```js +let mediaType = media.MediaType.MEDIA_TYPE_AUD; +let trackIndex = null; + +avPlayer.getCurrentTrack(mediaType (err, index) => { + if (err == null) { + console.info('getCurrentTrack success'); + trackIndex = index; + } else { + console.error('getCurrentTrack failed and error is ' + err.message); + } +}); +``` + +### getCurrentTrack10+ + +getCurrentTrack(trackType: MediaType): Promise\ + +Obtains the ID of the current track. This API uses a promise to return the result. It can be called only when the AVPlayer is in the prepared, playing, paused, or completed state. + +**System capability**: SystemCapability.Multimedia.Media.AVPlayer + +**Return value** + +| Type | Description | +| ---------------- | ------------------------------------------------------------ | +| trackType | [MediaType](#mediatype) | +| Promise\| Promise used to return the current track. If **-1** is returned, no track for the specified media type exists.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | + +**Example** + +```js +let mediaType = media.MediaType.MEDIA_TYPE_AUD; +let trackIndex = null; + +avPlayer.getCurrentTrack(mediaType).then((index) => { + console.info('getCurrentTrack success'); + trackIndex = index; +}).catch((err) => { + console.error('getCurrentTrack failed and catch error is ' + err.message); +}); +``` + ### seek9+ seek(timeMs: number, mode?:SeekMode): void Seeks to the specified playback position. This API can be called only when the AVPlayer is in the prepared, playing, paused, or completed state. You can check whether the seek operation takes effect by subscribing to the [seekDone](#seekDone_on) event. -This API is not supported in the live mode. +This API is not supported in live mode. **System capability**: SystemCapability.Multimedia.Media.AVPlayer @@ -1070,7 +1189,7 @@ avPlayer.off('seekDone') setSpeed(speed: PlaybackSpeed): void Sets the playback speed. This API can be called only when the AVPlayer is in the prepared, playing, paused, or completed state. You can check whether the setting takes effect by subscribing to the [speedDone](#speedDone_on) event. -This API is not supported in the live mode. +This API is not supported in live mode. **System capability**: SystemCapability.Multimedia.Media.AVPlayer @@ -1348,7 +1467,7 @@ avPlayer.off('endOfStream') on(type: 'timeUpdate', callback: Callback\): void Subscribes to playback position changes. It is used to refresh the current position of the progress bar. By default, this event is reported every 1 second. However, it is reported immediately upon a successful seek operation. -The **'timeUpdate'** event is not supported in the live mode. +The **'timeUpdate'** event is not supported in live mode. **System capability**: SystemCapability.Multimedia.Media.AVPlayer @@ -1392,7 +1511,7 @@ avPlayer.off('timeUpdate') on(type: 'durationUpdate', callback: Callback\): void Subscribes to media asset duration changes. It is used to refresh the length of the progress bar. By default, this event is reported once when the AVPlayer switches to the prepared state. However, it can be repeatedly reported for special streams that trigger duration changes. -The **'durationUpdate'** event is not supported in the live mode. +The **'durationUpdate'** event is not supported in live mode. **System capability**: SystemCapability.Multimedia.Media.AVPlayer @@ -1605,6 +1724,49 @@ Unsubscribes from the audio interruption event. avPlayer.off('audioInterrupt') ``` +### on('trackChange')10+ + +on(type: 'trackChange', callback: (index: number, isSelect: boolean) => void): void; + +Subscribes to track changes, which are triggered by calling **selectTrack** or **deselectTrack**. + +**System capability**: SystemCapability.Multimedia.Media.AVPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ----------------------------------------------------- | +| type | string | Yes | Event type, which is **'trackChange'** in this case.| +| callback | function | Yes | Callback invoked when the event is triggered. | + +**Example** + +```js +avPlayer.on('trackChange', (index: number, isSelect: boolean) => { + console.info('trackChange success, and index is:' + index + ', isSelect is :' + isSelect) +}) +``` + +### off('trackChange')10+ + +off(type: 'trackChange'): void + +Unsubscribes from track changes + +**System capability**: SystemCapability.Multimedia.Media.AVPlayer + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | --------------------------------------------------------- | +| type | string | Yes | Event type, which is **'trackChange'** in this case.| + +**Example** + +```js +avPlayer.off('trackChange') +``` + ## AVPlayerState9+ Enumerates the states of the [AVPlayer](#avplayer9). Your application can proactively obtain the AVPlayer state through the **state** attribute or obtain the reported AVPlayer state by subscribing to the [stateChange](#stateChange_on) event. For details about the rules for state transition, see [Audio Playback](../../media/using-avplayer-for-playback.md). @@ -3497,7 +3659,7 @@ Only one **AudioRecorder** instance can be created per device. | Type | Description | | ------------------------------- | ------------------------------------------------------------ | -| [AudioRecorder](#audiorecorderdeprecated) | If the operation is successful, the **AudioRecorder** instance is returned; otherwise, **null** is returned. The instance can be used to record audio.| +| [AudioRecorder](#audiorecorderdeprecated) | If the operation is successful, an **AudioRecorder** instance is returned; otherwise, **null** is returned. The instance can be used to record audio.| **Example** @@ -3542,7 +3704,7 @@ Provides APIs to manage and play audio. Before calling any API in **AudioPlayer* | Name | Type | Readable| Writable| Description | | ------------------------------- | ------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | -| src | string | Yes | Yes | Audio file URI. The mainstream audio formats (M4A, AAC, MP3, OGG, and WAV) are supported.
**Examples of supported URLs**:
1. FD: fd://xx
![](figures/en-us_image_url.png)
2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx
**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.INTERNET| +| src | string | Yes | Yes | Audio file URI. The mainstream audio formats (M4A, AAC, MP3, OGG, and WAV) are supported.
**Example of supported URLs**:
1. FD: fd://xx
![](figures/en-us_image_url.png)
2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx
**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.INTERNET| | fdSrc9+ | [AVFileDescriptor](#avfiledescriptor9) | Yes | Yes | Description of the audio file. This attribute is required when audio assets of an application are continuously stored in a file.
**Example:**
Assume that a music file that stores continuous music assets consists of the following:
Music 1 (address offset: 0, byte length: 100)
Music 2 (address offset: 101; byte length: 50)
Music 3 (address offset: 151, byte length: 150)
1. To play music 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }
2. To play music 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }
3. To play music 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }
To play an independent music file, use **src=fd://xx**.
| | loop | boolean | Yes | Yes | Whether to loop audio playback. The value **true** means to loop audio playback, and **false** means the opposite. | | audioInterruptMode9+ | [audio.InterruptMode](js-apis-audio.md#interruptmode9) | Yes | Yes | Audio interruption mode. | diff --git a/en/application-dev/reference/apis/js-apis-medialibrary.md b/en/application-dev/reference/apis/js-apis-medialibrary.md index c90acd7d15a4fa31f489f952569a1f4511eb77c7..4d7cc790180ad3d088633aed44e094611ec1f27e 100644 --- a/en/application-dev/reference/apis/js-apis-medialibrary.md +++ b/en/application-dev/reference/apis/js-apis-medialibrary.md @@ -77,7 +77,6 @@ let media = mediaLibrary.getMediaLibrary(); ### getFileAssets7+ - getFileAssets(options: MediaFetchOptions, callback: AsyncCallback<FetchFileResult>): void Obtains file assets (also called files). This API uses an asynchronous callback to return the result. @@ -105,7 +104,7 @@ async function example() { selectionArgs: [imageType.toString()], }; // Obtain the files in asynchronous callback mode. - media.getFileAssets(imagesFetchOp, (error, fetchFileResult) => { + media.getFileAssets(imagesFetchOp, async (error, fetchFileResult) => { // Check whether the result set of the obtained files is undefined. If yes, the API call fails. if (fetchFileResult == undefined) { console.error('get fetchFileResult failed with error: ' + error); @@ -124,8 +123,8 @@ async function example() { return; } console.info('Get fetchFileResult successfully, count: ' + count); - // Obtain the first file in the result set in asynchronous callback mode. - fetchFileResult.getFirstObject((error, fileAsset) => { + // Obtain the first file in the result set in asynchronous callback mode. If there are a large number of files, use getAllObject instead. + fetchFileResult.getFirstObject(async (error, fileAsset) => { // Check whether the first file is undefined. If yes, the API call fails. if (fileAsset == undefined) { console.error('get first object failed with error: ' + error); @@ -178,7 +177,7 @@ async function example() { selectionArgs: [imageType.toString()], }; // Obtain the files in promise mode. - media.getFileAssets(imagesFetchOp).then((fetchFileResult) => { + media.getFileAssets(imagesFetchOp).then(async (fetchFileResult) => { // Obtain the total number of files in the result set. const count = fetchFileResult.getCount(); // Check whether the number is less than 0. If yes, the API call fails. @@ -192,8 +191,8 @@ async function example() { return; } console.info('Get fetchFileResult successfully, count: ' + count); - // Obtain the first file in the result set in promise mode. - fetchFileResult.getFirstObject().then((fileAsset) => { + // Obtain the first file in the result set in promise mode. If there are a large number of files, use getAllObject instead. + fetchFileResult.getFirstObject().then(async (fileAsset) => { console.info('fileAsset.displayName ' + '0 : ' + fileAsset.displayName); // Call getNextObject to obtain the next file until the last one. for (let i = 1; i < count; i++) { @@ -514,17 +513,18 @@ Obtains the albums. This API uses an asynchronous callback to return the result. ```js async function example() { - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - media.getAlbums(AlbumNoArgsfetchOp, (error, albumList) => { - if (albumList != undefined) { - console.info('getAlbums successfully: ' + JSON.stringify(albumList)); - } else { - console.error('getAlbums failed with error: ' + error); - } - }) + // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'. + let AlbumNoArgsfetchOp = { + selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?', + selectionArgs:['New Album 1'], + }; + media.getAlbums(AlbumNoArgsfetchOp, (error, albumList) => { + if (albumList != undefined) { + console.info('getAlbums successfully: ' + JSON.stringify(albumList)); + } else { + console.error('getAlbums failed with error: ' + error); + } + }) } ``` @@ -554,15 +554,16 @@ Obtains the albums. This API uses a promise to return the result. ```js async function example() { - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - media.getAlbums(AlbumNoArgsfetchOp).then((albumList) => { - console.info('getAlbums successfully: ' + JSON.stringify(albumList)); - }).catch((error) => { - console.error('getAlbums failed with error: ' + error); - }); + // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'. + let AlbumNoArgsfetchOp = { + selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?', + selectionArgs:['New Album 1'], + }; + media.getAlbums(AlbumNoArgsfetchOp).then((albumList) => { + console.info('getAlbums successfully: ' + JSON.stringify(albumList)); + }).catch((error) => { + console.error('getAlbums failed with error: ' + error); + }); } ``` @@ -2021,7 +2022,7 @@ async function example() { ### getNextObject7+ - getNextObject(callback: AsyncCallback<FileAsset>): void +getNextObject(callback: AsyncCallback<FileAsset>): void Obtains the next file asset in the result set. This API uses an asynchronous callback to return the result. > **NOTE** @@ -2049,7 +2050,8 @@ async function example() { }; let fetchFileResult = await media.getFileAssets(getImageOp); let fileAsset = await fetchFileResult.getFirstObject(); - if (!fileAsset.isAfterLast) { + console.log('fetchFileResult getFirstObject successfully, displayName: ' + fileAsset.displayName); + if (!fetchFileResult.isAfterLast()) { fetchFileResult.getNextObject((error, fileAsset) => { if (error) { console.error('fetchFileResult getNextObject failed with error: ' + error); @@ -2065,7 +2067,7 @@ async function example() { ### getNextObject7+ - getNextObject(): Promise<FileAsset> +getNextObject(): Promise<FileAsset> Obtains the next file asset in the result set. This API uses a promise to return the result. > **NOTE** @@ -2093,7 +2095,8 @@ async function example() { }; let fetchFileResult = await media.getFileAssets(getImageOp); let fileAsset = await fetchFileResult.getFirstObject(); - if (!fileAsset.isAfterLast) { + console.log('fetchFileResult getFirstObject successfully, displayName: ' + fileAsset.displayName); + if (!fetchFileResult.isAfterLast()) { fetchFileResult.getNextObject().then((fileAsset) => { console.info('fetchFileResult getNextObject successfully, displayName: ' + fileAsset.displayName); fetchFileResult.close(); @@ -2369,20 +2372,21 @@ Commits the modification in the album attributes to the database. This API uses ```js async function example() { - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - const albumList = await media.getAlbums(AlbumNoArgsfetchOp); - const album = albumList[0]; - album.albumName = 'hello'; - album.commitModify((error) => { - if (error) { - console.error('commitModify failed with error: ' + error); - return; - } - console.info('commitModify successful.'); - }) + // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'. + let AlbumNoArgsfetchOp = { + selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?', + selectionArgs:['New Album 1'], + }; + const albumList = await media.getAlbums(AlbumNoArgsfetchOp); + const album = albumList[0]; + album.albumName = 'hello'; + album.commitModify((error) => { + if (error) { + console.error('commitModify failed with error: ' + error); + return; + } + console.info('commitModify successful.'); + }) } ``` @@ -2406,18 +2410,60 @@ Commits the modification in the album attributes to the database. This API uses ```js async function example() { - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - const albumList = await media.getAlbums(AlbumNoArgsfetchOp); - const album = albumList[0]; - album.albumName = 'hello'; - album.commitModify().then(() => { - console.info('commitModify successfully'); - }).catch((error) => { - console.error('commitModify failed with error: ' + error); - }); + // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'. + let AlbumNoArgsfetchOp = { + selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?', + selectionArgs:['New Album 1'], + }; + const albumList = await media.getAlbums(AlbumNoArgsfetchOp); + const album = albumList[0]; + album.albumName = 'hello'; + album.commitModify().then(() => { + console.info('commitModify successfully'); + }).catch((error) => { + console.error('commitModify failed with error: ' + error); + }); +} +``` + +### getFileAssets7+ + +getFileAssets(callback: AsyncCallback<FetchFileResult>): void + +Obtains the file assets in this album. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.READ_MEDIA + +**System capability**: SystemCapability.Multimedia.MediaLibrary.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ----------------------------------- | +| callback | AsyncCallback<[FetchFileResult](#fetchfileresult7)> | Yes | Callback used to return the file assets.| + +**Example** + +```js +async function example() { + // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'. + let AlbumNoArgsfetchOp = { + selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?', + selectionArgs:['New Album 1'], + }; + // Obtain the albums that meet the retrieval options and return the album list. + const albumList = await media.getAlbums(AlbumNoArgsfetchOp); + const album = albumList[0]; + // Obtain an album from the album list and obtain all media assets that meet the retrieval options in the album. + album.getFileAssets((error, fetchFileResult) => { + if (error) { + console.error('album getFileAssets failed with error: ' + error); + return; + } + let count = fetchFileResult.getCount(); + console.info('album getFileAssets successfully, count: ' + count); + fetchFileResult.close(); + }); } ``` @@ -2442,27 +2488,28 @@ Obtains the file assets in this album. This API uses an asynchronous callback to ```js async function example() { - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - let fileNoArgsfetchOp = { - selections: '', - selectionArgs: [], + // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'. + let AlbumNoArgsfetchOp = { + selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?', + selectionArgs:['New Album 1'], + }; + let fileNoArgsfetchOp = { + selections: '', + selectionArgs: [], + } + // Obtain the albums that meet the retrieval options and return the album list. + const albumList = await media.getAlbums(AlbumNoArgsfetchOp); + const album = albumList[0]; + // Obtain an album from the album list and obtain all media assets that meet the retrieval options in the album. + album.getFileAssets(fileNoArgsfetchOp, (error, fetchFileResult) => { + if (error) { + console.error('album getFileAssets failed with error: ' + error); + return; } - // Obtain the albums that meet the retrieval options and return the album list. - const albumList = await media.getAlbums(AlbumNoArgsfetchOp); - const album = albumList[0]; - // Obtain an album from the album list and obtain all media assets that meet the retrieval options in the album. - album.getFileAssets(fileNoArgsfetchOp, (error, fetchFileResult) => { - if (error) { - console.error('album getFileAssets failed with error: ' + error); - return; - } - let count = fetchFileResult.getCount(); - console.info('album getFileAssets successfully, count: ' + count); - fetchFileResult.close(); - }); + let count = fetchFileResult.getCount(); + console.info('album getFileAssets successfully, count: ' + count); + fetchFileResult.close(); + }); } ``` @@ -2492,25 +2539,26 @@ Obtains the file assets in this album. This API uses a promise to return the res ```js async function example() { - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - let fileNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - // Obtain the albums that meet the retrieval options and return the album list. - const albumList = await media.getAlbums(AlbumNoArgsfetchOp); - const album = albumList[0]; - // Obtain an album from the album list and obtain all media assets that meet the retrieval options in the album. - album.getFileAssets(fileNoArgsfetchOp).then((fetchFileResult) => { - let count = fetchFileResult.getCount(); - console.info('album getFileAssets successfully, count: ' + count); - fetchFileResult.close(); - }).catch((error) => { - console.error('album getFileAssets failed with error: ' + error); - }); + // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'. + let AlbumNoArgsfetchOp = { + selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?', + selectionArgs:['New Album 1'], + }; + let fileNoArgsfetchOp = { + selections: '', + selectionArgs: [], + }; + // Obtain the albums that meet the retrieval options and return the album list. + const albumList = await media.getAlbums(AlbumNoArgsfetchOp); + const album = albumList[0]; + // Obtain an album from the album list and obtain all media assets that meet the retrieval options in the album. + album.getFileAssets(fileNoArgsfetchOp).then((fetchFileResult) => { + let count = fetchFileResult.getCount(); + console.info('album getFileAssets successfully, count: ' + count); + fetchFileResult.close(); + }).catch((error) => { + console.error('album getFileAssets failed with error: ' + error); + }); } ``` diff --git a/en/application-dev/reference/apis/js-apis-osAccount.md b/en/application-dev/reference/apis/js-apis-osAccount.md index ff49d8d1d84f03186de36aca3665b5729486bafe..ed266a44339d9af7e1cdb351dd305cf225a0b7d1 100644 --- a/en/application-dev/reference/apis/js-apis-osAccount.md +++ b/en/application-dev/reference/apis/js-apis-osAccount.md @@ -2433,7 +2433,7 @@ Unsubscribes from the OS account activation states, including the states of the | -------- | -------------------------- | ---- | ------------------------------------------------------------ | | type | 'activate' \| 'activating' | Yes | Type of the event to unsubscribe from. The value **activate** means an event indicating that an OS account is activated, and **activating** means an event indicating that an OS account is being activated.| | name | string | Yes | Subscription name, which can be customized. The value cannot be empty or exceed 1024 bytes, and must be the same as the value passed by **on()**.| -| callback | Callback<number> | No | Callback to unregister. By default, **0** is returned. | +| callback | Callback<number> | No | Callback for the OS account activation state events. By default, no value is passed, which unsubscribes from all the callbacks for the OS account activation state events. | **Error codes** @@ -5649,7 +5649,7 @@ Obtains authentication information of the specified type. This API uses a promis | Name | Type | Mandatory| Description | | -------- | ----------------------------------- | ---- | -------- | -| authType | [AuthType](#authtype8) | No | Authentication credential type.| +| authType | [AuthType](#authtype8) | No | Authentication type. By default, no value is passed, which means to obtain information about all authentication types.| **Return value** @@ -5929,12 +5929,14 @@ Defines the executor property. **System capability**: SystemCapability.Account.OsAccount -| Name | Type | Mandatory | Description | -| ------------ | ---------------------------------------- | ----- | ----------------- | -| result | number | Yes | Result. | -| authSubType | [AuthSubType](#authsubtype8) | Yes | Authentication credential subtype.| -| remainTimes | number | No | Number of remaining authentication times. | -| freezingTime | number | No | Freezing time. | +| Name | Type | Readable| Writable| Description | +| ------------ | ---------------------------- | ----- | -----|----------------- | +| result | number | Yes | Yes | Result. | +| authSubType | [AuthSubType](#authsubtype8) | Yes | Yes | Authentication credential subtype.| +| remainTimes | number | Yes | Yes | Number of remaining authentication times. | +| freezingTime | number | Yes | Yes | Freezing time. | +| enrollmentProgress10+ | string | Yes | Yes | Enrollment progress. By default, no value is passed.| +| sensorInfo10+ | string | Yes | Yes | Sensor information. By default, no value is passed.| ## AuthResult8+ @@ -5946,9 +5948,9 @@ Defines the authentication result information. | Name | Type | Mandatory | Description | | ------------ | ----------- | ----- | ----------------- | -| token | Uint8Array | No | Authentication token. | -| remainTimes | number | No | Number of remaining authentication times. | -| freezingTime | number | No | Freezing time. | +| token | Uint8Array | No | Authentication token. By default, no value is passed. | +| remainTimes | number | No | Number of remaining authentication times. By default, no value is passed. | +| freezingTime | number | No | Freezing time. By default, no value is passed. | ## CredentialInfo8+ @@ -5974,7 +5976,7 @@ Defines the request result information. | Name | Type | Mandatory | Description | | ------------ | ----------- | ----- | ----------------- | -| credentialId | Uint8Array | No | Credential ID. | +| credentialId | Uint8Array | No | Credential ID. By default, no value is passed. | ## EnrolledCredInfo8+ @@ -6004,6 +6006,8 @@ Enumerates the types of properties to obtain. | AUTH_SUB_TYPE | 1 | Authentication credential subtype.| | REMAIN_TIMES | 2 | Remaining time. | | FREEZING_TIME | 3 | Freezing time. | +| ENROLLMENT_PROGRESS10+ | 4 | Enrollment progress. | +| SENSOR_INFO10+ | 5 | Sensor information. | ## SetPropertyType8+ @@ -6047,6 +6051,9 @@ Enumerates the authentication credential subtypes. | PIN_MIXED | 10002 | Custom mixed credentials.| | FACE_2D | 20000 | 2D face credential. | | FACE_3D | 20001 | 3D face credential. | +| FINGERPRINT_CAPACITIVE10+ | 30000 | Capacitive fingerprint. | +| FINGERPRINT_OPTICAL10+ | 30001 | Optical fingerprint. | +| FINGERPRINT_ULTRASONIC10+ | 30002 | Ultrasonic fingerprint. | | DOMAIN_MIXED9+ | 10240001 | Mixed domain authentication credentials. | ## AuthTrustLevel8+ @@ -6136,6 +6143,8 @@ Enumerates the tip codes for fingerprint authentication. | FINGERPRINT_TIP_PARTIAL | 3 | Only part of the fingerprint image is detected. | | FINGERPRINT_TIP_TOO_FAST | 4 | The fingerprint image is incomplete due to quick motion. | | FINGERPRINT_TIP_TOO_SLOW | 5 | Failed to read the fingerprint image due to lack of motion. | +| FINGERPRINT_TIP_FINGER_DOWN10+ | 6 | Press your finger. | +| FINGERPRINT_TIP_FINGER_UP10+ | 7 | Lift your finger. | ## OsAccountInfo @@ -6148,16 +6157,16 @@ Defines the OS account information. | localId | number | Yes | ID of the target OS account. | | localName | string | Yes | OS account name. | | type | [OsAccountType](#osaccounttype) | Yes | OS account type. | -| constraints | Array<string> | No | [Constraints](#constraints) on the OS account.| +| constraints | Array<string> | No | OS account [Constraints](#constraints). By default, no value is passed.| | isVerified8+ | boolean | Yes | Whether to verify the OS account. | -| photo8+ | string | No | Profile photo of the OS account. | +| photo8+ | string | No | OS account avatar. By default, no value is passed. | | createTime8+ | number | Yes | Time when the OS account was created. | -| lastLoginTime8+ | number | No | Last login time of the OS account. | +| lastLoginTime8+ | number | No | Last login time of the OS account. By default, no value is passed. | | serialNumber8+ | number | Yes | SN of the OS account. | | isActived8+ | boolean | Yes | Whether the OS account is activated. | | isCreateCompleted8+ | boolean | Yes | Whether the OS account information is complete. | -| distributedInfo | [distributedAccount.DistributedInfo](js-apis-distributed-account.md) | No | Distributed account information. | -| domainInfo8+ | [DomainAccountInfo](#domainaccountinfo8) | No | Domain account information. | +| distributedInfo | [distributedAccount.DistributedInfo](js-apis-distributed-account.md) | No | Distributed account information. By default, no value is passed. | +| domainInfo8+ | [DomainAccountInfo](#domainaccountinfo8) | No | Domain account information. By default, no value is passed. | ## DomainAccountInfo8+ @@ -6169,7 +6178,7 @@ Defines the domain account information. | ----------- | ------ | ---- | ---------- | | domain | string | Yes | Domain name. | | accountName | string | Yes | Domain account name.| -| accountId10+ | string | No | Domain account ID.
**System API**: This is a system API.| +| accountId10+ | string | No | Domain account ID.
**System API**: It is a system API and is left blank by default.| ## Constraints diff --git a/en/application-dev/reference/apis/js-apis-privacyManager.md b/en/application-dev/reference/apis/js-apis-privacyManager.md index 403d9a6db944073b19a80d1b086e4adc98d8f4dd..505ae1ec5d4c8eaa9f301f1adeaace7adb2173a0 100644 --- a/en/application-dev/reference/apis/js-apis-privacyManager.md +++ b/en/application-dev/reference/apis/js-apis-privacyManager.md @@ -59,7 +59,7 @@ import privacyManager from '@ohos.privacyManager'; let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. try { - privacyManager.addPermissionUsedRecord(tokenID, "ohos.permission.PERMISSION_USED_STATS", 1, 0).then(() => { + privacyManager.addPermissionUsedRecord(tokenID, 'ohos.permission.PERMISSION_USED_STATS', 1, 0).then(() => { console.log('addPermissionUsedRecord success'); }).catch((err) => { console.log(`addPermissionUsedRecord fail, err->${JSON.stringify(err)}`); @@ -88,7 +88,7 @@ The permission usage record includes the application identity (token ID) of the | permissionName | Permissions | Yes | Name of the permission.| | successCount | number | Yes | Number of successful accesses.| | failCount | number | Yes | Number of failed accesses.| -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If a usage record is added successfully, **err** is **undefine**. Otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If a usage record is added successfully, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** @@ -109,7 +109,7 @@ import privacyManager from '@ohos.privacyManager'; let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. try { - privacyManager.addPermissionUsedRecord(tokenID, "ohos.permission.PERMISSION_USED_STATS", 1, 0, (err, data) => { + privacyManager.addPermissionUsedRecord(tokenID, 'ohos.permission.PERMISSION_USED_STATS', 1, 0, (err, data) => { if (err) { console.log(`addPermissionUsedRecord fail, err->${JSON.stringify(err)}`); } else { @@ -161,14 +161,14 @@ For details about the error codes, see [Ability Access Control Error Codes](../e import privacyManager from '@ohos.privacyManager'; let request = { - "tokenId": 1, - "isRemote": false, - "deviceId": "device", - "bundleName": "bundle", - "permissionNames": [], - "beginTime": 0, - "endTime": 1, - "flag":privacyManager.PermissionUsageFlag.FLAG_PERMISSION_USAGE_DETAIL, + 'tokenId': 1, + 'isRemote': false, + 'deviceId': 'device', + 'bundleName': 'bundle', + 'permissionNames': [], + 'beginTime': 0, + 'endTime': 1, + 'flag':privacyManager.PermissionUsageFlag.FLAG_PERMISSION_USAGE_DETAIL, }; try { privacyManager.getPermissionUsedRecord(request).then((data) => { @@ -196,7 +196,7 @@ Obtains historical permission usage records. This API uses an asynchronous callb | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | | request | [PermissionUsedRequest](#permissionusedrequest) | Yes| Request for querying permission usage records.| -| callback | AsyncCallback<[PermissionUsedResponse](#permissionusedresponse)> | Yes| Callback invoked to return the result. If the query is successful, **err** is **undefine** and **data** is the permission usage record. Otherwise, **err** is an error object.| +| callback | AsyncCallback<[PermissionUsedResponse](#permissionusedresponse)> | Yes| Callback invoked to return the result. If the query is successful, **err** is **undefined** and **data** is the permission usage record. Otherwise, **err** is an error object.| **Error codes** @@ -216,14 +216,14 @@ For details about the error codes, see [Ability Access Control Error Codes](../e import privacyManager from '@ohos.privacyManager'; let request = { - "tokenId": 1, - "isRemote": false, - "deviceId": "device", - "bundleName": "bundle", - "permissionNames": [], - "beginTime": 0, - "endTime": 1, - "flag":privacyManager.PermissionUsageFlag.FLAG_PERMISSION_USAGE_DETAIL, + 'tokenId': 1, + 'isRemote': false, + 'deviceId': 'device', + 'bundleName': 'bundle', + 'permissionNames': [], + 'beginTime': 0, + 'endTime': 1, + 'flag':privacyManager.PermissionUsageFlag.FLAG_PERMISSION_USAGE_DETAIL, }; try { privacyManager.getPermissionUsedRecord(request, (err, data) => { @@ -281,7 +281,7 @@ import privacyManager from '@ohos.privacyManager'; let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. try { - privacyManager.startUsingPermission(tokenID, "ohos.permission.PERMISSION_USED_STATS").then(() => { + privacyManager.startUsingPermission(tokenID, 'ohos.permission.PERMISSION_USED_STATS').then(() => { console.log('startUsingPermission success'); }).catch((err) => { console.log(`startUsingPermission fail, err->${JSON.stringify(err)}`); @@ -307,7 +307,7 @@ Starts to use a permission and flushes the permission usage record. This API is | -------------- | --------------------- | ---- | ------------------------------------ | | tokenID | number | Yes | Application token ID of the invoker. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md).| | permissionName | Permissions | Yes | Permission to use. | -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the permission is successfully used, **err** is **undefine**. Otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the permission is successfully used, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** @@ -329,7 +329,7 @@ import privacyManager from '@ohos.privacyManager'; let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. try { - privacyManager.startUsingPermission(tokenID, "ohos.permission.PERMISSION_USED_STATS", (err, data) => { + privacyManager.startUsingPermission(tokenID, 'ohos.permission.PERMISSION_USED_STATS', (err, data) => { if (err) { console.log(`startUsingPermission fail, err->${JSON.stringify(err)}`); } else { @@ -384,7 +384,7 @@ import privacyManager from '@ohos.privacyManager'; let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. try { - privacyManager.stopUsingPermission(tokenID, "ohos.permission.PERMISSION_USED_STATS").then(() => { + privacyManager.stopUsingPermission(tokenID, 'ohos.permission.PERMISSION_USED_STATS').then(() => { console.log('stopUsingPermission success'); }).catch((err) => { console.log(`stopUsingPermission fail, err->${JSON.stringify(err)}`); @@ -410,7 +410,7 @@ Stops using a permission. This API is called by a system application and uses a | -------------- | --------------------- | ---- | ------------------------------------ | | tokenID | number | Yes | Application token ID of the invoker. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md).| | permissionName | Permissions | Yes | Permission to use. | -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefine**. Otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** @@ -432,7 +432,7 @@ import privacyManager from '@ohos.privacyManager'; let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. try { - privacyManager.stopUsingPermission(tokenID, "ohos.permission.PERMISSION_USED_STATS", (err, data) => { + privacyManager.stopUsingPermission(tokenID, 'ohos.permission.PERMISSION_USED_STATS', (err, data) => { if (err) { console.log(`stopUsingPermission fail, err->${JSON.stringify(err)}`); } else { @@ -482,7 +482,7 @@ import privacyManager from '@ohos.privacyManager'; let permissionList = []; try { privacyManager.on('activeStateChange', permissionList, (data) => { - console.debug("receive permission state change, data:" + JSON.stringify(data)); + console.debug('receive permission state change, data:' + JSON.stringify(data)); }); } catch(err) { console.log(`catch err->${JSON.stringify(err)}`); @@ -514,7 +514,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e | ID| Error Message| | -------- | -------- | | 12100001 | The permissionNames in the list are all invalid, or the list size exceeds 1024 bytes. | -| 12100004 | The interface is not used together with "on()".| +| 12100004 | The interface is not used together with 'on'.| | 12100007 | Service is abnormal. | | 12100008 | Out of memory. | @@ -550,14 +550,14 @@ Represents the request for querying permission usage records. | Name | Type | Mandatory | Description | | -------- | -------------- | ---- | ---------------------------------------- | -| tokenId | number | No | Token ID of the application (invoker). | -| isRemote | boolean | No | Whether the token ID belongs to the application on a remote device. The default value is **false**.| -| deviceId | string | No | ID of the device hosting the target application. | -| bundleName | string | No | Bundle name of the target application.| -| permissionNames | Array<Permissions> | No | Permissions to query. | -| beginTime | number | No | Start time of the query, in ms. The default value is **0**, indicating that no start time is set.| -| endTime | number | No | End time of the query, in ms. The default value is **0**, indicating that no end time is set.| -| flag | [PermissionUsageFlag](#permissionusageflag) | Yes | Query mode. The default value is **FLAG_PERMISSION_USAGE_SUMMARY**.| +| tokenId | number | No | Token ID of the application (invoker).
By default, all applications are queried. | +| isRemote | boolean | No | Whether to query the permission usage records of the remote device.
The default value is **false**, which means the permission usage records of the local device are queried by default.| +| deviceId | string | No | ID of the device hosting the target application.
The default value is the local device ID. | +| bundleName | string | No | Bundle name of the target application.
By default, all applications are queried.| +| permissionNames | Array<Permissions> | No | Permissions to query.
By default, the usage records of all permissions are queried. | +| beginTime | number | No | Start time of the query, in ms.
The default value is **0**, which means the start time is not set.| +| endTime | number | No | End time of the query, in ms.
The default value is **0**, which means the end time is not set.| +| flag | [PermissionUsageFlag](#permissionusageflag) | Yes | Query mode.| ## PermissionUsedResponse @@ -567,9 +567,9 @@ Represents the permission usage records of all applications. | Name | Type | Mandatory | Description | | -------- | -------------- | ---- | ---------------------------------------- | -| beginTime | number | No | Start time of the query, in ms.| -| endTime | number | No | End time of the query, in ms.| -| bundleRecords | Array<[BundleUsedRecord](#bundleusedrecord)> | No | Permission usage records. | +| beginTime | number | Yes | Start time of the query, in ms.| +| endTime | number | Yes | End time of the query, in ms.| +| bundleRecords | Array<[BundleUsedRecord](#bundleusedrecord)> | Yes | Permission usage records. | ## BundleUsedRecord @@ -579,11 +579,11 @@ Represents the permission access records of an application. | Name | Type | Mandatory | Description | | -------- | -------------- | ---- | ---------------------------------------- | -| tokenId | number | No | Token ID of the application (invoker). | -| isRemote | boolean | No | Whether the token ID belongs to the application on a remote device. The default value is **false**.| -| deviceId | string | No | ID of the device hosting the target application. | -| bundleName | string | No | Bundle name of the target application.| -| permissionRecords | Array<[PermissionUsedRecord](#permissionusedrecord)> | No | Permission usage records of the target application. | +| tokenId | number | Yes | Token ID of the application (invoker). | +| isRemote | boolean | Yes | Whether the token ID belongs to the application on a remote device. The default value is **false**.| +| deviceId | string | Yes | ID of the device hosting the target application. | +| bundleName | string | Yes | Bundle name of the target application.| +| permissionRecords | Array<[PermissionUsedRecord](#permissionusedrecord)> | Yes | Permission usage records of the target application. | ## PermissionUsedRecord @@ -593,14 +593,14 @@ Represents the usage records of a permission. | Name | Type | Mandatory | Description | | -------- | -------------- | ---- | ---------------------------------------- | -| permissionName | Permissions | No | Name of the permission. | -| accessCount | number | No | Total number of times that the permission is accessed.| -| rejectCount | number | No | Total number of times that the access to the permission is rejected.| -| lastAccessTime | number | No | Last time when the permission was accessed, accurate to ms.| -| lastRejectTime | number | No | Last time when the access to the permission was rejected, accurate to ms.| -| lastAccessDuration | number | No | Last access duration, in ms.| -| accessRecords | Array<[UsedRecordDetail](#usedrecorddetail)> | No | Successful access records. This parameter is valid only when **flag** is **FLAG_PERMISSION_USAGE_SUMMARY**. By default, 10 records are provided. | -| rejectRecords | Array<[UsedRecordDetail](#usedrecorddetail)> | No | Rejected access records. This parameter is valid only when **flag** is **FLAG_PERMISSION_USAGE_SUMMARY**. By default, 10 records are provided. | +| permissionName | Permissions | Yes | Name of the permission. | +| accessCount | number | Yes | Total number of times that the permission is accessed.| +| rejectCount | number | Yes | Total number of times that the access to the permission is rejected.| +| lastAccessTime | number | Yes | Last time when the permission was accessed, accurate to ms.| +| lastRejectTime | number | Yes | Last time when the access to the permission was rejected, accurate to ms.| +| lastAccessDuration | number | Yes | Last access duration, in ms.| +| accessRecords | Array<[UsedRecordDetail](#usedrecorddetail)> | Yes | Successful access records. This parameter is valid only when **flag** is **FLAG_PERMISSION_USAGE_SUMMARY**. By default, 10 records are provided. | +| rejectRecords | Array<[UsedRecordDetail](#usedrecorddetail)> | Yes | Rejected access records. This parameter is valid only when **flag** is **FLAG_PERMISSION_USAGE_SUMMARY**. By default, 10 records are provided. | ## UsedRecordDetail @@ -610,9 +610,9 @@ Represents the details of a single access record. | Name | Type | Mandatory | Description | | -------- | -------------- | ---- | ---------------------------------------- | -| status | number | No | Access status. | -| timestamp | number | No | Access timestamp, in ms.| -| accessDuration | number | No | Access duration, in ms. | +| status | number | Yes | Access status. | +| timestamp | number | Yes | Access timestamp, in ms.| +| accessDuration | number | Yes | Access duration, in ms. | ## PermissionActiveStatus diff --git a/en/application-dev/reference/apis/js-apis-reminderAgent.md b/en/application-dev/reference/apis/js-apis-reminderAgent.md index dc0a33ab0c33f9978b1985e5962067c2f2097cc2..0c7fa19432c45e801f82b2892d47fa9ed384ea4e 100644 --- a/en/application-dev/reference/apis/js-apis-reminderAgent.md +++ b/en/application-dev/reference/apis/js-apis-reminderAgent.md @@ -20,9 +20,7 @@ import reminderAgent from'@ohos.reminderAgent'; ## reminderAgent.publishReminder(deprecated) -```ts publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback\): void -``` Publishes a reminder through the reminder agent. This API uses an asynchronous callback to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8). @@ -39,7 +37,7 @@ Publishes a reminder through the reminder agent. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.| - | callback | AsyncCallback\ | Yes| Callback used to return the published reminder's ID.| + | callback | AsyncCallback\ | Yes| Callback used to return the published reminder's ID.| **Example** ```ts @@ -56,9 +54,7 @@ Publishes a reminder through the reminder agent. This API uses an asynchronous c ## reminderAgent.publishReminder(deprecated) -```ts publishReminder(reminderReq: ReminderRequest): Promise\ -``` Publishes a reminder through the reminder agent. This API uses a promise to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8). @@ -78,7 +74,7 @@ Publishes a reminder through the reminder agent. This API uses a promise to retu **Return value** | Type| Description| | -------- | -------- | - | Promise\ | Promise used to return the published reminder's ID.| + | Promise\ | Promise used to return the published reminder's ID.| **Example** ```ts @@ -95,9 +91,7 @@ Publishes a reminder through the reminder agent. This API uses a promise to retu ## reminderAgent.cancelReminder(deprecated) -```ts cancelReminder(reminderId: number, callback: AsyncCallback\): void -``` Cancels the reminder with the specified ID. This API uses an asynchronous callback to return the cancellation result. @@ -112,7 +106,7 @@ Cancels the reminder with the specified ID. This API uses an asynchronous callba | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | reminderId | number | Yes| ID of the reminder to cancel. The value is obtained by calling [publishReminder](#reminderagentpublishreminder).| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -125,9 +119,7 @@ reminderAgent.cancelReminder(1, (err, data) => { ## reminderAgent.cancelReminder(deprecated) -```ts cancelReminder(reminderId: number): Promise\ -``` Cancels the reminder with the specified ID. This API uses a promise to return the cancellation result. @@ -147,7 +139,7 @@ Cancels the reminder with the specified ID. This API uses a promise to return th | Type| Description| | -------- | -------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Example** @@ -159,9 +151,7 @@ reminderAgent.cancelReminder(1).then(() => { ## reminderAgent.getValidReminders(deprecated) -```ts getValidReminders(callback: AsyncCallback\>): void -``` Obtains all valid (not yet expired) reminders set by the current application. This API uses an asynchronous callback to return the reminders. @@ -175,7 +165,7 @@ Obtains all valid (not yet expired) reminders set by the current application. Th | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback\\> | Yes| Callback used to return an array of all valid reminders set by the current application.| +| callback | AsyncCallback\> | Yes| Callback used to return an array of all valid reminders set by the current application.| **Example** @@ -209,9 +199,7 @@ reminderAgent.getValidReminders((err, reminders) => { ## reminderAgent.getValidReminders(deprecated) -```ts getValidReminders(): Promise\> -``` Obtains all valid (not yet expired) reminders set by the current application. This API uses a promise to return the reminders. @@ -225,7 +213,7 @@ Obtains all valid (not yet expired) reminders set by the current application. Th | Type| Description| | -------- | -------- | -| Promise\\> | Promise used to return an array of all valid reminders set by the current application.| +| Promise\> | Promise used to return an array of all valid reminders set by the current application.| **Example** @@ -259,9 +247,7 @@ reminderAgent.getValidReminders().then((reminders) => { ## reminderAgent.cancelAllReminders(deprecated) -```ts cancelAllReminders(callback: AsyncCallback\): void -``` Cancels all reminders set by the current application. This API uses an asynchronous callback to return the cancellation result. @@ -275,7 +261,7 @@ Cancels all reminders set by the current application. This API uses an asynchron | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback\ | Yes| Callback used to return the result.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -288,9 +274,7 @@ reminderAgent.cancelAllReminders((err, data) =>{ ## reminderAgent.cancelAllReminders(deprecated) -```ts cancelAllReminders(): Promise\ -``` Cancels all reminders set by the current application. This API uses a promise to return the cancellation result. @@ -304,7 +288,7 @@ Cancels all reminders set by the current application. This API uses a promise to | Type| Description| | -------- | -------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Example** @@ -316,9 +300,7 @@ reminderAgent.cancelAllReminders().then(() => { ## reminderAgent.addNotificationSlot(deprecated) -```ts addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback\): void -``` Adds a notification slot. This API uses an asynchronous callback to return the result. @@ -333,7 +315,7 @@ Adds a notification slot. This API uses an asynchronous callback to return the r | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Notification slot, whose type can be set.| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -351,9 +333,7 @@ reminderAgent.addNotificationSlot(mySlot, (err, data) => { ## reminderAgent.addNotificationSlot(deprecated) -```ts addNotificationSlot(slot: NotificationSlot): Promise\ -``` Adds a notification slot. This API uses a promise to return the result. @@ -373,7 +353,7 @@ Adds a notification slot. This API uses a promise to return the result. | Type| Description| | -------- | -------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Example** @@ -391,9 +371,7 @@ reminderAgent.addNotificationSlot(mySlot).then(() => { ## reminderAgent.removeNotificationSlot(deprecated) -```ts removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback): void -``` Removes a notification slot of a specified type. This API uses an asynchronous callback to return the result. @@ -408,7 +386,7 @@ Removes a notification slot of a specified type. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the reminder notification slot to remove.| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -423,9 +401,7 @@ reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION, ## reminderAgent.removeNotificationSlot(deprecated) -```ts removeNotificationSlot(slotType: notification.SlotType): Promise -``` Removes a notification slot of a specified type. This API uses a promise to return the result. @@ -445,7 +421,7 @@ Removes a notification slot of a specified type. This API uses a promise to retu | Type| Description| | -------- | -------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Example** @@ -568,7 +544,6 @@ Defines the reminder to publish. ## ReminderRequestCalendar(deprecated) -ReminderRequestCalendar extends ReminderRequest Defines a reminder for a calendar event. @@ -581,13 +556,12 @@ Defines a reminder for a calendar event. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | dateTime | [LocalDateTime](#localdatetime) | Yes| Reminder time.| -| repeatMonths | Array\ | No| Month in which the reminder repeats.| -| repeatDays | Array\ | No| Date on which the reminder repeats.| +| repeatMonths | Array\ | No| Month in which the reminder repeats.| +| repeatDays | Array\ | No| Date on which the reminder repeats.| ## ReminderRequestAlarm(deprecated) -ReminderRequestAlarm extends ReminderRequest Defines a reminder for an alarm. @@ -601,13 +575,11 @@ Defines a reminder for an alarm. | -------- | -------- | -------- | -------- | | hour | number | Yes| Hour portion of the reminder time.| | minute | number | Yes| Minute portion of the reminder time.| -| daysOfWeek | Array\ | No| Days of a week when the reminder repeats. The value ranges from 1 to 7, corresponding to the data from Monday to Sunday.| +| daysOfWeek | Array\ | No| Days of a week when the reminder repeats. The value ranges from 1 to 7, corresponding to the data from Monday to Sunday.| ## ReminderRequestTimer(deprecated) -ReminderRequestTimer extends ReminderRequest - Defines a reminder for a scheduled timer. > **NOTE** diff --git a/en/application-dev/reference/apis/js-apis-reminderAgentManager.md b/en/application-dev/reference/apis/js-apis-reminderAgentManager.md index 7ec9eeb2c2070acee07603811e0bbd6417590555..87a8ea3167b1cc125eb8e2bf5e30b4cfe54cc5a3 100644 --- a/en/application-dev/reference/apis/js-apis-reminderAgentManager.md +++ b/en/application-dev/reference/apis/js-apis-reminderAgentManager.md @@ -170,7 +170,7 @@ Cancels the reminder with the specified ID. This API uses a promise to return th | Type| Description| | -------- | -------- | -| PPromise\ | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Error codes** @@ -611,7 +611,7 @@ Defines the reminder to publish. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | reminderType | [ReminderType](#remindertype) | Yes| Type of the reminder.| -| actionButton10+ | [ActionButton](#actionbutton) | No| Button displayed for the reminder in the notification panel. For common applications, a maximum of two buttons are supported. For system applications, a maximum of two buttons are supported in API version 9, and a maximum of three buttons are supported in API version 10 and later versions. | +| actionButton10+ | [ActionButton](#actionbutton) | No| Button displayed for the reminder in the notification panel. For common applications, a maximum of two buttons are supported. For system applications, a maximum of two buttons are supported in API version 9, and a maximum of three buttons are supported in API version 10 and later versions.| | wantAgent | [WantAgent](#wantagent) | No| Information about the ability that is redirected to when the reminder is clicked.| | maxScreenWantAgent | [MaxScreenWantAgent](#maxscreenwantagent) | No| Information about the ability that is automatically started when the reminder arrives. If the device is in use, a notification will be displayed.| | ringDuration | number | No| Ringing duration, in seconds. The default value is **1**.| diff --git a/en/application-dev/reference/apis/js-apis-systemSoundManager.md b/en/application-dev/reference/apis/js-apis-systemSoundManager.md new file mode 100644 index 0000000000000000000000000000000000000000..3689684d5d4d547c4ca5b5e8c60f94d7c80cc833 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-systemSoundManager.md @@ -0,0 +1,268 @@ +# @ohos.multimedia.systemSoundManager (System Sound Management) + +The **systemSoundManager** module provides basic capabilities for managing system sounds, including setting and obtaining system ringtones and obtaining a player to play the system ringtone. + +> **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. +> +> The APIs provided by this module are system APIs. + +## Modules to Import + +```js +import systemSoundManager from '@ohos.multimedia.systemSoundManager'; +``` + +## RingtoneType + +Enumerates the ringtone types. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.SystemSound.Core + +| Name | Value | Description | +| ------------------------------- | ------ | -------------------------------------------- | +| RINGTONE_TYPE_DEFAULT | 0 | Default ringtone type. | +| RINGTONE_TYPE_MULTISIM | 1 | Multi-SIM ringtone type. | + +## systemSoundManager.getSystemSoundManager + +getSystemSoundManager(): SystemSoundManager + +Obtains a system sound manager. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.SystemSound.Core + +**Return value** + +| Type | Description | +| ----------------------------- | ------------ | +| [SystemSoundManager](#systemsoundmanager) | System sound manager obtained.| + +**Example** +```js +let systemSoundManagerInstance = systemSoundManager.getSystemSoundManager(); +``` + +## SystemSoundManager + +Provides APIs to manage system sounds. Before calling any API in **SystemSoundManager**, you must use [getSystemSoundManager](#systemsoundmanagergetsystemsoundmanager) to create a **SystemSoundManager** instance. + +### setSystemRingtoneUri + +setSystemRingtoneUri(context: Context, uri: string, type: RingtoneType, callback: AsyncCallback<void>): void + +Sets a URI for the system ringtone. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.SystemSound.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------- | ---- | ------------------------ | +| context | Context | Yes | Application context. | +| uri | string | Yes | URI of the system ringtone. For details, see [media.AVPlayer](js-apis-media.md#avplayer9).| +| type | [RingtoneType](#ringtonetype) | Yes | Type of the system ringtone. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +let context = this.context; +let uri = 'file://data/test.wav'; // Set the URI of the target ringtone file. +let type = systemSoundManager.RingtoneType.RINGTONE_TYPE_DEFAULT; + +systemSoundManagerInstance.setSystemRingtoneUri(context, uri, type, (err) => { + if (err) { + console.error(`Failed to set system ringtone uri. ${err}`); + return; + } + console.info(`Callback invoked to indicate a successful setting of the system ringtone uri.`); +}); +``` + +### setSystemRingtoneUri + +setSystemRingtoneUri(context: Context, uri: string, type: RingtoneType): Promise<void> + +Sets a URI for the system ringtone. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.SystemSound.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------- | ---- | ------------------------ | +| context | Context | Yes | Application context. | +| uri | string | Yes | URI of the system ringtone. For details, see [media.AVPlayer](js-apis-media.md#avplayer9).| +| type | [RingtoneType](#ringtonetype) | Yes | Type of the system ringtone. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------- | +| Promise<void> | Promise used to return the result. | + +**Example** + +```js +let context = this.context; +let uri = 'file://data/test.wav'; // Set the URI of the target ringtone file. +let type = systemSoundManager.RingtoneType.RINGTONE_TYPE_DEFAULT; + +systemSoundManagerInstance.setSystemRingtoneUri(context, uri, type).then(() => { + console.info(`Promise returned to indicate a successful setting of the system ringtone uri.`); +}).catch ((err) => { + console.error(`Failed to set the system ringtone uri ${err}`); +}); +``` + +### getSystemRingtoneUri + +getSystemRingtoneUri(context: Context, type: RingtoneType, callback: AsyncCallback<string>): void + +Obtains the URI of a system ringtone. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.SystemSound.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------- | ---- | ------------------------ | +| context | Context | Yes | Application context. | +| type | [RingtoneType](#ringtonetype) | Yes | Type of the system ringtone. | +| callback | AsyncCallback<string> | Yes | Callback used to return the ringtone URI obtained.| + +**Example** + +```js +let context = this.context; +let type = systemSoundManager.RingtoneType.RINGTONE_TYPE_DEFAULT; + +systemSoundManagerInstance.getSystemRingtoneUri(context, type, (err, value) => { + if (err) { + console.error(`Failed to get system ringtone uri. ${err}`); + return; + } + console.info(`Callback invoked to indicate the value of the system ringtone uri is obtained ${value}.`); +}); +``` + +### getSystemRingtoneUri + +getSystemRingtoneUri(context: Context, type: RingtoneType): Promise<string> + +Obtains the URI of a system ringtone. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.SystemSound.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------- | ---- | ------------------------ | +| context | Context | Yes | Application context. | +| type | [RingtoneType](#ringtonetype) | Yes | Type of the system ringtone. | + +**Return value** + +| Type | Description | +| ------------------- | ---------------------------------- | +| Promise<string> | Promise used to return the ringtone URI obtained.| + +**Example** + +```js +let context = this.context; +let type = systemSoundManager.RingtoneType.RINGTONE_TYPE_DEFAULT; + +systemSoundManagerInstance.getSystemRingtoneUri(context, type).then((value) => { + console.info(`Promise returned to indicate that the value of the system ringtone uri is obtained ${value}.`); +}).catch ((err) => { + console.error(`Failed to get the system ringtone uri ${err}`); +}); +``` + +### getSystemRingtonePlayer + +getSystemRingtonePlayer(context: Context, type: RingtoneType, callback: AsyncCallback<RingtonePlayer>): void + +Obtains a player to play the system ringtone. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.SystemSound.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -----------------------------------------| ---- | --------------------------- | +| context | Context | Yes | Application context. | +| type | [RingtoneType](#ringtonetype) | Yes | Type of the system ringtone.| +| callback | AsyncCallback<[RingtonePlayer](js-apis-inner-multimedia-ringtonePlayer.md#ringtoneplayer)> | Yes| Callback used to return the ringtone player obtained.| + +**Example** + +```js +let context = this.context; +let type = systemSoundManager.RingtoneType.RINGTONE_TYPE_DEFAULT; +let systemRingtonePlayer = null; + +systemSoundManagerInstance.getSystemRingtonePlayer(context, type, (err, value) => { + if (err) { + console.error(`Failed to get system ringtone player. ${err}`); + return; + } + console.info(`Callback invoked to indicate the value of the system ringtone player is obtained.`); + systemRingtonePlayer = value; +}); +``` + +### getSystemRingtonePlayer + +getSystemRingtonePlayer(context: Context, type: RingtoneType): Promise<RingtonePlayer> + +Obtains a player to play the system ringtone. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.SystemSound.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -----------------------------------------| ---- | --------------------------- | +| context | Context | Yes | Application context. | +| type | [RingtoneType](#ringtonetype) | Yes | Type of the system ringtone.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------- | +| Promise<[RingtonePlayer](js-apis-inner-multimedia-ringtonePlayer.md#ringtoneplayer)> | Promise used to return the ringtone player obtained.| + +**Example** + +```js +let context = this.context; +let type = systemSoundManager.RingtoneType.RINGTONE_TYPE_DEFAULT; +let systemRingtonePlayer = null; + +systemSoundManagerInstance.getSystemRingtonePlayer(context, type).then((value) => { + console.info(`Promise returned to indicate that the value of the system ringtone player is obtained.`); + systemRingtonePlayer = value; +}).catch ((err) => { + console.error(`Failed to get the system ringtone player ${err}`); +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-taskpool.md b/en/application-dev/reference/apis/js-apis-taskpool.md index 4eb81b7153748544ead741b01fb8d3cdb334ea93..6de1a67d7af88229266bbdac7a4adb853479bb03 100644 --- a/en/application-dev/reference/apis/js-apis-taskpool.md +++ b/en/application-dev/reference/apis/js-apis-taskpool.md @@ -1,10 +1,10 @@ -# @ohos.taskpool (Using the Task Pool) +# @ohos.taskpool (Starting the Task Pool) The task pool provides a multi-thread running environment for applications. It helps reduce resource consumption and improve system performance. It also frees you from caring about the lifecycle of thread instances. You can use the **TaskPool** APIs to create background tasks and perform operations on them, for example, executing or canceling a task. Theoretically, you can create an unlimited number of tasks, but this is not recommended for memory considerations. In addition, you are not advised performing blocking operations in a task, especially indefinite blocking. Long-time blocking operations occupy worker threads and may block other task scheduling, adversely affecting your application performance. -You can determine the execution sequence of tasks with the same priority. They are executed in the same sequence as you call the task execution APIs. The default task priority is **MEDIUM**. (The task priority mechanism is not supported yet.) +You can determine the execution sequence of tasks with the same priority. They are executed in the same sequence as you call the task execution APIs. The default task priority is **MEDIUM**. -If the number of tasks to be executed is greater than the number of worker threads in the task pool, the task pool scales out based on load balancing to minimize the waiting duration. Similarly, when the number of tasks to be executed falls below the number of worker threads, the task pool scales in to reduce the number of worker threads. (The load balancing mechanism is not supported yet.) +If the number of tasks to be executed is greater than the number of worker threads in the task pool, the task pool scales out based on load balancing to minimize the waiting duration. Similarly, when the number of tasks to be executed falls below the number of worker threads, the task pool scales in to reduce the number of worker threads. The **TaskPool** APIs return error codes in numeric format. For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). @@ -32,13 +32,13 @@ Enumerates the priorities available for created tasks. **Example** ```ts -function func(args) { - "use concurrent"; - console.log("func: " + args); +@Concurrent +function printArgs(args) { + console.log("printArgs: " + args); return args; } -async function taskpoolTest() { - let task = new taskpool.Task(func, 100); +async function taskpoolPriority() { + let task = new taskpool.Task(printArgs, 100); let highCount = 0; let mediumCount = 0; @@ -65,7 +65,7 @@ async function taskpoolTest() { }) } } -taskpoolTest(); +taskpoolPriority(); ``` ## Task @@ -99,12 +99,12 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco ```ts @Concurrent -function func(args) { - console.log("func: " + args); +function printArgs(args) { + console.log("printArgs: " + args); return args; } -let task = new taskpool.Task(func, "this is my first Task"); +let task = new taskpool.Task(printArgs, "this is my first Task"); ``` ### Attributes @@ -151,17 +151,17 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco ```ts @Concurrent -function func(args) { - console.log("func: " + args); +function printArgs(args) { + console.log("printArgs: " + args); return args; } -async function taskpoolTest() { - let value = await taskpool.execute(func, 100); +async function taskpoolExecute() { + let value = await taskpool.execute(printArgs, 100); console.log("taskpool result: " + value); } -taskpoolTest(); +taskpoolExecute(); ``` ## taskpool.execute @@ -199,18 +199,18 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco ```ts @Concurrent -function func(args) { - console.log("func: " + args); +function printArgs(args) { + console.log("printArgs: " + args); return args; } -async function taskpoolTest() { - let task = new taskpool.Task(func, 100); +async function taskpoolExecute() { + let task = new taskpool.Task(printArgs, 100); let value = await taskpool.execute(task); console.log("taskpool result: " + value); } -taskpoolTest(); +taskpoolExecute(); ``` ## taskpool.cancel @@ -239,14 +239,14 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example of successful task cancellation** ```ts -function func(args) { - "use concurrent"; - console.log("func: " + args); +@Concurrent +function printArgs(args) { + console.log("printArgs: " + args); return args; } -async function taskpoolTest() { - let task = new taskpool.Task(func, 100); +async function taskpoolCancel() { + let task = new taskpool.Task(printArgs, 100); taskpool.execute(task); try { taskpool.cancel(task); @@ -255,20 +255,20 @@ async function taskpoolTest() { } } -taskpoolTest(); +taskpoolCancel(); ``` **Example of a failure to cancel a task that has been executed** ```ts -function func(args) { - "use concurrent"; - console.log("func: " + args); +@Concurrent +function printArgs(args) { + console.log("printArgs: " + args); return args; } -async function taskpoolTest() { - let task = new taskpool.Task(func, 100); +async function taskpoolCancel() { + let task = new taskpool.Task(printArgs, 100); let value = taskpool.execute(task); let start = new Date().getTime(); while (new Date().getTime() - start < 1000) {// Wait for 1s to ensure that the task has been executed. @@ -282,25 +282,25 @@ async function taskpoolTest() { } } -taskpoolTest(); +taskpoolCancel(); ``` **Example of a failure to cancel an ongoing task** ```ts -function func(args) { - "use concurrent"; - console.log("func: " + args); +@Concurrent +function printArgs(args) { + console.log("printArgs: " + args); return args; } -async function taskpoolTest() { - let task1 = new taskpool.Task(func, 100); - let task2 = new taskpool.Task(func, 200); - let task3 = new taskpool.Task(func, 300); - let task4 = new taskpool.Task(func, 400); - let task5 = new taskpool.Task(func, 500); - let task6 = new taskpool.Task(func, 600); +async function taskpoolCancel() { + let task1 = new taskpool.Task(printArgs, 100); + let task2 = new taskpool.Task(printArgs, 200); + let task3 = new taskpool.Task(printArgs, 300); + let task4 = new taskpool.Task(printArgs, 400); + let task5 = new taskpool.Task(printArgs, 500); + let task6 = new taskpool.Task(printArgs, 600); let res1 = taskpool.execute(task1); let res2 = taskpool.execute(task2); @@ -315,7 +315,7 @@ async function taskpoolTest() { } } -taskpoolTest(); +taskpoolCancel(); ``` ## Additional Information @@ -327,7 +327,7 @@ The following sequenceable data types are supported: All Primitive Type (excludi - The task pool APIs can be used only in the module with **compileMode** set to **esmodule** in the stage model. To check the **compileMode** setting of a module, open the **build-profile.json5** file of the module and check for **"compileMode": "esmodule"** under **buildOption**. - A task in the task pool can reference only variables passed in by input parameters or imported variables, rather than closure variables. The decorator **@Concurrent** is used to intercept unsupported variables. - A task in the task pool supports only common functions or async functions, rather than class member functions or anonymous functions. The decorator **@Concurrent** is used to intercept unsupported functions. -- The decorator **@Concurrent** can be used only in the .ets file. To create a task in the task pool in the .ts file, use the statement **use concurrent**. +- The decorator **@Concurrent** can be used only in .ets files. ### Using the Task Pool in Simple Mode @@ -336,23 +336,23 @@ The following sequenceable data types are supported: All Primitive Type (excludi ```ts // Common functions are supported, and variables passed in by input parameters are also supported. @Concurrent -function func(args) { +function printArgs(args) { console.log("func: " + args); return args; } -async function taskpoolTest() { +async function taskpoolExecute() { // taskpool.execute(task) - let task = new taskpool.Task(func, "create task, then execute"); + let task = new taskpool.Task(printArgs, "create task, then execute"); let val1 = await taskpool.execute(task); console.log("taskpool.execute(task) result: " + val1); // taskpool.execute(function) - let val2 = await taskpool.execute(func, "execute task by func"); + let val2 = await taskpool.execute(printArgs, "execute task by func"); console.log("taskpool.execute(function) result: " + val2); } -taskpoolTest(); +taskpoolExecute(); ``` **Example 2** @@ -367,24 +367,24 @@ export var c = 2000; import { c } from "./b"; @Concurrent -function test(a) { +function printArgs(a) { console.log(a); console.log(c); return a; } -async function taskpoolTest() { +async function taskpoolExecute() { // taskpool.execute(task) - let task = new taskpool.Task(test, "create task, then execute"); + let task = new taskpool.Task(printArgs, "create task, then execute"); let val1 = await taskpool.execute(task); console.log("taskpool.execute(task) result: " + val1); // taskpool.execute(function) - let val2 = await taskpool.execute(test, "execute task by func"); + let val2 = await taskpool.execute(printArgs, "execute task by func"); console.log("taskpool.execute(function) result: " + val2); } -taskpoolTest(); +taskpoolExecute(); ``` **Example 3** @@ -392,57 +392,52 @@ taskpoolTest(); ```ts // The async functions are supported. @Concurrent -async function task() { +async function delayExcute() { let ret = await Promise.all([ new Promise(resolve => setTimeout(resolve, 1000, "resolved")) ]); return ret; } -async function taskpoolTest() { - taskpool.execute(task).then((result) => { +async function taskpoolExecute() { + taskpool.execute(delayExcute).then((result) => { console.log("TaskPoolTest task result: " + result); }); } -taskpoolTest(); +taskpoolExecute(); ``` **Example 4** ```ts -// Use use concurrent to create a task in the task pool in the .ts file. -// c.ts -function test1(n) { - "use concurrent" - return n; +// c.ets +@Concurrent +function strSort(inPutArr) { + let newArr = inPutArr.sort(); + return newArr; } -export async function taskpoolTest1() { - console.log("taskpoolTest1 start"); - var task = new taskpool.Task(test1, 100); +export async function func1() { + console.log("taskpoolTest start"); + let strArray = ['c test string', 'b test string', 'a test string']; + var task = new taskpool.Task(strSort, strArray); var result = await taskpool.execute(task); - console.log("taskpoolTest1 result:" + result); + console.log("func1 result:" + result); } -async function test2() { - "use concurrent" - var ret = await Promise.all([ - new Promise(resolve => setTimeout(resolve, 1000, "resolved")) - ]); - return ret; -} -export async function taskpoolTest2() { +export async function func2() { console.log("taskpoolTest2 start"); - taskpool.execute(test2).then((result) => { - console.log("TaskPoolTest2 result: " + result); + let strArray = ['c test string', 'b test string', 'a test string']; + taskpool.execute(strSort, strArray).then((result) => { + console.log("func2 result: " + result); }); } ``` ```ts -/ / a.ets (in the same directory as c.ts) +/ / a.ets (in the same directory as c.ets) import { taskpoolTest1, taskpoolTest2 } from "./c"; -taskpoolTest1(); -taskpoolTest2(); +func1(); +func2(); ``` diff --git a/en/application-dev/reference/apis/js-apis-wifi.md b/en/application-dev/reference/apis/js-apis-wifi.md index 9eb6f28a9880ada20a1a5c6bce2bac006a6efd5f..76f27aa775302ff5d313d17f664401b6364e25b9 100644 --- a/en/application-dev/reference/apis/js-apis-wifi.md +++ b/en/application-dev/reference/apis/js-apis-wifi.md @@ -31,6 +31,17 @@ Enables WLAN. | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Example** + +```js +import wifi from '@ohos.wifi'; + +try { + wifi.enableWifi(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.disableWifi @@ -50,6 +61,18 @@ Disables WLAN. | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Example** + +```js +import wifi from '@ohos.wifi'; + +try { + wifi.disableWifi(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} + +``` ## wifi.isWifiActive @@ -67,6 +90,18 @@ Checks whether WLAN is enabled. | -------- | -------- | | boolean | Returns **true** if WLAN is enabled; returns **false** otherwise.| +**Example** + +```js +import wifi from '@ohos.wifi'; + +try { + let isActivate = wifi.isActivate(); + console.info("isActivate:" + isActivate); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.scan @@ -84,6 +119,17 @@ Starts a scan for WLAN. | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Example** + +```js +import wifi from '@ohos.wifi'; + +try { + wifi.scan(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.getScanInfos @@ -119,46 +165,47 @@ Obtains the scan result. This API uses an asynchronous callback to return the re | callback | AsyncCallback< Array<[WifiScanInfo](#wifiscaninfo)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the detected hotspots. Otherwise, **err** is a non-zero value and **data** is empty.| **Example** - ```js - import wifi from '@ohos.wifi'; - - wifi.getScanInfos((err, result) => { - if (err) { - console.error("get scan info error"); - return; - } - - var len = Object.keys(result).length; - console.log("wifi received scan info: " + len); - for (var i = 0; i < len; ++i) { - console.info("ssid: " + result[i].ssid); - console.info("bssid: " + result[i].bssid); - console.info("capabilities: " + result[i].capabilities); - console.info("securityType: " + result[i].securityType); - console.info("rssi: " + result[i].rssi); - console.info("band: " + result[i].band); - console.info("frequency: " + result[i].frequency); - console.info("channelWidth: " + result[i].channelWidth); - console.info("timestamp: " + result[i].timestamp); - } - }); - - wifi.getScanInfos().then(result => { - var len = Object.keys(result).length; - console.log("wifi received scan info: " + len); - for (var i = 0; i < len; ++i) { - console.info("ssid: " + result[i].ssid); - console.info("bssid: " + result[i].bssid); - console.info("capabilities: " + result[i].capabilities); - console.info("securityType: " + result[i].securityType); - console.info("rssi: " + result[i].rssi); - console.info("band: " + result[i].band); - console.info("frequency: " + result[i].frequency); - console.info("channelWidth: " + result[i].channelWidth); - console.info("timestamp: " + result[i].timestamp); - } - }); - ``` + +```js +import wifi from '@ohos.wifi'; + +wifi.getScanInfos((err, result) => { + if (err) { + console.error("get scan info error"); + return; + } + + var len = Object.keys(result).length; + console.log("wifi received scan info: " + len); + for (var i = 0; i < len; ++i) { + console.info("ssid: " + result[i].ssid); + console.info("bssid: " + result[i].bssid); + console.info("capabilities: " + result[i].capabilities); + console.info("securityType: " + result[i].securityType); + console.info("rssi: " + result[i].rssi); + console.info("band: " + result[i].band); + console.info("frequency: " + result[i].frequency); + console.info("channelWidth: " + result[i].channelWidth); + console.info("timestamp: " + result[i].timestamp); + } +}); + +wifi.getScanInfos().then(result => { + var len = Object.keys(result).length; + console.log("wifi received scan info: " + len); + for (var i = 0; i < len; ++i) { + console.info("ssid: " + result[i].ssid); + console.info("bssid: " + result[i].bssid); + console.info("capabilities: " + result[i].capabilities); + console.info("securityType: " + result[i].securityType); + console.info("rssi: " + result[i].rssi); + console.info("band: " + result[i].band); + console.info("frequency: " + result[i].frequency); + console.info("channelWidth: " + result[i].channelWidth); + console.info("timestamp: " + result[i].timestamp); + } +}); +``` ## WifiScanInfo @@ -238,6 +285,25 @@ Adds network configuration. This API uses a promise to return the result. | -------- | -------- | | Promise<number> | Promise used to return the WLAN configuration ID. If **-1** is returned, the network configuration fails to be added.| + **Example** + +```js +import wifi from '@ohos.wifi'; + +try { + let config = { + ssid : "****", + preSharedKey : "****", + securityType : 0 + } + wifi.addDeviceConfig(config).then(result => { + console.info("result:" + JSON.stringify(result)); + }); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` + ## WifiDeviceConfig Represents the WLAN configuration. @@ -252,13 +318,13 @@ Represents the WLAN configuration. | preSharedKey | string | Yes| No| PSK of the hotspot.| | isHiddenSsid | boolean | Yes| No| Whether the network is hidden.| | securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| Security type.| -| creatorUid | number | Yes| No| ID of the creator.
**System API**: This is a system API.| -| disableReason | number | Yes| No| Reason for disabling WLAN.
**System API**: This is a system API.| -| netId | number | Yes| No| Network ID.
**System API**: This is a system API.| -| randomMacType | number | Yes| No| Random MAC type.
**System API**: This is a system API.| -| randomMacAddr | string | Yes| No| Random MAC address.
**System API**: This is a system API.| -| ipType | [IpType](#iptype7) | Yes| No| IP address type.
**System API**: This is a system API.| -| staticIp | [IpConfig](#ipconfig7) | Yes| No| Static IP address configuration.
**System API**: This is a system API.| +| creatorUid | number | Yes| No| ID of the creator.
**System API**: This is a system API.| +| disableReason | number | Yes| No| Reason for disabling WLAN.
**System API**: This is a system API.| +| netId | number | Yes| No| Network ID.
**System API**: This is a system API.| +| randomMacType | number | Yes| No| Random MAC type.
**System API**: This is a system API.| +| randomMacAddr | string | Yes| No| Random MAC address.
**System API**: This is a system API.| +| ipType | [IpType](#iptype7) | Yes| No| IP address type.
**System API**: This is a system API.| +| staticIp | [IpConfig](#ipconfig7) | Yes| No| Static IP address configuration.
**System API**: This is a system API.| ## IpType7+ @@ -312,7 +378,24 @@ Adds network configuration. This API uses an asynchronous callback to return the | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| | callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| +**Example** + +```js +import wifi from '@ohos.wifi'; +try { + let config = { + ssid : "****", + preSharedKey : "****", + securityType : 0 + } + wifi.addDeviceConfig(config,(error,result) => { + console.info("result:" + JSON.stringify(result)); + }); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.addUntrustedConfig7+ addUntrustedConfig(config: WifiDeviceConfig): Promise<boolean> @@ -335,6 +418,23 @@ Adds the configuration of an untrusted network. This API uses a promise to retur | -------- | -------- | | Promise<boolean> | Promise used to return the result. If the operation is successful, **true** is returned; otherwise, **false** is returned.| +**Example** +```js +import wifi from '@ohos.wifi'; + +try { + let config = { + ssid : "****", + preSharedKey : "****", + securityType : 0 + } + wifi.addUntrustedConfig(config).then(result => { + console.info("result:" + JSON.stringify(result)); + }); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.addUntrustedConfig7+ @@ -353,6 +453,23 @@ Adds the configuration of an untrusted network. This API uses an asynchronous ca | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| | callback | AsyncCallback<boolean> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is **true**. If the operation fails, **data** is **false**. If **err** is not **0**, an error has occurred.| +**Example** +```js +import wifi from '@ohos.wifi'; + +try { + let config = { + ssid : "****", + preSharedKey : "****", + securityType : 0 + } + wifi.addUntrustedConfig(config,(error,result) => { + console.info("result:" + JSON.stringify(result)); + }); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.removeUntrustedConfig7+ @@ -376,6 +493,21 @@ Removes the configuration of an untrusted network. This API uses a promise to re | -------- | -------- | | Promise<boolean> | Promise used to return the result. If the operation is successful, **true** is returned; otherwise, **false** is returned.| +**Example** + +```js +import wifi from '@ohos.wifi'; + +try { + let networkId = 0; + wifi.removeUntrustedConfig(networkId).then(result => { + console.info("result:" + JSON.stringify(result)); + }); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` + ## wifi.removeUntrustedConfig7+ @@ -394,6 +526,19 @@ Removes the configuration of an untrusted network. This API uses an asynchronous | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to remove.| | callback | AsyncCallback<boolean> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is **true**. If the operation fails, **data** is **false**. If **err** is not **0**, an error has occurred.| +**Example** +```js +import wifi from '@ohos.wifi'; + +try { + let networkId = 0; + wifi.removeUntrustedConfig(networkId,(error,result) => { + console.info("result:" + JSON.stringify(result)); + }); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.connectToNetwork @@ -419,6 +564,18 @@ Connects to the specified network. | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Example** + +```js +import wifi from '@ohos.wifi'; + +try { + let networkId = 0; + wifi.connectToNetwork(networkId); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.connectToDevice @@ -445,6 +602,22 @@ Connects to the specified network. | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Example** +```js +import wifi from '@ohos.wifi'; + +try { + let config = { + ssid : "****", + preSharedKey : "****", + securityType : 3 + } + wifi.connectToDevice(config); + +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.disconnect @@ -465,6 +638,16 @@ Disconnects the network. | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Example** +```js +import wifi from '@ohos.wifi'; + +try { + wifi.disconnect(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.getSignalLevel @@ -489,6 +672,20 @@ Obtains the WLAN signal level. | -------- | -------- | | number | Signal level obtained. The value range is [0, 4].| +**Example** +```js +import wifi from '@ohos.wifi'; + +try { + let rssi = 0; + let band = 0; + let level = wifi.getSignalLevel(rssi,band); + console.info("lelvel:" + JSON.stringify(lelvel)); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} + +``` ## wifi.getLinkedInfo @@ -524,23 +721,23 @@ Obtains WLAN connection information. This API uses an asynchronous callback to r | callback | AsyncCallback<[WifiLinkedInfo](#wifilinkedinfo)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the WLAN connection information obtained. If **err** is not **0**, an error has occurred.| **Example** - ```js - import wifi from '@ohos.wifi'; - - wifi.getLinkedInfo((err, data) => { - if (err) { - console.error("get linked info error"); - return; - } - console.info("get wifi linked info: " + JSON.stringify(data)); - }); - - wifi.getLinkedInfo().then(data => { - console.info("get wifi linked info: " + JSON.stringify(data)); - }).catch(error => { - console.info("get linked info error"); - }); - ``` +```js +import wifi from '@ohos.wifi'; + +wifi.getLinkedInfo((err, data) => { + if (err) { + console.error("get linked info error"); + return; + } + console.info("get wifi linked info: " + JSON.stringify(data)); +}); + +wifi.getLinkedInfo().then(data => { + console.info("get wifi linked info: " + JSON.stringify(data)); +}).catch(error => { + console.info("get linked info error"); +}); +``` ## WifiLinkedInfo @@ -553,18 +750,18 @@ Represents the WLAN connection information. | -------- | -------- | -------- | -------- | -------- | | ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.| | bssid | string | Yes| No| BSSID of the hotspot.| -| networkId | number | Yes| No| Network configuration ID.
**System API**: This is a system API.| +| networkId | number | Yes| No| Network configuration ID.
**System API**: This is a system API.| | rssi | number | Yes| No| RSSI of the hotspot, in dBm.| | band | number | Yes| No| Frequency band of the WLAN AP.| | linkSpeed | number | Yes| No| Speed of the WLAN AP.| | frequency | number | Yes| No| Frequency of the WLAN AP.| | isHidden | boolean | Yes| No| Whether to hide the WLAN AP.| | isRestricted | boolean | Yes| No| Whether to restrict data volume at the WLAN AP.| -| chload | number | Yes| No| Channel load. A larger value indicates a higher load.
**System API**: This is a system API.| -| snr | number | Yes| No| Signal-to-noise ratio (SNR).
**System API**: This is a system API.| +| chload | number | Yes| No| Channel load. A larger value indicates a higher load.
**System API**: This is a system API.| +| snr | number | Yes| No| Signal-to-noise ratio (SNR).
**System API**: This is a system API.| | macAddress | string | Yes| No| MAC address of the device.| | ipAddress | number | Yes| No| IP address of the device that sets up the WLAN connection.| -| suppState | [SuppState](#suppstate) | Yes| No| Supplicant state.
**System API**: This is a system API.| +| suppState | [SuppState](#suppstate) | Yes| No| Supplicant state.
**System API**: This is a system API.| | connState | [ConnState](#connstate) | Yes| No| WLAN connection state.| @@ -684,6 +881,19 @@ Checks whether the device supports the specified WLAN feature. | -------- | -------- | | boolean | Returns **true** if the feature is supported; returns **false** otherwise.| +**Example** +```js +import wifi from '@ohos.wifi'; + +try { + let featureId = 0; + let ret = wifi.isFeatureSupported(featureId); + console.info("isFeatureSupported:" + ret); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} + +``` ## wifi.getDeviceMacAddress7+ @@ -703,6 +913,18 @@ Obtains the device MAC address. | -------- | -------- | | string[] | MAC address obtained.| +**Example** +```js +import wifi from '@ohos.wifi'; + +try { + let ret = wifi.getDeviceMacAddress(); + console.info("deviceMacAddress:" + JSON.stringify(ret)); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} + +``` ## wifi.getIpInfo7+ @@ -720,6 +942,17 @@ Obtains IP information. | -------- | -------- | | [IpInfo](#ipinfo7) | IP information obtained.| +**Example** +```js +import wifi from '@ohos.wifi'; + +try { + let info = wifi.getIpInfo(); + console.info("info:" + JSON.stringify(info)); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## IpInfo7+ @@ -754,6 +987,17 @@ Obtains the country code. | -------- | -------- | | string | Country code obtained.| +**Example** +```js +import wifi from '@ohos.wifi'; + +try { + let code = wifi.getCountryCode(); + console.info("code:" + code); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.reassociate7+ @@ -773,6 +1017,16 @@ Re-associates with the network. | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Example** +```js +import wifi from '@ohos.wifi'; + +try { + wifi.reassociate(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.reconnect7+ @@ -792,6 +1046,16 @@ Reconnects to the network. | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Example** +```js +import wifi from '@ohos.wifi'; + +try { + wifi.reconnect(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.getDeviceConfigs7+ @@ -811,6 +1075,17 @@ Obtains network configuration. | -------- | -------- | |  Array<[WifiDeviceConfig](#wifideviceconfig)> | Array of network configuration obtained.| +**Example** +```js +import wifi from '@ohos.wifi'; + +try { + let configs = wifi.getDeviceConfigs(); + console.info("configs:" + JSON.stringify(configs)); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.updateNetwork7+ @@ -836,6 +1111,22 @@ Updates network configuration. | -------- | -------- | | number | ID of the updated network configuration. The value **-1** indicates that the operation has failed.| +**Example** +```js +import wifi from '@ohos.wifi'; + +try { + let config = { + ssid : "****", + preSharedKey : "****", + securityType : 3 + } + let ret = wifi.updateNetwork(config); + console.error("ret:" + ret); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.disableNetwork7+ @@ -861,6 +1152,17 @@ Disables network configuration. | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Example** +```js +import wifi from '@ohos.wifi'; + +try { + let netId = 0; + wifi.disableNetwork(netId); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.removeAllNetwork7+ @@ -880,6 +1182,16 @@ Removes the configuration of all networks. | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Example** +```js +import wifi from '@ohos.wifi'; + +try { + wifi.removeAllNetwork(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.removeDevice7+ @@ -905,6 +1217,17 @@ Removes the specified network configuration. | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Example** +```js +import wifi from '@ohos.wifi'; + +try { + let id = 0; + wifi.removeDevice(id); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.enableHotspot7+ @@ -924,6 +1247,16 @@ Enables this hotspot. | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Example** +```js +import wifi from '@ohos.wifi'; + +try { + wifi.enableHotspot(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.disableHotspot7+ @@ -943,6 +1276,16 @@ Disables this hotspot. | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Example** +```js +import wifi from '@ohos.wifiManager'; + +try { + wifiManager.disableHotspot(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.isHotspotDualBandSupported7+ @@ -962,6 +1305,17 @@ Checks whether the hotspot supports dual band. | -------- | -------- | | boolean | Returns **true** if the feature is supported; returns **false** otherwise.| +**Example** +```js +import wifi from '@ohos.wifi'; + +try { + let ret = wifi.isHotspotDualBandSupported(); + console.info("result:" + ret); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.isHotspotActive7+ @@ -981,6 +1335,17 @@ Checks whether this hotspot is active. | -------- | -------- | | boolean | Returns **true** if the hotspot is active; returns **false** otherwise.| +**Example** +```js +import wifi from '@ohos.wifi'; + +try { + let ret = wifi.isHotspotActive(); + console.info("result:" + ret); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.setHotspotConfig7+ @@ -1006,6 +1371,25 @@ Sets hotspot configuration. | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Example** +```js +import wifi from '@ohos.wifi'; + +try { + let config = { + ssid: "****", + securityType: 3, + band: 0, + channel: 0, + preSharedKey: "****", + maxConn: 0 + } + let ret = wifi.setHotspotConfig(); + console.info("result:" + ret); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## HotspotConfig7+ @@ -1042,6 +1426,17 @@ obtains hotspot configuration. | -------- | -------- | | [HotspotConfig](#hotspotconfig7) | Hotspot configuration obtained.| +**Example** +```js +import wifi from '@ohos.wifi'; + +try { + let config = wifi.getHotspotConfig(); + console.info("result:" + JSON.stringify(config)); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.getStations7+ @@ -1061,6 +1456,17 @@ Obtains information about the connected stations. | -------- | -------- | |  Array<[StationInfo](#stationinfo7)> | Connected stations obtained.| +**Example** +```js +import wifi from '@ohos.wifi'; + +try { + let stations = wifi.getStations(); + console.info("result:" + JSON.stringify(stations)); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## StationInfo7+ @@ -1136,6 +1542,22 @@ Obtains P2P link information. This API uses an asynchronous callback to return t | -------- | -------- | -------- | -------- | | callback | AsyncCallback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the P2P link information. If **err** is not **0**, an error has occurred.| +**Example** +```js +import wifi from '@ohos.wifi'; + +wifi.getP2pLinkedInfo((err, data) => { + if (err) { + console.error("get p2p linked info error"); + return; + } + console.info("get wifi p2p linked info: " + JSON.stringify(data)); +}); + +wifi.getP2pLinkedInfo().then(data => { + console.info("get wifi p2p linked info: " + JSON.stringify(data)); +}); +``` ## wifi.getCurrentGroup8+ @@ -1170,6 +1592,22 @@ Obtains the current P2P group information. This API uses an asynchronous callbac | -------- | -------- | -------- | -------- | | callback | AsyncCallback<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| +**Example** +```js +import wifi from '@ohos.wifi'; + +wifi.getCurrentGroup((err, data) => { + if (err) { + console.error("get current P2P group error"); + return; + } + console.info("get current P2P group: " + JSON.stringify(data)); +}); + +wifi.getCurrentGroup().then(data => { + console.info("get current P2P group: " + JSON.stringify(data)); +}); +``` ## wifi.getP2pPeerDevices8+ @@ -1204,6 +1642,22 @@ Obtains the peer device list in the P2P connection. This API uses an asynchronou | -------- | -------- | -------- | -------- | | callback | AsyncCallback<[WifiP2pDevice[]](#wifip2pdevice8)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the peer device list obtained. If **err** is not **0**, an error has occurred.| +**Example** +```js +import wifi from '@ohos.wifiManager'; + +wifi.getP2pPeerDevices((err, data) => { + if (err) { + console.error("get P2P peer devices error"); + return; + } + console.info("get P2P peer devices: " + JSON.stringify(data)); +}); + +wifi.getP2pPeerDevices().then(data => { + console.info("get P2P peer devices: " + JSON.stringify(data)); +}); +``` ## WifiP2pDevice8+ @@ -1257,6 +1711,24 @@ Creates a P2P group. | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Example** +```js +import wifi from '@ohos.wifi'; + +try { + let config = { + deviceAddress: "****", + netId: 0, + passphrase: "*****", + groupName: "****", + goBand: 0 + } + wifi.createGroup(config); + +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## WifiP2PConfig8+ @@ -1302,6 +1774,16 @@ Removes this P2P group. | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Example** +```js +import wifi from '@ohos.wifi'; + +try { + wifi.removeGroup(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.p2pConnect8+ @@ -1328,71 +1810,71 @@ Sets up a P2P connection. **Example** - ```js - import wifi from '@ohos.wifi'; - - var recvP2pConnectionChangeFunc = result => { - console.info("p2p connection change receive event: " + JSON.stringify(result)); - wifi.getP2pLinkedInfo((err, data) => { - if (err) { - console.error('failed to get getP2pLinkedInfo: ' + JSON.stringify(err)); - return; - } - console.info("get getP2pLinkedInfo: " + JSON.stringify(data)); - }); - } - wifi.on("p2pConnectionChange", recvP2pConnectionChangeFunc); - - var recvP2pDeviceChangeFunc = result => { - console.info("p2p device change receive event: " + JSON.stringify(result)); - } - wifi.on("p2pDeviceChange", recvP2pDeviceChangeFunc); - - var recvP2pPeerDeviceChangeFunc = result => { - console.info("p2p peer device change receive event: " + JSON.stringify(result)); - wifi.getP2pPeerDevices((err, data) => { - if (err) { - console.error('failed to get peer devices: ' + JSON.stringify(err)); - return; - } - console.info("get peer devices: " + JSON.stringify(data)); - var len = Object.keys(data).length; - for (var i = 0; i < len; ++i) { - if (data[i].deviceName === "my_test_device") { - console.info("p2p connect to test device: " + data[i].deviceAddress); - var config = { - "deviceAddress":data[i].deviceAddress, - "netId":-2, - "passphrase":"", - "groupName":"", - "goBand":0, - } - wifi.p2pConnect(config); - } - } - }); - } - wifi.on("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); - - var recvP2pPersistentGroupChangeFunc = () => { - console.info("p2p persistent group change receive event"); - - wifi.getCurrentGroup((err, data) => { - if (err) { - console.error('failed to get current group: ' + JSON.stringify(err)); - return; - } - console.info("get current group: " + JSON.stringify(data)); - }); - } - wifi.on("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); - - setTimeout(function() {wifi.off("p2pConnectionChange", recvP2pConnectionChangeFunc);}, 125 * 1000); - setTimeout(function() {wifi.off("p2pDeviceChange", recvP2pDeviceChangeFunc);}, 125 * 1000); - setTimeout(function() {wifi.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc);}, 125 * 1000); - setTimeout(function() {wifi.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc);}, 125 * 1000); - console.info("start discover devices -> " + wifi.startDiscoverDevices()); - ``` +```js +import wifi from '@ohos.wifi'; + +var recvP2pConnectionChangeFunc = result => { + console.info("p2p connection change receive event: " + JSON.stringify(result)); + wifi.getP2pLinkedInfo((err, data) => { + if (err) { + console.error('failed to get getP2pLinkedInfo: ' + JSON.stringify(err)); + return; + } + console.info("get getP2pLinkedInfo: " + JSON.stringify(data)); + }); +} +wifi.on("p2pConnectionChange", recvP2pConnectionChangeFunc); + +var recvP2pDeviceChangeFunc = result => { + console.info("p2p device change receive event: " + JSON.stringify(result)); +} +wifi.on("p2pDeviceChange", recvP2pDeviceChangeFunc); + +var recvP2pPeerDeviceChangeFunc = result => { + console.info("p2p peer device change receive event: " + JSON.stringify(result)); + wifi.getP2pPeerDevices((err, data) => { + if (err) { + console.error('failed to get peer devices: ' + JSON.stringify(err)); + return; + } + console.info("get peer devices: " + JSON.stringify(data)); + var len = Object.keys(data).length; + for (var i = 0; i < len; ++i) { + if (data[i].deviceName === "my_test_device") { + console.info("p2p connect to test device: " + data[i].deviceAddress); + var config = { + "deviceAddress":data[i].deviceAddress, + "netId":-2, + "passphrase":"", + "groupName":"", + "goBand":0, + } + wifi.p2pConnect(config); + } + } + }); +} +wifi.on("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); + +var recvP2pPersistentGroupChangeFunc = () => { + console.info("p2p persistent group change receive event"); + + wifi.getCurrentGroup((err, data) => { + if (err) { + console.error('failed to get current group: ' + JSON.stringify(err)); + return; + } + console.info("get current group: " + JSON.stringify(data)); + }); +} +wifi.on("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); + +setTimeout(function() {wifi.off("p2pConnectionChange", recvP2pConnectionChangeFunc);}, 125 * 1000); +setTimeout(function() {wifi.off("p2pDeviceChange", recvP2pDeviceChangeFunc);}, 125 * 1000); +setTimeout(function() {wifi.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc);}, 125 * 1000); +setTimeout(function() {wifi.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc);}, 125 * 1000); +console.info("start discover devices -> " + wifi.startDiscoverDevices()); +``` ## wifi.p2pCancelConnect8+ @@ -1410,6 +1892,16 @@ Cancels this P2P connection. | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Example** +```js +import wifi from '@ohos.wifi'; + +try { + wifi.p2pCancelConnect(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.startDiscoverDevices8+ @@ -1427,6 +1919,16 @@ Starts to discover devices. | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Example** +```js +import wifi from '@ohos.wifi'; + +try { + wifi.startDiscoverDevices(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.stopDiscoverDevices8+ @@ -1444,6 +1946,16 @@ Stops discovering devices. | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Example** +```js +import wifi from '@ohos.wifi'; + +try { + wifi.stopDiscoverDevices(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.deletePersistentGroup8+ @@ -1470,6 +1982,17 @@ Deletes a persistent group. | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Example** +```js +import wifi from '@ohos.wifi'; + +try { + let netId = 0; + wifi.deletePersistentGroup(netId); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## WifiP2pGroupInfo8+ @@ -1514,6 +2037,17 @@ Sets the device name. | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Example** +```js +import wifi from '@ohos.wifi'; + +try { + let name = "****"; + wifi.setDeviceName(netId); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.on('wifiStateChange')7+ @@ -1560,19 +2094,19 @@ Unregisters the WLAN state change events. | callback | Callback<number> | No| Callback for the WLAN state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Example** - ```js - import wifi from '@ohos.wifi'; - - var recvPowerNotifyFunc = result => { - console.info("Receive power state change event: " + result); - } - - // Register an event. - wifi.on("wifiStateChange", recvPowerNotifyFunc); - - // Unregister an event. - wifi.off("wifiStateChange", recvPowerNotifyFunc); - ``` +```js +import wifi from '@ohos.wifi'; + +var recvPowerNotifyFunc = result => { + console.info("Receive power state change event: " + result); +} + +// Register an event. +wifi.on("wifiStateChange", recvPowerNotifyFunc); + +// Unregister an event. +wifi.off("wifiStateChange", recvPowerNotifyFunc); +``` ## wifi.on('wifiConnectionChange')7+ @@ -1617,6 +2151,20 @@ Unregisters the WLAN connection state change events. | type | string | Yes| Event type. The value is **wifiConnectionChange**.| | callback | Callback<number> | No| Callback for the WLAN connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +**Example** +```js +import wifi from '@ohos.wifi'; + +var recvWifiConnectionChangeFunc = result => { + console.info("Receive wifi connection change event: " + result); +} + +// Register an event. +wifi.on("wifiConnectionChange", recvWifiConnectionChangeFunc); + +// Unregister an event. +wifi.off("wifiConnectionChange", recvWifiConnectionChangeFunc); +``` ## wifi.on('wifiScanStateChange')7+ @@ -1660,6 +2208,20 @@ Unregisters the WLAN scan state change events. | type | string | Yes| Event type. The value is **wifiScanStateChange**.| | callback | Callback<number> | No| Callback for the WLAN scan state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +**Example** +```js +import wifi from '@ohos.wifi'; + +var recvWifiScanStateChangeFunc = result => { + console.info("Receive Wifi scan state change event: " + result); +} + +// Register an event. +wifi.on("wifiScanStateChange", recvWifiScanStateChangeFunc); + +// Unregister an event. +wifi.off("wifiScanStateChange", recvWifiScanStateChangeFunc); +``` ## wifi.on('wifiRssiChange')7+ @@ -1696,7 +2258,20 @@ Unregisters the RSSI change events. | type | string | Yes| Event type. The value is **wifiRssiChange**.| | callback | Callback<number> | No| Callback for the RSSI. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +**Example** +```js +import wifi from '@ohos.wifi'; + +var recvWifiRssiChangeFunc = result => { + console.info("Receive wifi rssi change event: " + result); +} + +// Register an event. +wifi.on("wifiRssiChange", recvWifiRssiChangeFunc); +// Unregister an event. +wifi.off("wifiRssiChange", recvWifiRssiChangeFunc); +``` ## wifi.on('hotspotStateChange')7+ on(type: "hotspotStateChange", callback: Callback<number>): void @@ -1723,6 +2298,20 @@ Registers the hotspot state change events. | 2 | Activating| | 3 | Deactivating| +**Example** +```js +import wifi from '@ohos.wifi'; + +var recvHotspotStateChangeFunc = result => { + console.info("Receive hotspot state change event: " + result); +} + +// Register an event. +wifi.on("hotspotStateChange", recvHotspotStateChangeFunc); + +// Unregister an event. +wifi.off("hotspotStateChange", recvHotspotStateChangeFunc); +``` ## wifi.off('hotspotStateChange')7+ @@ -1786,6 +2375,20 @@ Unregisters the P2P state change events. | type | string | Yes| Event type. The value is **p2pStateChange**.| | callback | Callback<number> | No| Callback for the P2P state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +**Example** +```js +import wifi from '@ohos.wifi'; + +var recvP2pStateChangeFunc = result => { + console.info("Receive p2p state change event: " + result); +} + +// Register an event. +wifi.on("p2pStateChange", recvP2pStateChangeFunc); + +// Unregister an event. +wifi.off("p2pStateChange", recvP2pStateChangeFunc); +``` ## wifi.on('p2pConnectionChange')8+ @@ -1822,6 +2425,20 @@ Unregisters the P2P connection state change events. | type | string | Yes| Event type. The value is **p2pConnectionChange**.| | callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | No| Callback for the P2P connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +**Example** +```js +import wifi from '@ohos.wifi'; + +var recvP2pConnectionChangeFunc = result => { + console.info("Receive p2p connection change event: " + result); +} + +// Register an event. +wifi.on("p2pConnectionChange", recvP2pConnectionChangeFunc); + +// Unregister an event. +wifi.off("p2pConnectionChange", recvP2pConnectionChangeFunc); +``` ## wifi.on('p2pDeviceChange')8+ @@ -1858,6 +2475,20 @@ Unregisters the P2P device state change events. | type | string | Yes| Event type. The value is **p2pDeviceChange**.| | callback | Callback<[WifiP2pDevice](#wifip2pdevice8)> | No| Callback for the P2P device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +**Example** +```js +import wifi from '@ohos.wifi'; + +var recvP2pDeviceChangeFunc = result => { + console.info("Receive recv p2p device change event: " + result); +} + +// Register an event. +wifi.on("p2pDeviceChange", recvP2pDeviceChangeFunc); + +// Unregister an event. +wifi.off("p2pDeviceChange", recvP2pDeviceChangeFunc); +``` ## wifi.on('p2pPeerDeviceChange')8+ @@ -1894,6 +2525,20 @@ Unregisters the P2P peer device state change events. | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| | callback | Callback<[WifiP2pDevice[]](#wifip2pdevice8)> | No| Callback for the peer device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +**Example** +```js +import wifi from '@ohos.wifi'; + +var recvP2pPeerDeviceChangeFunc = result => { + console.info("Receive recv p2p peer device change event: " + result); +} + +// Register an event. +wifi.on("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); + +// Unregister an event. +wifi.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); +``` ## wifi.on('p2pPersistentGroupChange')8+ @@ -1930,6 +2575,21 @@ Unregisters the P2P persistent group state change events. | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| | callback | Callback<void> | No| Callback for the P2P persistent group state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +**Example** +```js +import wifi from '@ohos.wifi'; + +var recvP2pPersistentGroupChangeFunc = result => { + console.info("Receive recv p2p persistent group change event: " + result); +} + +// Register an event. +wifi.on("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); + +// Unregister an event. +wifi.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); + +``` ## wifi.on('p2pDiscoveryChange')8+ @@ -1972,3 +2632,18 @@ Unregisters the P2P device discovery state change events. | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| | callback | Callback<number> | No| Callback for the P2P device discovery state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + +**Example** +```js +import wifi from '@ohos.wifi'; + +var recvP2pDiscoveryChangeFunc = result => { + console.info("Receive recv p2p discovery change event: " + result); +} + +// Register an event. +wifi.on("p2pDiscoveryChange", recvP2pDiscoveryChangeFunc); + +// Unregister an event. +wifi.off("p2pDiscoveryChange", recvP2pDiscoveryChangeFunc); +``` diff --git a/en/application-dev/reference/apis/js-apis-wifiManager.md b/en/application-dev/reference/apis/js-apis-wifiManager.md index dc9beb94d7fcc13d6c82e805bf8855d537e907bd..6d560d345805826369d8b83cfdcbee53a47b00f5 100644 --- a/en/application-dev/reference/apis/js-apis-wifiManager.md +++ b/en/application-dev/reference/apis/js-apis-wifiManager.md @@ -26,18 +26,29 @@ Enables WLAN. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| +**Example** + +``` + import wifi from '@ohos.wifiManager'; + + try { + wifiManager.enableWifi(); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` ## wifi.disableWifi9+ @@ -53,18 +64,30 @@ Disables WLAN. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| +**Example** + +``` + import wifi from '@ohos.wifiManager'; + + try { + wifiManager.disableWifi(); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + ## wifi.isWifiActive9+ isWifiActive(): boolean @@ -77,132 +100,119 @@ Checks whether WLAN is enabled. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if WLAN is enabled; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if WLAN is enabled; returns **false** otherwise.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| +**Example** + +``` + import wifi from '@ohos.wifiManager'; + + try { + let isActivate = wifiManager.isActivate(); + console.info("isActivate:" + isActivate); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + ## wifi.scan9+ scan(): void Starts a scan for WLAN. -**Required permissions**: **ohos.permission.SET_WIFI_INFO** and **ohos.permission.LOCATION** +**Required permissions**: ohos.permission.SET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.APPROXIMATELY_LOCATION **System capability**: SystemCapability.Communication.WiFi.STA **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| -## wifi.getScanResults9+ - -getScanResults(): Promise<Array<WifiScanInfo>> - -Obtains the scan result. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_PEERS_MAC (or ohos.permission.LOCATION) - -**System capability**: SystemCapability.Communication.WiFi.STA - -**Return value** - - | **Type**| **Description**| - | -------- | -------- | - | Promise< Array<[WifiScanInfo](#wifiscaninfo)> > | Promise used to return the hotspots detected.| - -**Error codes** +**Example** -For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). +``` + import wifi from '@ohos.wifiManager'; -| **Type**| **Description**| - | -------- | -------- | -| 2501000 | Operation failed.| + try { + wifiManager.scan(); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` -## wifi.getScanResults9+ +## wifi.getScanInfoList9+ -getScanResults(callback: AsyncCallback<Array<WifiScanInfo>>): void +getScanInfoList(): Array<WifiScanInfo>; -Obtains the scan result. This API uses an asynchronous callback to return the result. +Obtains the scan result. -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_PEERS_MAC (or ohos.permission.LOCATION) +**Required permissions**: ohos.permission.GET_WIFI_INFO and (ohos.permission.GET_WIFI_PEERS_MAC or (ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION)) **System capability**: SystemCapability.Communication.WiFi.STA -**Parameters** +**Return value** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback< Array<[WifiScanInfo](#wifiscaninfo)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the detected hotspots. Otherwise, **err** is a non-zero value and **data** is empty.| +| **Type**| **Description**| +| -------- | -------- | +| Array<[WifiScanInfo](#wifiscaninfo)> | Returns the hotspots detected.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| **Example** - ```js - import wifi from '@ohos.wifi'; - - wifi.getScanInfos((err, result) => { - if (err) { - console.error("get scan info error"); - return; - } - - var len = Object.keys(result).length; - console.log("wifi received scan info: " + len); - for (var i = 0; i < len; ++i) { - console.info("ssid: " + result[i].ssid); - console.info("bssid: " + result[i].bssid); - console.info("capabilities: " + result[i].capabilities); - console.info("securityType: " + result[i].securityType); - console.info("rssi: " + result[i].rssi); - console.info("band: " + result[i].band); - console.info("frequency: " + result[i].frequency); - console.info("channelWidth: " + result[i].channelWidth); - console.info("timestamp: " + result[i].timestamp); - } - }); - - wifi.getScanInfos().then(result => { - var len = Object.keys(result).length; - console.log("wifi received scan info: " + len); - for (var i = 0; i < len; ++i) { - console.info("ssid: " + result[i].ssid); - console.info("bssid: " + result[i].bssid); - console.info("capabilities: " + result[i].capabilities); - console.info("securityType: " + result[i].securityType); - console.info("rssi: " + result[i].rssi); - console.info("band: " + result[i].band); - console.info("frequency: " + result[i].frequency); - console.info("channelWidth: " + result[i].channelWidth); - console.info("timestamp: " + result[i].timestamp); - } - }); - ``` +``` + import wifi from '@ohos.wifiManager'; + + try { + let scanInfoList = wifiManager.getScanInfoList(); + console.info("scanInfoList:" + JSON.stringify(scanInfoList)); + let len = Object.keys(result).length; + console.log("wifi received scan info: " + len); + if(len > 0){ + for (var i = 0; i < len; ++i) { + console.info("ssid: " + scanInfoList[i].ssid); + console.info("bssid: " + scanInfoList[i].bssid); + console.info("capabilities: " + scanInfoList[i].capabilities); + console.info("securityType: " + scanInfoList[i].securityType); + console.info("rssi: " + scanInfoList[i].rssi); + console.info("band: " + scanInfoList[i].band); + console.info("frequency: " + scanInfoList[i].frequency); + console.info("channelWidth: " + scanInfoList[i].channelWidth); + console.info("timestamp: " + scanInfoList[i].timestamp); + } + } + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } + +``` ## WifiScanInfo9+ @@ -248,59 +258,65 @@ Enumerates the WLAN security types. | WIFI_SEC_TYPE_WAPI_PSK9+ | 9 | WAPI-PSK.| -## WifiInfoElem9+ +## WifiBandType10+ -Represents a WLAN information element. +Enumerates the Wi-Fi band types. **System capability**: SystemCapability.Communication.WiFi.STA +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| WIFI_BAND_NONE | 0 | Invalid band type| +| WIFI_BAND_2G | 1 | 2.4 GHz| +| WIFI_BAND_5G | 2 | 5 GHz| +| WIFI_BAND_6G | 3 | 6 GHz| +| WIFI_BAND_60G | 4 | 60 GHz| -| **Name**| **Type**| **Readable**| **Writable**| **Description**| -| -------- | -------- | -------- | -------- | -------- | -| eid | number | Yes| No| ID of the information element.| -| content | Uint8Array | Yes| No| Content of the information element.| - - -## WifiChannelWidth9+ +## WifiStandard10+ -Enumerates the WLAN channel widths. +Enumerates the Wi-Fi standards. **System capability**: SystemCapability.Communication.WiFi.STA - | **Name**| **Value**| **Description**| | -------- | -------- | -------- | -| WIDTH_20MHZ | 0 | 20 MHz.| -| WIDTH_40MHZ | 1 | 40 MHz.| -| WIDTH_80MHZ | 2 | 80 MHz.| -| WIDTH_160MHZ | 3 | 160 MHz.| -| WIDTH_80MHZ_PLUS | 4 | 80 MHz+.| -| WIDTH_INVALID | 5 | Invalid value.| +| WIFI_STANDARD_UNDEFINED | 0 | Invalid Wi-Fi standard| +| WIFI_STANDARD_11A | 1 | 802.11a| +| WIFI_STANDARD_11B | 2 | 802.11b| +| WIFI_STANDARD_11G | 3 | 802.11g| +| WIFI_STANDARD_11N | 4 | 802.11n| +| WIFI_STANDARD_11AC | 5 | 802.11ac| +| WIFI_STANDARD_11AX | 6 | 802.11ax| +| WIFI_STANDARD_11AD | 7 | 802.11ad| +## WifiInfoElem9+ -## wifi.getScanResultsSync9+ +Represents a WLAN information element. -getScanResultsSync():  Array<[WifiScanInfo](#wifiscaninfo)> +**System capability**: SystemCapability.Communication.WiFi.STA -Obtains the scan result. This API returns the result synchronously. -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_PEERS_MAC (or ohos.permission.LOCATION) +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| eid | number | Yes| No| ID of the information element.| +| content | Uint8Array | Yes| No| Content of the information element.| -**System capability**: SystemCapability.Communication.WiFi.STA -**Return value** +## WifiChannelWidth9+ - | **Type**| **Description**| - | -------- | -------- | - |  Array<[WifiScanInfo](#wifiscaninfo)> | Scan result obtained.| +Enumerates the WLAN channel widths. -**Error codes** +**System capability**: SystemCapability.Communication.WiFi.STA -For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | -| 2501000 | Operation failed.| +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| WIDTH_20MHZ | 0 | 20 MHz| +| WIDTH_40MHZ | 1 | 40 MHz| +| WIDTH_80MHZ | 2 | 80 MHz| +| WIDTH_160MHZ | 3 | 160 MHz| +| WIDTH_80MHZ_PLUS | 4 | 80 MHz+| +| WIDTH_INVALID | 5 | Invalid value| ## wifi.addDeviceConfig9+ @@ -316,24 +332,43 @@ Adds network configuration. This API uses a promise to return the result. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| **Return value** - | **Type**| **Description**| - | -------- | -------- | - | Promise<number> | Promise used to return the ID of the added network configuration. If **-1** is returned, the network configuration fails to be added.| +| **Type**| **Description**| +| -------- | -------- | +| Promise<number> | Promise used to return the ID of the added network configuration. If **-1** is returned, the network configuration fails to be added.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| +**Example** + +``` + import wifi from '@ohos.wifiManager'; + + try { + let config = { + ssid : "****", + preSharedKey : "****", + securityType : 0 + } + wifiManager.addDeviceConfig(config).then(result => { + console.info("result:" + JSON.stringify(result)); + }); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + ## WifiDeviceConfig9+ Represents the WLAN configuration. @@ -348,14 +383,14 @@ Represents the WLAN configuration. | preSharedKey | string | Yes| No| PSK of the hotspot.| | isHiddenSsid | boolean | Yes| No| Whether the network is hidden.| | securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| Security type.| -| creatorUid | number | Yes| No| ID of the creator.
**System API**: This is a system API.| -| disableReason | number | Yes| No| Reason for disabling WLAN.
**System API**: This is a system API.| -| netId | number | Yes| No| Network ID.
**System API**: This is a system API.| -| randomMacType | number | Yes| No| Random MAC type.
**System API**: This is a system API.| -| randomMacAddr | string | Yes| No| Random MAC address.
**System API**: This is a system API.| -| ipType | [IpType](#iptype9) | Yes| No| IP address type.
**System API**: This is a system API.| -| staticIp | [IpConfig](#ipconfig9) | Yes| No| Static IP address configuration.
**System API**: This is a system API.| -| eapConfig9+ | [WifiEapConfig](#wifieapconfig9) | Yes| No| EAP configuration.
**System API**: This is a system API.| +| creatorUid | number | Yes| No| ID of the creator.
**System API**: This is a system API.| +| disableReason | number | Yes| No| Reason for disabling WLAN.
**System API**: This is a system API.| +| netId | number | Yes| No| Network ID.
**System API**: This is a system API.| +| randomMacType | number | Yes| No| Random MAC type.
**System API**: This is a system API.| +| randomMacAddr | string | Yes| No| Random MAC address.
**System API**: This is a system API.| +| ipType | [IpType](#iptype9) | Yes| No| IP address type.
**System API**: This is a system API.| +| staticIp | [IpConfig](#ipconfig9) | Yes| No| Static IP address configuration.
**System API**: This is a system API.| +| eapConfig9+ | [WifiEapConfig](#wifieapconfig9) | Yes| No| EAP configuration.
**System API**: This is a system API.| ## IpType9+ @@ -473,19 +508,38 @@ Adds network configuration. This API uses an asynchronous callback to return the **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| - | callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| +| callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| +**Example** + +``` + import wifi from '@ohos.wifiManager'; + + try { + let config = { + ssid : "****", + preSharedKey : "****", + securityType : 0 + } + wifiManager.addDeviceConfig(config,(error,result) => { + console.info("result:" + JSON.stringify(result)); + }); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + ## wifi.addCandidateConfig9+ addCandidateConfig(config: WifiDeviceConfig): Promise<number> @@ -498,24 +552,42 @@ Adds the configuration of a candidate network. This API uses a promise to return **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| **Return value** - | **Type**| **Description**| - | -------- | -------- | - | Promise<number> | Promise used to return the network configuration ID.| +| **Type**| **Description**| +| -------- | -------- | +| Promise<number> | Promise used to return the network configuration ID.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| +**Example** +````` + import wifi from '@ohos.wifiManager'; + + try { + let config = { + ssid : "****", + preSharedKey : "****", + securityType : 0 + } + wifiManager.addCandidateConfig(config).then(result => { + console.info("result:" + JSON.stringify(result)); + }); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +````` + ## wifi.addCandidateConfig9+ addCandidateConfig(config: WifiDeviceConfig, callback: AsyncCallback<number>): void @@ -528,19 +600,37 @@ Adds the configuration of a candidate network. This API uses an asynchronous cal **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| - | callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| +| callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| +**Example** +````` + import wifi from '@ohos.wifiManager'; + + try { + let config = { + ssid : "****", + preSharedKey : "****", + securityType : 0 + } + wifiManager.addCandidateConfig(config,(error,result) => { + console.info("result:" + JSON.stringify(result)); + }); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +````` + ## wifi.removeCandidateConfig9+ removeCandidateConfig(networkId: number): Promise<void> @@ -553,24 +643,39 @@ Removes the configuration of a candidate network. This API uses a promise to ret **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | networkId | number | Yes| ID of the network configuration to remove.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| networkId | number | Yes| ID of the network configuration to remove.| **Return value** - | **Type**| **Description**| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| **Type**| **Description**| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| +**Example** + +``` + import wifi from '@ohos.wifiManager'; + + try { + let networkId = 0; + wifiManager.removeCandidateConfig(networkId).then(result => { + console.info("result:" + JSON.stringify(result)); + }); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + ## wifi.removeCandidateConfig9+ removeCandidateConfig(networkId: number, callback: AsyncCallback<void>): void @@ -583,48 +688,84 @@ Removes the configuration of a candidate network. This API uses an asynchronous **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | networkId | number | Yes| ID of the network configuration to remove.| - | callback | AsyncCallback<void> | Yes| Callback invoked to return the result. If the operation is successful, the value of **err** is **0**. If **err** is not **0**, an error has occurred.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| networkId | number | Yes| ID of the network configuration to remove.| +| callback | AsyncCallback<void> | Yes| Callback invoked to return the result. If the operation is successful, the value of **err** is **0**. If **err** is not **0**, an error has occurred.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + let networkId = 0; + wifiManager.removeCandidateConfig(networkId,(error,result) => { + console.info("result:" + JSON.stringify(result)); + }); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + ## wifi.getCandidateConfigs9+ getCandidateConfigs():  Array<[WifiDeviceConfig](#wifideviceconfig)> Obtains candidate network configuration. -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION +**Required permissions**: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.APPROXIMATELY_LOCATION **System capability**: SystemCapability.Communication.WiFi.STA **Return value** - | **Type**| **Description**| - | -------- | -------- | - |  Array<[WifiDeviceConfig](#wifideviceconfig)> | Candidate network configuration obtained.| +| **Type**| **Description**| +| -------- | -------- | +|  Array<[WifiDeviceConfig](#wifideviceconfig)> | Candidate network configuration obtained.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| +**Example** + +````` + import wifi from '@ohos.wifiManager'; + + try { + let configs = wifiManager.getCandidateConfigs(); + console.info("configs:" + JSON.stringify(configs)); + let len = Object.keys(configs).length; + console.log("result len: " + len); + if(len > 0){ + for (var i = 0; i < len; ++i) { + console.info("ssid: " + configs[i].ssid); + console.info("bssid: " + configs[i].bssid); + } + } + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } + +````` + ## wifi.connectToCandidateConfig9+ connectToCandidateConfig(networkId: number): void -Connects to a candidate network. +Connects to a candidate network added by the application. If the device is already connected to a hotspot, disconnect it from the hotspot first. **Required permissions**: ohos.permission.SET_WIFI_INFO @@ -632,24 +773,38 @@ Connects to a candidate network. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | networkId | number | Yes| ID of the candidate network configuration.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| networkId | number | Yes| ID of the candidate network configuration.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| | 2501001 | Wifi is closed.| +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + let networkId = 0; + let ret = wifiManager.connectToCandidateConfig(networkId); + console.info("result:" + ret); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } + +``` + ## wifi.connectToNetwork9+ connectToNetwork(networkId: number): void -Connects to the specified network. +Connects to the specified network. If the device is already connected to a hotspot, use **disconnect()** to disconnect it from the hotspot first. **System API**: This is a system API. @@ -659,24 +814,37 @@ Connects to the specified network. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | networkId | number | Yes| Network configuration ID.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| networkId | number | Yes| Network configuration ID.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| | 2501001 | Wifi is closed.| +**Example** + +``` + import wifi from '@ohos.wifiManager'; + + try { + let networkId = 0; + wifiManager.connectToNetwork(networkId); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + ## wifi.connectToDevice9+ connectToDevice(config: WifiDeviceConfig): void -Connects to the specified network. +Connects to the specified network. If the device is already connected to a hotspot, use **disconnect()** to disconnect it from the hotspot first. **System API**: This is a system API. @@ -687,19 +855,36 @@ Connects to the specified network. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| Configuration of the WLAN to connect. | **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| | 2501001 | Wifi is closed.| +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + let config = { + ssid : "****", + preSharedKey : "****", + securityType : 3 + } + wifiManager.connectToDevice(config); + + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + ## wifi.disconnect9+ disconnect(): void @@ -717,10 +902,21 @@ Disconnects the network. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + wifiManager.disconnect(); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + ## wifi.getSignalLevel9+ getSignalLevel(rssi: number, band: number): number @@ -733,25 +929,40 @@ Obtains the WLAN signal level. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | rssi | number | Yes| RSSI of the hotspot, in dBm.| - | band | number | Yes| Frequency band of the WLAN AP.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| rssi | number | Yes| RSSI of the hotspot, in dBm.| +| band | number | Yes| Frequency band of the WLAN AP.| **Return value** - | **Type**| **Description**| - | -------- | -------- | - | number | Signal level obtained. The value range is [0, 4].| +| **Type**| **Description**| +| -------- | -------- | +| number | Signal level obtained. The value range is [0, 4].| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + let rssi = 0; + let band = 0; + let level = wifiManager.getSignalLevel(rssi,band); + console.info("lelvel:" + JSON.stringify(lelvel)); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } + +``` + ## wifi.getLinkedInfo9+ getLinkedInfo(): Promise<WifiLinkedInfo> @@ -764,16 +975,16 @@ Obtains WLAN connection information. This API uses a promise to return the resul **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[WifiLinkedInfo](#wifilinkedinfo)> | Promise used to return the WLAN connection information obtained.| +| Type| Description| +| -------- | -------- | +| Promise<[WifiLinkedInfo](#wifilinkedinfo)> | Promise used to return the WLAN connection information obtained.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| | 2501001 | Wifi is closed.| @@ -789,22 +1000,22 @@ Obtains WLAN connection information. This API uses an asynchronous callback to r **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[WifiLinkedInfo](#wifilinkedinfo)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the WLAN connection information obtained. If **err** is not **0**, an error has occurred.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[WifiLinkedInfo](#wifilinkedinfo)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the WLAN connection information obtained. If **err** is not **0**, an error has occurred.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| | 2501001 | Wifi is closed.| **Example** ```js - import wifi from '@ohos.wifi'; + import wifi from '@ohos.wifiManager'; wifi.getLinkedInfo((err, data) => { if (err) { @@ -832,21 +1043,25 @@ Represents the WLAN connection information. | -------- | -------- | -------- | -------- | -------- | | ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.| | bssid | string | Yes| No| BSSID of the hotspot.| -| networkId | number | Yes| No| Network configuration ID.
**System API**: This is a system API.| +| networkId | number | Yes| No| Network configuration ID.
**System API**: This is a system API.| | rssi | number | Yes| No| RSSI of the hotspot, in dBm.| -| band | number | Yes| No| Frequency band of the WLAN AP.| -| linkSpeed | number | Yes| No| Speed of the WLAN AP.| +| band | number | Yes| No| Band of the WLAN AP.| +| linkSpeed | number | Yes| No| Uplink speed of the WLAN AP.| +| rxLinkSpeed10+ | number | Yes| No| Downlink speed of the WLAN AP.| +| maxSupportedTxLinkSpeed10+ | number | Yes| No| Maximum uplink speed supported.| +| maxSupportedRxLinkSpeed10+ | number | Yes| No| Maximum uplink speed supported.| | frequency | number | Yes| No| Frequency of the WLAN AP.| | isHidden | boolean | Yes| No| Whether to hide the WLAN AP.| | isRestricted | boolean | Yes| No| Whether to restrict data volume at the WLAN AP.| -| chload | number | Yes| No| Channel load. A larger value indicates a higher load.
**System API**: This is a system API.| -| snr | number | Yes| No| Signal-to-noise ratio (SNR).
**System API**: This is a system API.| -| macType9+ | number | Yes| No| MAC address type.| +| chload | number | Yes| No| Channel load. A larger value indicates a higher load.
**System API**: This is a system API.| +| snr | number | Yes| No| Signal-to-noise ratio (SNR).
**System API**: This is a system API.| +| macType | number | Yes| No| MAC address type.| | macAddress | string | Yes| No| MAC address of the device.| | ipAddress | number | Yes| No| IP address of the device that sets up the WLAN connection.| -| suppState | [SuppState](#suppstate) | Yes| No| Supplicant state.
**System API**: This is a system API.| +| suppState | [SuppState](#suppstate) | Yes| No| Supplicant state.
**System API**: This is a system API.| | connState | [ConnState](#connstate) | Yes| No| WLAN connection state.| - +| channelWidth10+ | [WifiChannelWidth](#wifichannelwidth) | Yes| No| Channel bandwidth of the connected hotspot.| +| wifiStandard10+ | [WifiStandard](#wifistandard) | Yes| No| Wi-Fi standard used by the connected hotspot.| ## ConnState9+ @@ -889,6 +1104,23 @@ Enumerates the supplicant states. | UNINITIALIZED | 10 | The supplicant failed to set up the connection.| | INVALID | 11 | Invalid value.| +## SuppState10+ + +Enumerates the Wi-Fi standards. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| Name| Value| Description| +| -------- | -------- | -------- | +| WIFI_STANDARD_UNDEFINED | 0 | Undefined| +| WIFI_STANDARD_11A | 1 | 802.11a| +| WIFI_STANDARD_11B | 2 | 802.11b| +| WIFI_STANDARD_11G | 3 | 802.11g| +| WIFI_STANDARD_11N | 4 | 802.11n| +| WIFI_STANDARD_11AC | 5 | 802.11ac| +| WIFI_STANDARD_11AX | 6 | 802.11ax| +| WIFI_STANDARD_11AD | 7 | 802.11ad| + ## wifi.isConnected9+ @@ -902,18 +1134,31 @@ Checks whether the WLAN is connected. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the WLAN is connected; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the WLAN is connected; returns **false** otherwise.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + let ret = wifiManager.isConnected(); + console.info("isConnected:" + ret); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } + +``` + ## wifi.getSupportedFeatures9+ getSupportedFeatures(): number @@ -928,9 +1173,9 @@ Obtains the features supported by this device. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | number | Feature value. | +| **Type**| **Description**| +| -------- | -------- | +| number | Feature value. | **Feature IDs** @@ -951,10 +1196,23 @@ Obtains the features supported by this device. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2401000 | Operation failed.| +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + let ret = wifiManager.getSupportedFeatures(); + console.info("supportedFeatures:" + ret); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } + +``` + ## wifi.isFeatureSupported9+ isFeatureSupported(featureId: number): boolean @@ -968,24 +1226,38 @@ Checks whether the device supports the specified WLAN feature. **Parameters** - | **Name**| **Type**| Mandatory| **Description**| - | -------- | -------- | -------- | -------- | - | featureId | number | Yes| Feature ID.| +| **Name**| **Type**| Mandatory| **Description**| +| -------- | -------- | -------- | -------- | +| featureId | number | Yes| Feature ID.| **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the feature is supported; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the feature is supported; returns **false** otherwise.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2401000 | Operation failed.| +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + let featureId = 0; + let ret = wifiManager.isFeatureSupported(featureId); + console.info("isFeatureSupported:" + ret); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } + +``` + ## wifi.getDeviceMacAddress9+ getDeviceMacAddress(): string[] @@ -1000,18 +1272,31 @@ Obtains the device MAC address. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | string[] | MAC address obtained.| +| **Type**| **Description**| +| -------- | -------- | +| string[] | MAC address obtained.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + let ret = wifiManager.getDeviceMacAddress(); + console.info("deviceMacAddress:" + JSON.stringify(ret)); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } + +``` + ## wifi.getIpInfo9+ getIpInfo(): IpInfo @@ -1024,18 +1309,30 @@ Obtains IP information. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | [IpInfo](#ipinfo9) | IP information obtained.| +| **Type**| **Description**| +| -------- | -------- | +| [IpInfo](#ipinfo9) | IP information obtained.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + let info = wifiManager.getIpInfo(); + console.info("info:" + JSON.stringify(info)); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + ## IpInfo9+ Represents IP information. @@ -1065,18 +1362,30 @@ Obtains the country code. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | string | Country code obtained.| +| **Type**| **Description**| +| -------- | -------- | +| string | Country code obtained.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2401000 | Operation failed.| +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + let code = wifiManager.getCountryCode(); + console.info("code:" + code); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + ## wifi.reassociate9+ reassociate(): void @@ -1093,11 +1402,22 @@ Re-associates with the network. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| | 2501001 | Wifi is closed.| +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + wifiManager.reassociate(); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + ## wifi.reconnect9+ reconnect(): void @@ -1114,11 +1434,22 @@ Reconnects to the network. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| | 2501001 | Wifi is closed.| +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + wifiManager.reconnect(); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + ## wifi.getDeviceConfigs9+ getDeviceConfigs():  Array<[WifiDeviceConfig](#wifideviceconfig)> @@ -1127,27 +1458,39 @@ Obtains network configuration. **System API**: This is a system API. -**Required permissions**: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.GET_WIFI_CONFIG +**Required permissions**: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, ohos.permission.APPROXIMATELY_LOCATION, and ohos.permission.GET_WIFI_CONFIG **System capability**: SystemCapability.Communication.WiFi.STA **Return value** - | **Type**| **Description**| - | -------- | -------- | - |  Array<[WifiDeviceConfig](#wifideviceconfig)> | Array of network configuration obtained.| +| **Type**| **Description**| +| -------- | -------- | +|  Array<[WifiDeviceConfig](#wifideviceconfig)> | Array of network configuration obtained.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| -## wifi.updateNetwork9+ +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + let configs = wifiManager.getDeviceConfigs(); + console.info("configs:" + JSON.stringify(configs)); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` -updateNetwork(config: WifiDeviceConfig): number +## wifi.updateDeviceConfig9+ + +updateDeviceConfig(config: WifiDeviceConfig): number Updates network configuration. @@ -1159,27 +1502,44 @@ Updates network configuration. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| New WLAN configuration.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| New WLAN configuration.| **Return value** - | **Type**| **Description**| - | -------- | -------- | - | number | ID of the updated network configuration. The value **-1** indicates that the operation has failed.| +| **Type**| **Description**| +| -------- | -------- | +| number | ID of the updated network configuration. The value **-1** indicates that the operation has failed.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| -## wifi.disableNetwork9+ +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + let config = { + ssid : "****", + preSharedKey : "****", + securityType : 3 + } + let ret = wifiManager.updateDeviceConfig(config); + console.error("ret:" + ret); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + +## wifi.disableDeviceConfig9+ -disableNetwork(netId: number): void +disableDeviceConfig(networkId: number): void Disables network configuration. @@ -1191,21 +1551,33 @@ Disables network configuration. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | netId | number | Yes| ID of the network configuration to disable.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| netId | number | Yes| ID of the network configuration to disable.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| -## wifi.removeAllNetwork9+ +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + let netId = 0; + wifiManager.disableDeviceConfig(netId); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + +## wifi.removeAllDeviceConfigs9+ -removeAllNetwork(): void +removeAllDeviceConfigs(): void Removes the configuration of all networks. @@ -1219,13 +1591,24 @@ Removes the configuration of all networks. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| -## wifi.removeDevice9+ +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + wifiManager.removeAllDeviceConfigs(); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + +## wifi.removeDeviceConfig9+ -removeDevice(id: number): void +removeDeviceConfig(networkId: number): void Removes the specified network configuration. @@ -1237,18 +1620,114 @@ Removes the specified network configuration. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | id | number | Yes| ID of the network configuration to remove.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| networkId | number | Yes| ID of the network configuration to remove.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | +| 2501000 | Operation failed.| + +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + let id = 0; + wifiManager.removeDeviceConfig(id); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + +## wifi.isBandTypeSupported10+ + +isBandTypeSupported(bandType: WifiBandType): boolean + +Checks whether the current frequency band is supported. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| bandType | WifiBandType | Yes| Wi-Fi band type.| + +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + let type = 0; + boolean isBandTypeSupported = wifiManager.isBandTypeSupported(type); + console.info("isBandTypeSupported:" + isBandTypeSupported); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + +## WifiBandType 10+ + +Enumerates the Wi-Fi band types. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| Name| Value| Description| +| -------- | -------- | -------- | +| WIFI_BAND_NONE | 0 | Undefined| +| WIFI_BAND_2G | 1 | 2 GHz| +| WIFI_BAND_5G | 2 | 5 GHz| +| WIFI_BAND_6G | 3 | 6 GHz| +| WIFI_BAND_60G | 4 | 60 GHz| + + +## wifi.get5GChannelList10+ + +get5GChannelList(): Array<number> + +Obtains the list of 5 GHz channels supported by this device. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **ID**| **Error Message**| +| -------- | -------- | +| 2501000 | Operation failed.| + +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + let channelList = wifiManager.get5GChannelList(); + console.info("channelList:" + JSON.stringify(channelList)); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + ## wifi.enableHotspot9+ enableHotspot(): void @@ -1265,10 +1744,21 @@ Enables this hotspot. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2601000 | Operation failed.| +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + wifiManager.enableHotspot(); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + ## wifi.disableHotspot9+ disableHotspot(): void @@ -1285,10 +1775,21 @@ Disables this hotspot. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2601000 | Operation failed.| +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + wifiManager.disableHotspot(); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + ## wifi.isHotspotDualBandSupported9+ isHotspotDualBandSupported(): boolean @@ -1303,18 +1804,30 @@ Checks whether the hotspot supports dual band. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the hotspot supports dual band; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the hotspot supports dual band; returns **false** otherwise.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2601000 | Operation failed.| +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + let ret = wifiManager.isHotspotDualBandSupported(); + console.info("result:" + ret); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + ## wifi.isHotspotActive9+ isHotspotActive(): boolean @@ -1329,18 +1842,30 @@ Checks whether this hotspot is active. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the hotspot is active; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the hotspot is active; returns **false** otherwise.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2601000 | Operation failed.| +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + let ret = wifiManager.isHotspotActive(); + console.info("result:" + ret); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + ## wifi.setHotspotConfig9+ setHotspotConfig(config: HotspotConfig): void @@ -1355,18 +1880,38 @@ Sets hotspot configuration. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | config | [HotspotConfig](#hotspotconfig9) | Yes| Hotspot configuration to set.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| config | [HotspotConfig](#hotspotconfig9) | Yes| Hotspot configuration to set.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2601000 | Operation failed.| +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + let config = { + ssid: "****", + securityType: 3, + band: 0, + channel: 0, + preSharedKey: "****", + maxConn: 0 + } + let ret = wifiManager.setHotspotConfig(); + console.info("result:" + ret); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + ## HotspotConfig9+ Represents the hotspot configuration. @@ -1377,12 +1922,12 @@ Represents the hotspot configuration. | **Name**| **Type**| **Readable**| **Writable**| **Description**| | -------- | -------- | -------- | -------- | -------- | -| ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.| -| securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| Security type.| -| band | number | Yes| No| Hotspot band. The value **1** stands for 2.4 GHz, the value **2** for 5 GHz, and the value **3** for dual band.| -| preSharedKey | string | Yes| No| PSK of the hotspot.| -| maxConn | number | Yes| No| Maximum number of connections allowed.| - +| ssid | string | Yes| Yes| SSID of the hotspot, in UTF-8 format.| +| securityType | [WifiSecurityType](#wifisecuritytype) | Yes| Yes| Security type.| +| band | number | Yes| Yes| Hotspot band. The value **1** stands for 2.4 GHz, the value **2** for 5 GHz, and the value **3** for dual band.| +| channel10+ | number | Yes| Yes| Hotspot channel (2.4 GHz: 1 to 14; 5 GHz: 7 to 196; Dual-band: not supported currently) | +| preSharedKey | string | Yes| Yes| PSK of the hotspot.| +| maxConn | number | Yes| Yes| Maximum number of connections allowed.| ## wifi.getHotspotConfig9+ @@ -1398,44 +1943,68 @@ Obtains hotspot configuration. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | [HotspotConfig](#hotspotconfig9) | Hotspot configuration obtained.| +| **Type**| **Description**| +| -------- | -------- | +| [HotspotConfig](#hotspotconfig9) | Hotspot configuration obtained.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2601000 | Operation failed.| -## wifi.getStations9+ +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + let config = wifiManager.getHotspotConfig(); + console.info("result:" + JSON.stringify(config)); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + +## wifi.getHotspotStations9+ -getStations():  Array<[StationInfo](#stationinfo9)> +getHotspotStations():  Array<[StationInfo](#stationinfo9)> Obtains information about the connected stations. **System API**: This is a system API. -**Required permissions**: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.MANAGE_WIFI_HOTSPOT (available only to system applications) +**Required permissions**: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, ohos.permission.APPROXIMATELY_LOCATION, and ohos.permission.MANAGE_WIFI_HOTSPOT (available only to system applications) **System capability**: SystemCapability.Communication.WiFi.AP.Core **Return value** - | **Type**| **Description**| - | -------- | -------- | - |  Array<[StationInfo](#stationinfo9)> | Connected stations obtained.| +| **Type**| **Description**| +| -------- | -------- | +|  Array<[StationInfo](#stationinfo9)> | Connected stations obtained.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2601000 | Operation failed.| +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + let stations = wifiManager.getHotspotStations(); + console.info("result:" + JSON.stringify(stations)); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + ## StationInfo9+ Represents the station information. @@ -1463,18 +2032,36 @@ Obtains P2P link information. This API uses a promise to return the result. **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | Promise used to return the P2P link information obtained.| +| Type| Description| +| -------- | -------- | +| Promise<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | Promise used to return the P2P link information obtained.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2801000 | Operation failed.| +**Example** +``` + import wifi from '@ohos.wifiManager'; + + wifi.getP2pLinkedInfo((err, data) => { + if (err) { + console.error("get p2p linked info error"); + return; + } + console.info("get wifi p2p linked info: " + JSON.stringify(data)); + }); + + wifi.getP2pLinkedInfo().then(data => { + console.info("get wifi p2p linked info: " + JSON.stringify(data)); + }); +``` + + ## WifiP2pLinkedInfo9+ Represents the P2P link information. @@ -1512,81 +2099,98 @@ Obtains P2P link information. This API uses an asynchronous callback to return t **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the P2P link information. If **err** is not **0**, an error has occurred.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the P2P link information. If **err** is not **0**, an error has occurred.| -## wifi.getCurrentGroup9+ +## wifi.getCurrentP2pGroup9+ -getCurrentGroup(): Promise<WifiP2pGroupInfo> +getCurrentP2pGroup(): Promise<WifiP2pGroupInfo> Obtains the current P2P group information. This API uses a promise to return the result. -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION +**Required permissions**: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.APPROXIMATELY_LOCATION **System capability**: SystemCapability.Communication.WiFi.P2P **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> | Promise used to return the P2P group information obtained.| +| Type| Description| +| -------- | -------- | +| Promise<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> | Promise used to return the P2P group information obtained.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2801000 | Operation failed.| -## wifi.getCurrentGroup9+ +## wifi.getCurrentP2pGroup9+ -getCurrentGroup(callback: AsyncCallback<WifiP2pGroupInfo>): void +getCurrentP2pGroup(callback: AsyncCallback<WifiP2pGroupInfo>): void Obtains the current P2P group information. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION +**Required permissions**: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.APPROXIMATELY_LOCATION **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2801000 | Operation failed.| +**Example** +``` + import wifi from '@ohos.wifiManager'; + + wifi.getCurrentP2pGroup((err, data) => { + if (err) { + console.error("get current P2P group error"); + return; + } + console.info("get current P2P group: " + JSON.stringify(data)); + }); + + wifi.getCurrentP2pGroup().then(data => { + console.info("get current P2P group: " + JSON.stringify(data)); + }); +``` + ## wifi.getP2pPeerDevices9+ getP2pPeerDevices(): Promise<WifiP2pDevice[]> Obtains the peer device list in the P2P connection. This API uses a promise to return the result. -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION +**Required permissions**: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.APPROXIMATELY_LOCATION **System capability**: SystemCapability.Communication.WiFi.P2P **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[WifiP2pDevice[]](#wifip2pdevice9)> | Promise used to return the peer device list.| +| Type| Description| +| -------- | -------- | +| Promise<[WifiP2pDevice[]](#wifip2pdevice9)> | Promise used to return the peer device list.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2801000 | Operation failed.| ## wifi.getP2pPeerDevices9+ @@ -1595,24 +2199,41 @@ getP2pPeerDevices(callback: AsyncCallback<WifiP2pDevice[]>): void Obtains the peer device list in the P2P connection. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION +**Required permissions**: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.APPROXIMATELY_LOCATION **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[WifiP2pDevice[]](#wifip2pdevice9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the peer device list obtained. If **err** is not **0**, an error has occurred.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[WifiP2pDevice[]](#wifip2pdevice9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the peer device list obtained. If **err** is not **0**, an error has occurred.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2801000 | Operation failed.| +**Example** +``` + import wifi from '@ohos.wifiManager'; + + wifi.getP2pPeerDevices((err, data) => { + if (err) { + console.error("get P2P peer devices error"); + return; + } + console.info("get P2P peer devices: " + JSON.stringify(data)); + }); + + wifi.getP2pPeerDevices().then(data => { + console.info("get P2P peer devices: " + JSON.stringify(data)); + }); +``` + ## WifiP2pDevice9+ Represents the P2P device information. @@ -1655,16 +2276,16 @@ Obtains the local device information in the P2P connection. This API uses a prom **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[WifiP2pDevice](#wifip2pdevice9)> | Promise used to return the local device information obtained.| +| Type| Description| +| -------- | -------- | +| Promise<[WifiP2pDevice](#wifip2pdevice9)> | Promise used to return the local device information obtained.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2801000 | Operation failed.| ## wifi.getP2pLocalDevice9+ @@ -1679,14 +2300,34 @@ Obtains the local device information in the P2P connection. This API uses an asy **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[WifiP2pDevice](#wifip2pdevice9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the local device information obtained. If **err** is not **0**, an error has occurred.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[WifiP2pDevice](#wifip2pdevice9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the local device information obtained. If **err** is not **0**, an error has occurred.| + +| **ID**| **Error Message**| +| -------- | -------- | +| 2801000 | Operation failed.| +**Example** +``` + import wifi from '@ohos.wifiManager'; + + wifiManager.getP2pLocalDevice((err, data) => { + if (err) { + console.error("get P2P local device error"); + return; + } + console.info("get P2P local device: " + JSON.stringify(data)); + }); + + wifi.getP2pLocalDevice().then(data => { + console.info("get P2P local device: " + JSON.stringify(data)); + }); +``` -## wifi.createGroup9+ +## wifi.createP2pGroup9+ -createGroup(config: WifiP2PConfig): void +createP2pGroup(config: WifiP2PConfig): void Creates a P2P group. @@ -1696,18 +2337,37 @@ Creates a P2P group. **Parameters** - | **Name**| **Type**| Mandatory| **Description**| - | -------- | -------- | -------- | -------- | - | config | [WifiP2PConfig](#wifip2pconfig9) | Yes| Group configuration.| +| **Name**| **Type**| Mandatory| **Description**| +| -------- | -------- | -------- | -------- | +| config | [WifiP2PConfig](#wifip2pconfig9) | Yes| Group configuration.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2801000 | Operation failed.| +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + let config = { + deviceAddress: "****", + netId: 0, + passphrase: "*****", + groupName: "****", + goBand: 0 + } + wifiManager.createP2pGroup(config); + + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + ## WifiP2PConfig9+ Represents P2P group configuration. @@ -1736,9 +2396,9 @@ Enumerates the P2P group frequency bands. | GO_BAND_5GHZ | 2 | 5 GHz.| -## wifi.removeGroup9+ +## wifi.removeP2pGroup9+ -removeGroup(): void +removeP2pGroup(): void Removes this P2P group. @@ -1750,33 +2410,43 @@ Removes this P2P group. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2801000 | Operation failed.| +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + wifiManager.removeP2pGroup(); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + ## wifi.p2pConnect9+ p2pConnect(config: WifiP2PConfig): void Sets up a P2P connection. -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION +**Required permissions**: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.APPROXIMATELY_LOCATION **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** - - | **Name**| **Type**| Mandatory| **Description**| - | -------- | -------- | -------- | -------- | - | config | [WifiP2PConfig](#wifip2pconfig9) | Yes| P2P group configuration.| +| **Name**| **Type**| Mandatory| **Description**| +| -------- | -------- | -------- | -------- | +| config | [WifiP2PConfig](#wifip2pconfig9) | Yes| P2P group configuration.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2801000 | Operation failed.| **Example** @@ -1843,7 +2513,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco setTimeout(function() {wifi.off("p2pDeviceChange", recvP2pDeviceChangeFunc);}, 125 * 1000); setTimeout(function() {wifi.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc);}, 125 * 1000); setTimeout(function() {wifi.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc);}, 125 * 1000); - console.info("start discover devices -> " + wifi.startDiscoverDevices()); + console.info("start discover devices -> " + wifi.startP2pDiscoverDevices()); ``` ## wifi.p2pCancelConnect9+ @@ -1860,17 +2530,28 @@ Cancels this P2P connection. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2801000 | Operation failed.| -## wifi.startDiscoverDevices9+ +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + wifiManager.p2pCancelConnect(); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + +## wifi.startDiscoverP2pDevices9+ -startDiscoverDevices(): void +startDiscoverP2pDevices(): void Starts to discover devices. -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION +**Required permissions**: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.APPROXIMATELY_LOCATION **System capability**: SystemCapability.Communication.WiFi.P2P @@ -1878,13 +2559,24 @@ Starts to discover devices. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2801000 | Operation failed.| -## wifi.stopDiscoverDevices9+ +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + wifiManager.startDiscoverP2pDevices(); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + +## wifi.stopDiscoverP2pDevices9+ -stopDiscoverDevices(): void +stopDiscoverP2pDevices(): void Stops discovering devices. @@ -1896,13 +2588,24 @@ Stops discovering devices. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2801000 | Operation failed.| -## wifi.deletePersistentGroup9+ +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + wifiManager.stopDiscoverP2pDevices(); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + +## wifi.deletePersistentP2pGroup9+ -deletePersistentGroup(netId: number): void +deletePersistentP2pGroup(netId: number): void Deletes a persistent group. @@ -1915,18 +2618,30 @@ Deletes a persistent group. **Parameters** - | **Name**| **Type**| Mandatory| **Description**| - | -------- | -------- | -------- | -------- | - | netId | number | Yes| ID of the group to delete.| +| **Name**| **Type**| Mandatory| **Description**| +| -------- | -------- | -------- | -------- | +| netId | number | Yes| ID of the group to delete.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2801000 | Operation failed.| +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + let netId = 0; + wifiManager.deletePersistentP2pGroup(netId); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + ## wifi.getP2pGroups9+ getP2pGroups(): Promise<Array<WifiP2pGroupInfo>> @@ -1935,24 +2650,42 @@ Obtains information about all P2P groups. This API uses a promise to return the **System API**: This is a system API. -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION +**Required permissions**: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.APPROXIMATELY_LOCATION **System capability**: SystemCapability.Communication.WiFi.P2P **Return value** - | Type| Description| - | -------- | -------- | - | Promise< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> > | Promise used to return the group information obtained.| +| Type| Description| +| -------- | -------- | +| Promise< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> > | Promise used to return the group information obtained.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2801000 | Operation failed.| +**Example** +``` + import wifi from '@ohos.wifiManager'; + + wifiManager.getP2pGroups((err, data) => { + if (err) { + console.error("get P2P groups error"); + return; + } + console.info("get P2P groups: " + JSON.stringify(data)); + }); + + wifi.getP2pGroups().then(data => { + console.info("get P2P groups: " + JSON.stringify(data)); + }); + +``` + ## WifiP2pGroupInfo9+ Represents the P2P group information. @@ -1980,27 +2713,27 @@ Obtains information about all P2P groups. This API uses an asynchronous callback **System API**: This is a system API. -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION +**Required permissions**: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.APPROXIMATELY_LOCATION **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo9)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo9)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2801000 | Operation failed.| -## wifi.setDeviceName9+ +## wifi.setP2pDeviceName9+ -setDeviceName(devName: string): void +setP2pDeviceName(devName: string): void Sets the device name. @@ -2012,18 +2745,30 @@ Sets the device name. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | devName | string | Yes| Device name to set.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| devName | string | Yes| Device name to set.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2801000 | Operation failed.| +**Example** +``` + import wifi from '@ohos.wifiManager'; + + try { + let name = "****"; + wifiManager.setP2pDeviceName(netId); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + ## wifi.on('wifiStateChange')9+ on(type: "wifiStateChange", callback: Callback<number>): void @@ -2036,17 +2781,17 @@ Registers the WLAN state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **wifiStateChange**.| - | callback | Callback<number> | Yes| Callback invoked to return the WLAN state.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **wifiStateChange**.| +| callback | Callback<number> | Yes| Callback invoked to return the WLAN state.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| **WLAN states** @@ -2071,17 +2816,17 @@ Unregisters the WLAN state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **wifiStateChange**.| - | callback | Callback<number> | No| Callback for the WLAN state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **wifiStateChange**.| +| callback | Callback<number> | No| Callback for the WLAN state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| **Example** @@ -2112,10 +2857,10 @@ Registers the WLAN connection state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **wifiConnectionChange**.| - | callback | Callback<number> | Yes| Callback invoked to return the WLAN connection state.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **wifiConnectionChange**.| +| callback | Callback<number> | Yes| Callback invoked to return the WLAN connection state.| **WLAN connection states** @@ -2128,8 +2873,8 @@ Registers the WLAN connection state change events. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| ## wifi.off('wifiConnectionChange')9+ @@ -2144,19 +2889,34 @@ Unregisters the WLAN connection state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **wifiConnectionChange**.| - | callback | Callback<number> | No| Callback for the WLAN connection state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **wifiConnectionChange**.| +| callback | Callback<number> | No| Callback for the WLAN connection state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| +**Example** + ```js + import wifi from '@ohos.wifi'; + + var recvWifiConnectionChangeFunc = result => { + console.info("Receive wifi connection change event: " + result); + } + + // Register an event. + wifi.on("wifiConnectionChange", recvWifiConnectionChangeFunc); + + // Unregister an event. + wifi.off("wifiConnectionChange", recvWifiConnectionChangeFunc); + ``` + ## wifi.on('wifiScanStateChange')9+ on(type: "wifiScanStateChange", callback: Callback<number>): void @@ -2169,10 +2929,10 @@ Registers the WLAN scan state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **wifiScanStateChange**.| - | callback | Callback<number> | Yes| Callback invoked to return the WLAN scan state.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **wifiScanStateChange**.| +| callback | Callback<number> | Yes| Callback invoked to return the WLAN scan state.| **WLAN scan states** @@ -2185,8 +2945,8 @@ Registers the WLAN scan state change events. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| ## wifi.off('wifiScanStateChange')9+ @@ -2210,10 +2970,25 @@ Unregisters the WLAN scan state change events. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| +**Example** + ```js + import wifi from '@ohos.wifi'; + + var recvWifiScanStateChangeFunc = result => { + console.info("Receive Wifi scan state change event: " + result); + } + + // Register an event. + wifi.on("wifiScanStateChange", recvWifiScanStateChangeFunc); + + // Unregister an event. + wifi.off("wifiScanStateChange", recvWifiScanStateChangeFunc); + ``` + ## wifi.on('wifiRssiChange')9+ on(type: "wifiRssiChange", callback: Callback<number>): void @@ -2226,17 +3001,17 @@ Registers the RSSI change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **wifiRssiChange**.| - | callback | Callback<number> | Yes| Callback invoked to return the RSSI, in dBm.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **wifiRssiChange**.| +| callback | Callback<number> | Yes| Callback invoked to return the RSSI, in dBm.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| ## wifi.off('wifiRssiChange')9+ @@ -2251,19 +3026,34 @@ Unregisters the RSSI change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **wifiRssiChange**.| - | callback | Callback<number> | No| Callback for the RSSI change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **wifiRssiChange**.| +| callback | Callback<number> | No| Callback for the RSSI change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2501000 | Operation failed.| +**Example** + ```js + import wifi from '@ohos.wifiManager'; + + var recvWifiRssiChangeFunc = result => { + console.info("Receive wifi rssi change event: " + result); + } + + // Register an event. + wifiManager.on("wifiRssiChange", recvWifiRssiChangeFunc); + + // Unregister an event. + wifiManager.off("wifiRssiChange", recvWifiRssiChangeFunc); + ``` + ## wifi.on('hotspotStateChange')9+ on(type: "hotspotStateChange", callback: Callback<number>): void @@ -2276,10 +3066,10 @@ Registers the hotspot state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **hotspotStateChange**.| - | callback | Callback<number> | Yes| Callback invoked to return the hotspot state.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **hotspotStateChange**.| +| callback | Callback<number> | Yes| Callback invoked to return the hotspot state.| **Hotspot states** @@ -2294,8 +3084,8 @@ Registers the hotspot state change events. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2601000 | Operation failed.| ## wifi.off('hotspotStateChange')9+ @@ -2310,19 +3100,34 @@ Unregisters the hotspot state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **hotspotStateChange**.| - | callback | Callback<number> | No| Callback for the hotspot state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **hotspotStateChange**.| +| callback | Callback<number> | No| Callback for the hotspot state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2601000 | Operation failed.| +**Example** + ```js + import wifi from '@ohos.wifiManager'; + + var recvHotspotStateChangeFunc = result => { + console.info("Receive hotspot state change event: " + result); + } + + // Register an event. + wifiManager.on("hotspotStateChange", recvHotspotStateChangeFunc); + + // Unregister an event. + wifiManager.off("hotspotStateChange", recvHotspotStateChangeFunc); + ``` + ## wifi.on('p2pStateChange')9+ on(type: "p2pStateChange", callback: Callback<number>): void @@ -2335,10 +3140,10 @@ Registers the P2P state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pStateChange**.| - | callback | Callback<number> | Yes| Callback invoked to return the P2P state.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pStateChange**.| +| callback | Callback<number> | Yes| Callback invoked to return the P2P state.| **P2P states** @@ -2354,8 +3159,8 @@ Registers the P2P state change events. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2801000 | Operation failed.| ## wifi.off('p2pStateChange')9+ @@ -2370,19 +3175,34 @@ Unregisters the P2P state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pStateChange**.| - | callback | Callback<number> | No| Callback for the P2P state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pStateChange**.| +| callback | Callback<number> | No| Callback for the P2P state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2801000 | Operation failed.| +**Example** + ```js + import wifi from '@ohos.wifiManager'; + + var recvP2pStateChangeFunc = result => { + console.info("Receive p2p state change event: " + result); + } + + // Register an event. + wifiManager.on("p2pStateChange", recvP2pStateChangeFunc); + + // Unregister an event. + wifiManager.off("p2pStateChange", recvP2pStateChangeFunc); + ``` + ## wifi.on('p2pConnectionChange')9+ on(type: "p2pConnectionChange", callback: Callback<WifiP2pLinkedInfo>): void @@ -2395,17 +3215,17 @@ Registers the P2P connection state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pConnectionChange**.| - | callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | Yes| Callback invoked to return the P2P connection state.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pConnectionChange**.| +| callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | Yes| Callback invoked to return the P2P connection state.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2801000 | Operation failed.| ## wifi.off('p2pConnectionChange')9+ @@ -2420,42 +3240,57 @@ Unregisters the P2P connection state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pConnectionChange**.| - | callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | No| Callback for the P2P connection state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pConnectionChange**.| +| callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | No| Callback for the P2P connection state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2801000 | Operation failed.| +**Example** + ```js + import wifi from '@ohos.wifiManager'; + + var recvP2pConnectionChangeFunc = result => { + console.info("Receive p2p connection change event: " + result); + } + + // Register an event. + wifiManager.on("p2pConnectionChange", recvP2pConnectionChangeFunc); + + // Unregister an event. + wifiManager.off("p2pConnectionChange", recvP2pConnectionChangeFunc); + ``` + ## wifi.on('p2pDeviceChange')9+ on(type: "p2pDeviceChange", callback: Callback<WifiP2pDevice>): void Registers the P2P device state change events. -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION +**Required permissions**: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.APPROXIMATELY_LOCATION **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pDeviceChange**.| - | callback | Callback<[WifiP2pDevice](#wifip2pdevice9)> | Yes| Callback invoked to return the P2P device state.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pDeviceChange**.| +| callback | Callback<[WifiP2pDevice](#wifip2pdevice9)> | Yes| Callback invoked to return the P2P device state.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2801000 | Operation failed.| ## wifi.off('p2pDeviceChange')9+ @@ -2464,48 +3299,63 @@ off(type: "p2pDeviceChange", callback?: Callback<WifiP2pDevice>): void Unregisters the P2P device state change events. -**Required permissions**: ohos.permission.LOCATION +**Required permissions**: ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pDeviceChange**.| - | callback | Callback<[WifiP2pDevice](#wifip2pdevice9)> | No| Callback for the P2P device state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pDeviceChange**.| +| callback | Callback<[WifiP2pDevice](#wifip2pdevice9)> | No| Callback for the P2P device state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2801000 | Operation failed.| +**Example** + ```js + import wifi from '@ohos.wifiManager'; + + var recvP2pDeviceChangeFunc = result => { + console.info("Receive recv p2p device change event: " + result); + } + + // Register an event. + wifiManager.on("p2pDeviceChange", recvP2pDeviceChangeFunc); + + // Unregister an event. + wifiManager.off("p2pDeviceChange", recvP2pDeviceChangeFunc); + ``` + ## wifi.on('p2pPeerDeviceChange')9+ on(type: "p2pPeerDeviceChange", callback: Callback<WifiP2pDevice[]>): void Registers the P2P peer device state change events. -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION +**Required permissions**: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.APPROXIMATELY_LOCATION **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| - | callback | Callback<[WifiP2pDevice[]](#wifip2pdevice9)> | Yes| Callback invoked to return the P2P peer device state.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| +| callback | Callback<[WifiP2pDevice[]](#wifip2pdevice9)> | Yes| Callback invoked to return the P2P peer device state.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2801000 | Operation failed.| ## wifi.off('p2pPeerDeviceChange')9+ @@ -2514,25 +3364,40 @@ off(type: "p2pPeerDeviceChange", callback?: Callback<WifiP2pDevice[]>): vo Unregisters the P2P peer device state change events. -**Required permissions**: ohos.permission.LOCATION +**Required permissions**: ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| - | callback | Callback<[WifiP2pDevice[]](#wifip2pdevice9)> | No| Callback for the P2P peer device state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| +| callback | Callback<[WifiP2pDevice[]](#wifip2pdevice9)> | No| Callback for the P2P peer device state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2801000 | Operation failed.| +**Example** + ```js + import wifi from '@ohos.wifiManager'; + + var recvP2pPeerDeviceChangeFunc = result => { + console.info("Receive recv p2p peer device change event: " + result); + } + + // Register an event. + wifiManager.on("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); + + // Unregister an event. + wifiManager.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); + ``` + ## wifi.on('p2pPersistentGroupChange')9+ on(type: "p2pPersistentGroupChange", callback: Callback<void>): void @@ -2545,17 +3410,17 @@ Registers the P2P persistent group state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| - | callback | Callback<void> | Yes| Callback invoked to return the P2P persistent group state.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| +| callback | Callback<void> | Yes| Callback invoked to return the P2P persistent group state.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2801000 | Operation failed.| ## wifi.off('p2pPersistentGroupChange')9+ @@ -2570,19 +3435,34 @@ Unregisters the P2P persistent group state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| - | callback | Callback<void> | No| Callback for the P2P persistent group state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| +| callback | Callback<void> | No| Callback for the P2P persistent group state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2801000 | Operation failed.| +**Example** + ```js + import wifi from '@ohos.wifiManager'; + + var recvP2pPersistentGroupChangeFunc = result => { + console.info("Receive recv p2p persistent group change event: " + result); + } + + // Register an event. + wifiManager.on("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); + + // Unregister an event. + wifiManager.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); + ``` + ## wifi.on('p2pDiscoveryChange')9+ on(type: "p2pDiscoveryChange", callback: Callback<number>): void @@ -2595,10 +3475,10 @@ Registers the P2P device discovery state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| - | callback | Callback<number> | Yes| Callback invoked to return the P2P device discovery state.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| +| callback | Callback<number> | Yes| Callback invoked to return the P2P device discovery state.| **P2P discovered device states** @@ -2611,8 +3491,8 @@ Registers the P2P device discovery state change events. For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2801000 | Operation failed.| ## wifi.off('p2pDiscoveryChange')9+ @@ -2627,15 +3507,30 @@ Unregisters the P2P device discovery state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| - | callback | Callback<number> | No| Callback for the P2P device discovery state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| +| callback | Callback<number> | No| Callback for the P2P device discovery state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). -| **Type**| **Description**| - | -------- | -------- | +| **ID**| **Error Message**| +| -------- | -------- | | 2801000 | Operation failed.| + +**Example** + ```js + import wifi from '@ohos.wifiManager'; + + var recvP2pDiscoveryChangeFunc = result => { + console.info("Receive recv p2p discovery change event: " + result); + } + + // Register an event. + wifiManager.on("p2pDiscoveryChange", recvP2pDiscoveryChangeFunc); + + // Unregister an event. + wifiManager.off("p2pDiscoveryChange", recvP2pDiscoveryChangeFunc); + ``` diff --git a/en/application-dev/reference/apis/js-apis-worker.md b/en/application-dev/reference/apis/js-apis-worker.md index 490e283c3689bbcf602bbe0c826ffc579523b426..7c74cdefcec7c61d2d2731ab64eae2f092a340ec 100644 --- a/en/application-dev/reference/apis/js-apis-worker.md +++ b/en/application-dev/reference/apis/js-apis-worker.md @@ -83,9 +83,9 @@ import worker from '@ohos.worker'; // Create a Worker instance. // In the FA model, the workers directory is at the same level as the pages directory in the entry module. -const workerFAModel01 = new worker.ThreadWorker("workers/worker.js", {name:"first worker in FA model"}); +const workerFAModel01 = new worker.ThreadWorker("workers/worker.ts", {name:"first worker in FA model"}); // In the FA model, the workers directory is at the same level as the parent directory of the pages directory in the entry module. -const workerFAModel02 = new worker.ThreadWorker("../workers/worker.js"); +const workerFAModel02 = new worker.ThreadWorker("../workers/worker.ts"); // In the stage model, the workers directory is at the same level as the pages directory in the entry module. const workerStageModel01 = new worker.ThreadWorker('entry/ets/workers/worker.ts', {name:"first worker in Stage model"}); @@ -872,13 +872,13 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example** ```js -// main.js +// Main thread import worker from '@ohos.worker'; const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.postMessage("hello world"); workerInstance.onmessage = function(e) { // let data = e.data; - console.log("receive data from worker.js"); + console.log("receive data from worker.ts"); } ``` @@ -920,13 +920,13 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example** ```js -// main.js +// Main thread import worker from '@ohos.worker'; const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.postMessage("hello world"); workerInstance.onmessage = function(e) { // let data = e.data; - console.log("receive data from worker.js"); + console.log("receive data from worker.ts"); } ``` @@ -936,7 +936,7 @@ import worker from '@ohos.worker'; const workerPort = worker.workerPort; workerPort.onmessage = function(e){ // let data = e.data; - workerPort.postMessage("receive data from main.js"); + workerPort.postMessage("receive data from main thread"); } ``` @@ -960,7 +960,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example** ```js -// main.js +// Main thread import worker from '@ohos.worker'; const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); ``` @@ -1002,7 +1002,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example** ```js -// main.js +// Main thread import worker from '@ohos.worker'; const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.postMessage("hello world"); @@ -1013,7 +1013,7 @@ workerInstance.postMessage("hello world"); import worker from '@ohos.worker'; const workerPort = worker.workerPort; workerPort.onmessage = function(e) { - console.log("receive main.js message"); + console.log("receive main thread message"); } ``` @@ -1045,7 +1045,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco **Example** ```js -// main.js +// Main thread import worker from '@ohos.worker'; const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); ``` @@ -1055,7 +1055,7 @@ const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); import worker from '@ohos.worker'; const parentPort = worker.workerPort; parentPort.onmessageerror = function(e) { - console.log("worker.js onmessageerror") + console.log("worker.ts onmessageerror") } ``` @@ -1130,7 +1130,7 @@ Defines the event handler to be called when an exception occurs during worker ex **Example** ```js -// main.js +// Main thread import worker from '@ohos.worker'; const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts") ``` @@ -1140,7 +1140,7 @@ const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts") import worker from '@ohos.worker'; const workerPort = worker.workerPort workerPort.onerror = function(e){ - console.log("worker.js onerror") + console.log("worker.ts onerror") } ``` @@ -1193,9 +1193,9 @@ import worker from '@ohos.worker'; // Create a Worker instance. // In the FA model, the workers directory is at the same level as the pages directory. -const workerFAModel01 = new worker.Worker("workers/worker.js", {name:"first worker in FA model"}); +const workerFAModel01 = new worker.Worker("workers/worker.ts", {name:"first worker in FA model"}); // In the FA model, the workers directory is at the same level as the parent directory of the pages directory. -const workerFAModel02 = new worker.Worker("../workers/worker.js"); +const workerFAModel02 = new worker.Worker("../workers/worker.ts"); // In the stage model, the workers directory is at the same level as the pages directory. const workerStageModel01 = new worker.Worker('entry/ets/workers/worker.ts', {name:"first worker in Stage model"}); @@ -1275,7 +1275,7 @@ Sends a message to the worker thread. The data type of the message must be seque **Example** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); var buffer = new ArrayBuffer(8); workerInstance.postMessage(buffer, [buffer]); @@ -1302,7 +1302,7 @@ Sends a message to the worker thread. The data type of the message must be seque **Example** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.postMessage("hello world"); @@ -1332,7 +1332,7 @@ Adds an event listener for the worker thread. This API provides the same functio **Example** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.on("alert", (e)=>{ console.log("alert listener callback"); }) @@ -1360,7 +1360,7 @@ Adds an event listener for the worker thread and removes the event listener afte **Example** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.once("alert", (e)=>{ console.log("alert listener callback"); }) @@ -1388,7 +1388,7 @@ Removes an event listener for the worker thread. This API provides the same func **Example** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); // Use on, once, or addEventListener to add a listener for the "alert" event, and use off to remove the listener. workerInstance.off("alert"); ``` @@ -1408,7 +1408,7 @@ Terminates the worker thread to stop it from receiving messages. **Example** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.terminate(); ``` @@ -1433,7 +1433,7 @@ Defines the event handler to be called when the worker thread exits. The handler **Example** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.onexit = function(e) { console.log("onexit"); } @@ -1467,7 +1467,7 @@ Defines the event handler to be called when an exception occurs during worker ex **Example** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.onerror = function(e) { console.log("onerror"); } @@ -1489,12 +1489,12 @@ Defines the event handler to be called when the host thread receives a message s | Name| Type | Mandatory| Description | | ------ | ------------------------------ | ---- | ---------------------- | -| event | [MessageEvent](#messageeventt) | Yes | Message received.| +| event | [MessageEvent](#messageeventt)| Yes | Message received.| **Example** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.onmessage = function(e) { // e: MessageEvent. The usage is as follows: // let data = e.data; @@ -1518,12 +1518,12 @@ Defines the event handler to be called when the worker thread receives a message | Name| Type | Mandatory| Description | | ------ | ------------------------------ | ---- | ---------- | -| event | [MessageEvent](#messageeventt) | Yes | Error data.| +| event | [MessageEvent](#messageeventt)| Yes | Error data.| **Example** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.onmessageerror= function(e) { console.log("onmessageerror"); } @@ -1555,7 +1555,7 @@ Adds an event listener for the worker thread. This API provides the same functio **Example** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); }) @@ -1583,7 +1583,7 @@ Removes an event listener for the worker thread. This API provides the same func **Example** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); }) @@ -1617,7 +1617,7 @@ Dispatches the event defined for the worker thread. **Example** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.dispatchEvent({type:"eventType", timeStamp:0}); // timeStamp is not supported yet. ``` @@ -1625,7 +1625,7 @@ workerInstance.dispatchEvent({type:"eventType", timeStamp:0}); // timeStamp is n The **dispatchEvent** API can be used together with the **on**, **once**, and **addEventListener** APIs. The sample code is as follows: ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); // Usage 1: workerInstance.on("alert_on", (e)=>{ @@ -1677,7 +1677,7 @@ Removes all event listeners for the worker thread. **Example** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); }) @@ -1732,17 +1732,17 @@ Sends a message to the host thread from the worker thread. **Example** ```js -// main.js +// Main thread import worker from '@ohos.worker'; -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.postMessage("hello world"); workerInstance.onmessage = function(e) { // let data = e.data; - console.log("receive data from worker.js"); + console.log("receive data from worker.ts"); } ``` ```js -// worker.js +// worker.ts import worker from '@ohos.worker'; const parentPort = worker.parentPort; parentPort.onmessage = function(e){ @@ -1773,22 +1773,22 @@ Sends a message to the host thread from the worker thread. **Example** ```js -// main.js +// Main thread import worker from '@ohos.worker'; -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.postMessage("hello world"); workerInstance.onmessage = function(e) { // let data = e.data; - console.log("receive data from worker.js"); + console.log("receive data from worker.ts"); } ``` ```js -// worker.js +// worker.ts import worker from '@ohos.worker'; const parentPort = worker.parentPort; parentPort.onmessage = function(e){ // let data = e.data; - parentPort.postMessage("receive data from main.js"); + parentPort.postMessage("receive data from main thread"); } ``` @@ -1806,12 +1806,12 @@ Terminates the worker thread to stop it from receiving messages. **Example** ```js -// main.js +// Main thread import worker from '@ohos.worker'; -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); ``` ```js -// worker.js +// worker.ts import worker from '@ohos.worker'; const parentPort = worker.parentPort; parentPort.onmessage = function(e) { @@ -1836,22 +1836,22 @@ Defines the event handler to be called when the worker thread receives a message | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------ | | this | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscopedeprecated) | Yes | Caller. | -| ev | [MessageEvent](#messageeventt) | Yes | Message received.| +| ev | [MessageEvent](#messageeventt) | Yes | Message received.| **Example** ```js -// main.js +// Main thread import worker from '@ohos.worker'; -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.postMessage("hello world"); ``` ```js -// worker.js +// worker.ts import worker from '@ohos.worker'; const parentPort = worker.parentPort; parentPort.onmessage = function(e) { - console.log("receive main.js message"); + console.log("receive main thread message"); } ``` @@ -1872,21 +1872,21 @@ Defines the event handler to be called when the worker thread receives a message | Name| Type | Mandatory| Description | | ------ | ------------------------------ | ---- | ---------- | | this | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscopedeprecated) | Yes | Caller.| -| ev | [MessageEvent](#messageeventt) | Yes | Error data.| +| ev | [MessageEvent](#messageeventt)| Yes | Error data.| **Example** ```js -// main.js +// Main thread import worker from '@ohos.worker'; -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); ``` ```js -// worker.js +// worker.ts import worker from '@ohos.worker'; const parentPort = worker.parentPort; parentPort.onmessageerror = function(e) { - console.log("worker.js onmessageerror") + console.log("worker.ts onmessageerror") } ``` @@ -1940,7 +1940,7 @@ Implements event listening. **Example** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); }) @@ -2010,16 +2010,16 @@ Defines the event handler to be called when an exception occurs during worker ex **Example** ```js -// main.js +// Main thread import worker from '@ohos.worker'; -const workerInstance = new worker.Worker("workers/worker.js") +const workerInstance = new worker.Worker("workers/worker.ts") ``` ```js -// worker.js +// worker.ts import worker from '@ohos.worker'; const parentPort = worker.parentPort parentPort.onerror = function(e){ - console.log("worker.js onerror") + console.log("worker.ts onerror") } ``` @@ -2045,17 +2045,17 @@ Exception: When an object created through a custom class is passed, no serializa > An FA project of API version 9 is used as an example. ```js -// main.js +// Main thread import worker from '@ohos.worker'; -const workerInstance = new worker.ThreadWorker("workers/worker.js"); -workerInstance.postMessage("message from main to worker"); +const workerInstance = new worker.ThreadWorker("workers/worker.ts"); +workerInstance.postMessage("message from main thread to worker"); workerInstance.onmessage = function(d) { // When the worker thread passes obj2, data contains obj2, excluding the Init or SetName method. let data = d.data; } ``` ```js -// worker.js +// worker.ts import worker from '@ohos.worker'; const workerPort = worker.workerPort; class MyModel { @@ -2065,7 +2065,7 @@ class MyModel { } } workerPort.onmessage = function(d) { - console.log("worker.js onmessage"); + console.log("worker.ts onmessage"); let data = d.data; let func1 = function() { console.log("post message is function"); @@ -2083,10 +2083,10 @@ workerPort.onmessage = function(d) { workerPort.postMessage(obj2); // No serialization error occurs when passing obj2. } workerPort.onmessageerror = function(e) { - console.log("worker.js onmessageerror"); + console.log("worker.ts onmessageerror"); } workerPort.onerror = function(e) { - console.log("worker.js onerror"); + console.log("worker.ts onerror"); } ``` @@ -2111,15 +2111,10 @@ Each actor concurrently processes tasks of the main thread. For each actor, ther ### FA Model ```js -// main.js (The following assumes that the workers directory and pages directory are at the same level.) +// Main thread (The following assumes that the workers directory and pages directory are at the same level.) import worker from '@ohos.worker'; // Create a Worker instance in the main thread. const workerInstance = new worker.ThreadWorker("workers/worker.ts"); -// Create either a .json or .ts file. -// const workerInstance = new worker.ThreadWorker("workers/worker.js"); - -// In versions earlier than API version 9, use the following to create a Worker instance in the main thread. -// const workerInstance = new worker.Worker("workers/worker.js"); // The main thread transfers information to the worker thread. workerInstance.postMessage("123"); @@ -2128,7 +2123,7 @@ workerInstance.postMessage("123"); workerInstance.onmessage = function(e) { // data carries the information sent by the worker thread. let data = e.data; - console.log("main.js onmessage"); + console.log("main thread onmessage"); // Terminate the Worker instance. workerInstance.terminate(); @@ -2136,7 +2131,7 @@ workerInstance.onmessage = function(e) { // Call onexit(). workerInstance.onexit = function() { - console.log("main.js terminate"); + console.log("main thread terminate"); } ``` ```js @@ -2146,9 +2141,6 @@ import worker from '@ohos.worker'; // Create an object in the worker thread for communicating with the main thread. const workerPort = worker.workerPort -// In versions earlier than API version 9, use the following to create an object in the worker thread for communicating with the main thread. -// const parentPort = worker.parentPort - // The worker thread receives information from the main thread. workerPort.onmessage = function(e) { // data carries the information sent by the main thread. @@ -2176,13 +2168,11 @@ Configuration of the **build-profile.json5** file: ``` ### Stage Model ```js -// main.js (The following assumes that the workers directory and pages directory are at different levels.) +// Main thread (The following assumes that the workers directory and pages directory are at different levels.) import worker from '@ohos.worker'; // Create a Worker instance in the main thread. const workerInstance = new worker.ThreadWorker("entry/ets/pages/workers/worker.ts"); -// Create either a .json or .ts file. -// const workerInstance = new worker.ThreadWorker("entry/ets/pages/workers/worker.js"); // The main thread transfers information to the worker thread. workerInstance.postMessage("123"); @@ -2191,14 +2181,14 @@ workerInstance.postMessage("123"); workerInstance.onmessage = function(e) { // data carries the information sent by the worker thread. let data = e.data; - console.log("main.js onmessage"); + console.log("main thread onmessage"); // Terminate the Worker instance. workerInstance.terminate(); } // Call onexit(). workerInstance.onexit = function() { - console.log("main.js terminate"); + console.log("main thread terminate"); } ``` ```js diff --git a/en/application-dev/reference/arkui-js/js-components-container-div.md b/en/application-dev/reference/arkui-js/js-components-container-div.md index e35eb42639301cfb6ce1a9a45880217ce1daf54b..295e0bd4d35d6ec824471b745fd7320b517d4ba6 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-div.md +++ b/en/application-dev/reference/arkui-js/js-components-container-div.md @@ -385,25 +385,25 @@ In addition to the [universal methods](js-components-common-methods.md), the fol ```js // xxx.js - import prompt from '@system.prompt'; + import promptAction from '@ohos.promptAction'; export default { pinchstart(e){ - prompt.showToast({ + promptAction.showToast({ message: 'pinchstart!!!' }) }, pinchupdate(e){ - prompt.showToast({ + promptAction.showToast({ message: 'Two-finger pinch update' }) }, pinchend(e){ - prompt.showToast({ + promptAction.showToast({ message: 'Finished with two fingers pinching' }) }, pinchcancel(e){ - prompt.showToast({ + promptAction.showToast({ message: 'Finger pinching is interrupted' }) } diff --git a/en/application-dev/reference/arkui-ts/figures/LoadingProgress.gif b/en/application-dev/reference/arkui-ts/figures/LoadingProgress.gif index 90d9c7bba27ef616fb6bfdea407358df25ac6f91..60d551dd3f1de3a5443bc594c5080b5692704fd0 100644 Binary files a/en/application-dev/reference/arkui-ts/figures/LoadingProgress.gif and b/en/application-dev/reference/arkui-ts/figures/LoadingProgress.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/animationComponent1.png b/en/application-dev/reference/arkui-ts/figures/animationComponent1.png deleted file mode 100644 index b2aa53b14b112434bb736d2dc2f301bac3b46043..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/animationComponent1.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/animationComponent2.png b/en/application-dev/reference/arkui-ts/figures/animationComponent2.png deleted file mode 100644 index c348c9305503698fab2f6b401450048a653e581a..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/animationComponent2.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/animationComponent3.png b/en/application-dev/reference/arkui-ts/figures/animationComponent3.png deleted file mode 100644 index b53d8f308a879d4b4ce84db7adac1289c8b85cfa..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/animationComponent3.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/animationComponent4.png b/en/application-dev/reference/arkui-ts/figures/animationComponent4.png deleted file mode 100644 index a93f8390861d3638a35de13f38e2ab51816b8083..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/animationComponent4.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/colorFilter.gif b/en/application-dev/reference/arkui-ts/figures/colorFilter.gif new file mode 100644 index 0000000000000000000000000000000000000000..e326b328a292ca96b3c2b687128d51cce1106d27 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/colorFilter.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001212058460.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001212058460.gif deleted file mode 100644 index f70d75a50c028de29ab4b60075b7644316927eab..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001212058460.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256978335.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256978335.gif deleted file mode 100644 index 7a0a33ad1f90625edd3f24f7c8702ada65d6febd..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256978335.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/list3.gif b/en/application-dev/reference/arkui-ts/figures/list3.gif new file mode 100644 index 0000000000000000000000000000000000000000..fee786913eb846e96189bf852e199d9185c7dafa Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/list3.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/pageTransition1.gif b/en/application-dev/reference/arkui-ts/figures/pageTransition1.gif new file mode 100644 index 0000000000000000000000000000000000000000..a8a8623279b5a93ca40461d522ccdb48eede1c42 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/pageTransition1.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/pageTransition2.gif b/en/application-dev/reference/arkui-ts/figures/pageTransition2.gif new file mode 100644 index 0000000000000000000000000000000000000000..d1ef2f2889cac0428733478c6d81cc8e0b1ad84c Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/pageTransition2.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/transitionComponent1.gif b/en/application-dev/reference/arkui-ts/figures/transitionComponent1.gif new file mode 100644 index 0000000000000000000000000000000000000000..6b5dd0f0ca7d09218af2641e4ae2900eb394623d Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/transitionComponent1.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/transitionComponent2.gif b/en/application-dev/reference/arkui-ts/figures/transitionComponent2.gif new file mode 100644 index 0000000000000000000000000000000000000000..80b08806d4cdf08effc321bf64bba653d4a7398b Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/transitionComponent2.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/transitionComponent3.gif b/en/application-dev/reference/arkui-ts/figures/transitionComponent3.gif new file mode 100644 index 0000000000000000000000000000000000000000..2ff38b3e852bb8bcfabe5dc4e924cec0fa363c39 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/transitionComponent3.gif differ diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-blank.md b/en/application-dev/reference/arkui-ts/ts-basic-components-blank.md index 12e26b39a1c19111f5e6feaa868d16a18d7b11ac..7ddaa3e007c8403fbd7e3e8f0df85af0ed2bc8a2 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-blank.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-blank.md @@ -1,6 +1,6 @@ # Blank -The **\** component is able to automatically fill the empty spaces in the container along the main axis. It is valid only when the parent container is **\** or **\**. +The **\** component is able to automatically fill the empty spaces in the container along the main axis. It works only when the parent component is **\**, **\**, or **\**. > **NOTE** > @@ -30,7 +30,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Description| | -------- | -------- | -------- | -| color | [ResourceColor](ts-types.md#resourcecolor) | Color to fill the empty spaces.
Default value: **Color.Transparent**
Since API version 9, this API is supported in ArkTS widgets. | +| color | [ResourceColor](ts-types.md#resourcecolor) | Color to fill the empty spaces.
Default value: **Color.Transparent**
Since API version 9, this API is supported in ArkTS widgets.| ## Events @@ -50,7 +50,7 @@ struct BlankExample { Row() { Text('Bluetooth').fontSize(18) Blank() - Toggle({ type: ToggleType.Switch }) + Toggle({ type: ToggleType.Switch }).margin({ top: 14, bottom: 14, left: 6, right: 6 }) }.width('100%').backgroundColor(0xFFFFFF).borderRadius(15).padding({ left: 12 }) }.backgroundColor(0xEFEFEF).padding(20) } @@ -80,16 +80,16 @@ struct BlankExample { Row() { Text('Bluetooth').fontSize(18) Blank().color(Color.Yellow) - Toggle({ type: ToggleType.Switch }) + Toggle({ type: ToggleType.Switch }).margin({ top: 14, bottom: 14, left: 6, right: 6 }) }.backgroundColor(0xFFFFFF).borderRadius(15).padding({ left: 12 }) Row() { Text('Bluetooth').fontSize(18) // Set the minimum width to 160. Blank('160').color(Color.Yellow) - Toggle({ type: ToggleType.Switch }) + Toggle({ type: ToggleType.Switch }).margin({ top: 14, bottom: 14, left: 6, right: 6 }) }.backgroundColor(0xFFFFFF).borderRadius(15).padding({ left: 12 }) - + }.backgroundColor(0xEFEFEF).padding(20).width('100%') } } diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-image.md b/en/application-dev/reference/arkui-ts/ts-basic-components-image.md index c14914b75ae50d9a2c78ee01514261e60aecfcef..ad23abd051a1cae666be7b4038e86fba30147fcc 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-image.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-image.md @@ -29,7 +29,7 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Type | Mandatory | Description | | ---- | ---------------------------------------- | ---- | ---------------------------------------- | -| src | [PixelMap](../apis/js-apis-image.md#pixelmap7) \|ResourceStr\| [DrawableDescriptor](../apis/js-apis-arkui-drawableDescriptor.md#drawabledescriptor) | Yes | Image source. Both local and online images are supported.
When using an image referenced using a relative path, for example, **Image("common/test.jpg")**, the **\** component cannot be called across bundles or modules. Therefore, you are advised to use **\$r** to reference image resources that need to be used globally.
- The following image formats are supported: PNG, JPG, BMP, SVG, GIF.
\- Base64 strings are supported. The value format is data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data], where [base64 data] is a Base64 string.
\- Strings with the **datashare://** path prefix are supported, which are used to access the image path provided by a Data ability.
\- Strings with the **file:///data/storage** prefix are supported, which are used to read image resources in the **files** folder in the installation directory of the application. Ensure that the application has the read permission to the files in the specified path.
\- [DrawableDescriptor](../apis/js-apis-arkui-drawableDescriptor.md#drawabledescriptor) objects are supported.
**NOTE**
- ArkTS widgets support GIF images, but the images are played only once when they are displayed.
- ArkTS widgets do not support the **http://**, **datashare://**, or **file://data/storage** path prefixes.
- ArkTS widgets do not support the [PixelMap](../apis/js-apis-image.md#pixelmap7) type.| +| src | [PixelMap](../apis/js-apis-image.md#pixelmap7) \| ResourceStr\| [DrawableDescriptor](../apis/js-apis-arkui-drawableDescriptor.md#drawabledescriptor) | Yes | Image source. Both local and online images are supported.
When using an image referenced using a relative path, for example, **Image("common/test.jpg")**, the **\** component cannot be called across bundles or modules. Therefore, you are advised to use **\$r** to reference image resources that need to be used globally.
- The following image formats are supported: PNG, JPG, BMP, SVG, GIF.
\- Base64 strings are supported. The value format is data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data], where [base64 data] is a Base64 string.
\- Strings with the **datashare://** prefix are supported, which are used to access the image path provided by a Data ability.
\- Strings with the **file:///data/storage** prefix are supported, which are used to read image resources in the **files** folder in the installation directory of the current application. Ensure that the application has the read permission to the files in the specified path.
\- [DrawableDescriptor](../apis/js-apis-arkui-drawableDescriptor.md#drawabledescriptor) objects are supported.
- For details, see [Displaying Images](../../ui/arkts-graphics-display.md).
**NOTE**
- ArkTS widgets support GIF animations, but the animations only play once on display.
- ArkTS widgets do not support the strings with the **http://**, **datashare://**, or **file:///data/storage** prefix.
- ArkTS widgets do not support the [PixelMap](../apis/js-apis-image.md#pixelmap7) type.| ## Attributes @@ -56,7 +56,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the > > To use shortcut keys to copy the image, the image must be in focus. To enable the image to gain focus, set both the **focusable** and **focusOnTouch** attributes to **true**. > -> For SVG images, only the following tags are included in the supported list: **svg**, **rect**, **circle**, **ellipse**, **path**, **line**, **polyline**, **polygon**, and **animate**. +> For SVG images, only the following tags are included in the supported list: **svg**, **rect**, **circle**, **ellipse**, **path**, **line**, **polyline**, and **polygon**. ### ImageInterpolation @@ -94,6 +94,8 @@ In addition to the [universal events](ts-universal-events-click.md), the followi Load and display different types of images and set the scale mode of the images. +The **overlay** attribute sets the mask text of an image. For details, see [Overlay](ts-universal-attributes-overlay.md). + ```ts @Entry @Component @@ -225,7 +227,7 @@ struct Index { ``` > **NOTE** -> +> > For details about the request mode, timeout, and additional request parameters for loading online images, see [request()](../../reference/apis/js-apis-http.md) in the HTTP module. ### Setting Attributes @@ -416,4 +418,86 @@ struct LoadImageExample { } } ``` - \ No newline at end of file + +### Applying a Filter to an Image + +```ts +// xxx.ets +@Entry +@Component +struct colorFilterExample { + @State colorFilterR: number = 0 + @State colorFilterG: number = 0 + @State colorFilterB: number = 0 + @State colorFilterA: number = 0 + + build() { + Row() { + Column() { + Image($r('app.media.sky')) + .width(200) + .height(200) + Image($r('app.media.sky')) + .width(200) + .height(200) + .colorFilter([ + this.colorFilterR, 0, this.colorFilterR, 0, 0, + 0, this.colorFilterG, this.colorFilterG, 0, 0, + this.colorFilterB, 0, this.colorFilterB, 0, 0, + 0, 0, this.colorFilterA, 0, 0 + ]) + + Row() { + Text('R') + Slider({ + min: 0, + max: 1, + step: 0.01 + }) + .onChange((valueR) => { + this.colorFilterR = valueR + }) + } + + Row() { + Text('G') + Slider({ + min: 0, + max: 1, + step: 0.01 + }) + .onChange((valueG) => { + this.colorFilterG = valueG + }) + } + + Row() { + Text('B') + Slider({ + min: 0, + max: 1, + step: 0.01 + }) + .onChange((valueB) => { + this.colorFilterB = valueB + }) + } + + Row() { + Text('A') + Slider({ + min: 0, + max: 1, + step: 0.01 + }) + .onChange((valueA) => { + this.colorFilterA = valueA + }) + } + }.width('90%').alignItems(HorizontalAlign.Center) + }.height('100%').width('100%').justifyContent(FlexAlign.Center) + } +} +``` + +![colorFilter](figures/colorFilter.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-navdestination.md b/en/application-dev/reference/arkui-ts/ts-basic-components-navdestination.md index 45fcd8c2bb0b7667f96dd869c19614a3981e0881..e637a22e1193f0fdb727b8ffe91e042ff167b6fd 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-navdestination.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-navdestination.md @@ -9,10 +9,9 @@ ## Child Components -> **NOTE** -> -> - Supported types of child components: built-in components and custom components, with support for ([if/else](../../quick-start/arkts-rendering-control-ifelse.md), [ForEach](../../quick-start/arkts-rendering-control-foreach.md), and [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md)) rendering control. -> - Number of child components: multiple. +Supported types of child components: built-in components and custom components, with support for ([if/else](../../quick-start/arkts-rendering-control-ifelse.md), [ForEach](../../quick-start/arkts-rendering-control-foreach.md), and [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md)) rendering control. + +Number of child components: multiple. ## APIs @@ -31,4 +30,11 @@ In addition to the [backgroundColor](ts-universal-attributes-background.md) attr ## Events -The [universal events](ts-universal-events-click.md) are supported. +In addition to the [universal events](ts-universal-events-click.md), the following events are supported. + + +| Name | Description | +| ---------------------------------------- | ---------------------------------------- | +| onShown(callback: (param: unknown) => void)10+ | Called when the navigation destination page is displayed. **param**: parameter information of the navigation destination page.
**NOTE**
The **onShown** API will be changed to **onShown(callback: () => void)**.| +| onHidden(callback: () => void)10+ | Called when the navigation destination page is hidden.| +| onBackPressed(callback: () => boolean)10+ | Called when the back button is pressed.
The value **true** means that the back button logic is overridden, and **false** means that the previous page is displayed.
| diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md b/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md index b761ae46e7409a709b37f39af778581f06186e96..72b9bb67da9e44ca5298039151dbe5b929ce408d 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md @@ -16,8 +16,17 @@ Since API version 9, it is recommended that this component be used together with ## APIs -Navigation() +**API 1**: Navigation() +**API 2**: Navigation(pathInfos: NavPathStack)10+ + +Binds a navigation stack to the **\** component. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ----------------------------------- | ---- | ------------- | +| pathInfos | [NavPathStack](#navpathstack10) | No | Information about the navigation stack.| ## Attributes @@ -32,13 +41,215 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | toolBar | [object](#object) \| [CustomBuilder](ts-types.md#custombuilder8)8+ | Content of the toolbar. If this attribute is not set, no toolbar is displayed.
**items**: items on the toolbar.
**NOTE**
Items are evenly distributed on the toolbar at the bottom. Text and icons are evenly distributed in each content area. If the text is too long, it is scaled down level by level, wrapped in two lines, and then clipped with an ellipsis (...).| | hideToolBar | boolean | Whether to hide the toolbar.
Default value: **false**
**true**: Hide the toolbar.
**false**: Display the toolbar.| | hideTitleBar | boolean | Whether to hide the title bar.
Default value: **false**
**true**: Hide the title bar.
**false**: Display the title bar.| -| hideBackButton | boolean | Whether to hide the Back button.
Default value: **false**
**true**: Hide the Back button.
**false**: Display the Back button.
The Back button in the title bar of the **\** component cannot be hidden.
**NOTE**
The Back button is available only when **titleMode** is set to **NavigationTitleMode.Mini**.| +| hideBackButton | boolean | Whether to hide the back button.
Default value: **false**
**true**: Hide the back button.
**false**: Display the back button.
The back button in the title bar of the **\** component cannot be hidden.
**NOTE**
The back button is available only when **titleMode** is set to **NavigationTitleMode.Mini**.| | navBarWidth9+ | [Length](ts-types.md#length) | Width of the navigation bar.
Default value: **200**
Unit: vp
**NOTE**
This attribute is valid only when the **\** component is split.| -| navBarPosition9+ | [NavBarPosition](#navbarposition) | Position of the navigation bar.
Default value: **NavBarPosition.Start**
**NOTE**
This attribute is valid only when the **\** component is split.| -| mode9+ | [NavigationMode](#navigationmode) | Display mode of the navigation bar.
Default value: **NavigationMode.Auto**
At the default settings, the component adapts to a single column or two columns based on the component width.| -| backButtonIcon9+ | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Back button icon on the navigation bar. The Back button in the title bar of the **\** component cannot be hidden.| +| navBarPosition9+ | [NavBarPosition](#navbarposition) | Position of the navigation bar.
Default value: **NavBarPosition.Start**
**NOTE**
This attribute is valid only when the **\** component is split.| +| mode9+ | [NavigationMode](#navigationmode) | Display mode of the navigation bar.
Default value: **NavigationMode.Auto**
At the default settings, the component adapts to a single column or two columns based on the component width.| +| backButtonIcon9+ | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Back button icon on the navigation bar. The back button in the title bar of the **\** component cannot be hidden.| | hideNavBar9+ | boolean | Whether to hide the navigation bar. This attribute is valid only when **mode** is set to **NavigationMode.Split**.| +| navDestination10+ | builder: (name: string, param: unknown) => void | Creates a **\** component.
**NOTE**
The **builder** function is used, with the **name** and **param** parameters passsed in. In the builder, a layer of custom components can be included outside the **\** component. However, no attributes or events can be set for the custom components. Otherwise, only blank components are displayed.| + +## NavPathStack10+ + +Implements a navigation stack. + +### push10+ + +push(info: NavPathInfo): void + +Pushes the NavDestination page information specified by **info** to the stack. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ----------------------- | ---- | --------------- | +| info | [NavPathInfo](#navpathinfo10) | Yes | Information about the navigation destination page. | + +### pushName10+ + +pushName(name: string, param: unknown): void + +Pushes the navigation destination page specified by **name** to the navigation stack. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ----------------------- | ---- | --------------- | +| name | string | Yes | Name of the navigation destination page. | +| param | unknown | Yes | Parameter information of the navigation destination page. | + +### pop10+ + +pop(): NavPathInfo | undefined + +Pops the top element out of the navigation stack. + +**Return value** + +| Type | Description | +| ------ | -------- | +| NavPathInfo | Returns the information about the navigation destination page at the top of the stack.| +| undefined | Returns **undefined** if the navigation stack is empty.| + +### popTo10+ + +popTo(name: string): number + +Returns the navigation stack to the first navigation destination page that matches the value of **name**. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ----------------------- | ---- | --------------- | +| name | string | Yes | Name of the navigation destination page. | + +**Return value** + +| Type | Description | +| ------ | -------- | +| number | Returns the index of the first navigation destination page that matches the value of **name** if it exists in the navigation stack; returns **-1** otherwise.| + +### popToIndex10+ + +popToIndex(index: number): void + +Returns the navigation stack to the navigation destination page that matches the value of **index**. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ----------------------- | ---- | --------------- | +| index | number | Yes | Index of the navigation destination page. | + +### moveToTop10+ + +moveToTop(name: string): number + +Moves to the top of the navigation stack the first navigation destination page that matches the value of **name**. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ----------------------- | ---- | --------------- | +| name | string | Yes | Name of the navigation destination page. | + +**Return value** + +| Type | Description | +| ------ | -------- | +| number | Returns the index of the first navigation destination page that matches the value of **name** if it exists in the navigation stack; returns **-1** otherwise.| + +### moveIndexToTop10+ + +moveIndexToTop(index: number): void + +Moves to the top of the navigation stack the navigation destination page that matches the value of **index**. +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ----------------------- | ---- | --------------- | +| index | number | Yes | Index of the navigation destination page. | + +### clear10+ + +clear(): void + +Clears the navigation stack. + +### getAllPathName10+ + +getAllPathName(): Array + +Obtains the names of all navigation destination pages in the navigation stack. + +**Return value** + +| Type | Description | +| ------ | -------- | +| Array | Names of all navigation destination pages in the navigation stack.| + +### getParamByIndex10+ + +getParamByIndex(index: number): unknown | undefined + +Obtains the parameter information of the navigation destination page that matches the value of **index**. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ----------------------- | ---- | --------------- | +| index | number | Yes | Index of the navigation destination page. | + +**Return value** + +| Type | Description | +| ------ | -------- | +| unknown | Returns the parameter information of the matching navigation destination page.| +| undefined | Returns **undefined** if the passed index is invalid.| + +### getParamByName10+ + +getParamByName(name: string): Array + +Obtains the parameter information of all the navigation destination pages that match the value of **name**. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ----------------------- | ---- | --------------- | +| name | string | Yes | Name of the navigation destination page. | + +**Return value** + +| Type | Description | +| ------ | -------- | +| Array | Parameter information of all the matching navigation destination pages.| + +### getIndexByName10+ + +getIndexByName(name: string): Array + +Obtains the indexes information of all the navigation destination pages that match the value of **name**. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ----------------------- | ---- | --------------- | +| name | string | Yes | Name of the navigation destination page. | + +**Return value** + +| Type | Description | +| ------ | -------- | +| Array | Indexes of all the matching navigation destination pages.| + +### size10+ + +size(): number + +Obtains the stack size. + +**Return value** + +| Type | Description | +| ------ | -------- | +| number | Stack size.| + +## NavPathInfo10+ + +Describes the navigation page information. + +### constructor + +constructor(name: string, param: unknown) + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ----------------------- | ---- | --------------- | +| name | string | Yes | Name of the navigation destination page. | +| param | unknown | No | Parameter information of the navigation destination page. | ## NavigationMenuItem @@ -102,6 +313,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the > **NOTE** +> > Among the scrollable components, only **\** is supported. @@ -109,8 +321,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name | Description | | ---------------------------------------- | ---------------------------------------- | -| onTitleModeChange(callback: (titleMode: NavigationTitleMode) => void) | Triggered when **titleMode** is set to **NavigationTitleMode.Free** and the title bar mode changes as content scrolls.| -| onNavBarStateChange(callback: (isVisible: boolean) => void) | Triggered when the navigation bar visibility status changes. The value **true** means that the navigation bar is displayed, and **false** means the opposite.| +| onTitleModeChange(callback: (titleMode: NavigationTitleMode) => void) | Called when **titleMode** is set to **NavigationTitleMode.Free** and the title bar mode changes as content scrolls.| +| onNavBarStateChange(callback: (isVisible: boolean) => void) | Called when the navigation bar visibility status changes. The value **true** means that the navigation bar is displayed, and **false** means the opposite.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-navrouter.md b/en/application-dev/reference/arkui-ts/ts-basic-components-navrouter.md index 8d35b928f71ec67a97fa45c7815cdd0387f3b0dd..3c1eba412a0dbe734c74ba07e586ffd8bf81e9b6 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-navrouter.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-navrouter.md @@ -1,6 +1,6 @@ # NavRouter -The **\** component provides default logic for click response processing, eliminating the need for manual logic definition. +The **\** component provides default processing logic for responding to clicks, eliminating the need for manual logic definition. > **NOTE** > @@ -10,16 +10,56 @@ The **\** component provides default logic for click response process This component must contain two child components, the second of which must be **[\](ts-basic-components-navdestination.md)**. +> **NOTE** +> +> 1. If there is only one child component, the navigation to the **\** component does not work. +> 2. If there is only the **\** child component, the navigation is not performed. +> 3. If there are more than two child components, the excess child components are not displayed. +> 4. If the second child component is not **\**, the navigation does not work. + ## APIs -NavRouter() +**API 1**: NavRouter() + +**API 2**: NavRouter(value: RouteInfo)10+ + +Provides route information so that clicking the **\** component redirects the user to the specified navigation destination page. + + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ----------------------------------- | ---- | ------------- | +| value | [RouteInfo](#routeinfo10) | No | Route information.| + +## Attributes + +In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. + +| Name | Type | Description | +| ----------------------------- | ---------------------------------------- | ---------------------------------------- | +| mode | [NavRouteMode](#navroutemode) | Route mode used for redirection.
Default value: **NavRouteMode.PUSH_WITH_RECREATE**
| + +## RouteInfo10+ + +| Name | Type | Mandatory| Description | +| -------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| name | string | Yes | Name of the navigation destination page to be redirected to.| +| param | unknown | No | Parameter transferred during redirection.| + +## NavRouteMode +| Name | Description | +| ----- | ---------------- | +| PUSH_WITH_RECREATE | The new navigation destination page replaces the current one. The current page is destroyed, but the information about this page is retained in the navigation stack.| +| PUSH | The new navigation destination page overwrites the current one. The current page is not destroyed, and the information about this page is retained in the navigation stack.| +| REPLACE | The new navigation destination page replaces the current one. The current page is destroyed, and the information about this page is removed from the navigation stack.| ## Events -| Name | Description | -| ---------------------------------------- | ---------------------------------------- | -| onStateChange(callback: (isActivated: boolean) => void) | Invoked when the component activation status changes. The value **true** means that component is activated, and **false** means the opposite.
**NOTE**
After the user clicks **NavRouter**, if the **\** component is activated and the corresponding **\** child component loaded, **onStateChange(true)** is called. If the corresponding **\** child component is no longer displayed, **onStateChange(false)** is called. | +| Name | Description | +| ------------------------------------------------------- | ------------------------------------------------------------ | +| onStateChange(callback: (isActivated: boolean) => void) | Called when the component activation status changes. The value **true** means that component is activated, and **false** means the opposite.
**NOTE**
**onStateChange(true)** is called when the **\** component is activated and its **\** child component is loaded. **onStateChange(false)** is called when the **\** child component is not displayed.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-qrcode.md b/en/application-dev/reference/arkui-ts/ts-basic-components-qrcode.md index 90705e2c5a20844a2346e45dee5835c128054aec..bc6f5ef081cf9c51067f4e15c63cf2f12482ce6e 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-qrcode.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-qrcode.md @@ -24,7 +24,7 @@ Since API version 9, this API is supported in ArkTS widgets. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | string | Yes| Content of the QR code. A maximum of 256 characters are supported. If the number of characters exceeds 256, the first 256 characters are used.| +| value | string | Yes| Content of the QR code. A maximum of 256 characters are supported. If the number of characters exceeds 256, the first 256 characters are used.
**NOTE**
The string cannot be **null**, **undefined**, or empty.| ## Attributes diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-span.md b/en/application-dev/reference/arkui-ts/ts-basic-components-span.md index 713d8ded01778b89be36d85afcc8a0ee4e39974c..53cdf20f46f1458ec62c6fafccf50e81514e4e00 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-span.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-span.md @@ -6,7 +6,7 @@ The **\** component is used to display inline text in the **\** comp > > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > -> Since API version 10, this component can inherit the attributes of the **\** parent component. That is, if no attribute is set for this component, it inherits the attributes (if set) of its parent component. The following attributes can be inherited: **fontColor**, **fontSize**, **fontStyle**, **fontWeight**, **decoration**, **letterSpacing**, **textCase**, **lineHeight**, and **fontfamily**. +> Since API version 10, this component can inherit the attributes of the **\** parent component. That is, if no attribute is set for this component, it inherits the attributes (if set) of its parent component. Only the following attributes can be inherited: **fontColor**, **fontSize**, **fontStyle**, **fontWeight**, **decoration**, **letterSpacing**, **textCase**, and **fontfamily**. ## Child Components diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md b/en/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md index 7427783669fc717e2b21857f16154c1fa4176817..07b043411ed7ce7658cb575490e559e0dbd3aab0 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md @@ -24,7 +24,7 @@ StepperItem() | -------- | -------- | -------- | | prevLabel | string | Text label of the button on the left, which is not displayed on the first page. When the **\** contains more than one page, the default value for all pages except the first page is **Back**.| | nextLabel | string | Text label of the button on the right. The default value is **Start** for the last page and **Next** for the other pages.| -| status | ItemState | Display status of **nextLabel** in the stepper.
Default value: **ItemState.Normal**| +| status | [ItemState](#itemstate) | Display status of **nextLabel** in the stepper. Optional.
Default value: **ItemState.Normal**| ## ItemState diff --git a/en/application-dev/reference/arkui-ts/ts-container-list.md b/en/application-dev/reference/arkui-ts/ts-container-list.md index 678358358c74f05506914cab3349a260f40ecfb8..e20063ba938358602853548c86cfba6275e0620a 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-list.md +++ b/en/application-dev/reference/arkui-ts/ts-container-list.md @@ -10,7 +10,7 @@ The **\** component provides a list container that presents a series of li ## Child Components -This component supports the **[\](ts-container-listitem.md)** and **[\](ts-container-listitemgroup.md)** child components. +This component supports the [\](ts-container-listitem.md) and [\](ts-container-listitemgroup.md) child components. > **NOTE** > @@ -43,7 +43,7 @@ Since API version 9, this API is supported in ArkTS widgets. | -------- | -------- | -------- | -------- | | space | number \| string | No| Spacing between list items along the main axis.
Default value: **0**
**NOTE**
If this parameter is set to a percentage or a negative number other than -1, the default value is used.
If the value of **space** is less than the width of the list divider, the latter is used as the spacing.| | initialIndex | number | No| Item displayed at the beginning of the viewport when the current list is loaded for the first time, that is, the first item to be displayed.
Default value: **0**
**NOTE**
If this parameter is set to a negative value other than -1 or is greater than the index value of the last item in the current list, the value is invalid. In this case, the default value is used.| -| scroller | [Scroller](ts-container-scroll.md#scroller) | No| Scroller, which can be bound to scrollable components.
**NOTE**
The scroller cannot be bound to other scrollable components. | +| scroller | [Scroller](ts-container-scroll.md#scroller) | No| Scroller, which can be bound to scrollable components.
**NOTE**
The scroller cannot be bound to other scrollable components.| ## Attributes @@ -52,14 +52,15 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Description| | -------- | -------- | -------- | | listDirection | [Axis](ts-appendix-enums.md#axis) | Direction in which the list items are arranged.
Default value: **Axis.Vertical**
Since API version 9, this API is supported in ArkTS widgets.| -| divider | {
strokeWidth: [Length](ts-types.md#length),
color?:[ResourceColor](ts-types.md#resourcecolor),
startMargin?: Length,
endMargin?: Length
} \| null | Style of the divider for the list items. By default, there is no divider. This attribute cannot be set in percentage.
- **strokeWidth**: stroke width of the divider.
- **color**: color of the divider.
- **startMargin**: distance between the divider and the start edge of the list.
- **endMargin**: distance between the divider and the end edge of the list.
Since API version 9, this API is supported in ArkTS widgets.
The sum of **endMargin** and **startMargin** cannot exceed the column width.
**startMargin** and **endMargin** cannot be set in percentage.
The divider is drawn between list items along the main axis, and not above the first list item and below the last list item.
In multi-column mode, the value of **startMargin** is calculated from the start edge of the cross axis of each column. In other cases, it is calculated from the start edge of the cross axis of the list.| +| divider | {
strokeWidth: [Length](ts-types.md#length),
color?:[ResourceColor](ts-types.md#resourcecolor),
startMargin?: Length,
endMargin?: Length
} \| null | Style of the divider for the list items. By default, there is no divider.
- **strokeWidth**: stroke width of the divider.
- **color**: color of the divider.
- **startMargin**: distance between the divider and the start edge of the list.
- **endMargin**: distance between the divider and the end edge of the list.
Since API version 9, this API is supported in ArkTS widgets.
The sum of **endMargin** and **startMargin** cannot exceed the column width.
**startMargin** and **endMargin** cannot be set in percentage.
The divider is drawn between list items along the main axis, and not above the first list item and below the last list item.
In multi-column mode, the value of **startMargin** is calculated from the start edge of the cross axis of each column. In other cases, it is calculated from the start edge of the cross axis of the list.| | scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.
Default value: **BarState.Off**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
In API version 9 and earlier versions, the default value is **BarState.Off**. In API version 10, the default value is **BarState.Auto**.| | cachedCount | number | Number of list items or list item groups to be preloaded (cached). It works only in [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md). A list item group is calculated as a whole, and all list items of the group are preloaded at the same time. For details, see [Minimizing White Blocks During Swiping](../../ui/arkts-performance-improvement-recommendation.md#minimizing-white-blocks-during-swiping).
Default value: **1**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
In single-column mode, the number of the list items to be cached before and after the currently displayed one equals the value of **cachedCount**.
In multi-column mode, the number of the list items to be cached is the value of **cachedCount** multiplied by the number of columns.| -| editMode(deprecated) | boolean | Whether to enter editing mode.
This API is deprecated since API version 9.
Default value: **false**| +| editMode(deprecated) | boolean | Whether to enter editing mode.
This API is deprecated since API version 9. For details about how to implement deletion of a selected list item, see [Example 3](#example-3).
Default value: **false**| | edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect. The spring effect and shadow effect are supported.
Default value: **EdgeEffect.Spring**
Since API version 9, this API is supported in ArkTS widgets.| -| chainAnimation | boolean | Whether to display chained animations on this list when it slides or its top or bottom is dragged. The list items are separated with even space, and one item animation starts after the previous animation during basic sliding interactions. The chained animation effect is similar with spring physics.
Default value: **false**
- **false**: No chained animations are displayed.
- **true**: Chained animations are displayed.
Since API version 9, this API is supported in ArkTS widgets.| +| chainAnimation | boolean | Whether to display chained animations on this list when it slides or its top or bottom is dragged. The list items are separated with even space, and one item animation starts after the previous animation during basic sliding interactions. The chained animation effect is similar with spring physics.
Default value: **false**
- **false**: No chained animations are displayed.
- **true**: Chained animations are displayed.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
When chained animations are in motion, the list divider is not displayed.
The following prerequisites must be met for the chained animations to take effect:
- The edge effect of the list is of the Spring type.
- The multi-column mode is not enabled for the list.| +|chainAnimationOptions10+| [ChainAnimationOptions](#chainanimationoptions10) | Chained animation settings.
**System API**: This is a system API.| | multiSelectable8+ | boolean | Whether to enable mouse frame selection.
Default value: **false**
- **false**: The mouse frame selection is disabled.
- **true**: The mouse frame selection is enabled.
Since API version 9, this API is supported in ArkTS widgets.| -| lanes9+ | number \| [LengthConstrain](ts-types.md#lengthconstrain) | In the following description, **listDirection** is set to **Axis.Vertical**:
Number of columns in which the list items are arranged along the cross axis.
Default value: **1**
The rules are as follows:
- If the value is set to a number, the column width is calculated by dividing the cross-axis width of the **\** component by the specified number.
- If the value is set to {minLength, maxLength}, the number of columns is adjusted adaptively based on the width of the **\** component, ensuring that the width respects the {minLength, maxLength} constraints during adaptation. The **minLength** constraint is prioritized.
- If the value is set to {minLength, maxLength}, and the cross-axis width constraint of the parent component is infinite, the parent component is arranged by column, and the column width is calculated based on the maximum width of list items in the display area.
- Each list item group occupies one row in multi-column mode. Its child list items are arranged based on the **lanes** attribute of the list.
- If the value is set to {minLength, maxLength}, the number of columns is calculated based on the cross-axis width of the list item group. If the cross-axis width of the list item group is different from that of the list, the number of columns in the list item group may be different from that in the list.
This API is supported in ArkTS widgets. | +| lanes9+ | number \| [LengthConstrain](ts-types.md#lengthconstrain) | In the following description, **listDirection** is set to **Axis.Vertical**:
Number of columns in which the list items are arranged along the cross axis.
Default value: **1**
The rules are as follows:
- If the value is set to a number, the column width is calculated by dividing the cross-axis width of the **\** component by the specified number.
- If the value is set to {minLength, maxLength}, the number of columns is adjusted adaptively based on the width of the **\** component, ensuring that the width respects the {minLength, maxLength} constraints during adaptation. The **minLength** constraint is prioritized.
- If the value is set to {minLength, maxLength}, and the cross-axis width constraint of the parent component is infinite, the parent component is arranged by column, and the column width is calculated based on the largest list item in the display area.
- Each list item group occupies one row in multi-column mode. Its child list items are arranged based on the **lanes** attribute of the list.
- If the value is set to {minLength, maxLength}, the number of columns is calculated based on the cross-axis width of the list item group. If the cross-axis width of the list item group is different from that of the list, the number of columns in the list item group may be different from that in the list.
This API is supported in ArkTS widgets.| | alignListItem9+ | [ListItemAlign](#listitemalign9) | Alignment mode of list items along the cross axis when: Cross-axis width of the **\** component > Cross-axis width of list items x Value of **lanes**.
Default value: **ListItemAlign.Start**
This API is supported in ArkTS widgets.| | sticky9+ | [StickyStyle](#stickystyle9) | Whether to pin the header to the top or the footer to the bottom in the **\** component. This attribute is used together with the **[\](ts-container-listitemgroup.md)** component.
Default value: **StickyStyle.None**
This API is supported in ArkTS widgets.
**NOTE**
The **sticky** attribute can be set to **StickyStyle.Header** or \| **StickyStyle.Footer** to support both the pin-to-top and pin-to-bottom features.| @@ -71,7 +72,7 @@ This API is supported in ArkTS widgets. | ------ | -------------------------------------- | | Start | The list items are packed toward the start edge of the **\** component along the cross axis.| | Center | The list items are centered in the **\** component along the cross axis.| -| End | The list items are packed toward the end edge of the **\** component in the cross axis.| +| End | The list items are packed toward the end edge of the **\** component along the cross axis.| ## StickyStyle9+ @@ -83,6 +84,31 @@ This API is supported in ArkTS widgets. | Header | In the **\** component, the header is pinned to the top, and the footer is not pinned to the bottom.| | Footer | In the **\** component, the footer is pinned to the bottom, and the header is not pinned to the top.| +## ChainEdgeEffect10+ + +Describes the chained animation edge effect. + +**System API**: This is a system API. + +| Name | Description | +| ------ | -------------------------------------- | +| DEFAULT | Default effect. After the list is scrolled to the edge, a continued drag of the list will result in reduced spacing between the list items in the drag direction and increased spacing between the list items in the direction opposite to the drag direction.| +| STRETCH | After the list is scrolled to the edge, a continued drag of the list result in increased spacing between all the list items.| + +## chainAnimationOptions10+ + +Provides the chained animation settings, which cover the maximum spacing, minimum spacing, intensity, conductivity, and edge effect. + +**System API**: This is a system API. + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | --------------- | +| minSpace | [Length](ts-types.md#length) | Yes | Minimum spacing between the chained animations.| +| maxSpace | [Length](ts-types.md#length) | Yes | Maximum spacing between the chained animations.| +| conductivity | number | No | Conductivity of the chained animations. The value range is [0,1]. A larger value indicates higher conductivity.
Default value: **0.7** | +| intensity | number | No | Intensity of the chained animations. The value range is [0,1]. A larger value indicates more obvious animations.
Default value: **0.3**| +| edgeEffect | [ChainEdgeEffect](#chainedgeeffect10)| No| Chained animation edge effect.
Default value: **ChainEdgeEffect.DEFAULT**| + > **NOTE** > > The default value of the universal attribute [clip](ts-universal-attributes-sharp-clipping.md) is **true** for the **\** component. @@ -93,7 +119,7 @@ This API is supported in ArkTS widgets. | -------- | -------- | | onItemDelete(deprecated)(event: (index: number) => boolean) | Triggered when a list item is deleted.
This API is deprecated since API version 9.
- **index**: index of the deleted list item.| | onScroll(event: (scrollOffset: number, scrollState: ScrollState) => void) | Triggered when the list scrolls.
- **scrollOffset**: scroll offset of each frame. The offset is positive when the list is scrolled up and negative when the list is scrolled down.
- **[scrollState](#scrollstate)**: current scroll state.
This event is not triggered when **ScrollEdge** and **ScrollToIndex** are called by using the controller. In other cases, this event is triggered when scrolling occurs.
Since API version 9, this API is supported in ArkTS widgets.| -| onScrollIndex(event: (start: number, end: number) => void) | Triggered when a child component enters or exits from the list display area.
During index calculation, each **\** component is taken as a whole and assigned an index, and the indexes of the list items within are not included in the calculation.
- **start**: index of the scroll start position.
- **end**: index of the scroll end position.
This event is triggered once when the list is initialized and when the index of the first list item or the next list item in the list display area changes.
When the list edge effect is the spring effect, the **onScrollIndex** event is not triggered when the user scrolls the list to the edge or releases the list to rebound.
Since API version 9, this API is supported in ArkTS widgets.| +| onScrollIndex(event: (start: number, end: number) => void) | Triggered when a child component enters or leaves the list display area.
During index calculation, each **\** component is taken as a whole and assigned an index, and the indexes of the list items within are not included in the calculation.
- **start**: index of the scroll start position.
- **end**: index of the scroll end position.
This event is triggered once when the list is initialized and when the index of the first list item or the next list item in the list display area changes.
When the list edge effect is the spring effect, the **onScrollIndex** event is not triggered when the user scrolls the list to the edge or releases the list to rebound.
Since API version 9, this API is supported in ArkTS widgets.| | onReachStart(event: () => void) | Triggered when the list reaches the start position.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This event is triggered once when **initialIndex** is **0** during list initialization and once when the list scrolls to the start position. When the list edge effect is the spring effect, this event is triggered once when the list passes the start position and is triggered again when the list returns to the start position.| | onReachEnd(event: () => void) | Triggered when the list reaches the end position.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
When the list edge effect is the spring effect, this event is triggered once when the list passes the end position and is triggered again when the list returns to the end position.| | onScrollFrameBegin9+(event: (offset: number, state: ScrollState) => { offsetRemain }) | Triggered when the list starts to scroll. The input parameters indicate the amount by which the list will scroll. The event handler then works out the amount by which the list needs to scroll based on the real-world situation and returns the result.
\- **offset**: amount to scroll by, in vp.
\- **state**: current sliding status.
- **offsetRemain**: actual amount by which the list scrolls, in vp.
This event is triggered when the user starts dragging the list or the list starts inertial scrolling. This event is not triggered when the list rebounds or the scrolling controller is used.
This API is supported in ArkTS widgets.
**NOTE**
If **listDirection** is set to **Axis.Vertical**, the return value is the amount by which the list needs to scroll in the vertical direction. If **listDirection** is set to **Axis.Horizontal**, the return value is the amount by which the list needs to scroll in the horizontal direction.| @@ -103,7 +129,7 @@ This API is supported in ArkTS widgets. | onItemDragStart(event: (event: ItemDragInfo, itemIndex: number) => ((() => any) \| void) | Triggered when a list element starts to be dragged.
- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).
- **itemIndex**: index of the dragged list element.| | onItemDragEnter(event: (event: ItemDragInfo) => void) | Triggered when the dragged item enters the drop target of the list.
- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).| | onItemDragMove(event: (event: ItemDragInfo, itemIndex: number, insertIndex: number) => void) | Triggered when the dragged item moves over the drop target of the list.
- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).
- **itemIndex**: initial position of the dragged item.
- **insertIndex**: index of the position to which the dragged item will be dropped.| -| onItemDragLeave(event: (event: ItemDragInfo, itemIndex: number) => void) | Triggered when the dragged item exits the drop target of the list.
- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).
- **itemIndex**: index of the list item.| +| onItemDragLeave(event: (event: ItemDragInfo, itemIndex: number) => void) | Triggered when the dragged item leaves the drop target of the list.
- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).
- **itemIndex**: index of the list item.| | onItemDrop(event: (event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => void) | Triggered when the dragged item is dropped on the drop target of the list.
- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).
- **itemIndex**: initial position of the dragged item.
- **insertIndex**: index of the position to which the dragged item will be dropped.
- **isSuccess**: whether the dragged item is successfully dropped.
**NOTE**
During dragging across lists, **true** is returned if the drop target is bound to **onItemDrop**. Otherwise, **false** is returned. During dragging within a list, **isSuccess** is the return value of the **onItemMove** event.| ## ScrollState @@ -133,7 +159,7 @@ Since API version 9, this API is supported in ArkTS widgets. > - The list item is bound to the **onDragStart** event and the event returns a floating UI during event callback. -## Example +## Example 1 ```ts // xxx.ets @@ -172,6 +198,9 @@ struct ListExample { ![en-us_image_0000001174264378](figures/en-us_image_0000001174264378.gif) + +## Example 2 + ```ts // xxx.ets @Entry @@ -198,7 +227,6 @@ struct ListLanesExample { } .height(300) .width("90%") - .editMode(true) .border({ width: 3, color: Color.Red }) .lanes({ minLength: 40, maxLength: 40 }) .alignListItem(this.alignListItem) @@ -218,3 +246,57 @@ struct ListLanesExample { ``` ![list](figures/list1.gif) + + +## Example 3 + +```ts +// xxx.ets +@Entry +@Component +struct ListExample{ + @State arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + @State editFlag: boolean = false + + build(){ + Stack({alignContent: Alignment.TopStart}) { + Column(){ + List({space:20, initialIndex:0}) { + ForEach(this.arr, (item, index) => { + ListItem() { + Flex({direction: FlexDirection.Row, alignItems: ItemAlign.Center}) { + Text('' + item) + .width('100%') + .height(80) + .fontSize(20) + .textAlign(TextAlign.Center) + .borderRadius(10) + .backgroundColor(0xFFFFFF) + .flexShrink(1) + if (this.editFlag) { + Button() { + Text("delete").fontSize(16) + }.width('30%').height(40) + .onClick(() => { + console.info(this.arr[index] + 'Delete') + this.arr.splice(index, 1) + console.info(JSON.stringify(this.arr)) + this.editFlag = false + }).stateEffect(true) + } + } + } + }, item => item) + }.width('90%') + }.width('100%') + + Button('edit list') + .onClick(() => { + this.editFlag = !this.editFlag + }).margin({ top: 5, left: 20 }) + }.width('100%').height('100%').backgroundColor(0xDCDCDC).padding({ top: 5 }) + } +} +``` + +![list](figures/list3.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-container-waterflow.md b/en/application-dev/reference/arkui-ts/ts-container-waterflow.md index 39c86b3cee5726a774379f039c0a450518dcbe02..44d2eeda5df735e9f81dbb9713b899cbd66037be 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-waterflow.md +++ b/en/application-dev/reference/arkui-ts/ts-container-waterflow.md @@ -260,9 +260,11 @@ struct WaterflowDemo { Text("N" + item).fontSize(12).height('16') Image('res/waterFlowTest(' + item % 5 + ').jpg') .objectFit(ImageFit.Fill) + .width('100%') + .layoutWeight(1) } } - .width(this.itemWidthArray[item]) + .width('100%') .height(this.itemHeightArray[item]) .backgroundColor(this.colors[item % 5]) }, item => item) diff --git a/en/application-dev/reference/arkui-ts/ts-media-components-video.md b/en/application-dev/reference/arkui-ts/ts-media-components-video.md index e5cedbf9e226c3b37ce9c0a525c70376075f6187..b2903343a1acb957d5563cc100a0e150a463732f 100644 --- a/en/application-dev/reference/arkui-ts/ts-media-components-video.md +++ b/en/application-dev/reference/arkui-ts/ts-media-components-video.md @@ -24,9 +24,9 @@ Video(value: {src?: string | Resource, currentProgressRate?: number | string | P | Name | Type | Mandatory| Description | | ------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| src | string \| [Resource](ts-types.md) | No | Path of the video source, which can be a local path or a URL.
The video resources can be stored in the **video** or **rawfile** folder under **resources**.
The path can include a **dataability://** prefix, which indicates that the path is provided by a Data ability. For details about the path, see [Data Ability Development](../../application-models/dataability-overview.md).
**NOTE**
The supported video formats are MP4, MKV, WebM, and TS.| +| src | string \| [Resource](ts-types.md) | No | Path of the video source, which can be a local path or a URL.
The video resources can be stored in the **video** or **rawfile** folder under **resources**.
The path can include a **dataability://** prefix, which indicates that the path is provided by a Data ability. For details about the path, see [Data Ability Development](../../application-models/dataability-overview.md).
- Strings with the **file:///data/storage** prefix are supported, which are used to read resources in the application sandbox. Ensure that the application has the read permission to the files in the specified path.
**NOTE**
The supported video formats are MP4, MKV, WebM, and TS. | | currentProgressRate | number \| string \| PlaybackSpeed8+ | No | Video playback speed.
**NOTE**
The value of the number type can only be **0.75**, **1.0**, **1.25**, **1.75**, or **2.0**.
Default value: 1.0 \| PlaybackSpeed.Speed_Forward_1_00_X | -| previewUri | string \|PixelMap \| [Resource](ts-types.md) | No | Path of the preview image. (The PixelMap type is not supported currently.) | +| previewUri | string \|PixelMap \| [Resource](ts-types.md) | No | Path of the preview image. | | controller | [VideoController](#videocontroller) | No | Video controller. | ## PlaybackSpeed8+ diff --git a/en/application-dev/reference/arkui-ts/ts-page-transition-animation.md b/en/application-dev/reference/arkui-ts/ts-page-transition-animation.md index 5cd36a45df7a1b6720be03d6ca9fe59d5f555cbf..e0a3bb339e1db622d902737a7f3a1d4f61d2cf64 100644 --- a/en/application-dev/reference/arkui-ts/ts-page-transition-animation.md +++ b/en/application-dev/reference/arkui-ts/ts-page-transition-animation.md @@ -1,6 +1,6 @@ # Page Transition -The page transition navigates users between pages. You can customize page transitions by configuring the page entrance and exit components in the **pageTransition** API. +You can customize the page entrance and exit animations in the **pageTransition** API for transition between pages. > **NOTE** > @@ -10,8 +10,8 @@ The page transition navigates users between pages. You can customize page transi | Name | Parameter | Mandatory| Description | | ------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| PageTransitionEnter | {
type?: RouteType,
duration?: number,
curve?: [Curve](ts-appendix-enums.md#curve) \| string,
delay?: number
} | No | Page entrance animation.
- **type**: route type for the page transition effect to take effect.
Default value: **RouteType.None**
**NOTE**
If no match is found, the default page transition effect is used (which may vary according to the device). To disable the default page transition effect, set **duration** to **0**.
- **duration**: animation duration.
Unit: ms
- **curve**: animation curve. The value of the string type can be any of the following: "ease", "ease-in", "ease-out", "ease-in-out", "extreme-deceleration", "fast-out-linear-in", "fast-out-slow-in", "friction", "linear", "linear-out-slow-in", "rhythm", "sharp", "smooth".
Default value: **Curve.Linear**
- **delay**: animation delay.
Default value: **0**
Unit: ms| -| PageTransitionExit | {
type?: RouteType,
duration?: number,
curve?: [Curve](ts-appendix-enums.md#curve) \| string,
delay?: number
} | No | Page exit animation.
- **type**: route type for the page transition effect to take effect.
Default value: **RouteType.None**
**NOTE**
If no match is found, the default page transition effect is used (which may vary according to the device). To disable the default page transition effect, set **duration** to **0**.
- **duration**: animation duration, in milliseconds.
- **curve**: animation curve. The value range of the string type is the same as that of **PageTransitionEnter**.
Default value: **Curve.Linear**
- **delay**: animation delay.
Default value: **0**
Unit: ms| +| PageTransitionEnter | {
type?: RouteType,
duration?: number,
curve?: [Curve](ts-appendix-enums.md#curve) \| string,
delay?: number
} | No | Page entrance animation.
- **type**: route type for the page transition effect to take effect.
Default value: **RouteType.None**
- **duration**: animation duration.
Unit: ms
Default value: **1000**
- **curve**: animation curve. The value of the string type can be any of the following: "ease", "ease-in", "ease-out", "ease-in-out", "extreme-deceleration", "fast-out-linear-in", "fast-out-slow-in", "friction", "linear", "linear-out-slow-in", "rhythm", "sharp", "smooth".
Default value: **Curve.Linear**
- **delay**: animation delay.
Unit: ms
Default value: **0**
**NOTE**
If no match is found, the default page transition effect is used (which may vary according to the device). To disable the default page transition effect, set **duration** to **0**.| +| PageTransitionExit | {
type?: RouteType,
duration?: number,
curve?: [Curve](ts-appendix-enums.md#curve) \| string,
delay?: number
} | No | Page exit animation.
- **type**: route type for the page transition effect to take effect.
Default value: **RouteType.None**
- **duration**: animation duration.
Unit: ms
Default value: **1000**
- **curve**: animation curve. The value range of the string type is the same as that of **PageTransitionEnter**.
Default value: **Curve.Linear**
- **delay**: animation delay.
Unit: ms
Default value: **0**
**NOTE**
If no match is found, the default page transition effect is used (which may vary according to the device). To disable the default page transition effect, set **duration** to **0**.| ## RouteType @@ -26,10 +26,10 @@ The page transition navigates users between pages. You can customize page transi | Name | Type | Mandatory| Description | | --------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| slide | [SlideEffect](#slideeffect) | No | Slide effect during page transition.
Default value: **SlideEffect.Right**| +| slide | [SlideEffect](#slideeffect) | No | Slide effect during page transition.| | translate | {
x? : number \| string,
y? : number \| string,
z? : number \| string
} | No | Translation effect during page transition, which is the value of the start point of entrance and the end point of exit. When this parameter is set together with **slide**, the latter takes effect by default.
- **x**: translation distance along the x-axis.
- **y**: translation distance along the y-axis.
- **z**: translation distance along the y-axis.| -| scale | {
x? : number,
y? : number,
z? : number,
centerX? : number \| string,
centerY? : number \| string
} | No | Scaling effect during page transition, which is the value of the start point of entrance and the end point of exit.
- **x**: scale ratio along the x-axis.
- **y**: scale ratio along the y-axis.
- **z**: scale ratio along the z-axis.
- **centerX** and **centerY**: scale center point.
- If the center point is 0, it refers to the upper left corner of the component. | -| opacity | number | No | Opacity, which is the opacity value of the start point of entrance or the end point of exit.
Default value: **1**| +| scale | {
x? : number,
y? : number,
z? : number,
centerX? : number \| string,
centerY? : number \| string
} | No | Scaling effect during page transition, which is the value of the start point of entrance and the end point of exit.
- **x**: scale ratio along the x-axis.
- **y**: scale ratio along the y-axis.
- **z**: scale ratio along the z-axis.
- **centerX** and **centerY**: scale center point. The default values are both **"50%"**, indicating that the center point of the page.
- If the center point is (0, 0), it refers to the upper left corner of the component.
| +| opacity | number | No | Opacity, which is the opacity value of the start point of entrance or the end point of exit.| ## SlideEffect @@ -43,15 +43,15 @@ The page transition navigates users between pages. You can customize page transi ## Events -| Name | Description | +| Name | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| onEnter(event: (type?: RouteType, progress?: number) => void) | Invoked once every animation frame until the entrance animation ends, when the value of **progress** changes from 0 to 1. The input parameter is the normalized progress of the current entrance animation. The value range is 0–1.
- **type**: route type.
- **progress**: current progress. | -| onExit(event: (type?: RouteType, progress?: number) => void) | Invoked once every animation frame until the exit animation ends, when the value of **progress** changes from 0 to 1. The input parameter is the normalized progress of the current exit animation. The value range is 0–1.
- **type**: route type.
- **progress**: current progress. | +| onEnter(event: (type?: RouteType, progress?: number) => void) | Invoked once every animation frame until the entrance animation ends, when the value of **progress** changes from 0 to 1. The input parameter is the normalized progress of the current entrance animation. The value range is 0–1.
- **type**: route type.
- **progress**: current progress.

| +| onExit(event: (type?: RouteType, progress?: number) => void) | Invoked once every animation frame until the exit animation ends, when the value of **progress** changes from 0 to 1. The input parameter is the normalized progress of the current exit animation. The value range is 0–1.
- **type**: route type.
- **progress**: current progress.

| ## Example -Customization method 1: The entrance animation of the current page is configured as fade-in, and the exit animation is configured as zoom-out. +Example 1: Apply the entrance animation of fade-in and the exit animation of zoom-out. ```ts // index.ets @@ -68,14 +68,14 @@ struct PageTransitionExample1 { } }.scale({ x: this.scale1 }).opacity(this.opacity1) } - // Customization method 1: Customize the transition process. + // Customize the transition process. pageTransition() { PageTransitionEnter({ duration: 1200, curve: Curve.Linear }) .onEnter((type: RouteType, progress: number) => { this.scale1 = 1 this.opacity1 = progress }) // The onEnter callback is triggered frame by frame during the entrance process. The input parameter is the normalized progress of the animation (0% to 100%). - PageTransitionExit({ duration: 1500, curve: Curve.Ease }) + PageTransitionExit({ duration: 1200, curve: Curve.Ease }) .onExit((type: RouteType, progress: number) => { this.scale1 = 1 - progress this.opacity1 = 1 @@ -99,14 +99,14 @@ struct AExample { } }.width('100%').height('100%').scale({ x: this.scale2 }).opacity(this.opacity2) } - // Customization method 1: Customize the transition process. + // Customize the transition process. pageTransition() { PageTransitionEnter({ duration: 1200, curve: Curve.Linear }) .onEnter((type: RouteType, progress: number) => { this.scale2 = 1 this.opacity2 = progress }) // The onEnter callback is triggered frame by frame during the entrance process. The input parameter is the normalized progress of the animation (0% to 100%). - PageTransitionExit({ duration: 1500, curve: Curve.Ease }) + PageTransitionExit({ duration: 1200, curve: Curve.Ease }) .onExit((type: RouteType, progress: number) => { this.scale2 = 1 - progress this.opacity2 = 1 @@ -115,31 +115,30 @@ struct AExample { } ``` -![en-us_image_0000001256978335](figures/en-us_image_0000001256978335.gif) +![pageTransition1](figures/pageTransition1.gif) -Customization method 2: The entrance animation of the current page is configured to slide in from the left, and the exit animation is configured to zoom out with opacity change. +Example 2: Apply the entrance animation of sliding in from the left and the exit animation of translating with opacity change. ```ts // index.ets @Entry @Component struct PageTransitionExample { - @State scale1: number = 1 - @State opacity1: number = 1 - build() { Column() { Navigator({ target: 'pages/page1', type: NavigationType.Push }) { Image($r('app.media.bg1')).width('100%').height('100%') // Store the image in the media folder. } - }.scale({ x: this.scale1 }).opacity(this.opacity1) + } } - // Customization method 2: Use the default effects provided by the system, such as translation, scaling, and opacity. + // Use the default effects provided by the system, such as translation, scaling, and opacity. pageTransition() { + // Set the duration of the entrance animation to 1200 ms, in the purpose of matching the duration of the exit animation of the other page. PageTransitionEnter({ duration: 1200 }) .slide(SlideEffect.Left) - PageTransitionExit({ delay: 100 }) + // Set the duration of the exit animation to 1000 ms, in the purpose of matching the duration of the entrance animation of the other page. + PageTransitionExit({ duration: 1000 }) .translate({ x: 100.0, y: 100.0 }) .opacity(0) } @@ -151,26 +150,25 @@ struct PageTransitionExample { @Entry @Component struct PageTransitionExample1 { - @State scale2: number = 1 - @State opacity2: number = 1 - build() { Column() { Navigator({ target: 'pages/index', type: NavigationType.Push }) { Image($r('app.media.bg2')).width('100%').height('100%') // Store the image in the media folder. } - }.scale({ x: this.scale2 }).opacity(this.opacity2) + } } - // Customization method 2: Use the default effects provided by the system, such as translation, scaling, and opacity. + // Use the default effects provided by the system, such as translation, scaling, and opacity. pageTransition() { - PageTransitionEnter({ duration: 1200 }) + // Set the duration of the entrance animation to 1000 ms, in the purpose of matching the duration of the exit animation of the other page. + PageTransitionEnter({ duration: 1000 }) .slide(SlideEffect.Left) - PageTransitionExit({ delay: 100 }) + // Set the duration of the exit animation to 1200 ms, in the purpose of matching the duration of the entrance animation of the other page. + PageTransitionExit({ duration: 1200 }) .translate({ x: 100.0, y: 100.0 }) .opacity(0) } } ``` -![en-us_image_0000001212058460](figures/en-us_image_0000001212058460.gif) +![pageTransition2](figures/pageTransition2.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-pixel-units.md b/en/application-dev/reference/arkui-ts/ts-pixel-units.md index 4f7099cc28fffbe5b72c6fa3ddd5fe0cfa1b969f..8a820840da5c7a8d5ad232f16f548acd585ed262 100644 --- a/en/application-dev/reference/arkui-ts/ts-pixel-units.md +++ b/en/application-dev/reference/arkui-ts/ts-pixel-units.md @@ -3,12 +3,12 @@ The framework provides four pixel units, with vp as the reference data unit. -| Name | Description | -| ---- | ---------------------------------------- | -| px | Physical pixel unit of the screen. | -| vp | Pixel unit specific to the screen density. Pixels in this unit are converted into physical pixels of the screen based on the screen pixel density. This unit is used for values whose unit is not specified.| -| fp | Font pixel, which is similar to vp and varies according to the system font size. | -| lpx | Logical pixel unit of the window. It is the ratio of the actual screen width to the logical width (configured by **designWidth**). For example, if **designWidth** is set to **720** (default value), then 1lpx is equal to 2px for a screen with an actual width of 1440 physical pixels.| +| Name| Description | +| ---- | ------------------------------------------------------------ | +| px | Physical pixel unit of the screen. | +| vp | Pixel unit specific to the screen density. Pixels in this unit are converted into physical pixels of the screen based on the screen pixel density. This unit is used for values whose unit is not specified. On a screen with an actual width of 1440 physical pixels, 1 vp is approximately equal to 3 px.| +| fp | Font pixel, which is similar to vp and varies according to the system font size.| +| lpx | Logical pixel unit of the window. It is the ratio of the actual screen width to the logical width (configured by **designWidth**). For example, if **designWidth** is set to **720** (default value), then 1 lpx is equal to 2 px for a screen with an actual width of 1440 physical pixels.| ## Pixel Unit Conversion @@ -37,33 +37,71 @@ struct Example { Flex({ wrap: FlexWrap.Wrap }) { Column() { Text("width(220)") - .width(220).height(40).backgroundColor(0xF9CF93) - .textAlign(TextAlign.Center).fontColor(Color.White).fontSize('12vp') + .width(220) + .height(40) + .backgroundColor(0xF9CF93) + .textAlign(TextAlign.Center) + .fontColor(Color.White) + .fontSize('12vp') }.margin(5) + Column() { Text("width('220px')") - .width('220px').height(40).backgroundColor(0xF9CF93) - .textAlign(TextAlign.Center).fontColor(Color.White) + .width('220px') + .height(40) + .backgroundColor(0xF9CF93) + .textAlign(TextAlign.Center) + .fontColor(Color.White) }.margin(5) + Column() { Text("width('220vp')") - .width('220vp').height(40).backgroundColor(0xF9CF93) - .textAlign(TextAlign.Center).fontColor(Color.White).fontSize('12vp') + .width('220vp') + .height(40) + .backgroundColor(0xF9CF93) + .textAlign(TextAlign.Center) + .fontColor(Color.White) + .fontSize('12vp') }.margin(5) + Column() { Text("width('220lpx') designWidth:720") - .width('220lpx').height(40).backgroundColor(0xF9CF93) - .textAlign(TextAlign.Center).fontColor(Color.White).fontSize('12vp') + .width('220lpx') + .height(40) + .backgroundColor(0xF9CF93) + .textAlign(TextAlign.Center) + .fontColor(Color.White) + .fontSize('12vp') }.margin(5) + Column() { Text("width(vp2px(220) + 'px')") - .width(vp2px(220) + 'px').height(40).backgroundColor(0xF9CF93) - .textAlign(TextAlign.Center).fontColor(Color.White).fontSize('12vp') + .width(vp2px(220) + 'px') + .height(40) + .backgroundColor(0xF9CF93) + .textAlign(TextAlign.Center) + .fontColor(Color.White) + .fontSize('12vp') }.margin(5) + Column() { Text("fontSize('12fp')") - .width(220).height(40).backgroundColor(0xF9CF93) - .textAlign(TextAlign.Center).fontColor(Color.White).fontSize('12fp') + .width(220) + .height(40) + .backgroundColor(0xF9CF93) + .textAlign(TextAlign.Center) + .fontColor(Color.White) + .fontSize('12fp') + }.margin(5) + + Column() { + Text("width(px2vp(220))") + .width(px2vp(220)) + .height(40) + .backgroundColor(0xF9CF93) + .textAlign(TextAlign.Center) + .fontColor(Color.White) + .fontSize('12fp') }.margin(5) }.width('100%') } diff --git a/en/application-dev/reference/arkui-ts/ts-transition-animation-component.md b/en/application-dev/reference/arkui-ts/ts-transition-animation-component.md index cd072648a81f68b080ae88b9a90cf6a157376dc6..8018ee5d626d0fcb04dd36f3d70e2081736b189d 100644 --- a/en/application-dev/reference/arkui-ts/ts-transition-animation-component.md +++ b/en/application-dev/reference/arkui-ts/ts-transition-animation-component.md @@ -1,6 +1,6 @@ # Component Transition -Configure the component transition animations for when a component is inserted or deleted. This feature takes effect only when [animateTo](ts-explicit-animation.md) is used. The animation duration, curve, and delay are the same as those configured in **animateTo**. +You can configure the component transition animations through the **transition** attribute for when a component is inserted or deleted. > **NOTE** > @@ -12,21 +12,54 @@ Configure the component transition animations for when a component is inserted o | Name| Type| Description| | -------- | -------- | -------- | -| transition | TransitionOptions | Transition effects when the component is inserted, displayed, deleted, or hidden.
If no transition effect is set, an opacity transition from 0 to 1 is applied.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
Transition parameters, which are all optional. For details, see **TransitionOptions**.| +| transition | TransitionOptions \| TransitionEffect10+ | Transition effects when the component is inserted, displayed, deleted, or hidden.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
For details, see the description of **TransitionOptions** and **TransitionEffect**.| ## TransitionOptions - +Defines the transition effect by setting parameters in the struct. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | [TransitionType](ts-appendix-enums.md#transitiontype) | No| Transition type, which includes component addition and deletion by default.
Default value: **TransitionType.All**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
If **type** is not specified, insertion and deletion use the same transition type.| -| opacity | number | No| Opacity of the component during transition, which is the value of the start point of insertion and the end point of deletion.
Default value: **1**
Value range: [0, 1]
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
A value less than 0 evaluates to the value **0**. A value greater than 1 evaluates to the value **1**.| +| type | [TransitionType](ts-appendix-enums.md#transitiontype) | No| Transition type.
Default value: **TransitionType.All**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
If **type** is not specified, the default value **TransitionType.All** is used, which means that the transition effect works for both component addition and deletion.| +| opacity | number | No| Opacity of the component during transition, which is the value of the start point of insertion and the end point of deletion.
Value range: [0, 1]
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
A value less than 0 or greater than 1 evaluates to the value **1**.| | translate | {
x? : number \| string,
y? : number \| string,
z? : number \| string
} | No| Translation of the component during transition, which is the value of the start point of insertion and the end point of deletion.
-**x**: distance to translate along the x-axis.
-**y**: distance to translate along the y-axis.
-**z**: distance to translate along the z-axis.
Since API version 9, this API is supported in ArkTS widgets.| -| scale | {
x? : number,
y? : number,
z? : number,
centerX? : number \| string,
centerY? : number \| string
} | No| Scaling of the component during transition, which is the value of the start point of insertion and the end point of deletion.
- **x**: scale factor along the x-axis.
- **y**: scale factor along the y-axis.
- **z**: scale factor along the z-axis.
- **centerX** and **centerY**: x coordinate and y coordinate of the scale center, respectively. The default values are both **"50%"**.
- If the center point is 0, it indicates the upper left corner of the component.
Since API version 9, this API is supported in ArkTS widgets.| -| rotate | {
x?: number,
y?: number,
z?: number,
angle?: number \| string,
centerX?: number \| string,
centerY?: number \| string
} | No| Rotation of the component during transition, which is the value of the start point of insertion and the end point of deletion.
- **x**: rotation vector along the x-axis.
- **y**: rotation vector along the y-axis.
- **z**: rotation vector along the z-axis.
- **centerX** and **centerY**: x coordinate and y coordinate of the rotation center, respectively. The default values are both **"50%"**.
- If the center point is (0, 0), it indicates the upper left corner of the component.
Since API version 9, this API is supported in ArkTS widgets.| +| scale | {
x? : number,
y? : number,
z? : number,
centerX? : number \| string,
centerY? : number \| string
} | No| Scaling of the component during transition, which is the value of the start point of insertion and the end point of deletion.
- **x**: scale factor along the x-axis.
- **y**: scale factor along the y-axis.
- **z**: scale factor along the z-axis.
- **centerX** and **centerY**: scale center point. The default values are both **"50%"**, indicating that the center point of the page.
- If the center point is (0, 0), it refers to the upper left corner of the component.
Since API version 9, this API is supported in ArkTS widgets.| +| rotate | {
x?: number,
y?: number,
z?: number,
angle: number \| string,
centerX?: number \| string,
centerY?: number \| string
} | No| Rotation of the component during transition, which is the value of the start point of insertion and the end point of deletion.
- **x**: X-component of the rotation vector.
- **y**: Y-component of the rotation vector.
- **z**: Z-component of the rotation vector.
- **centerX** and **centerY**: rotation center point. The default values are both **"50%"**, indicating that the center point of the page.
- If the center point is (0, 0), it refers to the upper left corner of the component.
Since API version 9, this API is supported in ArkTS widgets.| +> **NOTE** +> +> 1. When set to a value of the **TransitionOptions** type, the **transition** attribute must work with [animateTo](ts-explicit-animation.md). The animation duration, curve, and delay follow the settings in **animateTo**. +> 2. If the value of the **TransitionOptions** type has only **type** specified, the transition effect will take on the default opacity. For example, **{type: TransitionType.Insert}** produces the same effect as **{type: TransitionType.Insert, opacity: 0}**. If a specific style is specified, the transition effect will not take on the default opacity. +> 3. For details about the scale and rotate effects, see [Transformation](ts-universal-attributes-transformation.md). + +## TransitionEffect10+ +Defines the transition effect by using the provided APIs, as listed below. +| API| Type| Static Function| Description| +| -------- | ---------- | -------- | -------- | +| opacity | number | Yes| Opacity of the component during transition, which is the value of the start point of insertion and the end point of deletion.
Value range: [0, 1]
**NOTE**
A value less than 0 or greater than 1 evaluates to the value **1**.| +| translate | {
x? : number \| string,
y? : number \| string,
z? : number \| string
} | Yes| Translation of the component during transition, which is the value of the start point of insertion and the end point of deletion.
-**x**: distance to translate along the x-axis.
-**y**: distance to translate along the y-axis.
-**z**: distance to translate along the z-axis.| +| scale | {
x? : number,
y? : number,
z? : number,
centerX? : number \| string,
centerY? : number \| string
} | Yes| Scaling of the component during transition, which is the value of the start point of insertion and the end point of deletion.
- **x**: scale factor along the x-axis.
- **y**: scale factor along the y-axis.
- **z**: scale factor along the z-axis.
- **centerX** and **centerY**: scale center point. The default values are both **"50%"**, indicating that the center point of the page.
- If the center point is (0, 0), it refers to the upper left corner of the component.| +| rotate | {
x?: number,
y?: number,
z?: number,
angle: number \| string,
centerX?: number \| string,
centerY?: number \| string
} | Yes| Rotation of the component during transition, which is the value of the start point of insertion and the end point of deletion.
- **x**: rotation vector along the x-axis.
- **y**: Y-component of the rotation vector.
- **z**: Z-component of the rotation vector.
- **centerX** and **centerY**: rotation center point. The default values are both **"50%"**, indicating that the center point of the page.
- If the center point is (0, 0), it refers to the upper left corner of the component.| +| move | [TransitionEdge](ts-appendix-enums.md#transitionedge10) | Yes| Slide-in and slide-out of the component from the screen edge during transition. It is essentially a translation effect, which is the value of the start point of insertion and the end point of deletion.| +| asymmetric | appear: TransitionEffect,
disappear: TransitionEffect
| Yes| Asymmetric transition effect.
The first parameter indicates the transition effect for appearance, and the second parameter indicates the transition effect for disappearance.
If the **asymmetric** function is not used for **TransitionEffect**, the transition effect takes effect for both appearance and disappearance of the component.| +| combine | TransitionEffect | No| Combination of transition effects.| +| animation | [AnimateParam](ts-explicit-animation.md#animateparam) | No| Animation settings.
The **onFinish** callback in **AnimateParam** does not work here.
If **combine** is used for combining transition effects, the animation settings of a transition effect are applicable to the one following it.| + +The static functions listed in the preceding table are used to create a **TransitionEffect** object, while the non-static functions apply to the created **TransitionEffect** object. +**TransitionEffect** also provides some static member variables for transition effects: +| Static Member Variable| Description| +| -------- | -------- | +| IDENTITY | Disables the transition effect.| +| OPACITY | Applies a transition effect with the opacity of 0. It is equivalent to **TransitionEffect.opacity(0)**.| +| SLIDE | Applies a transition effect of sliding in from the left when the component appears and sliding out from the right when the component disappears. It is equivalent to **TransitionEffect.asymmetric(TransitionEffect.START, TrasitionEffect.END)**.| -## Example +> **NOTE** +> +> 1. For transition effects combined through the **combine** function, animation settings can be configured through the **animation** parameter on a one-on-one basis. In addition, the animation settings of a transition effect are applicable to the one following it. For example, with **TransitionEffect.OPACITY.animation({duration: 1000}).combine(TransitionEffect.translate({x: 100}))**, the **duration** settings (1000 ms) apply to both the OPACITY and translate effects. +> 2. The animation settings take effect in the following sequence: animation settings specified in the current **TransitionEffect** > animation settings specified in the previous **TransitionEffect** > animation settings specified in **animateTo** that triggers the component to appear and disappear. +> 3. If **animateTo** is not used and **TransitionEffect** does not have the **animation** parameter specified, the component will appear or disappear without any transition animation. +> 4. If the value of an attribute specified in **TransitionEffect** is the same as the default value, no transition animation is applied for the attribute. For example, with **TransitionEffect.opacity(1).animation({duration:1000})**, because the default value of **opacity** is also **1**, no opacity animation will be applied, and the component appears or disappears without any transition animation. +## Example +The following is an example of using **TransitionOptions** for appearance and disappearance of the component. ```ts // xxx.ets @Entry @@ -40,40 +73,121 @@ struct TransitionExample { Button(this.show).width(80).height(30).margin(30) .onClick(() => { // Click the button to show or hide the image. + if (this.flag) { + this.show = 'hide'; + } else { + this.show = 'show'; + } + // When set to a value of the TransitionOptions type, the transition attribute must work with animateTo. animateTo({ duration: 1000 }, () => { - if (this.flag) { - this.show = 'hide' - } else { - this.show = 'show' - } this.flag = !this.flag }) }) if (this.flag) { - // Apply different transition effects to the showing and hiding of the image. - Image($r('app.media.testImg')).width(300).height(300) + // Apply different transition effects to the appearance and disappearance of the image. + // When the image appears, it changes from the state where the scale factor is 0 along the x-axis and 1 along the y-axis to the state where the scale factor is both 1 along x-axis and y-axis. + // When the image disappears, it rotates from 0° to 180° clockwise around the z-axis. + Image($r('app.media.testImg')).width(200).height(200) .transition({ type: TransitionType.Insert, scale: { x: 0, y: 1.0 } }) - .transition({ type: TransitionType.Delete, rotate: { angle: 180 } }) + .transition({ type: TransitionType.Delete, rotate: { z: 1, angle: 180 } }) } }.width('100%') } } ``` -Diagrams: - -When the image is completely displayed: - -![animationComponent1](figures/animationComponent1.png) - -When the transition effect of 180° clockwise rotation is applied to the hiding of the image: - -![animationComponent3](figures/animationComponent3.png) +Below you can see the example in action.
+![transitionComponent1](figures/transitionComponent1.gif) -When the image disappears completely: +The following is an example of using the same transition effect for the appearance and disappearance (which are inverse processes) of the component. +```ts +// xxx.ets +@Entry +@Component +struct TransitionEffectExample1 { + @State flag: boolean = true; + @State show: string = 'show'; -![animationComponent2](figures/animationComponent2.png) + build() { + Column() { + Button(this.show).width(80).height(30).margin(30) + .onClick(() => { + // Click the button to show or hide the image. + if (this.flag) { + this.show = 'hide'; + } else { + this.show = 'show'; + } + this.flag = !this.flag; + }) + if (this.flag) { + // Apply the same transition effect to the appearance and disappearance of the image. + // When the image appears, it changes from the state where the opacity is 0 and the rotation angle is 180° around the z-axis to the state where the opacity is 1 and the rotation angle is 0°. The durations of the opacity and rotation animations are both 2000 ms. + // When the image disappears, it changes from the state where the opacity is 1 and the rotation angle is 0° to the state where the opacity is 0 and the rotation angle is 180° around the z-axis. The durations of the opacity and rotation animations are both 2000 ms. + Image($r('app.media.testImg')).width(200).height(200) + .transition(TransitionEffect.OPACITY.animation({ duration: 2000, curve: Curve.Ease }).combine( + TransitionEffect.rotate({ z: 1, angle: 180 }) + )) + } + }.width('100%') + } +} +``` +Below you can see the example in action.
+![transitionComponent2](figures/transitionComponent2.gif) -When the transition effect of zooming in twice horizontally is applied to the image displayed: +The following is an example of using different transition effects for the appearance and disappearance of the component. +```ts +// xxx.ets +@Entry +@Component +struct TransitionEffectExample2 { + @State flag: boolean = true; + @State show: string = 'show'; -![animationComponent4](figures/animationComponent4.png) + build() { + Column() { + Button(this.show).width(80).height(30).margin(30) + .onClick(() => { + // Click the button to show or hide the image. + if (this.flag) { + this.show = 'hide'; + } else { + this.show = 'show'; + } + animateTo({ duration: 2000 }, () => { + // In the first image, **TransitionEffect** contains **animation**, and therefore the animation settings are those configured in **TransitionEffect**. + // In the second image, **TransitionEffect** does not contain **animation**, and therefore the animation settings are those configured in **animateTo**. + this.flag = !this.flag; + }); + }) + if (this.flag) { + // Apply different transition effects to the appearance and disappearance of the image. + // When the image appears, its opacity changes 0 to 1 (default value) over the duration of 1000 ms, and after 1000 ms has elapsed, its rotation angle changes from 180° around the z-axis to 0° (default value) over the duration of 1000 ms. + // When the image disappears, after 1000 ms has elapsed, its opacity changes 1 (default value) to 0 over the duration of 1000 ms, and its rotation angle changes from 0° (default value) to 180° around the z-axis over the duration of 1000 ms. + Image($r('app.media.testImg')).width(200).height(200) + .transition( + TransitionEffect.asymmetric( + TransitionEffect.OPACITY.animation({ duration: 1000 }).combine( + TransitionEffect.rotate({ z: 1, angle: 180 }).animation({ delay: 1000, duration: 1000 })) + , + TransitionEffect.OPACITY.animation({ delay: 1000, duration: 1000 }).combine( + TransitionEffect.rotate({ z: 1, angle: 180 }).animation({ duration: 1000 })) + ) + ) + // When the image appears, the scale along the x- and y- axes is changed from 0 to 1 (default value). The animation duration is 2000 ms specified in **animateTo**. + // When the image disappears, no transition effect is applied. + Image($r('app.media.testImg')).width(200).height(200).margin({ top: 100 }) + .transition( + TransitionEffect.asymmetric( + TransitionEffect.scale({ x: 0, y: 0 }), + TransitionEffect.IDENTITY + ) + ) + } + }.width('100%') + } +} +``` +Below you can see the example in action.
+![transitionComponent3](figures/transitionComponent3.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-size.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-size.md index 875a75dd8059e56227fd9559368a073487c74c47..87fd75b9dfa56bf3ad799ce9d491f278b505623a 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-size.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-size.md @@ -10,17 +10,25 @@ The size attributes set the width, height, and margin of a component. ## Attributes -| Name | Type | Description | -| -------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| width | [Length](ts-types.md#length) | Width of the component. By default, the width required to fully hold the component content is used. If the width of the component is greater than that of the parent container, the range of the parent container is drawn.
Since API version 9, this API is supported in ArkTS widgets.
Since API version 10, this API supports the calc calculation feature.| -| height | [Length](ts-types.md#length) | Height of the component. By default, the height required to fully hold the component content is used. If the height of the component is greater than that of the parent container, the range of the parent container is drawn.
Since API version 9, this API is supported in ArkTS widgets.
Since API version 10, this API supports the calc calculation feature.| +| Name | Type | Description | +| -------------- | ---------------------------------------- | ---------------------------------------- | +| width | [Length](ts-types.md#length) | Width of the component. By default, the width required to fully hold the component content is used. If the width of the component is greater than that of the parent container, the range of the parent container is drawn.
Since API version 9, this API is supported in ArkTS widgets.
Since API version 10, this API supports the calc calculation feature.| +| height | [Length](ts-types.md#length) | Height of the component. By default, the height required to fully hold the component content is used. If the height of the component is greater than that of the parent container, the range of the parent container is drawn.
Since API version 9, this API is supported in ArkTS widgets.
Since API version 10, this API supports the calc calculation feature.| | size | {
width?: [Length](ts-types.md#length),
height?: [Length](ts-types.md#length)
} | Size of the component.
Since API version 9, this API is supported in ArkTS widgets.
Since API version 10, this API supports the calc calculation feature.| | padding | [Padding](ts-types.md#padding) \| [Length](ts-types.md#length) | Padding of the component.
When the parameter is of the **Length** type, the four paddings take effect.
Default value: **0**
When **padding** is set to a percentage, the width of the parent container is used as the basic value.
Since API version 9, this API is supported in ArkTS widgets.
Since API version 10, this API supports the calc calculation feature.| | margin | [Margin](ts-types.md#margin) \| [Length](ts-types.md#length) | Margin of the component.
When the parameter is of the **Length** type, the four margins take effect.
Default value: **0**
When **margin** is set to a percentage, the width of the parent container is used as the basic value.
Since API version 9, this API is supported in ArkTS widgets.
Since API version 10, this API supports the calc calculation feature.| -| constraintSize | {
minWidth?: [Length](ts-types.md#length),
maxWidth?: [Length](ts-types.md#length),
minHeight?: [Length](ts-types.md#length),
maxHeight?: [Length](ts-types.md#length)
} | Constraint size of the component, which is used to limit the size range during component layout. **constraintSize** takes precedence over **width** and **height**. If the value of **minWidth** is greater than that of **maxWidth**, only the value of **minWidth** takes effect. The same rule applies to **minHeight** and **maxHeight**.
Default value:
{
minWidth: 0,
maxWidth: Infinity,
minHeight: 0,
maxHeight: Infinity
}
Since API version 9, this API is supported in ArkTS widgets.
Since API version 10, this API supports the calc calculation feature.| -| layoutWeight | number \| string | Weight of the component during layout. When the container size is determined, the container space is allocated along the main axis among the component and sibling components based on the layout weight, and the component size setting is ignored.
Default value: **0**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute is valid only for the **\**, **\**, and **\** layouts.
The value can be a number greater than or equal to 0 or a string that can be converted to a number.| +| constraintSize | {
minWidth?: [Length](ts-types.md#length),
maxWidth?: [Length](ts-types.md#length),
minHeight?: [Length](ts-types.md#length),
maxHeight?: [Length](ts-types.md#length)
} | Constraint size of the component, which is used to limit the size range during component layout. **constraintSize** takes precedence over **width** and **height**. Learn [how the value of this attribute affects the width and height](#impact-of-constraintsize-on-widthheight).
Default value:
{
minWidth: 0,
maxWidth: Infinity,
minHeight: 0,
maxHeight: Infinity
}
Since API version 9, this API is supported in ArkTS widgets.
Since API version 10, this API supports the calc calculation feature.| +## Impact of constraintSize on width/height +| Size Arrangement | Result | +| ---------------------------------------- | ------------------ | +| minWidth/minHeight < width/height< maxWidth/maxHeight | width/height | +| minWidth/minHeight < maxWidth/maxHeight < width/height | maxWidth/maxHeight | +| maxWidth/maxHeight < minWidth/minHeight < width/height | minWidth/minHeight | +| maxWidth/maxHeight < width/height< minWidth/minHeight | minWidth/minHeight | +| width/height < maxWidth/maxHeight < minWidth/minHeight | minWidth/minHeight | +| width/height < minWidth/minHeight < maxWidth/maxHeight | minWidth/minHeight | ## Example ```ts diff --git a/en/application-dev/reference/errorcodes/errorcode-data-rdb.md b/en/application-dev/reference/errorcodes/errorcode-data-rdb.md index d0e4a40e4ce19f10f5470b6a4b83caaa72707611..823fb7b65b6cc277f64ba7b43b7314baa25d5971 100644 --- a/en/application-dev/reference/errorcodes/errorcode-data-rdb.md +++ b/en/application-dev/reference/errorcodes/errorcode-data-rdb.md @@ -4,11 +4,29 @@ > > This topic describes only module-specific error codes. For details about universal error codes, see [Universal Error Codes](errorcode-universal.md). +## 14800000 Internal Error + +**Error Message** + +Inner error. + +**Description** + +An error occurs at the underlying database. + +**Possible Causes** + +Invalid SQL statement is passed in. + +**Solution** + +Determine the cause of the error based on the log information. + ## 14800010 Invalid RDB Name **Error Message** -Invalid database name. +Failed to open or delete database by invalid database path. **Description** @@ -16,17 +34,17 @@ The RDB store name is invalid. **Possible Causes** -The RDB store name is empty or exceeds 1024 bytes. +The RDB store path is invalid. **Solution** -Check that the RDB store name is not empty and does not exceed 1024 bytes. +Check the RDB store path. ## 14800011 Database File Corrupted **Error Message** -Database corrupted. +Failed to open database by database corrupted. **Description** diff --git a/en/application-dev/reference/errorcodes/errorcode-datashare.md b/en/application-dev/reference/errorcodes/errorcode-datashare.md index d97e4218f2132e0e9fc211450df1e7faebff0fef..566ff62cb6d3d07038e930a472e19ffea8b2b3ef 100644 --- a/en/application-dev/reference/errorcodes/errorcode-datashare.md +++ b/en/application-dev/reference/errorcodes/errorcode-datashare.md @@ -8,7 +8,7 @@ **Error Message** -The dataShareHelper is not initialized successfully. +The DataShareHelper is not initialized successfully. **Description** @@ -23,3 +23,40 @@ The **DataShareHelper** class fails to be created. 1. Obtain the correct URI. 2. Check that the context of the stage model is used. + +## 15700011 Failed to Add or Delete a Template + +**Error Message** + +The uri is not exist. + +**Description** + +This error code is returned when a template fails to be added or deleted. + +**Possible Causes** + +1. The input parameter **uri** of **addTemplate()** is incorrect. +2. The input parameter **uri** of **delTemplate()** is incorrect. + +**Solution** + +Obtain the correct URI. + +## 15700012 Data Area Not Exist + +**Error Message** + +The data area is not exist. + +**Description** + +This error code is returned when a data update fails. + +**Possible Causes** + +The input parameter **bundleName** of **publish()** is incorrect. + +**Solution** + +Obtain the correct **bundleName** value from the DataShare server provider. diff --git a/en/application-dev/reference/errorcodes/errorcode-preferences.md b/en/application-dev/reference/errorcodes/errorcode-preferences.md index 67cd7ab9760d36627b0c29e0b4d3715bb3e9824a..d736c4fecfc1a2c6cc14f55c04dd927db761bde5 100644 --- a/en/application-dev/reference/errorcodes/errorcode-preferences.md +++ b/en/application-dev/reference/errorcodes/errorcode-preferences.md @@ -7,7 +7,7 @@ ## 15500010 Failed to Delete the User Preference Persistence File **Error Message** -Failed to delete preferences. +Failed to delete preferences file. **Description** diff --git a/en/application-dev/reference/native-lib/Readme-EN.md b/en/application-dev/reference/native-lib/Readme-EN.md index d0ac26033d50f5bf9b3a2f94bf90d141d6db86be..9b0fbca08e15c7b7e0e5e500d3532019bb56eb87 100644 --- a/en/application-dev/reference/native-lib/Readme-EN.md +++ b/en/application-dev/reference/native-lib/Readme-EN.md @@ -1,7 +1,8 @@ # Standard Libraries Supported by Native APIs -- [Node_API](third_party_napi/napi.md) +- [libc](third_party_libc/musl.md) +- [Node-API](third_party_napi/napi.md) - [libuv](third_party_libuv/libuv.md) -- [Native Standard Libraries Supported by Openharmony](third_party_libc/musl.md) +- [OpenSL ES](third_party_opensles/opensles.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/security/huks-guidelines.md b/en/application-dev/security/huks-guidelines.md index c23e9146f3f9e1a10206a003001339efa63f7444..60839bf7b35ee9043fa8fb70c140459e51d6356f 100644 --- a/en/application-dev/security/huks-guidelines.md +++ b/en/application-dev/security/huks-guidelines.md @@ -3,25 +3,22 @@ ## Key Generation -The HUKS provides the capability of randomly generating keys for services. For a key generated by the HUKS, the plaintext will never be exposed outside throughout the lifecycle. No one can access the plaintext of the key. Even the service, for which the key is generated, can call APIs provided by the HUKS to perform operations on the key and obtain the operation result, but not access the key. +The OpenHarmony Universal KeyStore (HUKS) provides key management and cryptography operations for services. For a key generated by the HUKS, the plaintext will never be exposed outside throughout the lifecycle. No one can obtain the key in plaintext. Even the service itself can call APIs provided by the HUKS to perform operations on the key and obtain the operation result, but cannot access the key. -**How to Develop** +**How to Develop** Use [huks.generateKeyItem(keyAlias,options,callback)](../reference/apis/js-apis-huks.md#huksgeneratekeyitem9) to generate a key. You need to pass in the key alias in **keyAlias**, key property set in **options**, and **callback** to return the result asynchronously. For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md). **Procedure** - -1. Determine the key alias. +1. Set the key alias. 2. Initialize the key property set.
Use [HuksParam](../reference/apis/js-apis-huks.md#huksparam) to encapsulate key properties and use a **HuksParam** array to assign values to the **properties** field of [HuksOptions](../reference/apis/js-apis-huks.md#huksoptions). The parameters [HuksKeyAlg](../reference/apis/js-apis-huks.md#hukskeyalg), [HuksKeySize](../reference/apis/js-apis-huks.md#hukskeysize), and [HuksKeyPurpose](../reference/apis/js-apis-huks.md#hukskeypurpose) are mandatory. 3. Pass in the key alias and key parameter set to generate a key. - - > **NOTE** > > The key alias cannot exceed 64 bytes. -**Sample Code** +**Sample code** ```ts /* @@ -30,7 +27,7 @@ Use [huks.generateKeyItem(keyAlias,options,callback)](../reference/apis/js-apis- import huks from '@ohos.security.huks'; /* - * Determine the key alias and encapsulate the key properties. + * Set the key alias and encapsulate the key properties. */ let keyAlias = 'dh_key'; let properties = new Array(); @@ -96,25 +93,20 @@ async function TestGenKey() { ``` ## Key Import -A key generated outside the HUKS (for example, generated through key agreement or by a server) can be imported to the HUKS for management. The HUKS supports import of keys in plaintext. However, if a key is imported in plaintext, the key is exposed in the REE memory. This operation applies to lightweight devices or security-insensitive services. For security-sensitive services, use the secure import provided by the HUKS. Secure import allows the keys generated for services to be transferred to the HUKS through an end-to-end encrypted transmission channel. - -Once a key is imported to the HUKS, its plaintext will not be exposed outside the HUKS throughout the lifecycle of the key. +A key generated outside the HUKS (for example, generated through key agreement or by a server) can be imported to the HUKS for management. The HUKS supports import of keys in plaintext. However, if a key is imported in plaintext, the key is exposed in the Rich Execution Environment (REE) memory. This type of import applies to lightweight devices or security-insensitive services. For security-sensitive services, use the secure import feature provided by the HUKS. Secure import allows the keys generated for services to be transferred to the HUKS through an end-to-end encrypted transmission channel. +Once a key is imported to the HUKS, its plaintext will never be exposed outside the HUKS throughout the lifecycle of the key. ### Importing a Key in Plaintext - Use [huks.importKeyItem(keyAlias,options,callback)](../reference/apis/js-apis-huks.md#huksimportkeyitem9) to import a key in plaintext. You need to pass in the key alias in **keyAlias**, key material and property set in **options**, and **callback** to return the result asynchronously. For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md). - -1. Determine the key alias. +1. Set the key alias. 2. Encapsulate the key material and key property set.
The key material must comply with [HUKS key material formats](./huks-appendix.md#key-material-formats). The **inData** value of [HuksOptions](../reference/apis/js-apis-huks.md#huksoptions) must be in the Uint8Array format. Encapsulate key properties in [HuksParam](../reference/apis/js-apis-huks.md#huksparam), and use a **HuksParam** array to assign values to the **properties** field. The key properties must contain [HuksKeyAlg](../reference/apis/js-apis-huks.md#hukskeyalg), [HuksKeySize](../reference/apis/js-apis-huks.md#hukskeysize), and [HuksKeyPurpose](../reference/apis/js-apis-huks.md#hukskeypurpose). 3. Import the key. - - -**Sample Code** +**Sample code** ```ts /* @@ -128,7 +120,7 @@ let plainTextSize32 = new Uint8Array([ ]); /* - * Determine the key alias. + * Set the key alias. */ let keyAlias = 'AES256Alias_sample'; @@ -174,7 +166,7 @@ try { Check whether the key exists. If yes, the key is imported successfully. -**Sample Code** +**Sample code** ```ts import huks from '@ohos.security.huks'; @@ -209,26 +201,28 @@ try { ### Importing a Key Securely -Compared with import of plaintext, secure import involves complex key material and operations. The following figure illustrates the basic development process of secure import. +Compared with import of a key in plaintext, secure import involves more complex key material and operations. The following figure illustrates the basic development process of secure import. -**Figure 1** Secure import process +**Figure 1** Development process of secure import ![huks_import_wrapped_key](figures/huks_import_wrapped_key.png) +**Available APIs** +You need to use the APIs listed in the following table in sequence. +**Table 1** APIs for importing a key securely -**Available APIs** - -You need to use the APIs for generating a key, exporting a public key, importing a wrapped key, and deleting a key in sequence. | API | Description | | -------------------------------------- | ----------------------------| |generateKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void| Generates a key.| -|exportKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback) : void| Exports the public key of a key pair.| -|importWrappedKeyItem(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions, callback: AsyncCallback) : void|Imports a wrapped key.| -|deleteKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback) : void|Deletes a key.| +|exportKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void| Exports the public key of a key pair.| +|importWrappedKeyItem(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void|Imports a encrypted key.| +|deleteKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void|Deletes a key.| ->**NOTE**
The public key plaintext material returned by **exportKeyItem()** is encapsulated in X.509 format, and the key material to be imported by **importWrappedKeyItem()** must be encapsulated in **LengthData-Data** format. Specifically, the application needs to request a Uint8Array and encapsulate the Uint8Array in the sequence listed in the following table. +>**NOTE** +> +>The public key plaintext material returned by **exportKeyItem()** is encapsulated in X.509 format, and the key material to be imported by **importWrappedKeyItem()** must be encapsulated in **LengthData-Data** format. Specifically, the application needs to request a Uint8Array and encapsulate the Uint8Array in the sequence listed in the following table. **Table 2** Format of the wrapped key material @@ -245,6 +239,7 @@ You need to use the APIs for generating a key, exporting a public key, importing **How to Develop** The following example presents the development involving HUKS APIs (using the ECDH key agreement suite). The operations performed by the service are not included. + 1. Convert the key material into the HUKS format. 2. Generate a key for secure import. 3. Export the public key material. @@ -261,7 +256,7 @@ The following example presents the development involving HUKS APIs (using the EC import huks from '@ohos.security.huks'; /* - * Determine the key alias. + * Set the key alias. */ let importAlias = "importAlias"; let wrapAlias = "wrappingKeyAlias"; @@ -591,13 +586,13 @@ async function ImportWrappedKeyNormalTest() { Check whether the key exists. If yes, the key is imported successfully. -**Sample Code** +**Sample code** ```ts import huks from '@ohos.security.huks'; /* - * Determine the key alias and encapsulate the key properties. + * Set the key alias and encapsulate the key properties. */ let keyAlias = 'importAlias'; let isKeyExist; @@ -627,7 +622,6 @@ try { } ``` - ## Common Key Operations **When to Use** @@ -637,11 +631,19 @@ To ensure data confidentiality and integrity, you may need to encrypt or decrypt **General Development Process** The HUKS operates data based on key sessions. The general process is as follows: -1. (Mandatory) Use [huks.initSession()](../reference/apis/js-apis-huks.md#huksinitsession9) to initialize a key session.
You need to pass in the key alias and key operation parameters to initialize a key session, and obtain the session handle. The key operation parameters must contain the parameters required by the cipher algorithm, including the cipher algorithm, key size, key purpose, working mode, padding mode, hash mode, IV, nonce, and AAD. If access control is set for the key, other parameters are required. For details, see [Key Access Control](#key-access-control). This step is mandatory. -2. (Optional) Use [huks.updateSession()](../reference/apis/js-apis-huks.md#huksupdatesession9) to pass in data by segment. Perform this step only if the data exceeds 100 KB or the cryptographic algorithm requires operations by data segment. Otherwise, skip this step. This step is optional. -3. (Mandatory) Use [huks.finishSession()](../reference/apis/js-apis-huks.md#huksfinishsession9) to finalize the key session operation.
Pass in the last data segment and perform the key session operation. If an error occurs during the process or the data passed in is not required, use [huks.abortSession()](../reference/apis/js-apis-huks.md#huksabortsession9) to abort the session. This step is mandatory. + +1. (Mandatory) Use [huks.initSession()](../reference/apis/js-apis-huks.md#huksinitsession9) to initialize a key session. + + You need to pass in the key alias and key operation parameters to initialize a key session, and obtain the session handle. The key operation parameters must contain the parameters required by the cipher algorithm, including the cipher algorithm, key size, key purpose, working mode, padding mode, hash mode, IV, nonce, and AAD. If access control is set for the key, other parameters are required. For details, see [Key Access Control](#key-access-control). + +2. (Optional) Use [huks.updateSession()](../reference/apis/js-apis-huks.md#huksupdatesession9) to pass in data by segment. Perform this step only if the data exceeds 100 KB or the cryptographic algorithm requires operations by data segment. Otherwise, skip this step. + +3. (Mandatory) Use [huks.finishSession()](../reference/apis/js-apis-huks.md#huksfinishsession9) to complete the key session operation. + + Pass in the last data segment and complete the key session operation. If an error occurs during the process or the data passed in is not required, use [huks.abortSession()](../reference/apis/js-apis-huks.md#huksabortsession9) to abort the session. ### Encryption and Decryption + ```ts /* * The following uses an AES 128-bit key and callback-based APIs as an example. @@ -958,6 +960,9 @@ struct Index { ``` ### Key Agreement + +You are advised to pass in [HuksKeyStorageType](../reference/apis/js-apis-huks.md#hukskeystoragetype) to specify the storage type in key agreement. From API version 10, only **HUKS_STORAGE_ONLY_USED_IN_HUKS** or **HUKS_STORAGE_KEY_EXPORT_ALLOWED** can be used for key agreement. If **HuksKeyStorageType** is not passed in, the key can be stored and exported by default, which poses security risks. + ```ts /* * Perform key agreement using an X25519 256-bit TEMP key and return the result in a callback. @@ -965,7 +970,7 @@ struct Index { import huks from '@ohos.security.huks'; /* - * Determine the key alias and encapsulate the key properties. + * Set the key alias and encapsulate the key properties. */ let srcKeyAliasFirst = "AgreeX25519KeyFirstAlias"; let srcKeyAliasSecond = "AgreeX25519KeySecondAlias"; @@ -1002,6 +1007,10 @@ properties[5] = { tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, value: huks.HuksCipherMode.HUKS_MODE_CBC, } +properties[6] = { + tag: huks.HuksTag.HUKS_TAG_DERIVED_AGREED_KEY_STORAGE_FLAG, + value: huks.HuksKeyStorageType.HUKS_STORAGE_ONLY_USED_IN_HUKS, +} let HuksOptions = { properties: properties, inData: new Uint8Array(new Array()) @@ -1010,8 +1019,8 @@ let HuksOptions = { /* Configure parameters for the first key agreement. */ let finishProperties = new Array(); finishProperties[0] = { - tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, - value: huks.HuksKeyStorageType.HUKS_STORAGE_TEMP, + tag: huks.HuksTag.HUKS_TAG_DERIVED_AGREED_KEY_STORAGE_FLAG, + value: huks.HuksKeyStorageType.HUKS_STORAGE_ONLY_USED_IN_HUKS, } finishProperties[1] = { tag: huks.HuksTag.HUKS_TAG_IS_KEY_ALIAS, @@ -1322,6 +1331,9 @@ async function testAgree() { ``` ### Key Derivation + +You are advised to pass in [HuksKeyStorageType](../reference/apis/js-apis-huks.md#hukskeystoragetype) for key derivation. From API version 10, only **HUKS_STORAGE_ONLY_USED_IN_HUKS** or **HUKS_STORAGE_KEY_EXPORT_ALLOWED** can be used for key derivation. If **HuksKeyStorageType** is not passed in, the key can be stored and exported by default, which poses security risks. + ```ts /* * The following uses an HKDF256 key and promise-based APIs as an example. @@ -1329,7 +1341,7 @@ async function testAgree() { import huks from '@ohos.security.huks'; /* - * Determine the key alias and encapsulate the key properties. + * Set the key alias and encapsulate the key properties. */ let srcKeyAlias = "hkdf_Key"; let deriveHkdfInData = "deriveHkdfTestIndata"; @@ -1355,6 +1367,10 @@ properties[3] = { tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128, } +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_DERIVED_AGREED_KEY_STORAGE_FLAG, + value: huks.HuksKeyStorageType.HUKS_STORAGE_ONLY_USED_IN_HUKS, +} let huksOptions = { properties: properties, inData: new Uint8Array(new Array()) @@ -1386,8 +1402,8 @@ let initOptions = { /* Configure the parameter set used for finish(). */ let finishProperties = new Array(); finishProperties[0] = { - tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, - value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT, + tag: huks.HuksTag.HUKS_TAG_DERIVED_AGREED_KEY_STORAGE_FLAG, + value: huks.HuksKeyStorageType.HUKS_STORAGE_ONLY_USED_IN_HUKS, } finishProperties[1] = { tag: huks.HuksTag.HUKS_TAG_IS_KEY_ALIAS, @@ -1646,12 +1662,13 @@ Services can access only their own keys, that is, the keys generated or imported In addition, the HUKS supports user identity authentication for security-sensitive services. Users can use the service keys only after the authentication (PIN or biometric authentication) is successful. The HUKS also restricts the key usage. For example, the AES keys can only be used for encryption and decryption, and the RSA keys can only be used for signing and signature verification. -**User Identity Authentication** +### User Identity Authentication -When generating or importing a key, you can enable user identity authentication for the key use. You can specify a subset of credentials (lock screen password, fingerprint, and face) for user identity authentication. After a key is generated or imported, unauthorized key access can be prevented even if the application process is attacked. Key access control applies to security-sensitive scenarios, such as password-free login, password-free payment, and automatic password filling. +During the key generation or import process, user identity authentication can be enabled to allow the use of the key only after the authentication is successful. You can specify a subset of credentials (lock screen password, fingerprint, and face) for user identity authentication. After a key is generated or imported, unauthorized key access can be prevented even if the application process is attacked. Key access control applies to security-sensitive scenarios, such as password-free login, password-free payment, and automatic password filling. In addition to user identity authentication, the HUKS provides the following modes for automatically invalidating a key: -- Invalidate the key when the screen lock password is cleared.
This mode takes effect only when a screen lock password has been set. If the screen lock password is cleared, the key becomes invalid permanently. The key will not be invalidated if the screen lock password is modified. This mode applies to user-related data protection and access based on screen lock passwords. + +- Invalidate the key when the screen lock password is cleared.
This mode takes effect only when a screen lock password has been set. If the screen lock password is cleared, the key becomes invalid permanently. The key will not be invalidated if the screen lock password is modified. This mode applies to user-related data protection or access based on screen lock passwords. - Invalidate the key when new biometric enrollments are added.
This mode takes effect only when at least one biometric feature (such as fingerprint) has been enrolled. The key becomes invalid permanently once a new biometric feature is enrolled. The key will not be invalidated if the biometric feature is deleted. This mode applies to scenarios, such as password-free login or payment. To ensure the validity of the user authentication result, the HUKS supports challenge verification. Before user identity authentication, obtain the challenge (in [HuksSessionHandle](../reference/apis/js-apis-huks.md#hukssessionhandle9) returned by [huks.initSession()](../reference/apis/js-apis-huks.md#huksinitsession9)) from the HUKS and pass in the challenge in [userIAM_userAuth.getAuthInstance](../reference/apis/js-apis-useriam-userauth.md#authinstance9). The challenge of the authentication token is then verified during key operations. @@ -1668,33 +1685,33 @@ When a key is generated or imported, [HuksUserAuthType](../reference/apis/js-api **Table 3** User authentication types -| Name | Value | Description | -| ------------------------------- |---|------------------------ | -| HUKS_USER_AUTH_TYPE_FINGERPRINT |0x0001 | Fingerprint authentication.
Fingerprint authentication, facial authentication, and PIN authentication can be enabled at the same time. | -| HUKS_USER_AUTH_TYPE_FACE |0x0002 | Facial authentication.
Fingerprint authentication, facial authentication, and PIN authentication can be enabled at the same time.| -| HUKS_USER_AUTH_TYPE_PIN |0x0004 | PIN authentication.
Fingerprint authentication, facial authentication, and PIN authentication can be enabled at the same time.| +| Name | Value | Description | +| ------------------------------- | ------ | ------------------------------------------------------------ | +| HUKS_USER_AUTH_TYPE_FINGERPRINT | 0x0001 | Fingerprint authentication, which can be enabled with facial authentication and PIN authentication at the same time. | +| HUKS_USER_AUTH_TYPE_FACE | 0x0002 | Facial authentication, whch can be enabled with fingerprint authentication and PIN authentication at the same time. | +| HUKS_USER_AUTH_TYPE_PIN | 0x0004 | PIN authentication, which can be enabled with fingerprint authentication and facial authenticationat the same time. | **Table 4** Secure access types -| Name | Value | Description | -| --------------------------------------- | ---- | ------------------------------------------------ | -| HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | 1 | Invalidate the key after the screen lock password is cleared. | -| HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | 2 | Invalidate the key after a biometric enrollment is added. The user authentication types must include the biometric authentication.| + +| Name | Value | Description | +| --------------------------------------- | ----- | ------------------------------------------------------------ | +| HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | 1 | Invalidate the key after the screen lock password is cleared. | +| HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | 2 | Invalidate the key after a biometric enrollment is added. The user authentication types must include the biometric authentication. | **Table 5** Challenge types -| Name | Value | Description | -| ------------------------------- | ---- | ------------------------------ | -| HUKS_CHALLENGE_TYPE_NORMAL | 0 | Normal challenge, which requires an independent user authentication for each use of the key.| -| HUKS_CHALLENGE_TYPE_CUSTOM | 1 | Custom challenge, which supports only one user authentication for multiple keys.| -| HUKS_CHALLENGE_TYPE_NONE | 2 | No challenge is required during user authentication.| + +| Name | Value | Description | +| -------------------------- | ----- | ------------------------------------------------------------ | +| HUKS_CHALLENGE_TYPE_NORMAL | 0 | Normal challenge, which requires an independent user authentication for each use of the key. | +| HUKS_CHALLENGE_TYPE_CUSTOM | 1 | Custom challenge, which supports only one user authentication for multiple keys. | +| HUKS_CHALLENGE_TYPE_NONE | 2 | No challenge is required during user authentication. | > **NOTICE** > > - The three challenge types are mutually exclusive. > - If the challenge type is **HUKS_CHALLENGE_TYPE_NONE**, no challenge is required. However, the key can be accessed within a specified time period (set by **HUKS_TAG_AUTH_TIMEOUT**) after a successful authentication. The maximum value of **HUKS_TAG_AUTH_TIMEOUT** is 60 seconds. - -To use a key, initialize the key session, and determine whether a challenge is required based on the challenge type specified when the key is generated or imported. - +To use a key, initialize the key session, and determine whether a challenge is required based on the challenge type specified when the key is generated or imported. **Table 6** APIs for using a key @@ -1702,390 +1719,836 @@ To use a key, initialize the key session, and determine whether a challenge is r | -------------------------------------- | ----------------------------| |initSession(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void| Initializes the key session and obtains the challenge.| |updateSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void| Operates data by segment and passes the authentication token.| -|finishSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void| Finalizes the key session operation. | +|finishSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void| Completes the key session operation.| + +**How to Develop** + +1. Generate a key and specify user authentication properties. + + ```ts + import huks from '@ohos.security.huks'; + + /* + * Set the key alias and encapsulate the key properties. + */ + let keyAlias = 'dh_key_fingerprint_access'; + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM4, + } + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, + } + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, + } + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC, + } + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, + } + // Enable fingerprint authentication. + properties[5] = { + tag: huks.HuksTag.HUKS_TAG_USER_AUTH_TYPE, + value: huks.HuksUserAuthType.HUKS_USER_AUTH_TYPE_FINGERPRINT + } + // Set the key expiration type. Invalidate the key when a new biometric feature (fingerprint) is enrolled. + properties[6] = { + tag: huks.HuksTag.HUKS_TAG_KEY_AUTH_ACCESS_TYPE, + value: huks.HuksAuthAccessType.HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL + } + // Use the default challenge type. + properties[7] = { + tag: huks.HuksTag.HUKS_TAG_CHALLENGE_TYPE, + value: huks.HuksChallengeType.HUKS_CHALLENGE_TYPE_NORMAL + } + let huksOptions = { + properties: properties, + inData: new Uint8Array(new Array()) + } + /* + * Generate a key. + */ + function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { + return new Promise((resolve, reject) => { + try { + huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); + } + async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback generateKeyItem`); + let throwObject = {isThrow: false}; + try { + await generateKeyItem(keyAlias, huksOptions, throwObject) + .then((data) => { + console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } + } + + async function TestGenKeyForFingerprintAccessControl() { + await publicGenKeyFunc(keyAlias, huksOptions); + } + ``` + +2. Initialize the key session to obtain a challenge, and initiate fingerprint authentication to obtain an authentication token. + + ```ts + import huks from '@ohos.security.huks'; + import userIAM_userAuth from '@ohos.userIAM.userAuth'; + + /* + * Set the key alias and encapsulate the key properties. + */ + let srcKeyAlias = 'sm4_key_fingerprint_access'; + let handle; + let challenge; + let fingerAuthToken; + let authType = userIAM_userAuth.UserAuthType.FINGERPRINT; + let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; + + /* Configure the key generation parameter set and key encryption parameter set. */ + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM4, + } + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, + } + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, + } + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC, + } + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, + } + let huksOptions = { + properties: properties, + inData: new Uint8Array(new Array()) + } + + function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { + return new Promise((resolve, reject) => { + try { + huks.initSession(keyAlias, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); + } + + async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback doInit`); + let throwObject = {isThrow: false}; + try { + await initSession(keyAlias, huksOptions, throwObject) + .then ((data) => { + console.info(`callback: doInit success, data = ${JSON.stringify(data)}`); + handle = data.handle; + challenge = data.challenge; + }) + .catch((error) => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); + } + } + + function userIAMAuthFinger(huksChallenge:Uint8Array) { + // Obtain an authentication object. + let auth; + try { + auth = userIAM_userAuth.getAuthInstance(huksChallenge, authType, authTrustLevel); + console.log("get auth instance success"); + } catch (error) { + console.log("get auth instance failed" + error); + } + + // Subscribe to the authentication result. + try { + auth.on("result", { + callback: (result: userIAM_userAuth.AuthResultInfo) => { + /* The authentication is successful, and the authentication token is obtained. */ + fingerAuthToken = result.token; + } + }); + console.log("subscribe authentication event success"); + } catch (error) { + console.log("subscribe authentication event failed " + error); + } + + // Start user authentication. + try { + auth.start(); + console.info("authV9 start auth success"); + } catch (error) { + console.info("authV9 start auth failed, error = " + error); + } + } + + async function testInitAndAuthFinger() { + /* Initialize the key session to obtain a challenge. */ + await publicInitFunc(srcKeyAlias, huksOptions); + /* Invoke userIAM to perform user identity authentication. */ + userIAMAuthFinger(challenge); + } + ``` + +3. Pass in the authentication token to perform data operations. + + ```ts + /* + *The following uses an SM4 128-bit key and callback-based APIs as an example. + */ + import huks from '@ohos.security.huks'; + + /* + *Set the key alias and encapsulate the key properties. + */ + let srcKeyAlias = 'sm4_key_fingerprint_access'; + let IV = '1234567890123456'; + let cipherInData = 'Hks_SM4_Cipher_Test_101010101010101010110_string'; + let handle; + let fingerAuthToken; + let updateResult = new Array(); + let finishOutData; + + /* Configure the key generation parameter set and key encryption parameter set. */ + let propertiesEncrypt = new Array(); + propertiesEncrypt[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM4, + } + propertiesEncrypt[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT, + } + propertiesEncrypt[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, + } + propertiesEncrypt[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, + } + propertiesEncrypt[4] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC, + } + propertiesEncrypt[5] = { + tag: huks.HuksTag.HUKS_TAG_IV, + value: StringToUint8Array(IV), + } + let encryptOptions = { + properties: propertiesEncrypt, + inData: new Uint8Array(new Array()) + } + + function StringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); + } + + function updateSession(handle:number, huksOptions:huks.HuksOptions, token:Uint8Array, throwObject) : Promise { + return new Promise((resolve, reject) => { + try { + huks.updateSession(handle, huksOptions, token, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); + } + + async function publicUpdateFunc(handle:number, token:Uint8Array, huksOptions:huks.HuksOptions) { + console.info(`enter callback doUpdate`); + let throwObject = {isThrow: false}; + try { + await updateSession(handle, huksOptions, token, throwObject) + .then ((data) => { + console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`); + } + } + + function finishSession(handle:number, huksOptions:huks.HuksOptions, token:Uint8Array, throwObject) : Promise { + return new Promise((resolve, reject) => { + try { + huks.finishSession(handle, huksOptions, token, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); + } + + async function publicFinishFunc(handle:number, token:Uint8Array, huksOptions:huks.HuksOptions) { + console.info(`enter callback doFinish`); + let throwObject = {isThrow: false}; + try { + await finishSession(handle, huksOptions, token, throwObject) + .then ((data) => { + finishOutData = data.outData; + console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); + } + } + + async function testSm4Cipher() { + encryptOptions.inData = StringToUint8Array(cipherInData); + /* Pass in the authentication token. */ + await publicUpdateFunc(handle, fingerAuthToken, encryptOptions); + encryptUpdateResult = updateResult; + + encryptOptions.inData = new Uint8Array(new Array()); + /* Pass in the authentication token. */ + await publicFinishFunc(handle, fingerAuthToken, encryptOptions); + if (finishOutData === cipherInData) { + console.info('test finish encrypt err '); + } else { + console.info('test finish encrypt success'); + } + } + ``` + + +### Fine-grained User Identity Authentication + +As an extension of the [Key Access Control](#key-access-control), the fine-grained access control allows secondary user identity authentication (biometric authentication and lock screen password) to be performed for key access in one or more scenarios, such as encryption, decryption, signing, signature verification, key agreement, and key derivation. For example, a service needs to use a HUKS key to encrypt the account password information. In this scenario, identity authentication is not required in encryption but required in decryption. To achieve this purpose, you can use the fine-grained user identity authentication feature provided by the HUKS. **How to Develop** -1. Generate a key and specify user authentication properties. -```ts -import huks from '@ohos.security.huks'; +1. Specify [**HUKS_TAG_KEY_AUTH_PURPOSE**](../reference/apis/js-apis-huks.md#hukstag) for key generation to allow user identity authentication to be performed when a specific algorithm is used. +2. The **HUKS_TAG_KEY_AUTH_PURPOSE** does not need to be specified for the key usage process. The development process is the same as that of the user identity authentication process. -/* - * Determine the key alias and encapsulate the key properties. - */ -let keyAlias = 'dh_key_fingerprint_access'; -let properties = new Array(); -properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM4, -} -properties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, -} -properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, -} -properties[3] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_CBC, -} -properties[4] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE, -} -// Enable fingerprint authentication. -properties[5] = { - tag: huks.HuksTag.HUKS_TAG_USER_AUTH_TYPE, - value: huks.HuksUserAuthType.HUKS_USER_AUTH_TYPE_FINGERPRINT -} -// Set the key expiration type. Invalidate the key when a new biometric feature (fingerprint) is enrolled. -properties[6] = { - tag: huks.HuksTag.HUKS_TAG_KEY_AUTH_ACCESS_TYPE, - value: huks.HuksAuthAccessType.HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL -} -// Use the default challenge type. -properties[7] = { - tag: huks.HuksTag.HUKS_TAG_CHALLENGE_TYPE, - value: huks.HuksChallengeType.HUKS_CHALLENGE_TYPE_NORMAL -} -let huksOptions = { - properties: properties, - inData: new Uint8Array(new Array()) -} +**Available APIs** -/* - * Generate a key. - */ -function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { - return new Promise((resolve, reject) => { - try { - huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); - } - }); -} +You can use the [**HUKS_TAG_KEY_AUTH_PURPOSE**](../reference/apis/js-apis-huks.md#hukstag) tag to specify the scenario, for which the fine-grained user identity authentication is performed. The value range of this tag is [HuksKeyAlg](../reference/apis/js-apis-huks.md#hukskeyalg). -async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback generateKeyItem`); - let throwObject = {isThrow: false}; - try { - await generateKeyItem(keyAlias, huksOptions, throwObject) - .then((data) => { - console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} +**Table 7** HUKS_TAG_KEY_AUTH_PURPOSE +| Name | Description | +| -------------------------------------- | ----------------------------| +|HUKS_TAG_KEY_AUTH_PURPOSE| Purpose of the user identity authentication, that is, perform the user identity authentication when a specific algorithm is used.| -async function TestGenKeyForFingerprintAccessControl() { - await publicGenKeyFunc(keyAlias, huksOptions); -} -``` +> **NOTE** +> +> - If [**HuksUserAuthType**](../reference/apis/js-apis-huks.md#huksuserauthtype9) is not specified, no user identity authentication is performed by default. In this case, the setting of **HUKS_TAG_KEY_AUTH_PURPOSE** is invalid by default. If **HuksUserAuthType** is specified and **HUKS_TAG_KEY_AUTH_PURPOSE** is not specified, user identity authentication will still be performed by default before the key is used with the algorithm that is specified in the key generation process. +> - If the AES or SM4 symmetric algorithm is used for encryption and decryption, only the CBC mode supports fine-grained user identity authentication. +**How to Develop** -2. Initialize the key session to obtain a challenge, and initiate fingerprint authentication to obtain an authentication token. -```ts -import huks from '@ohos.security.huks'; -import userIAM_userAuth from '@ohos.userIAM.userAuth'; +Scenario: When generating keys for encryption and decryption, enable user identity authentication only for decryption. Enable user identity authentication for decryption but not for encryption. -/* - * Determine the key alias and encapsulate the key properties. - */ -let srcKeyAlias = 'sm4_key_fingerprint_access'; -let handle; -let challenge; -let fingerAuthToken; -let authType = userIAM_userAuth.UserAuthType.FINGERPRINT; -let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; +1. Generate a key, set fingerprint authentication for key access control and related properties, and set **HUKS_TAG_KEY_AUTH_PURPOSE**. -/* Configure the key generation parameter set and key encryption parameter set. */ -let properties = new Array(); -properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM4, -} -properties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, -} -properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, -} -properties[3] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_CBC, -} -properties[4] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE, -} -let huksOptions = { - properties: properties, - inData: new Uint8Array(new Array()) -} + ```ts + import huks from '@ohos.security.huks'; -function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { - return new Promise((resolve, reject) => { - try { - huks.initSession(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); - } - }); -} + /* + * Set the key alias and encapsulate the key properties. + */ + let keyAlias = 'dh_key_fingerprint_access'; + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM4, + } + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, + } + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, + } + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC, + } + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, + } + // Enable fingerprint authentication. + properties[5] = { + tag: huks.HuksTag.HUKS_TAG_USER_AUTH_TYPE, + value: huks.HuksUserAuthType.HUKS_USER_AUTH_TYPE_FINGERPRINT + } + // Set the key expiration type. Invalidate the key when a new biometric feature (fingerprint) is enrolled. + properties[6] = { + tag: huks.HuksTag.HUKS_TAG_KEY_AUTH_ACCESS_TYPE, + value: huks.HuksAuthAccessType.HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL + } + // Use the default challenge type. + properties[7] = { + tag: huks.HuksTag.HUKS_TAG_CHALLENGE_TYPE, + value: huks.HuksChallengeType.HUKS_CHALLENGE_TYPE_NORMAL + } + // Perform user identity authentication when the key is used for decryption. + properties[8] = { + tag: huks.HuksTag.HUKS_TAG_KEY_AUTH_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT + } + let huksOptions = { + properties: properties, + inData: new Uint8Array(new Array()) + } -async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback doInit`); - let throwObject = {isThrow: false}; - try { - await initSession(keyAlias, huksOptions, throwObject) - .then ((data) => { - console.info(`callback: doInit success, data = ${JSON.stringify(data)}`); - handle = data.handle; - challenge = data.challenge; - }) - .catch((error) => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} + /* + * Generate a key. + */ + async function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { + return new Promise((resolve, reject) => { + try { + huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); + } -function userIAMAuthFinger(huksChallenge:Uint8Array) { - // Obtain an authentication object. - let auth; - try { - auth = userIAM_userAuth.getAuthInstance(huksChallenge, authType, authTrustLevel); - console.log("get auth instance success"); - } catch (error) { - console.log("get auth instance failed" + error); - } + async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback generateKeyItem`); + let throwObject = {isThrow: false}; + try { + await generateKeyItem(keyAlias, huksOptions, throwObject) + .then((data) => { + console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } + } - // Subscribe to the authentication result. - try { - auth.on("result", { - callback: (result: userIAM_userAuth.AuthResultInfo) => { - /* The authentication is successful, and the authentication token is obtained. */ - fingerAuthToken = result.token; - } - }); - console.log("subscribe authentication event success"); - } catch (error) { - console.log("subscribe authentication event failed " + error); - } + async function TestGenKeyForFingerprintAccessControl() { + await publicGenKeyFunc(keyAlias, huksOptions); + } + ``` + +2. Disable user identity authentication when the key is used for encryption. + + ```ts + import huks from '@ohos.security.huks'; + + /* + * Set the key alias and encapsulate the key properties. + */ + let srcKeyAlias = 'sm4_key_fingerprint_access'; + let cipherInData = 'Hks_SM4_Cipher_Test_101010101010101010110_string'; // Plaintext + let IV = '1234567890123456'; + let handle; + let cipherText; // Ciphertext after encryption. + + function StringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); + } - // Start user authentication. - try { - auth.start(); - console.info("authV9 start auth success"); - } catch (error) { - console.info("authV9 start auth failed, error = " + error); - } -} + /* Configure the key generation parameter set and key encryption parameter set. */ + let propertiesEncrypt = new Array(); + propertiesEncrypt[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM4, + } + propertiesEncrypt[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT, + } + propertiesEncrypt[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, + } + propertiesEncrypt[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, + } + propertiesEncrypt[4] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC, + } + propertiesEncrypt[5] = { + tag: huks.HuksTag.HUKS_TAG_IV, + value: StringToUint8Array(IV), + } + let encryptOptions = { + properties: propertiesEncrypt, + inData: new Uint8Array(new Array()) + } -async function testInitAndAuthFinger() { - /* Initialize the key session to obtain a challenge. */ - await publicInitFunc(srcKeyAlias, huksOptions); - /* Invoke userIAM to perform user identity authentication. */ - userIAMAuthFinger(challenge); -} -``` + function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { + return new Promise((resolve, reject) => { + try { + huks.initSession(keyAlias, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); + } -3. Pass in the authentication token to perform data operations. -```ts -/* - * The following uses an SM4 128-bit key and callback-based APIs as an example. - */ -import huks from '@ohos.security.huks'; + async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback doInit`); + let throwObject = {isThrow: false}; + try { + await initSession(keyAlias, huksOptions, throwObject) + .then ((data) => { + console.info(`callback: doInit success, data = ${JSON.stringify(data)}`); + handle = data.handle; + }) + .catch((error) => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); + } + } -/* - * Determine the key alias and encapsulate the key properties. - */ -let srcKeyAlias = 'sm4_key_fingerprint_access'; -let IV = '1234567890123456'; -let cipherInData = 'Hks_SM4_Cipher_Test_101010101010101010110_string'; -let handle; -let fingerAuthToken; -let updateResult = new Array(); -let finishOutData; + function finishSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : Promise { + return new Promise((resolve, reject) => { + try { + huks.finishSession(handle, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); + } -/* Configure the key generation parameter set and key encryption parameter set. */ -let propertiesEncrypt = new Array(); -propertiesEncrypt[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM4, -} -propertiesEncrypt[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT, -} -propertiesEncrypt[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, -} -propertiesEncrypt[3] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE, -} -propertiesEncrypt[4] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_CBC, -} -propertiesEncrypt[5] = { - tag: huks.HuksTag.HUKS_TAG_IV, - value: StringToUint8Array(IV), -} -let encryptOptions = { - properties: propertiesEncrypt, - inData: new Uint8Array(new Array()) -} + async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) { + console.info(`enter callback doFinish`); + let throwObject = {isThrow: false}; + try { + await finishSession(handle, huksOptions, throwObject) + .then ((data) => { + cipherText = data.outData; + console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); + } + } -function StringToUint8Array(str) { - let arr = []; - for (let i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - return new Uint8Array(arr); -} + async function testSm4Cipher() { + /* Initialize the key session to obtain a challenge. */ + await publicInitFunc(srcKeyAlias, encryptOptions); -function updateSession(handle:number, huksOptions:huks.HuksOptions, token:Uint8Array, throwObject) : Promise { - return new Promise((resolve, reject) => { - try { - huks.updateSession(handle, huksOptions, token, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); - } - }); -} + /** Encryption */ + encryptOptions.inData = StringToUint8Array(cipherInData); + await publicFinishFunc(handle, encryptOptions); + } + ``` + +3. Enable user identity authentication when the key is used for decryption. + + ```ts + import huks from '@ohos.security.huks'; + import userIAM_userAuth from '@ohos.userIAM.userAuth'; + + /* + * Set the key alias and encapsulate the key properties. + */ + let srcKeyAlias = 'sm4_key_fingerprint_access'; + let cipherText = 'r56ywtTJUQC6JFJ2VV2kZw=='; // Ciphertext obtained, which may vary in actual situation. + let IV = '1234567890123456'; + let handle; + let finishOutData; // Plaintext after decryption. + let fingerAuthToken; + let authType = userIAM_userAuth.UserAuthType.FINGERPRINT; + let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; + + function StringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); + } -async function publicUpdateFunc(handle:number, token:Uint8Array, huksOptions:huks.HuksOptions) { - console.info(`enter callback doUpdate`); - let throwObject = {isThrow: false}; - try { - await updateSession(handle, huksOptions, token, throwObject) - .then ((data) => { - console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} + /* Configure the key generation parameter set and key encryption parameter set. */ + let propertiesDecrypt = new Array(); + propertiesDecrypt[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM4, + } + propertiesDecrypt[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, + } + propertiesDecrypt[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, + } + propertiesDecrypt[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, + } + propertiesDecrypt[4] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC, + } + propertiesDecrypt[5] = { + tag: huks.HuksTag.HUKS_TAG_IV, + value: StringToUint8Array(IV), + } + let decryptOptions = { + properties: propertiesDecrypt, + inData: new Uint8Array(new Array()) + } -function finishSession(handle:number, huksOptions:huks.HuksOptions, token:Uint8Array, throwObject) : Promise { - return new Promise((resolve, reject) => { - try { - huks.finishSession(handle, huksOptions, token, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); - } - }); -} + function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { + return new Promise((resolve, reject) => { + try { + huks.initSession(keyAlias, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); + } -async function publicFinishFunc(handle:number, token:Uint8Array, huksOptions:huks.HuksOptions) { - console.info(`enter callback doFinish`); - let throwObject = {isThrow: false}; - try { - await finishSession(handle, huksOptions, token, throwObject) - .then ((data) => { - finishOutData = data.outData; - console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} + async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback doInit`); + let throwObject = {isThrow: false}; + try { + await initSession(keyAlias, huksOptions, throwObject) + .then ((data) => { + console.info(`callback: doInit success, data = ${JSON.stringify(data)}`); + handle = data.handle; + challenge = data.challenge; + }) + .catch((error) => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); + } + } -async function testSm4Cipher() { - encryptOptions.inData = StringToUint8Array(cipherInData); - /* Pass in the authentication token. */ - await publicUpdateFunc(handle, fingerAuthToken, encryptOptions); - encryptUpdateResult = updateResult; + function userIAMAuthFinger(huksChallenge:Uint8Array) { + // Obtain an authentication object. + let auth; + try { + auth = userIAM_userAuth.getAuthInstance(huksChallenge, authType, authTrustLevel); + console.log("get auth instance success"); + } catch (error) { + console.log("get auth instance failed" + error); + } + + // Subscribe to the authentication result. + try { + auth.on("result", { + callback: (result: userIAM_userAuth.AuthResultInfo) => { + /* The authentication is successful, and the authentication token is obtained. */ + fingerAuthToken = result.token; + } + }); + console.log("subscribe authentication event success"); + } catch (error) { + console.log("subscribe authentication event failed " + error); + } + + // Start user authentication. + try { + auth.start(); + console.info("authV9 start auth success"); + } catch (error) { + console.info("authV9 start auth failed, error = " + error); + } + } - encryptOptions.inData = new Uint8Array(new Array()); - /* Pass in the authentication token. */ - await publicFinishFunc(handle, fingerAuthToken, encryptOptions); - if (finishOutData === cipherInData) { - console.info('test finish encrypt err '); - } else { - console.info('test finish encrypt success'); - } -} -``` + function finishSession(handle:number, huksOptions:huks.HuksOptions, token:Uint8Array, throwObject) : Promise { + return new Promise((resolve, reject) => { + try { + huks.finishSession(handle, huksOptions, token, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); + } + + async function publicFinishFunc(handle:number, token:Uint8Array, huksOptions:huks.HuksOptions) { + console.info(`enter callback doFinish`); + let throwObject = {isThrow: false}; + try { + await finishSession(handle, huksOptions, token, throwObject) + .then ((data) => { + finishOutData = data.outData; + console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); + } + } + + async function testSm4Cipher() { + /* Initialize the key session to obtain a challenge. */ + await publicInitFunc(srcKeyAlias, decryptOptions); + + /* Invoke userIAM to perform user identity authentication. */ + userIAMAuthFinger(challenge); + + /* Perform decryption after the authentication is successful. The **authToken** value obtained by Auth needs to be passed in. */ + decryptOptions.inData = StringToUint8Array(cipherText); + await publicFinishFunc(handle, fingerAuthToken, decryptOptions); + } + ``` ## Key Attestation The HUKS provides attestation for the public keys of asymmetric key pairs. The HUKS can issue a certificate for the public key of an asymmetric key pair stored in the HUKS using the public key infrastructure (PKI) certificate chain technology. The certificate can prove the validity of the public key. The service can use the root CA certificate provided by the OpenHarmony to verify the key certificate issued by the HUKS level by level to ensure that the public key and private key in the certificate are from a trusted hardware device and stored in the HUKS. **How to Develop** + 1. Pass in the key alias and the property tag of the key to be attested. 2. Call a HUKS API to generate an X.509 certificate chain, which consists of the root CA certificate, device CA certificate, device certificate, and key certificate in sequence, for the application. 3. Send the certificate chain to a trusted server. The server parses and verifies the validity of the certificate chain and whether a single certificate is revoked. **Available APIs** -**Table 7** API for key attestation - +**Table 8** API for key attestation | API | Description | | -------------------------------------- | ----------------------------| |attestKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void| Attests a key.| @@ -2099,7 +2562,7 @@ The HUKS provides attestation for the public keys of asymmetric key pairs. The H import huks from '@ohos.security.huks'; /* - * Determine the key alias and encapsulate the key properties. + * Set the key alias and encapsulate the key properties. */ let keyAliasString = "key attest"; let aliasString = keyAliasString; @@ -2268,4 +2731,4 @@ async function AttestKeyTest() { ### Property 'finishSession' does not exist on type 'typeof huks'. Did you mean 'finish'? -**finishSession()** is supported from API version 9. Update the SDK version or use the latest **security.huks.d.ts** file. \ No newline at end of file + **finishSession()** is supported from API version 9. Update the SDK version or use the latest **security.huks.d.ts** file. diff --git a/en/application-dev/ui/Readme-EN.md b/en/application-dev/ui/Readme-EN.md index 09b8c42877602d230810e9c299cd6a1ab8d73c41..2828cf88464c8dcfee6552cdfd232f7dcdf15cd1 100644 --- a/en/application-dev/ui/Readme-EN.md +++ b/en/application-dev/ui/Readme-EN.md @@ -1,36 +1,68 @@ # UI Development - [ArkUI Overview](arkui-overview.md) -- ArkTS-based Declarative Development Paradigm - - [Overview](ui-ts-overview.md) - - [Declarative UI Development Guidelines](ui-ts-developing-intro.md) - - Declarative UI Development Examples - - [Creating a Simple Page](ui-ts-creating-simple-page.md) - - Building a Comprehensive Example - - [Building a Food Data Model](ui-ts-building-data-model.md) - - [Building a Food Category List Layout](ui-ts-building-category-list-layout.md) - - [Building a Food Category Grid Layout](ui-ts-building-category-grid-layout.md) - - [Implementing Page Redirection and Data Transmission](ui-ts-page-redirection-data-transmission.md) - - Adding a Splash Screen Animation - - [Using the Drawing Feature](ui-ts-drawing-feature.md) - - [Using the Animation Feature](ui-ts-animation-feature.md) - - [Common Components](ui-ts-components-intro.md) - - Common Layout Development - - Adaptive Layouts - - [Linear Layout](ui-ts-layout-linear.md) - - [Statck Layout](ui-ts-layout-stack.md) - - [Flex Layout](ui-ts-layout-flex.md) - - [Grid Layout](ui-ts-layout-grid.md) - - Responsive Layouts - - [Grid Layout](ui-ts-layout-grid-container-new.md) - - [Media Query](ui-ts-layout-mediaquery.md) - - [Custom Component Lifecycle Callbacks](ui-ts-custom-component-lifecycle-callbacks.md) - - [Web Component Development](ui-ts-components-web.md) - - [Recommendations for Improving Performance](ui-ts-performance-improvement-recommendation.md) -- JavaScript-compatible Web-like Development Paradigm - - [Overview](ui-js-overview.md) - - Framework Overview - - [File Organization](js-framework-file.md) +- UI Development (ArkTS-based Declarative Development Paradigm) + - [UI Development (ArkTS-based Declarative Development Paradigm) Overview](arkts-ui-development-overview.md) + - Layout Development + - [Layout Overview](arkts-layout-development-overview.md) + - Building a Layout + - [Linear Layout](arkts-layout-development-linear.md) + - [Stack Layout](arkts-layout-development-stack-layout.md) + - [Flex Layout](arkts-layout-development-flex-layout.md) + - [Relative Layout](arkts-layout-development-relative-layout.md) + - [Responsive Grid Layout](arkts-layout-development-grid-layout.md) + - [Media Query](arkts-layout-development-media-query.md) + - [Creating a List](arkts-layout-development-create-list.md) + - [Creating a Grid](arkts-layout-development-create-grid.md) + - [Creating a Swiper](arkts-layout-development-create-looping.md) + - [Improving Layout Performance](arkts-layout-development-performance-boost.md) + - Adding a Component + - Adding a Common Component + - [Button](arkts-common-components-button.md) + - [Radio Button](arkts-common-components-radio-button.md) + - [Toggle](arkts-common-components-switch.md) + - [Progress Indicator](arkts-common-components-progress-indicator.md) + - [Text Display](arkts-common-components-text-display.md) + - [Text Input](arkts-common-components-text-input.md) + - [Custom Dialog Box](arkts-common-components-custom-dialog.md) + - [Video Playback](arkts-common-components-video-player.md) + - [XComponent](arkts-common-components-xcomponent.md) + - Adding a Bubble and Menu + - [Bubble](arkts-popup-and-menu-components-popup.md) + - [Menu](arkts-popup-and-menu-components-menu.md) + - Setting Page Routing and Component Navigation + - [Page Routing](arkts-routing.md) + - Component Navigation + - [Navigation](arkts-navigation-navigation.md) + - [Tabs](arkts-navigation-tabs.md) + - Using Graphics + - [Displaying Images](arkts-graphics-display.md) + - [Drawing Geometric Shapes](arkts-geometric-shape-drawing.md) + - [Drawing Custom Graphics on the Canvas](arkts-drawing-customization-on-canvas.md) + - Using Animation + - [Animation Overview](arkts-animation-overview.md) + - Animation Within a Page + - [Layout Update Animation](arkts-layout-update-animation.md) + - [Transition Animation Within a Component](arkts-transition-animation-within-component.md) + - [Spring Curve Animation](arkts-spring-animation.md) + - Animation Between Pages + - [Zoom Animation](arkts-zoom-animation.md) + - [Page Transition Animation](arkts-page-transition-animation.md) + - Using Interaction Events + - [Interaction Event Overview](arkts-event-overview.md) + - Universal Events + - [Touchscreen Event](arkts-common-events-touch-screen-event.md) + - [Keyboard and Mouse Event](arkts-common-events-device-input-event.md) + - [Focus Event](arkts-common-events-focus-event.md) + - Gesture Events + - [Gesture Binding](arkts-gesture-events-binding.md) + - [Single Gesture](arkts-gesture-events-single-gesture.md) + - [Combined Gestures](arkts-gesture-events-combined-gestures.md) + - [Recommendations for Improving Performance](arkts-performance-improvement-recommendation.md) +- UI Development (JavaScript-compatible Web-like Development Paradigm) + - [UI Development (JavaScript-compatible Web-like Development Paradigm) Overview](ui-js-overview.md) + - Framework Overview + - [File Organization](js-framework-file.md) - ["js" Tag](js-framework-js-tag.md) - [app.js](js-framework-js-file.md) - Syntax diff --git a/en/application-dev/ui/arkts-animation-overview.md b/en/application-dev/ui/arkts-animation-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..d75619d1c1acb3bb0d0273d7f44738101b43e59e --- /dev/null +++ b/en/application-dev/ui/arkts-animation-overview.md @@ -0,0 +1,27 @@ +# Animation Overview + + +The principle of animation is that the UI appearance is changed for multiple times within a period of time. Because human eyes retain persistence of vision, what you finally see is a continuous animation. A change of the UI is called an animation frame, which corresponds to a screen refresh. An important indicator that determines the animation smoothness is the frame rate (FPS), that is, the number of animation frames per second. The higher the frame rate, the smoother the animation. + + +In ArkUI, an animation is generated by changing the attribute value and specifying the animation parameters. Animation parameters include animation duration, change rule (that is, curve), and more. After the attribute value changes, the original state is transited to the new state according to the animation parameters. In this way, an animation is formed. + + +The animation capability provided by ArkUI can be classified into intra-page animation and inter-page animation based on the page classification mode. As shown in the following figure, an animation on a page refers to an animation that can occur on a page, and an animation between pages refers to an animation that occurs only with redirection between pages. + + + **Figure 1** Animation by page + +![en-us_image_0000001562700385](figures/en-us_image_0000001562700385.png) + + +By capability, the animation can be divided into three parts: attribute animation, explicit animation, and transition animation, as shown in the following figure. + + + **Figure 2** Animation classified by basic capability + + +![en-us_image_0000001562820753](figures/en-us_image_0000001562820753.png) + + +This topic will introduce you to the usage and precautions of animations by the preceding classification and use cases. diff --git a/en/application-dev/ui/arkts-common-components-button.md b/en/application-dev/ui/arkts-common-components-button.md new file mode 100644 index 0000000000000000000000000000000000000000..82c893d33aa0049e5b2e815ae6a31b7d13a1775a --- /dev/null +++ b/en/application-dev/ui/arkts-common-components-button.md @@ -0,0 +1,261 @@ +# Button + + +The **\