diff --git a/CODEOWNERS b/CODEOWNERS
index 24411de3dbc2ce0663ee65f2cfd514c27f94bb81..23303c92c5a24ed1894449ea30b52c7de2685226 100644
--- a/CODEOWNERS
+++ b/CODEOWNERS
@@ -98,7 +98,6 @@ zh-cn/application-dev/dfx/hitracechain-guidelines.md @zengyawen @stone2050 @stes
zh-cn/application-dev/dfx/errormanager-guidelines.md @littlejerry1 @ccllee @chengxingzhen @RayShih
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 @nobuggers
zh-cn/application-dev/napi/mindspore-lite-guidelines.md @ge-yafang @principal87 @jianghui58
zh-cn/application-dev/napi/mindspore-lite-offline-model-guidelines.md @ge-yafang @principal87 @jianghui58
@@ -124,7 +123,7 @@ zh-cn/application-dev/device/sample-server-overview.md @ningningW @hughes802 @zh
zh-cn/application-dev/device/sample-server-guidelines.md @ningningW @hughes802 @zhangzhengxue @mamba-ting
zh-cn/application-dev/reference/arkui-js/ @HelloCrease @niulihua @tomatodevboy
zh-cn/application-dev/reference/arkui-ts/ @HelloCrease @niulihua @tomatodevboy
-zh-cn/application-dev/reference/native-lib @zengyawen @gongjunsong @liwentao_uiw @BlackStone
+zh-cn/application-dev/reference/native-lib @zengyawen @gongjunsong @liwentao_uiw @blackstone-oh
zh-cn/application-dev/quick-start/start-overview.md @ge-yafang
zh-cn/application-dev/quick-start/start-with-ets-stage.md @ge-yafang
zh-cn/application-dev/quick-start/start-with-ets-fa.md @ge-yafang
@@ -197,13 +196,13 @@ zh-cn/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.
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-arraylist.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh
zh-cn/application-dev/reference/apis/js-apis-audio.md @liuyuehua1 @zengyawen @magekkkk @currydavids
zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md @chenmingJay @ningningW @nan-xiansen @iceice1001
zh-cn/application-dev/reference/apis/js-apis-battery-info.md @aqxyjay @zengyawen @aqxyjay @alien0208
zh-cn/application-dev/reference/apis/js-apis-bluetooth.md @cheng_guohong @RayShih @cheng_guohong @quanli125
zh-cn/application-dev/reference/apis/js-apis-brightness.md @aqxyjay @zengyawen @aqxyjay @alien0208
-zh-cn/application-dev/reference/apis/js-apis-buffer.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
+zh-cn/application-dev/reference/apis/js-apis-buffer.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh
zh-cn/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md @shuaytao @RayShih @wangzhen107 @inter515
zh-cn/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md @shuaytao @RayShih @wangzhen107 @inter515
zh-cn/application-dev/reference/apis/js-apis-bundle-BundleInfo.md @shuaytao @RayShih @wangzhen107 @inter515
@@ -232,7 +231,7 @@ zh-cn/application-dev/reference/apis/js-apis-Context.md @littlejerry1 @RayShih @
zh-cn/application-dev/reference/apis/js-apis-continuation-continuationExtraParams.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-continuation-continuationManager.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-continuation-continuationResult.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
-zh-cn/application-dev/reference/apis/js-apis-convertxml.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
+zh-cn/application-dev/reference/apis/js-apis-convertxml.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh
zh-cn/application-dev/reference/apis/js-apis-data-ability.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
zh-cn/application-dev/reference/apis/js-apis-data-dataShare.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
zh-cn/application-dev/reference/apis/js-apis-data-dataSharePredicates.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
@@ -248,7 +247,7 @@ zh-cn/application-dev/reference/apis/js-apis-data-storage.md @feng-aiwen @ge-yaf
zh-cn/application-dev/reference/apis/js-apis-data-ValuesBucket.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
zh-cn/application-dev/reference/apis/js-apis-dataAbilityHelper.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
zh-cn/application-dev/reference/apis/js-apis-DataUriUtils.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
-zh-cn/application-dev/reference/apis/js-apis-deque.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
+zh-cn/application-dev/reference/apis/js-apis-deque.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh
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
@@ -276,8 +275,8 @@ zh-cn/application-dev/reference/apis/js-apis-formhost.md @littlejerry1 @RayShih
zh-cn/application-dev/reference/apis/js-apis-formInfo.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-formprovider.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-geolocation.md @cheng_guohong @RayShih @cheng_guohong @xiangkejin123
-zh-cn/application-dev/reference/apis/js-apis-hashmap.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
-zh-cn/application-dev/reference/apis/js-apis-hashset.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
+zh-cn/application-dev/reference/apis/js-apis-hashmap.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh
+zh-cn/application-dev/reference/apis/js-apis-hashset.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh
zh-cn/application-dev/reference/apis/js-apis-hiappevent.md @stone2050 @zengyawen @stesen @elsen-liu
zh-cn/application-dev/reference/apis/js-apis-hichecker.md @stone2050 @zengyawen @stesen @elsen-liu
zh-cn/application-dev/reference/apis/js-apis-hidebug.md @stone2050 @zengyawen @stesen @elsen-liu
@@ -301,11 +300,11 @@ zh-cn/application-dev/reference/apis/js-apis-inputmonitor.md @yuanxinying @ningn
zh-cn/application-dev/reference/apis/js-apis-intl.md @Buda-Liu @ningningW @mengjingzhimo @yangqing3
zh-cn/application-dev/reference/apis/js-apis-keycode.md @yuanxinying @ningningW @cococoler @alien0208
zh-cn/application-dev/reference/apis/js-apis-keyevent.md @yuanxinying @ningningW @cococoler @alien0208
-zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
-zh-cn/application-dev/reference/apis/js-apis-lightweightset.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
-zh-cn/application-dev/reference/apis/js-apis-linkedlist.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
-zh-cn/application-dev/reference/apis/js-apis-list.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
-zh-cn/application-dev/reference/apis/js-apis-logs.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
+zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh
+zh-cn/application-dev/reference/apis/js-apis-lightweightset.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh
+zh-cn/application-dev/reference/apis/js-apis-linkedlist.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh
+zh-cn/application-dev/reference/apis/js-apis-list.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh
+zh-cn/application-dev/reference/apis/js-apis-logs.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh
zh-cn/application-dev/reference/apis/js-apis-media.md @liuyuehua1 @zengyawen @xxb-wzy @currydavids
zh-cn/application-dev/reference/apis/js-apis-medialibrary.md @panqinxu @zengyawen @bubble_mao @jinhaihw
zh-cn/application-dev/reference/apis/js-apis-mediaquery.md @HelloCrease @niulihua @tomatodevboy
@@ -320,15 +319,15 @@ zh-cn/application-dev/reference/apis/js-apis-osAccount.md @nianCode @zengyawen @
zh-cn/application-dev/reference/apis/js-apis-particleAbility.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-pasteboard.md @han-zhengshi @ge-yafang @logic42
zh-cn/application-dev/reference/apis/js-apis-permissionrequestresult.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
-zh-cn/application-dev/reference/apis/js-apis-plainarray.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
+zh-cn/application-dev/reference/apis/js-apis-plainarray.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh
zh-cn/application-dev/reference/apis/js-apis-pointer.md @yuanxinying @ningningW @cococoler @alien0208
zh-cn/application-dev/reference/apis/js-apis-power.md @aqxyjay @zengyawen @aqxyjay @alien0208
zh-cn/application-dev/reference/apis/js-apis-privacyManager.md @nianCode @zengyawen @shuqinglin2 @jinhaihw
-zh-cn/application-dev/reference/apis/js-apis-process.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
+zh-cn/application-dev/reference/apis/js-apis-process.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh
zh-cn/application-dev/reference/apis/js-apis-processrunninginfo.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-processrunninginformation.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-prompt.md @HelloCrease @niulihua @tomatodevboy
-zh-cn/application-dev/reference/apis/js-apis-queue.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
+zh-cn/application-dev/reference/apis/js-apis-queue.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh
zh-cn/application-dev/reference/apis/js-apis-radio.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785
zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md @jayleehw @RayShih @li-weifeng2 @currydavids
zh-cn/application-dev/reference/apis/js-apis-request.md @feng-aiwen @ningningW @nagexiucai @murphy1984
@@ -346,7 +345,7 @@ zh-cn/application-dev/reference/apis/js-apis-settings.md @xue-seu @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-sim.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785
zh-cn/application-dev/reference/apis/js-apis-sms.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785
zh-cn/application-dev/reference/apis/js-apis-socket.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785
-zh-cn/application-dev/reference/apis/js-apis-stack.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
+zh-cn/application-dev/reference/apis/js-apis-stack.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh
zh-cn/application-dev/reference/apis/js-apis-statfs.md @panqinxu @zengyawen @bubble_mao @jinhaihw
zh-cn/application-dev/reference/apis/js-apis-storage-statistics.md @panqinxu @zengyawen @bubble_mao @jinhaihw
zh-cn/application-dev/reference/apis/js-apis-system-app.md @HelloCrease @niulihua @tomatodevboy
@@ -376,22 +375,22 @@ zh-cn/application-dev/reference/apis/js-apis-system-vibrate.md @hellohyh001 @nin
zh-cn/application-dev/reference/apis/js-apis-telephony-data.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785
zh-cn/application-dev/reference/apis/js-apis-testRunner.md @inter515 @littlejerry1 @RayShih @inter515 @jiyong
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-timer.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh
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-treemap.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh
+zh-cn/application-dev/reference/apis/js-apis-treeset.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh
zh-cn/application-dev/reference/apis/js-apis-uitest.md @inter515 @ningningW @inter515 @jiyong
zh-cn/application-dev/reference/apis/js-apis-update.md @hughes802 @ningningW @zhangzhengxue @mamba-ting
-zh-cn/application-dev/reference/apis/js-apis-uri.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
-zh-cn/application-dev/reference/apis/js-apis-url.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
+zh-cn/application-dev/reference/apis/js-apis-uri.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh
+zh-cn/application-dev/reference/apis/js-apis-url.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh
zh-cn/application-dev/reference/apis/js-apis-usbManager.md @ge-yafang @Kevin-Lau @liuhonggang123
zh-cn/application-dev/reference/apis/js-apis-usb.md @ge-yafang @Kevin-Lau @liuhonggang123
zh-cn/application-dev/reference/apis/js-apis-usb-deprecated.md @ge-yafang @Kevin-Lau @liuhonggang123
zh-cn/application-dev/reference/apis/js-apis-useriam-userauth.md @gaoyong @zengyawen @niejiteng @jumozhanjiang
-zh-cn/application-dev/reference/apis/js-apis-util.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
-zh-cn/application-dev/reference/apis/js-apis-vector.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
+zh-cn/application-dev/reference/apis/js-apis-util.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh
+zh-cn/application-dev/reference/apis/js-apis-vector.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh
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
@@ -404,12 +403,12 @@ zh-cn/application-dev/reference/apis/js-apis-wifi.md @cheng_guohong @RayShih @ch
zh-cn/application-dev/reference/apis/js-apis-wifiext.md @cheng_guohong @RayShih @cheng_guohong @quanli125
zh-cn/application-dev/reference/apis/js-apis-window.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee @nobuggers
zh-cn/application-dev/reference/apis/js-apis-windowAnimationManager.md @zhangqiang183 @ge-yafang @liuchao92 @zxg-gitee
-zh-cn/application-dev/reference/apis/js-apis-worker.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
-zh-cn/application-dev/reference/apis/js-apis-taskpool.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
+zh-cn/application-dev/reference/apis/js-apis-worker.md @gongjunsong @ge-yafang @flyingwolf @weng-changcheng @blackstone-oh
+zh-cn/application-dev/reference/apis/js-apis-taskpool.md @gongjunsong @ge-yafang @flyingwolf @weng-changcheng @blackstone-oh
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-xml.md @gongjunsong @ge-yafang @flyingwolf@blackstone-oh
zh-cn/application-dev/reference/apis/js-apis-zlib.md @shuaytao @RayShih @wangzhen107 @inter515
zh-cn/application-dev/reference/apis/js-apis-webview.md @bigpumpkin @HelloCrease @litao33 @zhang-xinyue15
zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md @bigpumpkin @HelloCrease @litao33 @zhang-xinyue15
@@ -554,4 +553,37 @@ zh-cn/application-dev/reference/errorcodes/errorcode-webview.md @HelloCrease
zh-cn/application-dev/reference/errorcodes/errorcode-window.md @ge-yafang
zh-cn/application-dev/reference/errorcodes/errorcode-workScheduler.md @ningningW
zh-cn/application-dev/reference/errorcodes/errorcode-zlib.md @RayShih
-zh-cn/application-dev/reference/apis/js-apis-calendarManager.md @ge-yafang @jt_123456 @edollar
\ No newline at end of file
+zh-cn/application-dev/reference/apis/js-apis-calendarManager.md @ge-yafang @jt_123456 @edollar
+zh-cn/application-dev/arkts-utils/arkts-commonlibrary-overview.md @ge-yafang @gongjunsong @weng-changcheng @blackstone-oh
+zh-cn/application-dev/arkts-utils/concurrency-overview.md @ge-yafang @gongjunsong @weng-changcheng @blackstone-oh
+zh-cn/application-dev/arkts-utils/async-concurrency-overview.md @ge-yafang @gongjunsong @weng-changcheng @blackstone-oh
+zh-cn/application-dev/arkts-utils/single-io-development.md @ge-yafang @gongjunsong @weng-changcheng @blackstone-oh
+zh-cn/application-dev/arkts-utils/multi-thread-concurrency-overview.md @ge-yafang @gongjunsong @weng-changcheng @blackstone-oh
+zh-cn/application-dev/arkts-utils/taskpool-vs-worker.md @ge-yafang @gongjunsong @weng-changcheng @blackstone-oh
+zh-cn/application-dev/arkts-utils/cpu-intensive-task-development.md @ge-yafang @gongjunsong @weng-changcheng @blackstone-oh
+zh-cn/application-dev/arkts-utils/io-intensive-task-development.md @ge-yafang @gongjunsong @weng-changcheng @blackstone-oh
+zh-cn/application-dev/arkts-utils/sync-task-development.md @ge-yafang @gongjunsong @weng-changcheng @blackstone-oh
+zh-cn/application-dev/arkts-utils/container-overview.md @ge-yafang @gongjunsong @blackstone-oh
+zh-cn/application-dev/arkts-utils/linear-container.md @ge-yafang @gongjunsong @blackstone-oh
+zh-cn/application-dev/arkts-utils/nonlinear-container.md @ge-yafang @gongjunsong @blackstone-oh
+zh-cn/application-dev/arkts-utils/xml-overview.md @ge-yafang @gongjunsong @blackstone-oh
+zh-cn/application-dev/arkts-utils/xml-generation.md @ge-yafang @gongjunsong @blackstone-oh
+zh-cn/application-dev/arkts-utils/xml-parsing.md @ge-yafang @gongjunsong @blackstone-oh
+zh-cn/application-dev/arkts-utils/xml-conversion.md @ge-yafang @gongjunsong @blackstone-oh
+zh-cn/application-dev/database/data-mgmt-overview.md @ge-yafang @feng-aiwen @gong-a-shi @logic42
+zh-cn/application-dev/database/app-data-persistence-overview.md @ge-yafang @feng-aiwen @gong-a-shi @logic42
+zh-cn/application-dev/database/data-persistence-by-preferences.md @ge-yafang @feng-aiwen @gong-a-shi @logic42
+zh-cn/application-dev/database/data-persistence-by-kv-store.md @ge-yafang @feng-aiwen @gong-a-shi @logic42
+zh-cn/application-dev/database/data-persistence-by-rdb-store.md @ge-yafang @feng-aiwen @gong-a-shi @logic42
+zh-cn/application-dev/database/sync-app-data-across-devices-overview.md @ge-yafang @feng-aiwen @gong-a-shi @logic42
+zh-cn/application-dev/database/data-sync-of-rdb-store.md @ge-yafang @feng-aiwen @gong-a-shi @logic42
+zh-cn/application-dev/database/data-sync-of-kv-store.md @ge-yafang @feng-aiwen @gong-a-shi @logic42
+zh-cn/application-dev/database/data-reliability-security-overview.md @ge-yafang @feng-aiwen @gong-a-shi @logic42
+zh-cn/application-dev/database/data-backup-and-restore.md @ge-yafang @feng-aiwen @gong-a-shi @logic42
+zh-cn/application-dev/database/data-encryption.md @ge-yafang @feng-aiwen @gong-a-shi @logic42
+zh-cn/application-dev/database/access-control-by-device-and-data-level.md @ge-yafang @feng-aiwen @gong-a-shi @logic42
+zh-cn/application-dev/database/data-share-overview.md @ge-yafang @feng-aiwen @gong-a-shi @logic42
+zh-cn/application-dev/database/unified-data-definition.md @ge-yafang @feng-aiwen @gong-a-shi @logic42
+zh-cn/application-dev/database/share-data-by-datashareextensionability.md @ge-yafang @feng-aiwen @gong-a-shi @logic42
+zh-cn/application-dev/database/share-data-by-silent-access.md @ge-yafang @feng-aiwen @gong-a-shi @logic42
+zh-cn/application-dev/database/unified-data-channels.md @ge-yafang @feng-aiwen @gong-a-shi @logic42
\ No newline at end of file
diff --git a/en/OpenHarmony-Overview.md b/en/OpenHarmony-Overview.md
index 1aecb0171e73b02bcbcb9347497f594bf96c912e..16f95e959d2ec9c0d93d7421d4954f5ead748669 100644
--- a/en/OpenHarmony-Overview.md
+++ b/en/OpenHarmony-Overview.md
@@ -146,7 +146,7 @@ The following table describes the subsystems of OpenHarmony. For details about t
## Supported Development Boards
-Currently, the OpenHarmony community supports 22 types of development boards, which are listed in [Development Boards Supported](device-dev/dev-board-on-the-master.md). The following table describes three of them, which are the first three integrated into the OpenHarmony master. You can visit http://ci.openharmony.cn/dailys/dailybuilds to obtain daily builds.
+Currently, the OpenHarmony community supports 22 types of development boards, which are listed in [Development Boards Supported](device-dev/dev-board-on-the-master.md). The following table describes three of them, which are the first three integrated into the OpenHarmony master. You can visit http://ci.openharmony.cn/workbench/cicd/dailybuild/dailylist to obtain daily builds.
| System Type| Board Model| Chip Model|
Function Description and Use Case
| Application Scenario| Code Repository |
| -------- | -------- | -------- | -------- | -------- | -------- |
diff --git a/en/application-dev/IDL/idl-guidelines.md b/en/application-dev/IDL/idl-guidelines.md
index 102992de24a2879f9b08a5274058c2cdf4c0a280..7753e85d309ebbf350b7825a9ad3f76e3a3fcddf 100644
--- a/en/application-dev/IDL/idl-guidelines.md
+++ b/en/application-dev/IDL/idl-guidelines.md
@@ -62,7 +62,7 @@ sequenceable a.b..C.D
The preceding statement is parsed into the following code in the C++ header file:
```cpp
-#include "a/b/d.h"
+#include "a/b/d.h"
using C::D;
```
@@ -347,11 +347,10 @@ export default {
#### Calling Methods from the Client for IPC
-When the client calls **connectAbility()** to connect to a Service ability, the **onConnect** callback in **onAbilityConnectDone** of the client receives the **IRemoteObject** instance returned by the **onConnect()** method of the Service ability. The client and Service ability are in different applications. Therefore, the directory of the client application must contain a copy of the .idl file (the SDK automatically generates the proxy class). The **onConnect** callback then uses the **IRemoteObject** instance to create the **testProxy** instance of the **IdlTestServiceProxy** class and calls the related IPC method. The sample code is as follows:
+When the client calls **connectServiceExtensionAbility()** to connect to a Service ability, the **onConnect** callback in **onAbilityConnectDone** of the client receives the **IRemoteObject** instance returned by the **onConnect()** method of the Service ability. The client and Service ability are in different applications. Therefore, the directory of the client application must contain a copy of the .idl file (the SDK automatically generates the proxy class). The **onConnect** callback then uses the **IRemoteObject** instance to create the **testProxy** instance of the **IdlTestServiceProxy** class and calls the related IPC method. The sample code is as follows:
```ts
import IdlTestServiceProxy from './idl_test_service_proxy'
-import featureAbility from '@ohos.ability.featureAbility';
function callbackTestIntTransaction(result: number, ret: number): void {
if (result == 0 && ret == 124) {
@@ -396,13 +395,13 @@ var onAbilityConnectDone = {
}
};
-function connectAbility: void {
+function connectAbility(): void {
let want = {
bundleName: 'com.example.myapplicationidl',
abilityName: 'com.example.myapplicationidl.ServiceAbility'
};
let connectionId = -1;
- connectionId = featureAbility.connectAbility(want, onAbilityConnectDone);
+ connectionId = this.context.connectServiceExtensionAbility(want, onAbilityConnectDone);
}
diff --git a/en/application-dev/application-models/context-switch.md b/en/application-dev/application-models/context-switch.md
index 53047adb03ff8508f1428f62a4f6d982fedc0aeb..fe2051bcb244c10771bde056a4152da59838a6b7 100644
--- a/en/application-dev/application-models/context-switch.md
+++ b/en/application-dev/application-models/context-switch.md
@@ -10,7 +10,7 @@
| [getBundleName(callback : AsyncCallback<string>): void;](../reference/apis/js-apis-inner-app-context.md#contextgetbundlename7) [getBundleName(): Promise<string>;](../reference/apis/js-apis-inner-app-context.md#contextgetbundlename7-1) | application\UIAbilityContext.d.ts | [abilityInfo.bundleName: string;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#attributes)|
| [getDisplayOrientation(callback : AsyncCallback<bundle.DisplayOrientation>): void;](../reference/apis/js-apis-inner-app-context.md#contextgetdisplayorientation7) [getDisplayOrientation(): Promise<bundle.DisplayOrientation>;](../reference/apis/js-apis-inner-app-context.md#contextgetdisplayorientation7-1) | \@ohos.screen.d.ts | [readonly orientation: Orientation;](../reference/apis/js-apis-screen.md#orientation) |
| [setDisplayOrientation(orientation:bundle.DisplayOrientation, callback:AsyncCallback<void>):void;](../reference/apis/js-apis-inner-app-context.md#contextsetdisplayorientation7) [setDisplayOrientation(orientation:bundle.DisplayOrientation):Promise<void>;](../reference/apis/js-apis-inner-app-context.md#contextsetdisplayorientation7-1) | \@ohos.screen.d.ts | [setOrientation(orientation: Orientation, callback: AsyncCallback<void>): void;](../reference/apis/js-apis-screen.md#setorientation) [setOrientation(orientation: Orientation): Promise<void>;](../reference/apis/js-apis-screen.md#setorientation-1) |
-| [setShowOnLockScreen(show:boolean, callback:AsyncCallback<void>):void;](../reference/apis/js-apis-inner-app-context.md#contextsetshowonlockscreen7) [setShowOnLockScreen(show:boolean):Promise<void>;](../reference/apis/js-apis-inner-app-context.md#contextsetshowonlockscreen7-1) | \@ohos.window.d.ts | [setShowOnLockScreen(showOnLockScreen: boolean): void;](../reference/apis/js-apis-window.md#setshowonlockscreen9) |
+| [setShowOnLockScreen(show:boolean, callback:AsyncCallback<void>):void;](../reference/apis/js-apis-inner-app-context.md#contextsetshowonlockscreendeprecated) [setShowOnLockScreen(show:boolean):Promise<void>;](../reference/apis/js-apis-inner-app-context.md#contextsetshowonlockscreendeprecated-1) | \@ohos.window.d.ts | [setShowOnLockScreen(showOnLockScreen: boolean): void;](../reference/apis/js-apis-window.md#setshowonlockscreen9) |
| [setWakeUpScreen(wakeUp:boolean, callback:AsyncCallback<void>):void;](../reference/apis/js-apis-inner-app-context.md#contextsetwakeupscreen7) [setWakeUpScreen(wakeUp:boolean):Promise<void>;](../reference/apis/js-apis-inner-app-context.md#contextsetwakeupscreen7-1) | \@ohos.window.d.ts | [setWakeUpScreen(wakeUp: boolean): void;](../reference/apis/js-apis-window.md#setwakeupscreen9) |
| [getProcessInfo(callback:AsyncCallback<ProcessInfo>):void;](../reference/apis/js-apis-inner-app-context.md#contextgetprocessinfo7) [getProcessInfo():Promise<ProcessInfo>;](../reference/apis/js-apis-inner-app-context.md#contextgetprocessinfo7-1) | \@ohos.app.ability.abilityManager.d.ts | [getAbilityRunningInfos(callback: AsyncCallback<Array<AbilityRunningInfo>>): void;](../reference/apis/js-apis-app-ability-abilityManager.md#getabilityrunninginfos) [getAbilityRunningInfos(): Promise<Array<AbilityRunningInfo>>;](../reference/apis/js-apis-app-ability-abilityManager.md#getabilityrunninginfos-1) |
| [getElementName(callback:AsyncCallback<ElementName>):void;](../reference/apis/js-apis-inner-app-context.md#contextgetelementname7) [getElementName():Promise<ElementName>;](../reference/apis/js-apis-inner-app-context.md#contextgetelementname7-1) | application\UIAbilityContext.d.ts | [abilityInfo.name: string;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#attributes) [abilityInfo.bundleName: string;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#attributes)|
@@ -26,5 +26,3 @@
| [getAbilityInfo(callback:AsyncCallback<AbilityInfo>):void;](../reference/apis/js-apis-inner-app-context.md#contextgetabilityinfo7) [getAbilityInfo():Promise<AbilityInfo>;](../reference/apis/js-apis-inner-app-context.md#contextgetabilityinfo7-1) | application\UIAbilityContext.d.ts | [abilityInfo: AbilityInfo;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#attributes)|
| [isUpdatingConfigurations(callback:AsyncCallback<boolean>):void;](../reference/apis/js-apis-inner-app-context.md#contextisupdatingconfigurations7) [isUpdatingConfigurations():Promise<boolean>;](../reference/apis/js-apis-inner-app-context.md#contextisupdatingconfigurations7-1) | There is no corresponding API in the stage model.| OpenHarmony applications do not restart when the system environment changes. The **onConfigurationUpdated** callback is invoked to notify the applications of the changes. This API provides an empty implementation in the FA model, and the stage model does not provide a corresponding API.|
| [printDrawnCompleted(callback:AsyncCallback<void>):void;](../reference/apis/js-apis-inner-app-context.md#contextprintdrawncompleted7) [printDrawnCompleted():Promise<void>;](../reference/apis/js-apis-inner-app-context.md#contextprintdrawncompleted7-1) | There is no corresponding API in the stage model.| This API provides an empty implementation in the FA model. The stage model does not provide a corresponding API.|
-
-
\ No newline at end of file
diff --git a/en/application-dev/application-models/explicit-implicit-want-mappings.md b/en/application-dev/application-models/explicit-implicit-want-mappings.md
index 32482e090b41fa9497a8f385e2126e5b7152287b..15b7fd78a569258bdcc7697d716a38d717cf0d83 100644
--- a/en/application-dev/application-models/explicit-implicit-want-mappings.md
+++ b/en/application-dev/application-models/explicit-implicit-want-mappings.md
@@ -18,7 +18,7 @@ The table below describes the matching rules of explicit [Want](../reference/api
| action | string | No| No| This field is not used for matching. It is passed to the target application component as a parameter.|
| entities | Array<string> | No| No| This field is not used for matching. It is passed to the target application component as a parameter.|
| flags | number | No| No| This field is not used for matching and is directly transferred to the system for processing. It is generally used to set runtime information, such as URI data authorization.|
-| parameters | {[key: string]: any} | No| No| This field is not used for matching. It is passed to the target application component as a parameter.|
+| parameters | {[key: string]: Object} | No| No| This field is not used for matching. It is passed to the target application component as a parameter.|
## Matching Rules for Implicit Want
@@ -35,7 +35,7 @@ The table below describes the matching rules of implicit [Want](../reference/api
| action | string | Yes | No | |
| entities | Array<string> | Yes | No | |
| flags | number | No | No | This field is not used for matching and is directly transferred to the system for processing. It is generally used to set runtime information, such as URI data authorization.|
-| parameters | {[key: string]: any} | No | No | This field is not used for matching. It is passed to the target application component as a parameter. |
+| parameters | {[key: string]: Object} | No | No | This field is not used for matching. It is passed to the target application component as a parameter. |
Get familiar with the following about implicit Want:
diff --git a/en/application-dev/application-models/lifecycleapp-switch.md b/en/application-dev/application-models/lifecycleapp-switch.md
index e2fa51264d4d41f52cef0a91e119a9e9d8e75d78..ae18625ecee0d281e9bd37b806bba5ae69a385c2 100644
--- a/en/application-dev/application-models/lifecycleapp-switch.md
+++ b/en/application-dev/application-models/lifecycleapp-switch.md
@@ -9,11 +9,11 @@
| onCreate?(): void; | \@ohos.app.ability.UIAbility.d.ts | [onCreate(want: Want, param: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncreate) |
| onWindowDisplayModeChanged?(isShownInMultiWindow: boolean, newConfig: resourceManager.Configuration): void; | There is no corresponding API in the stage model.| No corresponding API is provided.|
| onStartContinuation?(): boolean; | There is no corresponding API in the stage model.| In the stage model, an application does not need to detect whether the continuation is successful (detected when the application initiates the continuation request). Therefore, the **onStartContinuation()** callback is deprecated.|
-| onSaveData?(data: Object): boolean; | \@ohos.app.ability.UIAbility.d.ts | [onContinue(wantParam : {[key: string]: any}): AbilityConstant.OnContinueResult;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue) |
+| onSaveData?(data: Object): boolean; | \@ohos.app.ability.UIAbility.d.ts | [onContinue(wantParam : {[key: string]: Object}): AbilityConstant.OnContinueResult;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue) |
| onCompleteContinuation?(result: number): void; | application\ContinueCallback.d.ts | [onContinueDone(result: number): void;](../reference/apis/js-apis-distributedMissionManager.md#continuecallback) |
| onRestoreData?(data: Object): void; | \@ohos.app.ability.UIAbility.d.ts | [onCreate(want: Want, param: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncreate) [onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) In multiton or singleton mode, the target ability completes data restoration in the **onCreate()** callback. In the callback, **launchParam.launchReason** is used to determine whether it is a continuation-based launch scenario. If it is, the data saved before continuation can be obtained from the **want** parameter.|
| onRemoteTerminated?(): void; | application\ContinueCallback.d.ts | [onContinueDone(result: number): void;](../reference/apis/js-apis-distributedMissionManager.md#continuecallback) |
-| onSaveAbilityState?(outState: PacMap): void; | \@ohos.app.ability.UIAbility.d.ts | [onSaveState(reason: AbilityConstant.StateType, wantParam : {[key: string]: any}): AbilityConstant.OnSaveResult;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonsavestate) |
+| onSaveAbilityState?(outState: PacMap): void; | \@ohos.app.ability.UIAbility.d.ts | [onSaveState(reason: AbilityConstant.StateType, wantParam : {[key: string]: Object}): AbilityConstant.OnSaveResult;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonsavestate) |
| onRestoreAbilityState?(inState: PacMap): void; | \@ohos.app.ability.UIAbility.d.ts | [onCreate(want: Want, param: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncreate) After an application is restarted, the **onCreate()** callback is triggered. In the callback, **launchParam.launchReason** is used to determine whether it is a self-recovery scenario. If it is, the data saved before the restart can be obtained from the **want** parameter.|
| onInactive?(): void; | \@ohos.app.ability.UIAbility.d.ts | [onBackground(): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonbackground) |
| onActive?(): void; | \@ohos.app.ability.UIAbility.d.ts | [onForeground(): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonforeground) |
diff --git a/en/application-dev/application-models/lifecycleform-switch.md b/en/application-dev/application-models/lifecycleform-switch.md
index 6356d632e2dc20d5217bb32f2088061d9ab8fe8f..aee1059999aaca41b0c4b725201c6198d4fea209 100644
--- a/en/application-dev/application-models/lifecycleform-switch.md
+++ b/en/application-dev/application-models/lifecycleform-switch.md
@@ -10,4 +10,4 @@
| onEvent?(formId: string, message: string): void; | \@ohos.app.form.FormExtensionAbility.d.ts | [onFormEvent(formId: string, message: string): void;](../reference/apis/js-apis-app-form-formExtensionAbility.md#onformevent) |
| onDestroy?(formId: string): void; | \@ohos.app.form.FormExtensionAbility.d.ts | [onRemoveForm(formId: string): void;](../reference/apis/js-apis-app-form-formExtensionAbility.md#onremoveform) |
| onAcquireFormState?(want: Want): formInfo.FormState; | \@ohos.app.form.FormExtensionAbility.d.ts | [onAcquireFormState?(want: Want): formInfo.FormState;](../reference/apis/js-apis-app-form-formExtensionAbility.md#onacquireformstate) |
-| onShare?(formId: string): {[key: string]: any}; | \@ohos.app.form.FormExtensionAbility.d.ts | [onShareForm?(formId: string): { [key: string]: any };](../reference/apis/js-apis-app-form-formExtensionAbility.md#onshareform) |
+| onShare?(formId: string): {[key: string]: Object}; | \@ohos.app.form.FormExtensionAbility.d.ts | [onShareForm?(formId: string): { [key: string]: Object };](../reference/apis/js-apis-app-form-formExtensionAbility.md#onshareform) |
diff --git a/en/application-dev/application-models/particleability-switch.md b/en/application-dev/application-models/particleability-switch.md
index 7686ab281f8b6dd8b17e13fa0cbebd8cd6382d09..a5972c93f4c806f69ea80d6fa1d27dd344098bfd 100644
--- a/en/application-dev/application-models/particleability-switch.md
+++ b/en/application-dev/application-models/particleability-switch.md
@@ -8,7 +8,5 @@
| [connectAbility(request: Want, options:ConnectOptions ): number;](../reference/apis/js-apis-ability-particleAbility.md#particleabilityconnectability) | application\ServiceExtensionContext.d.ts | [connectAbility(want: Want, options: ConnectOptions): number;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextconnectserviceextensionability) [connectServiceExtensionAbility(want: Want, options: ConnectOptions): number;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextconnectserviceextensionability) |
| [disconnectAbility(connection: number, callback:AsyncCallback<void>): void;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitydisconnectability) [disconnectAbility(connection: number): Promise<void>;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitydisconnectability-1) | application\ServiceExtensionContext.d.ts | [disconnectAbility(connection: number, callback:AsyncCallback<void>): void; ](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextdisconnectserviceextensionability) [disconnectAbility(connection: number): Promise<void>;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextdisconnectserviceextensionability-1) [disconnectServiceExtensionAbility(connection: number, callback: AsyncCallback<void>): void;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextdisconnectserviceextensionability) [disconnectServiceExtensionAbility(connection: number): Promise<void>;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextdisconnectserviceextensionability-1) |
| [acquireDataAbilityHelper(uri: string): DataAbilityHelper;](../reference/apis/js-apis-ability-particleAbility.md#particleabilityacquiredataabilityhelper) | \@ohos.data.dataShare.d.ts [\@ohos.data.fileAccess.d.ts | [createDataShareHelper(context: Context, uri: string, callback: AsyncCallback<DataShareHelper>): void;](../reference/apis/js-apis-data-dataShare.md#datasharecreatedatasharehelper) [createDataShareHelper(context: Context, uri: string): Promise<DataShareHelper>;](../reference/apis/js-apis-data-dataShare.md#datasharecreatedatasharehelper-1) [createFileAccessHelper(context: Context): FileAccessHelper;](../reference/apis/js-apis-fileAccess.md#fileaccesscreatefileaccesshelper-1) [createFileAccessHelper(context: Context, wants: Array<Want>): FileAccessHelper;](../reference/apis/js-apis-fileAccess.md#fileaccesscreatefileaccesshelper) |
-| [startBackgroundRunning(id: number, request: NotificationRequest, callback: AsyncCallback<void>): void;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitystartbackgroundrunning) [startBackgroundRunning(id: number, request: NotificationRequest): Promise<void>;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitystartbackgroundrunning-1) | \@ohos.resourceschedule.backgroundTaskManager.d.ts | [startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback): void;](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerstartbackgroundrunningcallback) [startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise<void>;](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerstartbackgroundrunningpromise) |
-| [cancelBackgroundRunning(callback: AsyncCallback<void>): void;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitycancelbackgroundrunning) [cancelBackgroundRunning(): Promise<void>;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitycancelbackgroundrunning-1) | \@ohos.resourceschedule.backgroundTaskManager.d.ts | [stopBackgroundRunning(context: Context, callback: AsyncCallback): void;](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerstopbackgroundrunningcallback) [stopBackgroundRunning(context: Context): Promise<void>;](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerstopbackgroundrunningpromise) |
-
-
\ No newline at end of file
+| [startBackgroundRunning(id: number, request: NotificationRequest, callback: AsyncCallback<void>): void;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitystartbackgroundrunning) [startBackgroundRunning(id: number, request: NotificationRequest): Promise<void>;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitystartbackgroundrunning-1) | \@ohos.resourceschedule.backgroundTaskManager.d.ts | [startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback): void;](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerstartbackgroundrunning) [startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise<void>;](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerstartbackgroundrunning-1) |
+| [cancelBackgroundRunning(callback: AsyncCallback<void>): void;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitycancelbackgroundrunning) [cancelBackgroundRunning(): Promise<void>;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitycancelbackgroundrunning-1) | \@ohos.resourceschedule.backgroundTaskManager.d.ts | [stopBackgroundRunning(context: Context, callback: AsyncCallback): void;](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerstopbackgroundrunning) [stopBackgroundRunning(context: Context): Promise<void>;](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerstopbackgroundrunning-1) |
diff --git a/en/application-dev/application-models/uiability-intra-device-interaction.md b/en/application-dev/application-models/uiability-intra-device-interaction.md
index 2ed36f466408f4280ef516f405bc0e6837fb31f6..56dd9198f291352413f72e3b2ada766c5c729e38 100644
--- a/en/application-dev/application-models/uiability-intra-device-interaction.md
+++ b/en/application-dev/application-models/uiability-intra-device-interaction.md
@@ -35,8 +35,8 @@ Assume that your application has two UIAbility components: EntryAbility and Func
let want = {
deviceId: '', // An empty deviceId indicates the local device.
bundleName: 'com.example.myapplication',
- abilityName: 'FuncAbility',
moduleName: 'func', // moduleName is optional.
+ abilityName: 'FuncAbility',
parameters: { // Custom information.
info: 'From the Index page of EntryAbility',
},
@@ -100,8 +100,8 @@ When starting FuncAbility from EntryAbility, you may want the result to be retur
let want = {
deviceId: '', // An empty deviceId indicates the local device.
bundleName: 'com.example.myapplication',
- abilityName: 'FuncAbility',
moduleName: 'func', // moduleName is optional.
+ abilityName: 'FuncAbility',
parameters: { // Custom information.
info: 'From the Index page of EntryAbility',
},
@@ -123,8 +123,8 @@ When starting FuncAbility from EntryAbility, you may want the result to be retur
resultCode: RESULT_CODE,
want: {
bundleName: 'com.example.myapplication',
+ moduleName: 'func', // moduleName is optional.
abilityName: 'FuncAbility',
- moduleName: 'func',
parameters: {
info: 'From the Index page of FuncAbility',
},
@@ -219,7 +219,8 @@ The following example describes how to start the UIAbility of another applicatio
})
```
- The following figure shows the effect. When you click **Open PDF**, a dialog box is displayed for you to select the application to use.
+ The following figure shows the effect. When you click **Open PDF**, a dialog box is displayed for you to select the application to use.
+

3. To stop the **UIAbility** instance when the document application is not in use, call [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself).
@@ -296,9 +297,9 @@ If you want to obtain the return result when using implicit Want to start the UI
let abilityResult = {
resultCode: RESULT_CODE,
want: {
- bundleName: 'com.example.myapplication',
+ bundleName: 'com.example.funcapplication',
+ moduleName: 'entry', // moduleName is optional.
abilityName: 'EntryAbility',
- moduleName: 'entry',
parameters: {
payResult: 'OKay',
},
@@ -366,8 +367,8 @@ let context = ...; // UIAbilityContext
let want = {
deviceId: '', // An empty deviceId indicates the local device.
bundleName: 'com.example.myapplication',
- abilityName: 'FuncAbility',
moduleName: 'func', // moduleName is optional.
+ abilityName: 'FuncAbility',
parameters: { // Custom information.
info: 'From the Index page of EntryAbility',
},
@@ -383,7 +384,7 @@ context.startAbility(want, options).then(() => {
})
```
-The display effect is shown below.
+The display effect is shown below.

@@ -400,13 +401,13 @@ When the initiator UIAbility starts another UIAbility, it usually needs to redir
```ts
let context = ...; // UIAbilityContext
let want = {
- deviceId: '', // An empty deviceId indicates the local device.
- bundleName: 'com.example.myapplication',
- abilityName: 'FuncAbility',
- moduleName: 'func', // moduleName is optional.
- parameters: { // Custom parameter used to pass the page information.
- router: 'funcA',
- },
+ deviceId: '', // An empty deviceId indicates the local device.
+ bundleName: 'com.example.funcapplication',
+ moduleName: 'entry', // moduleName is optional.
+ abilityName: 'EntryAbility',
+ parameters: { // Custom parameter used to pass the page information.
+ router: 'funcA',
+ },
}
// context is the UIAbilityContext of the initiator UIAbility.
context.startAbility(want).then(() => {
@@ -423,24 +424,24 @@ When the target UIAbility is started for the first time, in the **onWindowStageC
```ts
-import UIAbility from '@ohos.app.ability.UIAbility'
-import Window from '@ohos.window'
+import AbilityConstant from '@ohos.app.ability.AbilityConstant';
+import UIAbility from '@ohos.app.ability.UIAbility';
+import Want from '@ohos.app.ability.Want';
+import window from '@ohos.window';
export default class FuncAbility extends UIAbility {
- funcAbilityWant;
+ funcAbilityWant: Want;
- onCreate(want, launchParam) {
+ onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
// Receive the parameters passed by the initiator UIAbility.
this.funcAbilityWant = want;
}
- onWindowStageCreate(windowStage: Window.WindowStage) {
+ onWindowStageCreate(windowStage: window.WindowStage) {
// Main window is created. Set a main page for this UIAbility.
let url = 'pages/Index';
- if (this.funcAbilityWant?.parameters?.router) {
- if (this.funcAbilityWant.parameters.router === 'funA') {
- url = 'pages/Second';
- }
+ if (this.funcAbilityWant?.parameters?.router && this.funcAbilityWant.parameters.router === 'funcA') {
+ url = 'pages/Second';
}
windowStage.loadContent(url, (err, data) => {
...
@@ -449,51 +450,90 @@ export default class FuncAbility extends UIAbility {
}
```
-
### Starting a Page When the Target UIAbility Is Not Started for the First Time
-You start application A, and its home page is displayed. Then you return to the home screen and start application B. Now you need to start application A again from application B and access a specified page of application A. An example scenario is as follows: When you open the home page of the SMS application and return to the home screen, the SMS application is in the opened state with its home page. Then you open the home page of the Contacts application, access user A's details page, and touch the SMS icon to send an SMS message to user A. The SMS application is started again and the sending page is displayed.
+If the target UIAbility has been started, the initialization logic is not executed again. Instead, the **onNewWant()** lifecycle callback is directly triggered. To implement redirection, parse the required parameters in **onNewWant()**.
+
+An example scenario is as follows:
+
+1. A user opens the SMS application. The UIAbility instance of the SMS application is started, and the home page of the application is displayed.
+2. The user returns to the home screen, and the SMS application switches to the background.
+3. The user opens the Contacts application and finds a contact.
+4. The user touches the SMS button next to the contact. The UIAbility instance of the SMS application is restarted.
+5. Since the UIAbility instance of the SMS application has been started, the **onNewWant()** callback of the UIAbility is triggered, and the initialization logic such as **onCreate()** and **onWindowStageCreate()** is skipped.
+
+```mermaid
+sequenceDiagram
+Participant U as User
+Participant S as SMS app
+Participant C as Contacts app
+
+U->>S: Open the SMS app.
+S-->>U: The home page of the SMS app is displayed.
+U->>S: Return to the home screen.
+S->>S: The SMS app enters the background.
+U->>C: Open the Contacts app.
+C-->>U: The page of the Contact app is displayed.
+U->>C: Touch the SMS button next to a contact.
+C->>S: Start the SMS app with Want.
+S-->>U: The page for sending an SMS message to the contact is displayed.
+```
-
+The development procedure is as follows:
-In summary, when a UIAbility instance of application A has been created and the main page of the UIAbility instance is displayed, you need to start the UIAbility of application A from application B and access a different page.
+1. When the UIAbility instance of the SMS application is started for the first time, call [getUIContext()](../reference/apis/js-apis-window.md#getuicontext10) in the **onWindowStageCreate()** lifecycle callback to obtain the [UIContext](../reference/apis/js-apis-arkui-UIContext.md).
-1. In the target UIAbility, the **Index** page is loaded by default. The UIAbility instance has been created, and the **onNewWant()** callback rather than **onCreate()** and **onWindowStageCreate()** will be invoked. In the **onNewWant()** callback, parse the **want** parameter and bind it to the global variable **globalThis**.
-
```ts
- import UIAbility from '@ohos.app.ability.UIAbility'
+ import AbilityConstant from '@ohos.app.ability.AbilityConstant';
+ import UIAbility from '@ohos.app.ability.UIAbility';
+ import Want from '@ohos.app.ability.Want';
+ import window from '@ohos.window';
- export default class FuncAbility extends UIAbility {
- onNewWant(want, launchParam) {
- // Receive the parameters passed by the initiator UIAbility.
- globalThis.funcAbilityWant = want;
+ import { Router, UIContext } from '@ohos.arkui.UIContext';
+
+ export default class EntryAbility extends UIAbility {
+ funcAbilityWant: Want;
+ uiContext: UIContext;
+
+ ...
+
+ onWindowStageCreate(windowStage: window.WindowStage) {
+ // Main window is created. Set a main page for this UIAbility.
...
+
+ let windowClass: window.Window;
+ windowStage.getMainWindow((err, data) => {
+ if (err.code) {
+ console.error(`Failed to obtain the main window. Code is ${err.code}, message is ${err.message}`);
+ return;
+ }
+ windowClass = data;
+ this.uiContext = windowClass.getUIContext();
+ })
}
}
```
-2. In FuncAbility, use the router module to implement redirection to the specified page on the **Index** page. Because the **Index** page of FuncAbility is active, the variable will not be declared again and the **aboutToAppear()** callback will not be triggered. Therefore, the page routing functionality can be implemented in the **onPageShow()** callback of the **Index** page.
-
+2. Parse the **want** parameter passed in the **onNewWant()** callback of the UIAbility of the SMS application, call [getRouter()](../reference/apis/js-apis-arkui-UIContext.md#getrouter) in the **UIContext** class to obtain a [Router](../reference/apis/js-apis-arkui-UIContext.md#router) instance, and specify the target page. When the UIAbility instance of the SMS application is started again, the specified page of the UIAbility instance of the SMS application is displayed.
+
```ts
- import router from '@ohos.router';
-
- @Entry
- @Component
- struct Index {
- onPageShow() {
- let funcAbilityWant = globalThis.funcAbilityWant;
- let url2 = funcAbilityWant?.parameters?.router;
- if (url2 && url2 === 'funcA') {
- router.replaceUrl({
- url: 'pages/Second',
+ export default class EntryAbility extends UIAbility {
+ funcAbilityWant: Want;
+ uiContext: UIContext;
+
+ onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam) {
+ if (want?.parameters?.router && want.parameters.router === 'funcA') {
+ let funcAUrl = 'pages/Second';
+ let router: Router = this.uiContext.getRouter();
+ router.pushUrl({
+ url: funcAUrl
+ }).catch((err) => {
+ console.error(`Failed to push url. Code is ${err.code}, message is ${err.message}`);
})
}
}
- // Page display.
- build() {
- ...
- }
+ ...
}
```
diff --git a/en/application-dev/application-models/uiability-launch-type.md b/en/application-dev/application-models/uiability-launch-type.md
index 3b91469c1db08e2cbed59c7fceb4563547b54a72..03ae09de4f54a956506881e20a4bf45ec3bb8fe4 100644
--- a/en/application-dev/application-models/uiability-launch-type.md
+++ b/en/application-dev/application-models/uiability-launch-type.md
@@ -157,4 +157,4 @@ The following steps are used as an example.
1. Open file A. A UIAbility instance, UIAbility instance 1, is started.
2. Close the process of file A in Recents. UIAbility instance 1 is destroyed. Return to the home screen and open file A again. A new UIAbility instance, UIAbility instance 2, is started.
3. Return to the home screen and open file B. A new UIAbility instance, UIAbility instance 3, is started.
- 4. Return to the home screen and open file A again. UIAbility instance 2 is started. This is because the system automatically matches the key with the UIAbility instance and starts the UIAbility instance that has a matching key. In this example, UIAbility instance 2 has the same key as file A. Therefore, the system pulls back UIAbility instance 2 and focuses it without creating a new instance.hao
+ 4. Return to the home screen and open file A again. UIAbility instance 2 is started. This is because the system automatically matches the key with the UIAbility instance and starts the UIAbility instance that has a matching key. In this example, UIAbility instance 2 has the same key as file A. Therefore, the system pulls back UIAbility instance 2 and focuses it without creating a new instance.
diff --git a/en/application-dev/application-models/widget-development-fa.md b/en/application-dev/application-models/widget-development-fa.md
index 5405cf30050269a97039bc2e9d898da7b5ee1dc8..7061ad6db08cca845f478c9a18685d2301cdafbe 100644
--- a/en/application-dev/application-models/widget-development-fa.md
+++ b/en/application-dev/application-models/widget-development-fa.md
@@ -85,7 +85,7 @@ The **FormBindingData** class has the following APIs. For details, see [FormBind
| API| Description|
| -------- | -------- |
-| createFormBindingData(obj?: Object \ string): FormBindingData| | Creates a **FormBindingData** object.|
+| createFormBindingData(obj?: Object \| string): FormBindingData | Creates a **FormBindingData** object. |
## How to Develop
@@ -327,9 +327,11 @@ For details about how to implement persistent data storage, see [Application Dat
The **Want** object passed in by the widget host to the widget provider contains a flag that specifies whether the requested widget is normal or temporary.
-- Normal widget: a widget persistently used by the widget host
+- Normal widget: a widget persistently used by the widget host, for example, a widget added to the home screen.
-- Temporary widget: a widget temporarily used by the widget host
+- Temporary widget: a widget temporarily used by the widget host, for example, the widget displayed when you swipe up on a widget application.
+
+Converting a temporary widget to a normal one: After you swipe up on a widget application, a temporary widget is displayed. If you touch the pin button on the widget, it is displayed as a normal widget on the home screen.
Data of a temporary widget will be deleted on the Widget Manager if the widget framework is killed and restarted. The widget provider, however, is not notified of the deletion and still keeps the data. Therefore, the widget provider needs to clear the data of temporary widgets proactively if the data has been kept for a long period of time. If the widget host has converted a temporary widget into a normal one, the widget provider should change the widget data from temporary storage to persistent storage. Otherwise, the widget data may be deleted by mistake.
diff --git a/en/application-dev/arkts-utils/cpu-intensive-task-development.md b/en/application-dev/arkts-utils/cpu-intensive-task-development.md
index 80ecd66bb86f11bb4b0dace92e8e6924bdbd8b4f..da11a1866dbeb1d374972fde6579676387d97ada 100644
--- a/en/application-dev/arkts-utils/cpu-intensive-task-development.md
+++ b/en/application-dev/arkts-utils/cpu-intensive-task-development.md
@@ -15,6 +15,7 @@ If a task does not need to occupy a background thread for a long time (3 minutes
1. Implement the logic of image processing.
2. Segment the data, and initiate associated task scheduling through task groups.
+
Create a [task group](../reference/apis/js-apis-taskpool.md#taskgroup10), call [addTask()](../reference/apis/js-apis-taskpool.md#addtask10) to add tasks, call [execute()](../reference/apis/js-apis-taskpool.md#taskpoolexecute10) to execute the tasks in the task group, and set [a high priority](../reference/apis/js-apis-taskpool.md#priority) for the task group. After all the tasks in the task group are complete, the histogram processing result is returned simultaneously.
3. Summarize and process the result arrays.
@@ -78,7 +79,7 @@ The following uses the training of a region-specific house price prediction mode

-2. In the main thread, call [ThreadWorker()](../reference/apis/js-apis-worker.md#threadworker9) to create a **Worker** object. The calling thread is the host thread.
+2. In the main thread, call [constructor()](../reference/apis/js-apis-worker.md#constructor9) of **ThreadWorker** to create a **Worker** object. The calling thread is the host thread.
```js
import worker from '@ohos.worker';
@@ -167,24 +168,22 @@ The following uses the training of a region-specific house price prediction mode
6. After the task is completed in the worker thread, destroy the worker thread. The worker thread can be destroyed by itself or the host thread. Then, call [onexit()](../reference/apis/js-apis-worker.md#onexit9) in the host thread to define the processing logic after the worker thread is destroyed.
-
```js
// After the worker thread is destroyed, execute the onexit() callback.
workerInstance.onexit = function() {
console.info("main thread terminate");
}
```
-
- In the host thread, call [terminate()](../reference/apis/js-apis-worker.md#terminate9) to destroy the worker thread and stop the worker thread from receiving messages.
-
+ Method 1: In the host thread, call [terminate()](../reference/apis/js-apis-worker.md#terminate9) to destroy the worker thread and stop the worker thread from receiving messages.
+
```js
- // Destroy the worker thread.
+// Destroy the worker thread.
workerInstance.terminate();
```
-
- In the worker thread, call [close()](../reference/apis/js-apis-worker.md#close9) to destroy the worker thread and stop the worker thread from receiving messages.
+ Method 2: In the worker thread, call [close()](../reference/apis/js-apis-worker.md#close9) to destroy the worker thread and stop the worker thread from receiving messages.
+
```js
// Destroy the worker thread.
workerPort.close();
diff --git a/en/application-dev/arkts-utils/linear-container.md b/en/application-dev/arkts-utils/linear-container.md
index 2a160f113f68e3257278e5a18168bb811a8efe30..84ed8ab890864a7d525aa24c096431b12d3d18e5 100644
--- a/en/application-dev/arkts-utils/linear-container.md
+++ b/en/application-dev/arkts-utils/linear-container.md
@@ -44,14 +44,14 @@ The APIs provided by **Vector** are deprecated since API version 9. You are advi
| Accessing elements| Use **vec\[index]** to obtain the value at a given position (specified by **index**).|
| Accessing elements| Use **get(index: number)** to obtain the element at a given position (specified by **index**).|
| Accessing elements| Use **getLastElement()** to obtain the last element in this container.|
-| Accessing elements| Use **getlndexOf(element: T)** to obtain the index of the first occurrence of the specified element.|
-| Accessing elements| Use **getLastlndexOf(element: T)** to obtain the index of the last occurrence of the specified element.|
+| Accessing elements| Use **getIndexOf(element: T)** to obtain the index of the first occurrence of the specified element.|
+| Accessing elements| Use **getLastIndexOf(element: T)** to obtain the index of the last occurrence of the specified element.|
| Accessing elements| Use **forEach(callbackFn: (value: T, index?: number, Vector?: Vector<T>) => void, thisArg?: Object)** to traverse the elements in this container.|
| Accessing elements| Use **\[Symbol.iterator]():IterableIterator<T>** for data access.|
| Modifying elements| Use **vec\[index]=xxx** to change the value at a given position (specified by **index**).|
| Modifying elements| Use **set(index: number, element: T)** to replace an element at a given position (specified by **index**) with a given element.|
| Modifying elements| Use **setLength(newSize: number)** to set the size of this container.|
-| Deleting elements| Use **removeBylndex(index: number)** to remove the value at a given position (specified by **index**).|
+| Deleting elements| Use **removeByIndex(index: number)** to remove the value at a given position (specified by **index**).|
| Deleting elements| Use **remove(element: T)** to remove the first occurrence of the specified element.|
| Deleting elements| Use **removeByRange(fromIndex: number, toIndex: number)** to remove all of the elements within a range.|
@@ -74,14 +74,14 @@ You are advised to use **List** for frequent insertion and removal operations.
| Accessing elements| Use **get(index: number)** to obtain the element at a given position (specified by **index**).|
| Accessing elements| Use **getFirst()** to obtain the first element in this container.|
| Accessing elements| Use **getLast()** to obtain the last element in this container.|
-| Accessing elements| Use **getlndexOf(element: T)** to obtain the index of the first occurrence of the specified element.|
-| Accessing elements| Use **getLastlndexOf(element: T)** to obtain the index of the last occurrence of the specified element.|
+| Accessing elements| Use **getIndexOf(element: T)** to obtain the index of the first occurrence of the specified element.|
+| Accessing elements| Use **getLastIndexOf(element: T)** to obtain the index of the last occurrence of the specified element.|
| Accessing elements| Use **forEach(callbackfn: (value: T, index?: number, list?: List<T>)=> void, thisArg?: Object)** to traverse the elements in this container.|
| Accessing elements| Use **\[Symbol.iterator]():IterableIterator<T>** for data access.|
| Modifying elements| Use **list\[index] = xxx** to change the value at a given position (specified by **index**).|
| Modifying elements| Use **set(index: number, element: T)** to replace an element at a given position (specified by **index**) with a given element.|
| Modifying elements| Use **replaceAllElements(callbackFn:(value: T,index?: number,list?: List<T>)=>T,thisArg?: Object)** to replace all elements in this container with new elements.|
-| Deleting elements| Use **removeBylndex(index: number)** to remove the value at a given position (specified by **index**).|
+| Deleting elements| Use **removeByIndex(index: number)** to remove the value at a given position (specified by **index**).|
| Deleting elements| Use **remove(element: T)** to remove the first occurrence of the specified element.|
@@ -105,13 +105,13 @@ You are advised to use **LinkedList** for frequent insertion and removal operati
| Accessing elements| Use **get(index: number)** to obtain the element at a given position (specified by **index**).|
| Accessing elements| Use **getFirst()** to obtain the first element in this container.|
| Accessing elements| Use **getLast()** to obtain the last element in this container.|
-| Accessing elements| Use **getlndexOf(element: T)** to obtain the index of the first occurrence of the specified element.|
-| Accessing elements| Use **getLastlndexOf(element: T)** to obtain the index of the last occurrence of the specified element.|
+| Accessing elements| Use **getIndexOf(element: T)** to obtain the index of the first occurrence of the specified element.|
+| Accessing elements| Use **getLastIndexOf(element: T)** to obtain the index of the last occurrence of the specified element.|
| Accessing elements| Use **forEach(callbackFn: (value: T, index?: number, list?: LinkedList<T>) => void, thisArg?: Object)** to traverse the elements in this container.|
| Accessing elements| Use **\[Symbol.iterator]():IterableIterator<T>** for data access.|
| Modifying elements| Use **list\[index]=xxx** to change the value at a given position (specified by **index**).|
| Modifying elements| Use **set(index: number, element: T)** to replace an element at a given position (specified by **index**) with a given element.|
-| Deleting elements| Use **removeBylndex(index: number)** to remove the value at a given position (specified by **index**).|
+| Deleting elements| Use **removeByIndex(index: number)** to remove the value at a given position (specified by **index**).|
| Deleting elements| Use **remove(element: T)** to remove the first occurrence of the specified element.|
diff --git a/en/application-dev/arkts-utils/multi-thread-concurrency-overview.md b/en/application-dev/arkts-utils/multi-thread-concurrency-overview.md
index 2d42ea1a56cd56eb06cd1e8394735e17fed70a2b..08451191025d01ecfcd3b70f8fb8170826c35dc4 100644
--- a/en/application-dev/arkts-utils/multi-thread-concurrency-overview.md
+++ b/en/application-dev/arkts-utils/multi-thread-concurrency-overview.md
@@ -12,7 +12,7 @@ Due to the memory isolation feature of the actor model, cross-thread serializati
## Data Transfer Objects
-Data objects that can be transferred are classified into three types: [common objects](#common-objects), [transferable objects](#transferable-objects), and [shared objects](#shared-objects).
+Data objects that can be transferred are classified into the following types: [common objects](#common-objects), [transferable objects](#transferable-objects), [shared objects](#shared-objects), and [native binding objects](#native-binding-objects).
### Common Objects
@@ -24,7 +24,7 @@ The following object types are supported: basic types except Symbol, Date, Strin
### Transferable Objects
-Transferable objects are serialized through address transfer. It transfers the ownership of an object of the ArrayBuffer type object, rather than the content in it. After the ownership is transferred, the object becomes unavailable in the sender and can be used only in the receiver.
+Transferable objects are serialized through address transfer. It transfers the ownership of an object of the ArrayBuffer type, rather than the content in it. After the ownership is transferred, the object becomes unavailable in the sender and can be used only in the receiver.
```js
@@ -47,6 +47,15 @@ If multiple operations are simultaneously performed to modify data stored in an
let sharedBuffer = new SharedArrayBuffer(1024);
```
+### Native Binding Objects
+
+Native binding objects are provided by the system. They are bound to underlying system services and enables direct access to these services.
+
+Currently, native bound objects that support serialization include [Context](../application-models/application-context-stage.md) and [RemoteObject](../reference/apis/js-apis-rpc.md#remoteobject).
+
+The **Context** object provides the context information about an application component. It provides a way to access system services and resources so that the application component can interact with the system. For details about how to obtain context information, see [Context (Stage Model)](../application-models/application-context-stage.md).
+
+The **RemoteObject** object implements remote communication. It transfers the reference of an object between processes so that these processes can share the status and methods of the object. The service provider must inherit this class. For details about how to create a **RemoteObject** object, see [RemoteObject](../reference/apis/js-apis-rpc.md#remoteobject).
## TaskPool and Worker
diff --git a/en/application-dev/arkts-utils/nonlinear-container.md b/en/application-dev/arkts-utils/nonlinear-container.md
index 3287d2675528cd73c0e43c562263b5af07bfaf46..b5c6380ae873b9dc47b69a6754b357f7dac8c1c8 100644
--- a/en/application-dev/arkts-utils/nonlinear-container.md
+++ b/en/application-dev/arkts-utils/nonlinear-container.md
@@ -52,9 +52,9 @@ You are advised to use **HashSet** when you need a set that has only unique elem
| Adding elements| Use **add(value: T)** to add a value to this container.|
| Accessing elements| Use **values()** to return an iterator that contains all the values in this container.|
| Accessing elements| Use **entries()** to return an iterator that contains all the elements in this container.|
-| Accessing elements| Use **forEach(callbackFn: (value?: T, key?: T, set?: HashSet) => void, thisArg?: Object)** to traverse the elements in this container.|
+| Accessing elements| Use **forEach(callbackFn: (value?: T, key?: T, set?: HashSet\) => void, thisArg?: Object)** to traverse the elements in this container.|
| Accessing elements| Use **\[Symbol.iterator]():IterableIterator<T>** for data access.|
-| Modifying elements| Use **forEach(callbackFn: (value?: T, key?: T, set?: HashSet) => void, thisArg?: Object)** to change a value in this container.|
+| Modifying elements| Use **forEach(callbackFn: (value?: T, key?: T, set?: HashSet\) => void, thisArg?: Object)** to change a value in this container.|
| Deleting elements| Use **remove(value: T)** to remove a value.|
| Deleting elements| Use **clear()** to clear this container.|
@@ -109,9 +109,9 @@ You are advised to use **TreeSet** when you need to store data in sorted order.
| Accessing elements| Use **entries()** to return an iterator that contains all the elements in this container.|
| Accessing elements| Use **getFirstValue()** to obtain the first value in this container.|
| Accessing elements| Use **getLastValue()** to obtain the last value in this container.|
-| Accessing elements| Use **forEach(callbackFn: (value?: T, key?: T, set?: TreeSet) => void, thisArg?: Object)** to traverse the elements in this container.|
+| Accessing elements| Use **forEach(callbackFn: (value?: T, key?: T, set?: TreeSet\) => void, thisArg?: Object)** to traverse the elements in this container.|
| Accessing elements| Use **\[Symbol.iterator]():IterableIterator<T>** for data access.|
-| Modifying elements| Use **forEach(callbackFn: (value?: T, key?: T, set?: TreeSet) => void, thisArg?: Object)** to change a value in this container.|
+| Modifying elements| Use **forEach(callbackFn: (value?: T, key?: T, set?: TreeSet\) => void, thisArg?: Object)** to change a value in this container.|
| Deleting elements| Use **remove(value: T)** to remove a value.|
| Deleting elements| Use **clear()** to clear this container.|
@@ -169,9 +169,9 @@ You are advised to use **LightWeightSet** when you need a set that has only uniq
| Accessing elements| Use **values()** to return an iterator that contains all the values in this container.|
| Accessing elements| Use **entries()** to return an iterator that contains all the elements in this container.|
| Accessing elements| Use **getValueAt(index: number)** to obtain the value of an element at a given position (specified by **index**).|
-| Accessing elements| Use **forEach(callbackFn: (value?: T, key?: T, set?: LightWeightSet) => void, thisArg?: Object)** to traverse the elements in this container.|
+| Accessing elements| Use **forEach(callbackFn: (value?: T, key?: T, set?: LightWeightSet\) => void, thisArg?: Object)** to traverse the elements in this container.|
| Accessing elements| Use **\[Symbol.iterator]():IterableIterator<T>** for data access.|
-| Modifying elements| Use **forEach(callbackFn: (value?: T, key?: T, set?: LightWeightSet) => void, thisArg?: Object)** to change a value in this container.|
+| Modifying elements| Use **forEach(callbackFn: (value?: T, key?: T, set?: LightWeightSet\) => void, thisArg?: Object)** to change a value in this container.|
| Deleting elements| Use **remove(key: K)** to remove an element with the specified key.|
| Deleting elements| Use **removeAt(index: number)** to remove an element at a given position (specified by **index**).|
| Deleting elements| Use **clear()** to clear this container.|
@@ -197,10 +197,10 @@ You are advised to use PlainArray when you need to store KV pairs whose keys are
| Accessing elements| Use **getIndexOfValue(value: T)** to obtain the index of the specified value.|
| Accessing elements| Use **getKeyAt(index: number)** to obtain the key of an element at a given position (specified by **index**).|
| Accessing elements| Use **getValueAt(index: number)** to obtain the value of an element at a given position (specified by **index**).|
-| Accessing elements| Use **forEach(callbackFn: (value: T, index?: number, PlainArray?: PlainArray) => void, thisArg?: Object)** to traverse the elements in this container.|
+| Accessing elements| Use **forEach(callbackFn: (value: T, index?: number, PlainArray?: PlainArray\) => void, thisArg?: Object)** to traverse the elements in this container.|
| Accessing elements| Use **\[Symbol.iterator]():IterableIterator<[number, T]>** for data access.|
| Modifying elements| Use **setValueAt(index:number, value: T)** to change the value of an element at a given position (specified by **index**).|
-| Modifying elements| Use **forEach(callbackFn: (value: T, index?: number, PlainArray?: PlainArray) => void, thisArg?: Object)** to modify an element in this container.|
+| Modifying elements| Use **forEach(callbackFn: (value: T, index?: number, PlainArray?: PlainArray\) => void, thisArg?: Object)** to modify an element in this container.|
| Deleting elements| Use **remove(key: number)** to remove an element with the specified key.|
| Deleting elements| Use **removeAt(index: number)** to remove an element at a given position (specified by **index**).|
| Deleting elements| Use **removeRangeFrom(index: number, size: number)** to remove elements in a specified range.|
diff --git a/en/application-dev/arkts-utils/xml-parsing.md b/en/application-dev/arkts-utils/xml-parsing.md
index dd3e46517b3eec6aafce6d6566a2da982bbd8d6c..89ed22585be75803b281517d390f400ceeda9d4d 100644
--- a/en/application-dev/arkts-utils/xml-parsing.md
+++ b/en/application-dev/arkts-utils/xml-parsing.md
@@ -4,7 +4,7 @@
Data transferred in XML format must be parsed in actual use. Generally, three types of elements need to be parsed, as described in [Parsing XML Tags and Tag Values](#parsing-xml-tags-and-tag-values), [Parsing XML Attributes and Attribute Values](#parsing-xml-attributes-and-attribute-values), and [Parsing XML Event Types and Element Depths](#parsing-xml-event-types-and-element-depths).
-The **xml** module provides the **XmlPullParser** class to parse XML files. The input is an object of the ArrayBufffer or DataView type containing XML text, and the output is the parsed information.
+The **xml** module provides the **XmlPullParser** class to parse XML files. The input is an object of the ArrayBuffer or DataView type containing XML text, and the output is the parsed information.
**Table 1** XML parsing options
diff --git a/en/application-dev/connectivity/Readme-EN.md b/en/application-dev/connectivity/Readme-EN.md
index c09ca21b6d0814bd1cd2cecb95b0d2896fada8c4..729e641a3f526025ff218a4b64b32f064038b5ba 100755
--- a/en/application-dev/connectivity/Readme-EN.md
+++ b/en/application-dev/connectivity/Readme-EN.md
@@ -9,6 +9,7 @@
- [Ethernet Connection](net-ethernet.md)
- [Network Connection Management](net-connection-manager.md)
- [mDNS Management](net-mdns.md)
+ - [VPN Management](net-vpn.md)
- IPC & RPC
- [IPC & RPC Overview](ipc-rpc-overview.md)
- [IPC & RPC Development](ipc-rpc-development-guideline.md)
diff --git a/en/application-dev/connectivity/net-connection-manager.md b/en/application-dev/connectivity/net-connection-manager.md
index c443c93759caddbc5203b65022426882c0bb960b..fba108e73cd8e5e3dd81a43880cf25a54aee6ee5 100644
--- a/en/application-dev/connectivity/net-connection-manager.md
+++ b/en/application-dev/connectivity/net-connection-manager.md
@@ -107,7 +107,7 @@ conn.on('netAvailable', (data => {
// Listen to network status change events. If the network is unavailable, an on_netUnavailable event is returned.
conn.on('netUnavailable', (data => {
- console.log("net is unavailable, netId is " + data.netId);
+ console.log("net is unavailable, data is " + JSON.stringify(data));
}));
// Register an observer for network status changes.
diff --git a/en/application-dev/connectivity/net-vpn.md b/en/application-dev/connectivity/net-vpn.md
new file mode 100644
index 0000000000000000000000000000000000000000..adf38f9676f29937532579e0bbdb4a94467095f3
--- /dev/null
+++ b/en/application-dev/connectivity/net-vpn.md
@@ -0,0 +1,362 @@
+# VPN Management
+
+## Overview
+
+A virtual private network (VPN) is a dedicated network established on a public network. On a VPN, the connection between any two nodes does not have an end-to-end physical link required by the traditional private network. Instead, user data is transmitted over a logical link because a VPN is a logical network deployed over the network platform (such as the Internet) provided by the public network service provider.
+
+> **NOTE**
+> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [Traffic Management](../reference/apis/js-apis-net-vpn.md).
+
+The following describes the development procedure specific to each application scenario.
+
+## Available APIs
+
+For the complete list of APIs and example code, see [VPN Management](../reference/apis/js-apis-net-vpn.md).
+
+| Type| API| Description|
+| ---- | ---- | ---- |
+| ohos.net.vpn | setUp(config: VpnConfig, callback: AsyncCallback\): void | Establishes a VPN. This API uses an asynchronous callback to return the result.|
+| ohos.net.vpn | protect(socketFd: number, callback: AsyncCallback\): void | Enables VPN tunnel protection. This API uses an asynchronous callback to return the result.|
+| ohos.net.vpn | destroy(callback: AsyncCallback\): void | Destroys a VPN. This API uses an asynchronous callback to return the result.|
+
+## Starting a VPN
+
+1. Establish a VPN tunnel. The following uses the UDP tunnel as an example.
+2. Enable protection for the UDP tunnel.
+3. Establish a VPN.
+4. Process data of the virtual network interface card (vNIC), such as reading or writing data.
+5. Destroy the VPN.
+
+This example shows how to develop an application using native C++ code. For details, see [Simple Native C++ Example (ArkTS) (API9)] (https://gitee.com/openharmony/codelabs/tree/master/NativeAPI/NativeTemplateDemo).
+
+The sample application consists of two parts: JS code and C++ code.
+
+## JS Code
+The JS code is used to implement the service logic, such as creating a tunnel, establishing a VPN, enabling VPN protection, and destroying a VPN.
+
+```js
+import hilog from '@ohos.hilog';
+import vpn from '@ohos.net.vpn';
+import UIAbility from '@ohos.app.ability.UIAbility';
+import vpn_client from "libvpn_client.so"
+
+class EntryAbility extends UIAbility {
+ onWindowStageCreate(windowStage) {
+ globalThis.context = this.context;
+ }
+}
+
+let TunnelFd = -1
+let VpnConnection = vpn.createVpnConnection(globalThis.context)
+
+@Entry
+@Component
+struct Index {
+ @State message: string = 'Test VPN'
+
+ //1. Establish a VPN tunnel. The following uses the UDP tunnel as an example.
+ CreateTunnel() {
+ TunnelFd = vpn_client.udpConnect("192.168.43.208", 8888)
+ }
+
+ // 2. Enable protection for the UDP tunnel.
+ Protect() {
+ VpnConnection.protect(TunnelFd).then(function () {
+ console.info("vpn Protect Success.")
+ }).catch(function (err) {
+ console.info("vpn Protect Failed " + JSON.stringify(err))
+ })
+ }
+
+ SetupVpn() {
+ let config = {
+ addresses: [{
+ address: {
+ address: "10.0.0.5",
+ family: 1
+ },
+ prefixLength: 24,
+ }],
+ routes: [],
+ mtu: 1400,
+ dnsAddresses: [
+ "114.114.114.114"
+ ],
+ acceptedApplications: [],
+ refusedApplications: []
+ }
+
+ try {
+ // 3. Create a VPN.
+ VpnConnection.setUp(config, (error, data) => {
+ console.info("tunfd: " + JSON.stringify(data));
+ // 4. Process data of the virtual vNIC, such as reading or writing data.
+ vpn_client.startVpn(data, TunnelFd)
+ })
+ } catch (error) {
+ console.info("vpn setUp fail " + JSON.stringify(error));
+ }
+ }
+
+ // 5. Destroy the VPN.
+ Destroy() {
+ vpn_client.stopVpn(TunnelFd)
+ VpnConnection.destroy().then(function () {
+ console.info("vpn Destroy Success.")
+ }).catch(function (err) {
+ console.info("vpn Destroy Failed " + JSON.stringify(err))
+ })
+ }
+
+ build() {
+ Row() {
+ Column() {
+ Text(this.message)
+ .fontSize(50)
+ .fontWeight(FontWeight.Bold)
+ .onClick(() => {
+ console.info("vpn Client")
+ })
+ Button('CreateTunnel').onClick(() => {
+ this.CreateTunnel()
+ }).fontSize(50)
+ Button('Protect').onClick(() => {
+ this.Protect()
+ }).fontSize(50)
+ Button('SetupVpn').onClick(() => {
+ this.SetupVpn()
+ }).fontSize(50)
+ Button('Destroy').onClick(() => {
+ this.Destroy()
+ }).fontSize(50)
+ }
+ .width('100%')
+ }
+ .height('100%')
+ }
+}
+```
+
+## C++ Code
+The C++ code is used for underlying service implementation, such as UDP tunnel client implementation and vNIC data read and write.
+
+```c++
+#include "napi/native_api.h"
+#include "hilog/log.h"
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include
+#include
+#include
+
+#define BUFFER_SIZE 2048
+
+#define VPN_LOG_TAG "NetMgrVpn"
+#define VPN_LOG_DOMAIN 0x15b0
+#define MAKE_FILE_NAME (strrchr(__FILE__, '/') + 1)
+
+#define NETMANAGER_VPN_LOGE(fmt, ...) \
+ OH_LOG_Print(LOG_APP, LOG_ERROR, VPN_LOG_DOMAIN, VPN_LOG_TAG, "vpn [%{public}s %{public}d] " fmt, MAKE_FILE_NAME, \
+ __LINE__, ##__VA_ARGS__)
+
+#define NETMANAGER_VPN_LOGI(fmt, ...) \
+ OH_LOG_Print(LOG_APP, LOG_INFO, VPN_LOG_DOMAIN, VPN_LOG_TAG, "vpn [%{public}s %{public}d] " fmt, MAKE_FILE_NAME, \
+ __LINE__, ##__VA_ARGS__)
+
+#define NETMANAGER_VPN_LOGD(fmt, ...) \
+ OH_LOG_Print(LOG_APP, LOG_DEBUG, VPN_LOG_DOMAIN, VPN_LOG_TAG, "vpn [%{public}s %{public}d] " fmt, MAKE_FILE_NAME, \
+ __LINE__, ##__VA_ARGS__)
+
+struct FdInfo {
+ int32_t tunFd = 0;
+ int32_t tunnelFd = 0;
+ struct sockaddr_in serverAddr;
+};
+
+static FdInfo fdInfo;
+static bool threadRunF = false;
+static std::thread threadt1;
+static std::thread threadt2;
+
+// Obtain the IP address of the UDP server.
+static constexpr const int MAX_STRING_LENGTH = 1024;
+std::string GetStringFromValueUtf8(napi_env env, napi_value value) {
+ std::string result;
+ char str[MAX_STRING_LENGTH] = {0};
+ size_t length = 0;
+ napi_get_value_string_utf8(env, value, str, MAX_STRING_LENGTH, &length);
+ if (length > 0) {
+ return result.append(str, length);
+ }
+ return result;
+}
+
+void HandleReadTunfd(FdInfo fdInfo) {
+ uint8_t buffer[BUFFER_SIZE] = {0};
+ while (threadRunF) {
+ int ret = read(fdInfo.tunFd, buffer, sizeof(buffer));
+ if (ret <= 0) {
+ if (errno != 11) {
+ NETMANAGER_VPN_LOGE("read tun device error: %{public}d, tunfd: %{public}d", errno, fdInfo.tunFd);
+ }
+ continue;
+ }
+
+ // Read data from the vNIC and send the data to the UDP server through the UDP tunnel.
+ NETMANAGER_VPN_LOGD("buffer: %{public}s, len: %{public}d", buffer, ret);
+ ret = sendto(fdInfo.tunnelFd, buffer, ret, 0, (struct sockaddr *)&fdInfo.serverAddr, sizeof(fdInfo.serverAddr));
+ if (ret <= 0) {
+ NETMANAGER_VPN_LOGE("send to server[%{public}s:%{public}d] failed, ret: %{public}d, error: %{public}s",
+ inet_ntoa(fdInfo.serverAddr.sin_addr), ntohs(fdInfo.serverAddr.sin_port), ret,
+ strerror(errno));
+ continue;
+ }
+ }
+}
+
+void HandleTcpReceived(FdInfo fdInfo) {
+ int addrlen = sizeof(struct sockaddr_in);
+ uint8_t buffer[BUFFER_SIZE] = {0};
+ while (threadRunF) {
+ int length = recvfrom(fdInfo.tunnelFd, buffer, sizeof(buffer), 0, (struct sockaddr *)&fdInfo.serverAddr,
+ (socklen_t *)&addrlen);
+ if (length < 0) {
+ if (errno != 11) {
+ NETMANAGER_VPN_LOGE("read tun device error: %{public}d, tunnelfd: %{public}d", errno, fdInfo.tunnelFd);
+ }
+ continue;
+ }
+
+ // Receive data from the UDP server and write the data to the vNIC.
+ NETMANAGER_VPN_LOGD("from [%{public}s:%{public}d] data: %{public}s, len: %{public}d",
+ inet_ntoa(fdInfo.serverAddr.sin_addr), ntohs(fdInfo.serverAddr.sin_port), buffer, length);
+ int ret = write(fdInfo.tunFd, buffer, length);
+ if (ret <= 0) {
+ NETMANAGER_VPN_LOGE("error Write To Tunfd, errno: %{public}d", errno);
+ }
+ }
+}
+
+static napi_value UdpConnect(napi_env env, napi_callback_info info) {
+ size_t argc = 2;
+ napi_value args[2] = {nullptr};
+ napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
+
+ int32_t port = 0;
+ napi_get_value_int32(env, args[1], &port);
+ std::string ipAddr = GetStringFromValueUtf8(env, args[0]);
+
+ NETMANAGER_VPN_LOGI("ip: %{public}s port: %{public}d", ipAddr.c_str(), port);
+
+ // Establish a UDP tunnel.
+ int32_t sockFd = socket(AF_INET, SOCK_DGRAM, 0);
+ if (sockFd == -1) {
+ NETMANAGER_VPN_LOGE("socket() error");
+ return 0;
+ }
+
+ struct timeval timeout = {1, 0};
+ setsockopt(sockFd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(struct timeval));
+
+ memset(&fdInfo.serverAddr, 0, sizeof(fdInfo.serverAddr));
+ fdInfo.serverAddr.sin_family = AF_INET;
+ fdInfo.serverAddr.sin_addr.s_addr = inet_addr(ipAddr.c_str()); // server's IP addr
+ fdInfo.serverAddr.sin_port = htons(port); // port
+
+ NETMANAGER_VPN_LOGI("Connection successful");
+
+ napi_value tunnelFd;
+ napi_create_int32(env, sockFd, &tunnelFd);
+ return tunnelFd;
+}
+
+static napi_value StartVpn(napi_env env, napi_callback_info info) {
+ size_t argc = 2;
+ napi_value args[2] = {nullptr};
+ napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
+
+ napi_get_value_int32(env, args[0], &fdInfo.tunFd);
+ napi_get_value_int32(env, args[1], &fdInfo.tunnelFd);
+
+ if (threadRunF) {
+ threadRunF = false;
+ threadt1.join();
+ threadt2.join();
+ }
+
+ // Start two threads. One is used to read data from the vNIC, and the other is used to receive data from the server.
+ threadRunF = true;
+ std::thread tt1(HandleReadTunfd, fdInfo);
+ std::thread tt2(HandleTcpReceived, fdInfo);
+
+ threadt1 = std::move(tt1);
+ threadt2 = std::move(tt2);
+
+ NETMANAGER_VPN_LOGI("StartVpn successful");
+
+ napi_value retValue;
+ napi_create_int32(env, 0, &retValue);
+ return retValue;
+}
+
+static napi_value StopVpn(napi_env env, napi_callback_info info) {
+ size_t argc = 1;
+ napi_value args[1] = {nullptr};
+ napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
+
+ int32_t tunnelFd;
+ napi_get_value_int32(env, args[0], &tunnelFd);
+ if (tunnelFd) {
+ close(tunnelFd);
+ tunnelFd = 0;
+ }
+
+ // Stop the two threads.
+ if (threadRunF) {
+ threadRunF = false;
+ threadt1.join();
+ threadt2.join();
+ }
+
+ NETMANAGER_VPN_LOGI("StopVpn successful");
+
+ napi_value retValue;
+ napi_create_int32(env, 0, &retValue);
+ return retValue;
+}
+
+EXTERN_C_START
+static napi_value Init(napi_env env, napi_value exports) {
+ napi_property_descriptor desc[] = {
+ {"udpConnect", nullptr, UdpConnect, nullptr, nullptr, nullptr, napi_default, nullptr},
+ {"startVpn", nullptr, StartVpn, nullptr, nullptr, nullptr, napi_default, nullptr},
+ {"stopVpn", nullptr, StopVpn, nullptr, nullptr, nullptr, napi_default, nullptr},
+ };
+ napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
+ return exports;
+}
+EXTERN_C_END
+
+static napi_module demoModule = {
+ .nm_version = 1,
+ .nm_flags = 0,
+ .nm_filename = nullptr,
+ .nm_register_func = Init,
+ .nm_modname = "entry",
+ .nm_priv = ((void *)0),
+ .reserved = {0},
+};
+
+extern "C" __attribute__((constructor)) void RegisterEntryModule(void) {
+ napi_module_register(&demoModule);
+}
+```
diff --git a/en/application-dev/database/data-persistence-by-preferences.md b/en/application-dev/database/data-persistence-by-preferences.md
index e37c12369d59d2165220c8d8f5bbaa85029c37df..553050a55a585dc34e620623eb187a0365b8488e 100644
--- a/en/application-dev/database/data-persistence-by-preferences.md
+++ b/en/application-dev/database/data-persistence-by-preferences.md
@@ -68,7 +68,7 @@ The following table lists the APIs used for persisting user preference data. For
return;
}
console.info('Succeeded in getting preferences.');
- // Perform related data operations.
+ // Before performing related data operations, obtain a Preferences instance.
})
} catch (err) {
console.error(`Failed to get preferences. Code:${err.code},message:${err.message}`);
@@ -93,7 +93,7 @@ The following table lists the APIs used for persisting user preference data. For
return;
}
console.info('Succeeded in getting preferences.');
- // Perform related data operations.
+ // Before performing related data operations, obtain a Preferences instance.
})
} catch (err) {
console.error(`Failed to get preferences. Code is ${err.code},message:${err.message}`);
@@ -220,4 +220,4 @@ The following table lists the APIs used for persisting user preference data. For
} catch (err) {
console.error(`Failed to delete preferences. Code:${err.code}, message:${err.message}`);
}
- ```
+ ```
\ No newline at end of file
diff --git a/en/application-dev/database/data-persistence-by-rdb-store.md b/en/application-dev/database/data-persistence-by-rdb-store.md
index ff37d0fdce056ca143015f39c81892c990f6545d..5879f73dac606c956fa305e9602eb1673f1fb369 100644
--- a/en/application-dev/database/data-persistence-by-rdb-store.md
+++ b/en/application-dev/database/data-persistence-by-rdb-store.md
@@ -50,7 +50,7 @@ The following table lists the APIs used for RDB data persistence. Most of the AP
## How to Develop
-1. Obtain an **RdbStore** instance. Example:
+1. Obtain an **RdbStore** instance. Example:
Stage model:
@@ -97,7 +97,7 @@ The following table lists the APIs used for RDB data persistence. Most of the AP
store.version = 3;
}
- // Perform operations such as adding, deleting, modifying, and querying data in the RDB store.
+ // Before performing data operations on the database, obtain an RdbStore instance.
});
}
@@ -151,7 +151,7 @@ The following table lists the APIs used for RDB data persistence. Most of the AP
store.version = 3;
}
- // Perform operations such as adding, deleting, modifying, and querying data in the RDB store.
+ // Before performing data operations on the database, obtain an RdbStore instance.
});
```
@@ -256,7 +256,9 @@ The following table lists the APIs used for RDB data persistence. Most of the AP
5. Delete the RDB store.
- Use **deleteRdbStore()** to delete the RDB store and related database files.
+ Use **deleteRdbStore()** to delete the RDB store and related database files.
+
+ Example:
> **NOTE**
>
@@ -299,4 +301,4 @@ The following table lists the APIs used for RDB data persistence. Most of the AP
store = null;
console.info('Succeeded in deleting RdbStore.');
});
- ```
+ ```
\ No newline at end of file
diff --git a/en/application-dev/database/data-sync-of-kv-store.md b/en/application-dev/database/data-sync-of-kv-store.md
index eb8994570f04b0d6690c2b91b1b1745602e980fb..b23dd91ed1a7b4ea0cd13f6d9b49de82e1821190 100644
--- a/en/application-dev/database/data-sync-of-kv-store.md
+++ b/en/application-dev/database/data-sync-of-kv-store.md
@@ -171,7 +171,7 @@ The following uses a single KV store as an example to describe how to implement
return;
}
console.info('Succeeded in getting KVStore.');
- // Perform related data operations.
+ // Before performing related data operations, obtain a KV store instance.
});
} catch (e) {
console.error(`An unexpected error occurred. Code:${e.code},message:${e.message}`);
@@ -275,4 +275,4 @@ The following uses a single KV store as an example to describe how to implement
}
}
});
- ```
+ ```
\ No newline at end of file
diff --git a/en/application-dev/dfx/cppcrash-guidelines.md b/en/application-dev/dfx/cppcrash-guidelines.md
index 4454422fe4f3aec6c781090a2e833ee103488dab..c3ca07a4dc3a069272d89986329c2cbe103a45cb 100644
--- a/en/application-dev/dfx/cppcrash-guidelines.md
+++ b/en/application-dev/dfx/cppcrash-guidelines.md
@@ -1,4 +1,4 @@
-# cppcrash Log Analysis
+# Process Crash (cppcrash) Log Analysis
## Introduction
@@ -23,7 +23,7 @@ Process crash detection is implemented based on the Linux signal mechanism. Curr
## Crash Log Collection
-Process crash log is the fault log managed together with the app freeze and JS application crash logs by the FaultLogger module. You can collect process crash logs in any of the following ways:
+Process crash log is a type of fault logs managed together with the app freeze and JS application crash logs by the FaultLogger module. You can collect process crash logs in any of the following ways:
### Collecting Logs by Using Shell
@@ -72,17 +72,14 @@ Thread name:crasher <- Abnormal thread
### Locating Faults Through Logs
-1. Determine the faulty module and fault type based on fault logs.
-
- Generally, you can identify the faulty module based on the crash process name and identify the crash cause based on the signal. Besides, you can restore the function call chain of the crash stack based on the method name in the stack.
-
- In the example, **SIGSEGV** is thrown by the Linux kernel because of access to an invalid memory address. The problem occurs in the **TriggerSegmentFaultException** function.
-
- In most scenarios, a crash is caused by the top layer of the crash stack, such as null pointer access and proactive program abort.
+- Determine the faulty module and fault type based on fault logs.
+ Generally, you can identify the faulty module based on the crash process name and identify the crash cause based on the signal. Besides, you can restore the function call chain of the crash stack based on the method name in the stack.\
+ In the example, **SIGSEGV** is thrown by the Linux kernel because of access to an invalid memory address. The problem occurs in the **TriggerSegmentFaultException** function.\
+ In most scenarios, a crash is caused by the top layer of the crash stack, such as null pointer access and proactive program abort.\
If the cause cannot be located through the call stack, you need to check for other faults, for example, memory corruption or stack overflow.
-2. Use the addr2line tool of Linux to parse the code line number to restore the call stack at the time of process crash.
+- Use the addr2line tool of Linux to parse the code line number to restore the call stack at the time of process crash.
When using the addr2line tool to parse the code line number of the crash stack, make sure that binary files with debugging information is used. Generally, such files are generated during version build or application build.
@@ -94,17 +91,17 @@ Thread name:crasher <- Abnormal thread
\code root directory\out\product\exe.unstripped
```
- You can run `apt-get install addr2line` to install the addr2line tool on Linux.
-
+ You can run `apt-get install addr2line` to install the addr2line tool on Linux.\
On On DevEco Studio, you can also use the llvm-addr2line tool archived in the SDK to parse code line numbers. The usage method is the same.
- The following example shows how to use the addr2line tool to parse the code line number based on the offset address:
+ The following example shows how to use the addr2line tool to parse the code line number based on the offset address.
+
+ **[product name]** indicates the device name.
```
- root:~/OpenHarmony/out/rk3568/exe.unstripped/hiviewdfx/faultloggerd$ addr2line -e crasher 0000332c
+ root:~/OpenHarmony/out/[product name]/exe.unstripped/hiviewdfx/faultloggerd$ addr2line -e crasher 0000332c
base/hiviewdfx/faultloggerd/tools/crasher/dfx_crasher.c:57
```
- In this example, the crash is caused by assignment of a value to an unwritable area. It is in code line 57 in the **dfx_crasher.c** file. You can modify it to avoid the crash.
-
+ In this example, the crash is caused by assignment of a value to an unwritable area. It is in code line 57 in the **dfx_crasher.c** file. You can modify it to avoid the crash.\
If the obtained code line number is seemingly incorrect, you can fine-tune the address (for example, subtract the address by 1) or disable some compilation optimization items. It is known that the obtained code line number may be incorrect when Link Time Optimization (LTO) is enabled.
diff --git a/en/application-dev/faqs/faqs-ability.md b/en/application-dev/faqs/faqs-ability.md
index e42fc81eca4b256ec1dc2e242c9f777f5cda0923..01bd10fa524f0a7d7de7b26262562f0f5f5160ee 100644
--- a/en/application-dev/faqs/faqs-ability.md
+++ b/en/application-dev/faqs/faqs-ability.md
@@ -217,7 +217,7 @@ Use **Context.cacheDir** to obtain the cache directory of the application.
**Reference**
-[Obtaining Application File Paths](../application-models/application-context-stage.md#obtaining-application-file-paths)
+[cacheDir](../application-models/application-context-stage.md#obtaining-application-file-paths)
## In which JS file is the service widget lifecycle callback invoked?
@@ -282,7 +282,7 @@ Applicable to: OpenHarmony 3.2 Beta5 (API version 9)
**Solution**
-Refer to the code snippet below:
+Refer to the code snippet below:
```
let want = {
@@ -472,7 +472,7 @@ To start a continuous task in the background, you must configure the permission
[Continuous Task Permission](../security/permission-list.md#ohospermissionkeep_background_running)
-[Continuous Task Development](../task-management/continuous-task.md#stage-model)
+[Continuous Task](../task-management/continuous-task.md)
## How do FA widgets exchange data?
diff --git a/en/application-dev/faqs/faqs-arkui-animation-interactive-event.md b/en/application-dev/faqs/faqs-arkui-animation-interactive-event.md
index 56c1f44dfd74cec442e94b6116a0bab8965cbc66..cc07a581e4fb9a271b566928e8a5c991185c42c8 100644
--- a/en/application-dev/faqs/faqs-arkui-animation-interactive-event.md
+++ b/en/application-dev/faqs/faqs-arkui-animation-interactive-event.md
@@ -36,10 +36,11 @@ You can use [attribute animation](../reference/arkui-ts/ts-animatorproperty.md)
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
-**Solution**
+**Solution**
-- Add **focusable\(true\)** to the list item to enable it to obtain focus.
+ Use either of the following:
+- Add **focusable\(true\)** to the list item to enable it to obtain focus.
- Nest a focusable component, for example, **\**, at the outer layer of each item.
## Why is the click event not triggered for the focused component upon the press of the Enter key after keyboard navigation?
@@ -139,6 +140,8 @@ Currently, the menu is displayed when the bound component is clicked or long pre
Applicable to: OpenHarmony 3.2 Beta5 (API version 9)
+**Solution**
+
Set the **focusable** attribute of the **\** component to **false**. In this way, the component is not focusable and therefore will not bring up the keyboard.
## How do I implement the slide up and slide down effect for page transition?
@@ -199,7 +202,7 @@ Applicable to: OpenHarmony 3.2 Beta5 (API version 9)
**Symptom**
-Custom components A and B need to deliver the following effects: When custom component A, displayed at the bottom of the screen by default, is touched, it is hidden, and custom component B slides in from the bottom. When custom component B is touched, it is hidden, and custom component A slides in from the bottom.
+Custom components A and B need to deliver the following effects: When custom component A, displayed at the bottom of the screen by default, is touched, it is hidden, and custom component B slides in from the bottom; when custom component B is touched, it is hidden, and custom component A slides in from the bottom.
**Solution**
@@ -266,4 +269,4 @@ struct ComponentChild2 {
**Reference**
-[Transition Animation Within the Component](../ui/arkts-enter-exit-transition.md)
+[Enter/Exit Transition](../ui/arkts-enter-exit-transition.md)
diff --git a/en/application-dev/faqs/faqs-multimedia.md b/en/application-dev/faqs/faqs-multimedia.md
index 5ebfdb20da6c3b7e53b15bdd1b09ec9107f72d52..e6f9e571cfe88717192e1a1725cd6adf29bd3745 100644
--- a/en/application-dev/faqs/faqs-multimedia.md
+++ b/en/application-dev/faqs/faqs-multimedia.md
@@ -98,7 +98,7 @@ Music cannot be played in the background.
**Reference**
-[Continuous Task Development](../task-management/continuous-task.md)
+[Continuous Task](../task-management/continuous-task.md)
[AVSession Development](../media/using-avsession-developer.md)
@@ -197,4 +197,4 @@ CameraStatus: Enumerates the camera statuses.
**Reference**
-[CameraStatus](../reference/apis/js-apis-camera.md#oncamerastatus)
\ No newline at end of file
+[CameraStatus](../reference/apis/js-apis-camera.md#oncamerastatus)
diff --git a/en/application-dev/file-management/Readme-EN.md b/en/application-dev/file-management/Readme-EN.md
index f976a47e09917c74f143a5cd84f3e7824825dc47..ba9de10386b364074c8e1c1f87fc40af39c5e053 100644
--- a/en/application-dev/file-management/Readme-EN.md
+++ b/en/application-dev/file-management/Readme-EN.md
@@ -1,31 +1,31 @@
# File Management
- [File Management Overview](file-management-overview.md)
-- Application File
+- Application Files
- [Application File Overview](app-file-overview.md)
- [Application Sandbox Directory](app-sandbox-directory.md)
- Application File Access and Management
- [Accessing Application Files](app-file-access.md)
- [Uploading and Downloading Application Files](app-file-upload-download.md)
- [Obtaining Application and File System Space Statistics](app-fs-space-statistics.md)
- - [Sending Files to an Application Sandbox](send-file-to-app-sandbox.md)
+ - [Pushing Files to an Application Sandbox](send-file-to-app-sandbox.md)
- [Sharing an Application File](share-app-file.md)
- Application Data Backup and Restoration
- [Application Data Backup and Restoration Overview](app-file-backup-overview.md)
- - [Backing Up and Restoring Application Access Data](app-file-backup-extension.md)
- - [Backing Up and Restoring Application-triggered Data (for System Applications Only)](app-file-backup.md)
-- User File
+ - [Backup and Restoration Accessed by Applications](app-file-backup-extension.md)
+ - [Backup and Restoration Triggered by System Applications](app-file-backup.md)
+- User Files
- [User File Overview](user-file-overview.md)
- Selecting and Saving User Files (FilePicker)
- [Selecting User Files](select-user-file.md)
- [Saving User Files](save-user-file.md)
- Album Management (photoAccessHelper)
- [photoAccessHelper Overview](photoAccessHelper-overview.md)
- - [Media Asset (Image and video) Management](photoAccessHelper-resource-guidelines.md)
- - [User Album Management](photoAccessHelper-userAlbum-guidelines.md)
- - [System Album Management](photoAccessHelper-systemAlbum-guidelines.md)
- - [Media Asset Change Notification Management](photoAccessHelper-notify-guidelines.md)
- - [Developing a FileManager Application (for System Applications Only)](dev-user-file-manager.md)
+ - [Managing Media Assets (Images and Videos)](photoAccessHelper-resource-guidelines.md)
+ - [Managing User Albums](photoAccessHelper-userAlbum-guidelines.md)
+ - [Managing System Albums](photoAccessHelper-systemAlbum-guidelines.md)
+ - [Managing Media Asset Change Notifications](photoAccessHelper-notify-guidelines.md)
+ - [Developing a File Manager Application (for System Applications Only)](dev-user-file-manager.md)
- [Managing External Storage Devices (for System Applications Only)](manage-external-storage.md)
- Distributed File System
- [Distributed File System Overview](distributed-fs-overview.md)
diff --git a/en/application-dev/file-management/app-file-access.md b/en/application-dev/file-management/app-file-access.md
index a98e1ec1d8e82af603621f8cb41bad58ecc79d93..4d3a21c0902535a3d81fd4be678973b6e8dfab23 100644
--- a/en/application-dev/file-management/app-file-access.md
+++ b/en/application-dev/file-management/app-file-access.md
@@ -1,42 +1,42 @@
# Accessing Application Files
-This topic describes how to view, create, read, write, delete, move, or copy a file in the application file directory and obtain the file information.
+This topic describes how to enable an application to view, create, read, write, delete, move, or copy an application and obtain file information.
## Available APIs
-You can use [ohos.file.fs](../reference/apis/js-apis-file-fs.md) to implement the application file access capabilities. The following table describes the APIs.
+You can use [ohos.file.fs](../reference/apis/js-apis-file-fs.md) to implement access to application files. The following table describes the APIs.
**Table 1** APIs for basic application file operations
-| API| Description| Type| Synchronous Programming| Asynchronous Programming|
+| API| Description| Type| Synchronous Programming| Asynchronous Programming|
| -------- | -------- | -------- | -------- | -------- |
-| access | Checks whether a file exists.| Method| √ | √ |
-| close | Closes a file.| Method| √ | √ |
-| copyFile | Copies a file.| Method| √ | √ |
-| createStream | Creates a stream based on the specified file path.| Method| √ | √ |
-| listFile | Lists all files in a directory.| Method| √ | √ |
-| mkdir | Creates a directory.| Method| √ | √ |
-| moveFile | Moves a file.| Method| √ | √ |
-| open | Opens a file.| Method| √ | √ |
-| read | Reads data from a file.| Method| √ | √ |
-| rename | Renames a file or folder.| Method| √ | √ |
-| rmdir | Deletes a directory.| Method| √ | √ |
-| stat | Obtains detailed file information.| Method| √ | √ |
-| unlink | Deletes a single file.| Method| √ | √ |
-| write | Writes data to a file.| Method| √ | √ |
-| Stream.close | Closes a stream.| Method| √ | √ |
-| Stream.flush | Flushes all data from this stream.| Method| √ | √ |
-| Stream.write | Writes data to a stream.| Method| √ | √ |
-| Stream.read | Reads data from a stream.| Method| √ | √ |
-| File.fd | Defines a file descriptor.| Attribute| √ | × |
-| OpenMode | Defines the mode for opening a file.| Attribute| √ | × |
-| Filter | Defines the options for setting the file filter.| Type| × | × |
+| access | Checks whether a file exists.| Method| √ | √ |
+| close | Closes a file.| Method| √ | √ |
+| copyFile | Copies a file.| Method| √ | √ |
+| createStream | Creates a stream based on the specified file path.| Method| √ | √ |
+| listFile | Lists all files in a directory.| Method| √ | √ |
+| mkdir | Creates a directory.| Method| √ | √ |
+| moveFile | Moves a file.| Method| √ | √ |
+| open | Opens a file.| Method| √ | √ |
+| read | Reads data from a file.| Method| √ | √ |
+| rename | Renames a file or folder.| Method| √ | √ |
+| rmdir | Deletes a directory.| Method| √ | √ |
+| stat | Obtains detailed file information.| Method| √ | √ |
+| unlink | Deletes a single file.| Method| √ | √ |
+| write | Writes data to a file.| Method| √ | √ |
+| Stream.close | Closes a stream.| Method| √ | √ |
+| Stream.flush | Flushes all data from this stream.| Method| √ | √ |
+| Stream.write | Writes data to a stream.| Method| √ | √ |
+| Stream.read | Reads data from a stream.| Method| √ | √ |
+| File.fd | Defines a file descriptor.| Attribute| √ | × |
+| OpenMode | Defines the mode for opening a file.| Attribute| √ | × |
+| Filter | Defines the options for setting the file filter.| Type| × | × |
## Development Example
-Obtain the [application file path](../application-models/application-context-stage.md#obtaining-the-application-development-path). The following example shows how to obtain a HAP file path using **UIAbilityContext**. For details about how to obtain **UIAbilityContext**, see [Obtaining the Context of UIAbility](../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
+First, obtain the [application file path](../application-models/application-context-stage.md#obtaining-application-file-paths). The following example shows how to obtain a HAP file path using **UIAbilityContext**. For details about how to obtain **UIAbilityContext**, see [Obtaining the Context of UIAbility](../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
-The following describes common file operations.
+Then, perform common file operations.
### Creating, Reading, and Writing a File
@@ -68,8 +68,8 @@ function createFile() {
### Copying Data to Another File
- The following example demonstrates how to write the data read from a file to another file.
-
+ The following example demonstrates how to read data from a file and write it to another file.
+
```ts
// pages/xxx.ets
import fs from '@ohos.file.fs';
@@ -101,12 +101,12 @@ function readWriteFile() {
> **NOTE**
>
-> When using **read()** or **write()**, pay attention to the optional parameter **offset**. For a file that has been read or written, the offset pointer is at the end position of the last read or write operation by default.
+> When using **read()** or **write()**, pay attention to the optional parameter **offset**. For a file that has been read or written, **offset** points to the end position of the last read or write operation by default.
### Reading and Writing Files in a Stream
The following example demonstrates how to read and write file data using a stream.
-
+
```ts
// pages/xxx.ets
import fs from '@ohos.file.fs';
@@ -138,12 +138,14 @@ async function readWriteFileWithStream() {
```
> **NOTE**
->
-> Close the stream that is no longer used in a timely manner. Comply with the related programming specifications for **Stream** APIs in asynchronous mode and avoid mixed use of the APIs in synchronous mode and asynchronous mode. The **Stream** APIs do not support concurrent read and write operations.
+>
+> - Close the stream that is no longer used in a timely manner.
+> - Comply with the programming specifications for **Stream** APIs in asynchronous mode and avoid mixed use of the APIs in synchronous mode and asynchronous mode.
+> - The **Stream** APIs do not support concurrent read and write operations.
### Listing Files
-The following example demonstrates how to list files.
+The following example demonstrates how to list files that meet the specified conditions.
```ts
// List files.
@@ -162,7 +164,7 @@ let options = {
suffix: ['.png', '.jpg', '.txt'], // The filename extension can be '.png', '.jpg', or '.txt'.
displayName: ['test%'], // The filename starts with 'test'.
fileSizeOver: 0, // The file size is greater than or equal to 0.
- lastModifiedAfter: new Date(0).getTime(), // The latest modification time of the file is later than January 1, 1970.
+ lastModifiedAfter: new Date(0).getTime(), // The latest modification time of the file is later than January 1, 1970.
},
}
let files = fs.listFileSync(filesDir, options);
diff --git a/en/application-dev/file-management/app-file-backup-extension.md b/en/application-dev/file-management/app-file-backup-extension.md
index 724f51db698895e006d83b6737889fa6956d7076..005c772600ba3e078b30221d6d0bb711173cbd6a 100644
--- a/en/application-dev/file-management/app-file-backup-extension.md
+++ b/en/application-dev/file-management/app-file-backup-extension.md
@@ -1,19 +1,19 @@
-# Backing Up and Restoring Application Access Data
+# Backup and Restoration Accessed by Applications
-You can use BackupExtensionAbility to implement backup and restoration of application access data.
+You can use BackupExtensionAbility to enable an application to access the backup and restoration framework.
-BackupExtensionAbility is a class derived from the [ExtensionAbility](../application-models/extensionability-overview.md) component in [Stage Model](../../application-dev/application-models/stage-model-development-overview.md). You can modify the configuration file to customize the behavior of the backup and restoration framework, including whether backup and restoration are allowed and which files are backed up.
+BackupExtensionAbility is a class derived from the [ExtensionAbility](../application-models/extensionability-overview.md) component in [Stage Model](../../application-dev/application-models/stage-model-development-overview.md). You can modify the configuration file to customize the backup and restoration framework behavior, including whether to allow backup and restoration and specifying the files to be backed up.
## Constraints
- The paths of all files and directories to be backed up cannot exceed 4095 bytes. Otherwise, undefined behavior may occur.
- If a directory needs to be backed up, the application process must have the permission to read the directory and all its subdirectories (**r** in DAC). Otherwise, the backup fails.
-- If a file needs to be backed up, the application process must have the permission to search for its grandparent directory of the file (**x** in DAC). Otherwise, the backup fails.
+- If a file needs to be backed up, the application process must have the permission to retrieve the grandparent directory of the file (**x** in DAC). Otherwise, the backup fails.
## How to Develop
-1. Add the **extensionAbilities** configuration in the application's **module.json5** file.
+1. Add **extensionAbilities** to the application's **module.json5** file.
- Add **extensionAbilities**, set **type** to **backup**, and add **name: ohos.extension.backup** to **[metadata]**(../../application-dev/reference/apis/js-apis-bundleManager-metadata.md).
+ Add the **extensionAbilities** field, set **type** to **backup**, and add a record with **name** of **ohos. extension. backup** to **[metadata](../../application-dev/reference/apis/js-apis-bundleManager-metadata.md)**.
BackupExtensionAbility configuration example:
@@ -40,7 +40,7 @@ BackupExtensionAbility is a class derived from the [ExtensionAbility](../applica
2. Add a metadata resource configuration file.
- The metadata resource configuration file defines the files to be transferred during backup and restoration. The file name must be the same as the value of **resource** under **metadata** in the **module.json5** file. This file is stored in the **Profile** folder.
+ The metadata resource configuration file defines the files to be transferred during the backup and restoration process. The file is located in the **Profile** folder, and the file name must be the same as the value of **resource** under **metadata** in the **module.json5** file.
Metadata resource configuration file example:
@@ -61,8 +61,8 @@ BackupExtensionAbility is a class derived from the [ExtensionAbility](../applica
| Name | Type | Mandatory| Description |
| -------------------- | ---------- | ---- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| allowToBackupRestore | Boolean | Yes | Whether to allow backup and restoration. The default value is **false**. |
-| includes | String array| No | Files and directories to be backed up in the application sandbox. Each item in the array is a pattern string, which can contain shell-style wildcards such as *****, **?**, and **[**. The pattern string that does not start with a slash (/) indicates a relative path relative to the root path. If **includes** is configured, the backup and restoration framework uses the pattern strings configured. Otherwise, the backup and restoration framework uses the **includes** default value (see the following code segment).|
-| excludes | String array| No | Exception items in **includes** that do not need to be backed up. The value is in the same format as **includes**. If **excludes** is configured, the backup and restoration framework uses the pattern strings configured. Otherwise, the backup and restoration framework uses an empty array as the default value. |
+| includes | String array| No | Files and directories to be backed up in the application sandbox. Each item in the array is a pattern string, which can contain shell-style wildcards such as (`*`, `?`, `[`). The pattern string that does not start with a slash (/) indicates a relative path. If **includes** is configured, the backup and restoration framework uses the pattern strings configured. Otherwise, the backup and restoration framework uses the **includes** default value (see the following code segment).|
+| excludes | String array| No | Items in **includes** that do not need to be backed up. The value is in the same format as **includes**. If **excludes** is configured, the backup and restoration framework uses the pattern strings configured. Otherwise, the backup and restoration framework uses an empty array as the default value. |
**includes** default value:
@@ -77,4 +77,4 @@ BackupExtensionAbility is a class derived from the [ExtensionAbility](../applica
"data/storage/el2/base/haps/*/preferences/",
]
}
-```
+```
\ No newline at end of file
diff --git a/en/application-dev/file-management/app-file-backup-overview.md b/en/application-dev/file-management/app-file-backup-overview.md
index c18cf73bfd407bd7f626edda73cc3b815de6155a..ecfceb9df408b35c5adec20db0b91e186da155b1 100644
--- a/en/application-dev/file-management/app-file-backup-overview.md
+++ b/en/application-dev/file-management/app-file-backup-overview.md
@@ -1,15 +1,15 @@
# Application Data Backup and Restoration Overview
-Application data, such as the configuration and service data, is generated when an application is used. To ensure that user data will not be lost due to operations, such as application updates and hopping, applications need to access data backup and restoration.
+Application data, such as the configuration and service data, is generated when an application is used. To prevent user data against loss due to operations such as application updates and hopping, the application data needs to be backed up and restored.
-Before development, you need to understand the ExtensionAbility component. For details, see [ExtensionAbility Component Overview](../application-models/extensionability-overview.md).
+Before development, you need to understand the [ExtensionAbility](../application-models/extensionability-overview.md) component.
-BackupExtensionAbility is a class derived from ExtensionAbility in the stage model. It provides the capabilities of backing up and restoring application data. It is an extended component without the UI. It runs when a backup or restoration task starts and exits when the task is complete.
+Derived from ExtensionAbility in the stage model, BackupExtensionAbility provides the capabilities of backing up and restoring application data. It is an extended component without the UI. It runs when a backup or restoration task starts and exits when the task is complete.
The implementation includes the following:
-- [Backup and restoration of application access data](app-file-backup-extension.md): All applications can access data backup and restoration. After accessed, the application can modify the configuration file to customize the behavior of the backup and restoration framework, including whether to allow backup and restoration and specifying the data to be backed up.
+- [Backup and restoration accessed by applications](app-file-backup-extension.md): All applications can access the data backup and restoration framework. You can customize the backup and restoration framework behavior for the application, including whether to allow backup and restoration and specifying the data to be backed up, by modifying the application configuration file.
- Applications can perform backup and restoration configurations, but not trigger data backup and restoration.
+ The application itself cannot trigger data backup and restoration.
-- [Backup and restoration of application-triggered data](app-file-backup.md): Only system applications can trigger data backup and restoration. After data backup or restoration is triggered, the backup and restoration framework checks whether each application has accessed data backup and restoration. If yes, the backup and restore framework backs up or restores data based on the application's configuration file.
+- [Backup and restoration triggered by system applications](app-file-backup.md): Only system applications can trigger data backup and restoration. After data backup or restoration is triggered, the backup and restoration framework locates the applications that have accessed the data backup and restoration framework and backs up or restores data based on the application's configuration file.
diff --git a/en/application-dev/file-management/app-file-backup.md b/en/application-dev/file-management/app-file-backup.md
index 991e228e680ad4a0b7e1e23636df52f3996b8452..ccfb8641f4db47a71029c2c4591382081aeb0697 100644
--- a/en/application-dev/file-management/app-file-backup.md
+++ b/en/application-dev/file-management/app-file-backup.md
@@ -1,14 +1,14 @@
-# Backing Up and Restoring Application-triggered Data (for System Applications Only)
+# Backup and Restoration Triggered by System Applications
-The backup and restoration module provides a complete data backup and restoration solution for application data, user data, and system services on devices. You can implement data backup or restoration for applications by performing the following operations:
+The backup and restoration framework provides a complete data backup and restoration solution for application data, user data, and system services on devices. You can follow the procedure below to enable an application to trigger data backup or restoration:
-- [Obtaining the capability file](#obtaining-the-capability-file): Obtain the capability file of all applications of the system user. The capability file is indispensable for data backup and restoration.
+- [Obtain capability files](#obtaining-capability-files): Obtain capability files of all applications of the user in the system. The capability files are indispensable for data backup and restoration.
-- [Backing up application data](#backing-up-application-data): Select the application data to be backed up based on the application information provided by the capability file, and back up the data.
+- [Back up application data](#backing-up-application-data): Back up the application data based on the application information in the capability files.
-- [Restoring application data](#restoring-application-data): Select the application data to be restored based on the application information provided in the capability file and restore the data.
+- [Restore application data](#restoring-application-data): Restore the application data based on the application information in the capability files.
-- [Installing the application during data restoration](#installing-the-application-during-data-restoration): Install the application if the application has not been installed. As an extended function of application data restoration, this function allows the application to be installed on the device before data restoration.
+- [Install the application during data restoration](#installing-the-application-during-data-restoration): Install the application if the application with data to be restored has not been installed. As an extended function of application data restoration, this function allows the application to be installed on the device before data restoration.
## How to Develop
@@ -16,7 +16,7 @@ For details about the APIs to be used, see [Backup and Restoration](../reference
Before using the APIs, you need to:
-1. Apply for the ohos.permission.BACKUP permission. For details, see [Apply for permissions](../security/accesstoken-guidelines.md).
+1. Apply for the **ohos.permission.BACKUP** permission. For details, see [Apply for Permissions](../security/accesstoken-guidelines.md).
2. Import **@ohos.file.backup**.
@@ -24,13 +24,13 @@ Before using the APIs, you need to:
import backup from '@ohos.file.backup';
```
-## Obtaining the Capability File
+## Obtaining Capability Files
-Obtain the application capability file of the current system user. This file is indispensable for application data backup and restoration.
+Obtain capability files of all applications of the current user. The capability files are indispensable for application data backup and restoration.
-This file contains the device type and version and basic application information, such as the application name, application data size, application version, whether to allow backup and restoration, and whether to install the application during restoration.
+The capability file of an application contains the device type, device version, and basic application information, such as the application name, application size, application version, whether to allow backup and restoration, and whether to install the application during restoration.
-Use **backup.getLocalCapabilities()** to obtain the capability file.
+Use **backup.getLocalCapabilities()** to obtain capability files.
```js
import fs from '@ohos.file.fs';
@@ -79,9 +79,9 @@ Use **backup.getLocalCapabilities()** to obtain the capability file.
## Backing Up Application Data
-You need to select the application data to be backed up based on the application information provided by the capability file.
+You can select the application data to be backed up based on the application information in the capability files.
-The Backup & Restore service packages the application data into a file. The file handle is returned by the [onFileReady](../reference/apis/js-apis-file-backup.md#onfileready) callback registered when the instance is created.
+The Backup & Restore service packages the application data to be backed up. The package file handle is returned by the [onFileReady](../reference/apis/js-apis-file-backup.md#onfileready) callback registered when the **SessionBackup** instance is created.
You can save the file to a local directory as required.
@@ -152,9 +152,9 @@ You can save the file to a local directory as required.
## Restoring Application Data
-You can select the application data to be restored based on the application information provided by the capability file.
+You can select the application data to be restored based on the application information in the capability files.
-During the restoration, the Backup and Restore service returns the file handle of the application data to be restored in the [onFileReady](../reference/apis/js-apis-file-backup.md#onfileready) callback registered when the instance is created based on the [getFileHandle](../reference/apis/js-apis-file-backup.md#getfilehandle) called. Then, the data to be restored is written to the file handle based on the [uri](../reference/apis/js-apis-file-backup.md#filemeta) returned. After the data is written, use [publishFile()](../reference/apis/js-apis-file-backup.md#publishfile) to notify the service that the data write is complete.
+The Backup and Restore service returns the file handle of the application data to be restored in the [onFileReady](../reference/apis/js-apis-file-backup.md#onfileready) callback registered when the **SessionRestore** instance is created. The file handle is obtained by [getFileHandle](../reference/apis/js-apis-file-backup.md#getfilehandle). Then, the data to be restored is written to the file handle based on the [uri](../reference/apis/js-apis-file-backup.md#filemeta) returned. After the data is written, use [publishFile()](../reference/apis/js-apis-file-backup.md#publishfile) to notify the service that the data write is complete.
When all the data of the application is ready, the service starts to restore the application data.
@@ -184,7 +184,7 @@ When all the data of the application is ready, the service starts to restore the
}
fs.copyFileSync(bundlePath, file.fd);
fs.closeSync(file.fd);
- // After the data is transferred, notify the server that the file is ready.
+ // After the data is transferred, notify the server that the files are ready.
publishFile(file);
console.info('onFileReady success');
},
@@ -220,11 +220,11 @@ When all the data of the application is ready, the service starts to restore the
"com.example.hiworld",
]
// You can obtain the capability file based on actual situation. The following is an example only.
- // You can also construct a capability file as required.
+ // You can also construct capability files as required.
let fileData = await backup.getLocalCapabilities();
await g_session.appendBundles(fileData.fd, backupApps);
console.info('appendBundles success');
- // After the application to be restored is added, call getFileHandle() to obtain the handle of the application file to be restored based on the application name.
+ // After the applications to be restored are added, call getFileHandle() to obtain the handles of the application files to be restored based on the application name.
// The number of application data files to be restored varies depending on the number of backup files. The following is only an example.
await g_session.getFileHandle({
bundleName: restoreApps[0],
@@ -240,11 +240,11 @@ When all the data of the application is ready, the service starts to restore the
## Installing the Application During Data Restoration
-You can enable the application to be installed before application data restoration. To achieve this purpose, the value of **needToInstall** in **bundleInfos** in the [capability file](#obtaining-the-capability-file) must be **true**.
+If the application has not been installed, you can install the application and then restore the application data. To achieve this purpose, the value of **needToInstall** in **bundleInfos** in the [capability file](#obtaining-capability-files) must be **true**.
> **NOTE**
> - [Application data backup](#backing-up-application-data) does not support backup of the application installation package. Therefore, you need to obtain the application installation package.
-> - To obtain the file handle of the application installation package, call [getFileHandle()](../reference/apis/js-apis-file-backup.md#getfilehandle) with **FileMeta.uri** set to **/data/storage/el2/restore/bundle.hap**. The file handle of the application installation package is returned through the **onFileReady()** callback registered when the instance is created. The returned **File.uri** is **data/storage/el2/restore/bundle.hap**.
+> - To obtain the file handle of an application installation package, call [getFileHandle()](../reference/apis/js-apis-file-backup.md#getfilehandle) with **FileMeta.uri** set to **/data/storage/el2/restore/bundle.hap**. The file handle of the application installation package is returned through the **onFileReady()** callback registered when the instance is created. The returned **File.uri** is **data/storage/el2/restore/bundle.hap**.
**Example**
@@ -277,7 +277,7 @@ You can enable the application to be installed before application data restorati
}
fs.copyFileSync(bundlePath, file.fd);
fs.closeSync(file.fd);
- // After the data is transferred, notify the server that the file is ready.
+ // After the data is transferred, notify the server that the files are ready.
publishFile(file);
console.info('onFileReady success');
},
diff --git a/en/application-dev/file-management/app-file-overview.md b/en/application-dev/file-management/app-file-overview.md
index f3d49fd0c640ca1602575a917c37fc7f97818842..d1176912225ad505bc245889d1e38291156c29e5 100644
--- a/en/application-dev/file-management/app-file-overview.md
+++ b/en/application-dev/file-management/app-file-overview.md
@@ -4,8 +4,8 @@ Application files are files of an application, including the application's insta
- The data used and saved by an application is stored in files, key-value (KV) pairs, and databases in a dedicated directory on a device. This directory is called application file directory, and the files in the directory are application files.
-- The directories visible to an application include the application file directory and a directory containing the minimum system files required for the running of the application. These two directories constitute an [application sandbox directory](app-sandbox-directory.md). That means, the application file directory is a subset of the application sandbox directory.
+- The directories visible to an application include the application file directory and a directory containing the minimum system files required for the running of the application. These two directories constitute an [application sandbox directory](app-sandbox-directory.md). That is, the application file directory is a subset of the application sandbox directory.
- The system files and directories are read-only for the application. The application can only save files to sub-directories in the [application file directory](app-sandbox-directory.md#application-file-directory-and-application-file-path) based on certain rules.
-The following topics describe the application sandbox, application file directories, and how to access, manage, and share application files.
+The following topics describe the application sandbox, application file directories, and how to access, manage, and share application files.
\ No newline at end of file
diff --git a/en/application-dev/file-management/app-file-upload-download.md b/en/application-dev/file-management/app-file-upload-download.md
index a73fc9568cc03e791074866c20dc963b028cdb55..75fb0646cf2dbfa1422209c4d4b9b176e547f749 100644
--- a/en/application-dev/file-management/app-file-upload-download.md
+++ b/en/application-dev/file-management/app-file-upload-download.md
@@ -1,6 +1,6 @@
# Uploading and Downloading an Application File
-This topic describes how to upload an application file to a network server and download a network resource file from a network server to a local application directory.
+This topic describes how to enable an application to upload an application file to a network server and download a network resource file from a network server to a local application directory.
## Uploading an Application File
@@ -10,7 +10,7 @@ You can use [ohos.request](../reference/apis/js-apis-request.md) **uploadFile()*
>
> Currently, only the files in the **cache/** directories (**cacheDir**) can be uploaded.
>
-> The **ohos.permission.INTERNET** permission is required for using **ohos.request**. For details about how to apply for a permission, see [Applying for Permissions](../security/accesstoken-guidelines.md).
+> The **ohos.permission.INTERNET** permission is required for using **ohos.request**. For details about how to apply for a permission, see [Applying for Permissions](../security/accesstoken-guidelines.md).
The following example demonstrates how to upload a file in the **cache** directory of an application to a network server.
@@ -62,13 +62,13 @@ try {
## Downloading a Network Resource File to the Application File Directory
-You can use [ohos.request](../reference/apis/js-apis-request.md) **downloadFile()** to download network resource files to a local application directory. You can use the ([ohos.file.fs](../reference/apis/js-apis-file-fs.md) APIs to access the downloaded files. For details, see [Accessing Application Files](app-file-access.md). The system service proxy implements the download.
+You can use [ohos.request](../reference/apis/js-apis-request.md) **downloadFile()** to download network resource files to a local application directory. You can use the [ohos.file.fs](../reference/apis/js-apis-file-fs.md) APIs to access the downloaded files in the same way as [accessing application files](app-file-access.md). The system service proxy implements the download.
> **NOTE**
>
> Currently, network resource files can be downloaded only to an application file directory.
>
-> The **ohos.permission.INTERNET** permission is required for using **ohos.request**. For details about how to apply for a permission, see [Applying for Permissions](../security/accesstoken-guidelines.md).
+> The **ohos.permission.INTERNET** permission is required for using **ohos.request**. For details about how to apply for a permission, see [Applying for Permissions](../security/accesstoken-guidelines.md).
The following example demonstrates how to download a network resource file to a local application file directory.
diff --git a/en/application-dev/file-management/app-fs-space-statistics.md b/en/application-dev/file-management/app-fs-space-statistics.md
index 9596834a5b5bda14e810061817dcdf55da3aaf3a..74ffbc6c6f39441be0a9c0043389458025bc0c0d 100644
--- a/en/application-dev/file-management/app-fs-space-statistics.md
+++ b/en/application-dev/file-management/app-fs-space-statistics.md
@@ -10,22 +10,22 @@ For details about the APIs, see [ohos.file.statvfs](../reference/apis/js-apis-fi
| Module| API| Description|
| -------- | -------- | -------- |
-| \@ohos.file.storageStatistics | getCurrentBundleStats | Obtains the storage space of the current application, in bytes.|
-| \@ohos.file.statvfs | getFreeSize | Obtains the free space of a file system, in bytes.|
-| \@ohos.file.statvfs | getTotalSize | Obtains the total space of a file system, in bytes.|
+| \@ohos.file.storageStatistics | getCurrentBundleStats | Obtains the storage space of the current application, in bytes.|
+| \@ohos.file.statvfs | getFreeSize | Obtains the free space of a file system, in bytes.|
+| \@ohos.file.statvfs | getTotalSize | Obtains the total space of a file system, in bytes.|
**Table 2** Attributes for application space statistics
-| BundleStats Attribute| Description| Directory for Statistics|
+| BundleStats Attribute| Description| Directory for Statistics|
| -------- | -------- | -------- |
-| appSize | Size of the application installation files, in bytes.| Application installation file directory: **/data/storage/el1/bundle **|
-| cacheSize | Size of the application cache files, in bytes.| Application cache file directories: **/data/storage/el1/base/cache** **/data/storage/el1/base/haps/entry/cache** **/data/storage/el2/base/cache** **/data/storage/el2/base/haps/entry/cache **|
-| dataSize | Size of the application files (excluding the application installation files and cache files), in bytes.| The application files include local files, distributed files, and database files. - Local application file directories (parent directories of the **cache** directories): **/data/storage/el1/base** **/data/storage/el2/base** - Distributed application directory: /data/storage/el2/distributedfiles - Database directories: **/data/storage/el1/database** **/data/storage/el2/database **|
+| appSize | Size of the application installation files, in bytes.| /data/storage/el1/bundle |
+| cacheSize | Size of the application cache files, in bytes.| /data/storage/el1/base/cache /data/storage/el1/base/haps/entry/cache /data/storage/el2/base/cache /data/storage/el2/base/haps/entry/cache |
+| dataSize | Size of the application files (excluding the application installation files and cache files), in bytes.| The application files include local files, distributed files, and database files. - Local application file directories (parent directories of the **cache** directories): **/data/storage/el1/base** **/data/storage/el2/base** - Distributed application directory: **/data/storage/el2/distributedfiles** - Database directories: **/data/storage/el1/database** **/data/storage/el2/database** |
## Development Example
- Obtain the free space of **/data** of the file system.
-
+
```ts
import statvfs from '@ohos.file.statvfs';
@@ -40,7 +40,7 @@ For details about the APIs, see [ohos.file.statvfs](../reference/apis/js-apis-fi
```
- Obtain the space occupied by the current application.
-
+
```ts
import storageStatistics from "@ohos.file.storageStatistics";
diff --git a/en/application-dev/file-management/app-sandbox-directory.md b/en/application-dev/file-management/app-sandbox-directory.md
index 1f012ece997fa09706d01353cbf91dfc80bb945f..66cfb57126c94f406a5696a492afbad58168a923 100644
--- a/en/application-dev/file-management/app-sandbox-directory.md
+++ b/en/application-dev/file-management/app-sandbox-directory.md
@@ -1,29 +1,31 @@
# Application Sandbox Directory
-The application sandbox is an isolation mechanism to prevent data from being accessed through path traversal. This mechanism allows only the application sandbox directory visible to an application.
+The application sandbox is an isolation mechanism used to prevent malicious data access through path traversal. With this mechanism, only the application sandbox directory is visible to an application.
-- The system maps a dedicated application sandbox directory in the internal storage space for each application. The directory is a collection of the [application file directory](app-file-overview.md) and a directory containing the minimum system files required during application's runtime.
+- The system has a dedicated application sandbox directory in the internal storage to map the directory of each application. The application sandbox directory holds [application files](app-file-overview.md) and the minimum system files required for running of the application.
-- The application sandbox specifies the minimum range of data visible to each application. In the application sandbox directory, an application can access only its own application files and the system files required for its running. The application cannot access files of other applications. The security of application files is protected in this way.
+- The application sandbox specifies the minimum data range visible to each application. In the application sandbox directory, an application can access only its own application files and the system files required for its running. The application cannot access files of other applications. This ensures application file security.
-- In each application sandbox directory, the application can save and process its own application files in the [application file directory](app-file-overview.md), and can only read the system files and directories. The application can access [user files](user-file-overview.md) by using specific APIs only with authorization from the user.
+- In each application sandbox directory, the application can save and process its application files in the [application file directory](app-file-overview.md), and can only read the system files and directories. To access [user files](user-file-overview.md), the application need to call specific APIs and have authorization from the user.
-The following figure illustrates the file access scope and modes for an application in an application sandbox.
+The following figure illustrates the file access mechanism in an application sandbox.
+
+**Figure 1** File access mechanism in an application sandbox
-**Figure 1** File access in an application sandbox

## Application Sandbox Directory and Application Sandbox Path
-With the application sandbox mechanism, an application cannot learn the location and existence of other applications' directories and user file directories. In addition, all the application directories visible to an application are isolated by permission and namespace to form an independent directory view and shield the real (physical) paths.
+With the application sandbox mechanism, an application is not aware of the existence and location of other applications' directories and user file directories. Even the application directories visible to an application are isolated by permission and namespace to form an independent directory view and shield the real (physical) paths.
-- As shown in the following figure, the sandbox mechanism minimizes the number of directories and files visible to a common application (third-party application). The directories and file paths visible to a common application are different from those visible to a system process. The path of a file or folder in the application sandbox directory visible to a common application is called the application sandbox path.
+- As shown in the following figure, the sandbox mechanism minimizes the number of directories and files visible to a common application (third-party application). In addition, the directories and file paths visible to a common application are different from those visible to a system process. The path of a file or folder in the application sandbox directory visible to a common application is called the application sandbox path.
- You can view the real application paths (the directory view visible to a system process) in the HDC shell environment. For details about the mappings between the application sandbox paths and real application paths, see [Mappings Between Application Sandbox Paths and Physical Paths](send-file-to-app-sandbox.md#mappings-between-application-sandbox-paths-and-physical-paths).
- The application sandbox paths and physical paths are not in one-to-one mappings. The application sandbox paths are always less than the physical paths. You may not obtain the application sandbox path based on a physical path in certain cases, but you can obtain the physical path based on an application sandbox path.
-**Figure 2** Different directory views to processes and applications
+**Figure 2** Different directory views to processes and applications
+

## Application File Directory and Application File Path
@@ -32,31 +34,33 @@ The application sandbox directory includes application file directories and syst
The system file directories visible to an application are preset by OpenHarmony.
-The following figure shows the application file directories. The path of a file or a folder in the application file directory is called the application file path. The file paths in the application file directory have different attributes and characteristics.
+The following figure shows the application file directories. The path of a file or a folder in the application file directory is called the application file path. The sub-directories in the application file directory have different attributes.
+
+**Figure 3** Application file directory structure
-**Figure 3** Application file directory structure

-1. Level 1 directory **data/**: indicates the application file directory.
+1. Level 1 directory **data/** indicates the application file directory.
-2. Level 2 directory **storage/**: indicates a directory for persistent files of the application.
+2. Level 2 directory **storage/** indicates a directory for persistent files of the application.
-3. Level 3 directories **el1/** and **el2/**: indicate directories for files of different encryption levels (els).
+3. Level 3 directories **el1/** and **el2/** indicate directories for files of different encryption levels (els).
- **el1**: directory for the data that can be accessed once the device starts. This directory contains device-focused files.
- - **el2**: directory for the data that can be accessed only after at lease one successful unlocking operation (by PIN, fingerprint, or facial authentication, or password-free sign-in) upon the start of the device. This directory contains user-focused files.
- Unless otherwise required, application data is placed in the **el2** directory for security purposes. However, the data that needs to be accessed before the screen is unlocked (such as the clock, alarm, and wallpaper data) can be placed in the **el1** directory. For details about how to switch to and modify the **el** directories, see [Obtaining and Modifying el Directories](../application-models/application-context-stage.md#obtaining-and-modifying-encryption-levels).
-
+ - **el2**: directory for the data that can be accessed only after at lease one successful unlock operation (by PIN, fingerprint, or facial authentication, or password-free sign-in) upon the start of the device. This directory contains user-focused files.
+
+ Unless otherwise required, application data is placed in the **el2** directory for security purposes. However, the data that needs to be accessed before the screen is unlocked (such as the clock, alarm, and wallpaper data) can be placed in the **el1** directory. For details about the operations on **el** directories, see [Obtaining and Modifying el Directories](../application-models/application-context-stage.md#obtaining-and-modifying-encryption-levels).
+
4. Level 4 and level 5 directories:
The application's global data is stored in the **files**, **cache**, **preferences**, **temp**, and **distributedfiles** folders in **base**. You can use **ApplicationContext** to obtain the application file paths of these folders.
- You can use **UIAbilityContext**, **AbilityStageContext**, and **ExtensionContext** to obtain application file paths related to the OpenHarmony Ability Package (HAP). When the HAP is uninstalled, the files stored in these directories are automatically deleted, without affecting the files in app-level directories. An application in the development state contains one or more HAPs. For details, see [Application Package Structure in Stage Mode](../quick-start/application-package-structure-stage.md).
+ You can use **UIAbilityContext**, **AbilityStageContext**, and **ExtensionContext** to obtain application file paths related to the OpenHarmony Ability Package (HAP). When the HAP is uninstalled, the files stored in these directories are automatically deleted, without affecting the files in app-level directories. An application in the development state has one or more HAPs. For details, see [Application Package Structure in Stage Mode](../quick-start/application-package-structure-stage.md).
For details about how to obtain the context and application file paths, see [Context (Stage Model)](../application-models/application-context-stage.md).
> **NOTE**
>
- > - Do not directly use file paths made up by level 1 to level 4 directory names. Incompatibility problems may occur if the directory names are changed in later versions.
- > - Use **Context** to obtain application file paths, which include but are not limited to the directories highlighted in green in **Figure 3**.
+ > - Do not use file paths made up by level 1 to level 4 directory names. Incompatibility problems may occur if the directory names are changed in later versions.
+ > - Use **Context** to obtain the application file paths, including but are not limited to the directories highlighted in green in **Figure 3**.
The following table describes the application file paths and lifecycle.
@@ -64,7 +68,7 @@ The following figure shows the application file directories. The path of a file
| Folder| Context Attribute Name| Type| Description|
| -------- | -------- | -------- | -------- |
- | bundle | bundleCodeDir | Installation file directory| Directory for saving the HAPs of the application after an application is installed. This directory is cleared when the application is uninstalled. Do not access resource files by concatenating paths. Use [@ohos.resourceManager](../reference/apis/js-apis-resource-manager.md) instead. |
+ | bundle | bundleCodeDir | Installation file directory| Directory for saving the HAPs after an application is installed. This directory is cleared when the application is uninstalled. Do not access resource files using concatenated paths. Use [@ohos.resourceManager](../reference/apis/js-apis-resource-manager.md) instead.|
| base | NA | Directory for local device files| Directory for saving the application's persistent data on the device. Subdirectories include **files/**, **cache/**, **temp/**, and **haps/**. This directory is cleared when the application is uninstalled.|
| database | databaseDir | Database directory| Directory in **el1** for saving the files operated by the distributed database service. This directory is cleared when the application is uninstalled.|
| distributedfiles | distributedFilesDir | Distributed file directory| Directory in **el2** for saving the application files that can be directly accessed across devices. This directory is cleared when the application is uninstalled.|
@@ -73,7 +77,7 @@ The following figure shows the application file directories. The path of a file
| preferences | preferencesDir | Preferences file directory| Directory for saving common application configuration and user preference data managed by using database APIs. This directory is cleared when the application is uninstalled. For details, see [Persisting Preferences Data](../database/data-persistence-by-preferences.md).|
| temp | tempDir | Temporary file directory| Directory for saving the files generated and required during the application's runtime on the device. This directory is cleared when the application exits.|
- The application file paths are used in the following scenarios:
+ The application scenarios of the application file directories are as follows:
- Installation file directory
Used to store the code resource data of the application, including the HAPs of the application, reusable library files, and plug-ins. The code stored in this directory can be dynamically loaded.
@@ -83,9 +87,9 @@ The following figure shows the application file directories. The path of a file
Used to store the application's data used for distributed scenarios, including file sharing, file backup, and file processing across devices. The data stored in this directory enables the application to run smoothly on multiple devices.
- Application file directory
Used to store private data of the application, including persistent files, images, media files, and log files. The data is stored in this directory to ensure privacy, security, and permanent validity.
- - Cached application file directory
+ - Cache application file directory
Used to store cached data of the application, including offline data, cached images, database backup, and temporary files. Data stored in this directory may be automatically deleted by the system. Therefore, do not store important data in this directory.
- Preferences file directory
Used to store application preferences data, including preference files and configuration files. This directory applied to storing only a small amount of data.
- Temporary file directory
- Used to store temporarily generated data of an application, including cached database data and images, temporary log files, downloaded application installation package files. The data stored in this directory is deleted after being used.
+ Used to store temporarily generated data of an application, including cached database data and images, temporary log files, downloaded application installation package. The data stored in this directory is deleted after being used.
\ No newline at end of file
diff --git a/en/application-dev/file-management/dev-user-file-manager.md b/en/application-dev/file-management/dev-user-file-manager.md
index 26181bb321310d1261ce2b87138b7fd2aa118552..ffcea027cfc56ad761064bd686f06452bc6be390 100644
--- a/en/application-dev/file-management/dev-user-file-manager.md
+++ b/en/application-dev/file-management/dev-user-file-manager.md
@@ -1,23 +1,23 @@
-# Developing a FileManager Application (for System Applications Only)
+# Developing a File Manager Application (for System Applications Only)
-OpenHarmony is prebuilt with the **FileManager** application. You can also develop your own **FileManager** as required.
+OpenHarmony is prebuilt with the **FileManager** application. You can also develop your own file manager application as required.
## Available APIs
-For details about the APIs, see [User File Access and Management](../reference/apis/js-apis-fileAccess.md).
+For details about the APIs used to develop a file manager application, see [User File Access and Management](../reference/apis/js-apis-fileAccess.md).
## How to Develop
-1. Configure the permissions required and import dependent modules.
+1. Apply for permissions required.
Apply for the **ohos.permission.FILE_ACCESS_MANAGER** and **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permissions. For details, see [Applying for Permissions](../security/accesstoken-guidelines.md).
> **NOTE**
>
- > **ohos.permission.FILE_ACCESS_MANAGER** is required for using the user file access framework APIs.
+ > **ohos.permission.FILE_ACCESS_MANAGER** allows your application to use the user file access framework APIs.
>
- > **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** is required for querying information about file management server applications supported by the system.
+ > **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** allows your application to obtain information about file management server applications supported by the system.
-2. Import the dependent modules.
+2. Import dependent modules.
```ts
import fileAccess from '@ohos.file.fileAccess';
@@ -26,8 +26,8 @@ For details about the APIs, see [User File Access and Management](../reference/a
The **fileAccess** module provides APIs for basic file operations, and the **fileExtensionInfo** module provides key structs for application development.
-3. Query device information.
- You can obtain attributes of one or all devices managed by the file management server in the current system. You can also filter devices as required.
+3. Query device information.
+ You can obtain attributes of the devices managed by one or all file management servers in the system. You can also filter devices as required.
In the user file access framework, **RootInfo** indicates the attribute information of a device. For example, obtain **RootInfo** of all devices.
@@ -68,19 +68,19 @@ For details about the APIs, see [User File Access and Management](../reference/a
```
4. View directories.
- In the user file access framework, **FileInfo** indicates basic information about a file (directory). You can use **listfile()** to traverse all files (directories) of the next level to obtain a **FileIterator** object or use **scanfile()** to filter the specified directories and obtain the **FileIterator** object that meets the conditions.
+ In the user file access framework, **FileInfo** indicates basic information about a file (directory). You can use **listfile()** to obtain a **FileIterator** object that traverses all files (directories) of the next level or use **scanfile()** to obtain a **FileIterator** object that meets the specified conditions.
- Currently, **listfile()** and **scanfile()** can be called by the **RootInfo** object to traverse lower-level files or filter the entire directory tree. In addition, **listfile()** and **scanfile()** can be called by the **FileInfo** object to traverse lower-level files or filter specified directories.
+ Currently, **listfile()** and **scanfile()** can be called by the **RootInfo** object to traverse the next-level files or filter the entire directory tree. In addition, **listfile()** and **scanfile()** can be called by the **FileInfo** object to traverse the next-level files or filter the specified directories.
```ts
// Start from the root directory.
let rootInfo = rootinfos[0];
let fileInfos = [];
let isDone = false;
- let filter = {suffix: [".txt", ".jpg", ".xlsx"]}; // Set filter criteria.
+ let filter = {suffix: [".txt", ".jpg", ".xlsx"]}; // Set filter criteria.
try {
let fileIterator = rootInfo.listFile(); // Traverse the root directory of rootinfos[0] and return an iterator object.
- // let fileIterator = rootInfo.scanFile(filter); // Filter the file information of device rootinfos[0] that meets the specified conditions and return an iteration object.
+ // let fileIterator = rootInfo.scanFile(filter); // Filter device rootinfos[0] files that meet the specified conditions and return an iteration object.
if (!fileIterator) {
console.error("listFile interface returns an undefined object");
return;
@@ -97,12 +97,12 @@ For details about the APIs, see [User File Access and Management](../reference/a
}
// Start from the specified directory.
- let fileInfoDir = fileInfos[0]; // fileInfoDir indicates information about a directory.
+ let fileInfoDir = fileInfos[0]; // fileInfoDir indicates information about a directory.
let subFileInfos = [];
let isDone = false;
- let filter = {suffix: [".txt", ".jpg", ".xlsx"]}; // Set filter criteria.
+ let filter = {suffix: [".txt", ".jpg", ".xlsx"]}; // Set filter criteria.
try {
- let fileIterator = fileInfoDir.listFile(); // Traverse files in the specified directory and return an iterator object.
+ let fileIterator = fileInfoDir.listFile(); // Traverse files in the specified directory and return an iterator object.
// let fileIterator = rootInfo.scanFile(filter); // Filter the files in the specified directory and return an iterator object.
if (!fileIterator) {
console.error("listFile interface returns an undefined object");
diff --git a/en/application-dev/file-management/distributed-fs-overview.md b/en/application-dev/file-management/distributed-fs-overview.md
index aaa8235b947033ab95905aa1e393bc6fd78d622f..43bd19ff7ff4f1e90a5ea975c0247a666edf43b5 100644
--- a/en/application-dev/file-management/distributed-fs-overview.md
+++ b/en/application-dev/file-management/distributed-fs-overview.md
@@ -1,12 +1,12 @@
# Distributed File System Overview
-OpenHarmony distributed file system (hmdfs) provides cross-device file access capabilities applicable to the following scenarios:
+OpenHarmony distributed file system (hmdfs) provides cross-device file access capabilities in the following scenarios:
-- The user can use the editing software on one device to edit the files on another device.
+- The user uses the editing software on one device to edit the files on another device.
-- Music stored on a tablet can be directly viewed and played by a in-car system.
+- Music stored on a tablet can be directly viewed and played by an in-car system.
-- The user can use a tablet to view the photos taken by another device.
+- The user uses a tablet to view the photos taken by another device.
The hmdfs provides a globally consistent access view for each device dynamically connected to a network via DSoftBus and allows you to implement high-performance read and write operations on files with low latency by using basic file system APIs.
@@ -16,13 +16,13 @@ The hmdfs provides a globally consistent access view for each device dynamically
- distributedfile_daemon: listens for device online status, establishes links over DSoftBus, and applies data transfer policies based on the security level of the device.
-- hmdfs: implements a network file system in the kernel, providing cache management, file access, metadata management, and conflict management.
- - Buffer management
- - After devices are connected to form a Virtual Device, hmdfs provides file access capabilities, but does not proactively transmit or copy files. Active copy is required when an application needs to save data to a local directory.
+- hmdfs: implements a network file system in the kernel and provides cache management, file access, metadata management, and conflict management.
+ - Cache management
+ - After devices are connected to form a Virtual Device, the hmdfs provides file access capabilities, but does not proactively transmit or copy files. Active copy is required when an application needs to save data to a local directory.
- The hmdfs ensures close-to-open cache consistency, which allows data to flushed when a client closes a file. Then, the latest data can be read when the file is opened on any other client. The hmdfs does not ensure real-time consistency of the file content.
- - If data written at the peer end has not been flushed to the local end in a timely manner due to network problems, the file system flushes the data to the local end upon the next network access. However, if the data has been modified on the remote end, only the latest data can be flushed.
+ - If data written at the remote end has not been flushed to the local end in a timely manner due to network problems, the file system flushes the data to the local end upon the next network access. However, if the data has been modified on the remote end, only the latest data can be flushed.
- File access
- - OpenHarmony provides the same interface, [ohos.file.fs](../reference/apis/js-apis-file-fs.md), for accessing files in the local and distributed file systems.
+ - OpenHarmony provides the unified [ohos.file.fs](../reference/apis/js-apis-file-fs.md) for accessing files in the local and distributed file systems.
- The files in the local file system are accessed in overlay mode.
- The files on another device are accessed over a synchronous network.
> **NOTE**
@@ -31,9 +31,9 @@ The hmdfs provides a globally consistent access view for each device dynamically
- Metadata management
- In distributed networking, when a file is created, deleted, or modified on a client, the latest file can be viewed on another client. The speed varies depending on the network status.
- If a device goes offline, its data is no longer visible to other devices. However, due to the delay in sensing the device offline, the files of some offline devices may also be visible to other devices. Therefore, you need to consider the network delay in application development.
- - Conflict Handling
- - If a file on the local end and a file on the remote end have the same name, the file on the remote end will be renamed.
- - If multiple remote devices have files of the same name, the name of the file with the smallest device access ID is retained and the files on other devices will be renamed.
- - In the networking scenario, the directory tree has remote files. If "duplicate file name" is displayed when a file is created,
- - the conflict file is renamed "_conflict_dev_ID". The ID automatically increases from 1.
- - If a local directory has the same name as a remote directory, "_remote_directory" will be added to the end of the peer directory.
+ - Conflict management
+ - If a file name conflict occurs on the local and remote devices, the file on the remote device is renamed.
+ - If a file name conflict occurs between multiple remote devices, the name of the file with the smallest device access ID is retained and the files on other devices are renamed.
+ - If the directory tree already has remote files in networking scenario, a file with duplicate file name cannot be created successfully.
+ - The conflict files are renamed in "_conflict_dev_ID" format. The IDs automatically increment from 1.
+ - If a local directory and a remote directory have the same name, it does not yield a conflict. If the two directories have files with the same name, "_remote_directory" is added to the end of the remote directory.
diff --git a/en/application-dev/file-management/file-access-across-devices.md b/en/application-dev/file-management/file-access-across-devices.md
index 840078f5f982d55a9d9a3713fafa49d632d352f8..1fefd8c41154597235e718b77309f34c94a36778 100644
--- a/en/application-dev/file-management/file-access-across-devices.md
+++ b/en/application-dev/file-management/file-access-across-devices.md
@@ -1,16 +1,20 @@
-# Accessing Files Across Devices
+# Access Files Across Devices
-The distributed file system provides cross-device file access capabilities for applications. For the same application installed on multiple devices, you can implement read and write of the files in the application's distributed directory (**/data/storage/el2/distributedfiles/**) across devices by using [ohos.file.fs](app-file-access.md). For example, device A and device B are installed with the same application. After device A and device B are connected to form a Virtual Device, the application on device A can access the files of the same application on Device B. What you need to do is place the files to the distributed directory.
+The distributed file system provides cross-device file access capabilities for applications. For the same application installed on multiple devices that form a Super Device, you can use [ohos.file.fs](app-file-access.md) APIs to implement read and write of the files in the application's distributed directory (**/data/storage/el2/distributedfiles/**).
-## How to Develop
+For example, device A and device B are installed with the same application. After device A and device B are connected to form a Super Device, the application on device A can access the files in the distributed directory of the same application on Device B.
-1. Complete distributed networking for the devices.
- Connect the devices to a LAN, and complete authentication of the devices. The devices must have the same account number.
+## How to Develop
+1. Connect the devices to form a Super Device.
+
+Connect the devices to a LAN, and complete authentication of the devices. The devices must have the same account number.
+
2. Implement cross-device access to the files of the same application.
+
Place the files in the **distributedfiles/** directory of the application sandbox to implement access from difference devices.
- For example, create a test file in the **distributedfiles/** directory on device A and write data to the file. For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
+ For example, create a file in the **distributedfiles/** directory on device A and write data to the file. For details about how to obtain the application context, see [Obtaining the Context of UIAbility](../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
```ts
import fs from '@ohos.file.fs';
diff --git a/en/application-dev/file-management/file-management-overview.md b/en/application-dev/file-management/file-management-overview.md
index 2fbd4b4a036de1f20f8aa64825ab1dcb60f23414..50248aaf0dc767cb8be20b20114a2bf398167378 100644
--- a/en/application-dev/file-management/file-management-overview.md
+++ b/en/application-dev/file-management/file-management-overview.md
@@ -2,23 +2,23 @@
The data in an operating system (OS) can be classified into the following types based on the data structure:
-- Structured data: data that can be defined in a unified data model. The structured data is generally stored in a database. In application development, the management of structured data is implemented by the [data management module](../database/data-mgmt-overview.md).
+- Structured data: data that can be defined in a unified data model and is generally stored in a database. In OpenHarmony application development, the management of structured data is implemented by the [data management module](../database/data-mgmt-overview.md).
-- Unstructured data: data that does not conform to any predefined data structure or model and cannot be easily presented in two-dimensional database tables. Unstructured data includes files in a variety of formats, such as documents, images, videos, and audio clips. In application development, the management of unstructured data is implemented by the file management module, which will be elaborated in this document.
+- Unstructured data: data that does not conform to any predefined data structure or model and cannot be easily presented in two-dimensional database tables. Unstructured data includes files in a variety of formats, such as documents, images, videos, and audio clips. In OpenHarmony application development, the management of unstructured data is implemented by the file management module, which will be elaborated in this document.
In the file management module, the files can be classified into the following types based on the file owner:
-- [Application files](app-file-overview.md): files of an application, including the application's installation files, resource files, and cached files.
+- [Application files](app-file-overview.md): files of an application, including the installation files, resource files, and cache files of the application.
-- [User files](user-file-overview.md): files of a user who logs in to the device, including the user's images, video and audio clips, and documents.
+- [User files](user-file-overview.md): files of a user who has logged in to the device. User files include the user's images, video and audio clips, and documents.
-- System files: files irrelevant to applications and users, including public libraries, device files, and system resource files. System files do not need to be managed by developers and are not described in this document.
+- System files: files irrelevant to applications and users. System files include public libraries, device files, and system resource files. The system files do not need to be managed by developers and are not described in this document.
The file systems can be classified into the following types based on the file storage location (data source location):
-- Local file system: provides capabilities for accessing the files stored on a local device or its external storage devices (such as USB flash drives and removable hard drives). The local file system is the most basic file system and is not described in this document.
+- Local file system: allows access to the files stored on a device and its external storage devices (such as USB flash drives and removable hard drives). The local file system is the most basic file system and is not described in this document.
-- [Distributed file system](distributed-fs-overview.md): provides capabilities for accessing files across devices, which are connected through a computer network.
+- [Distributed file system](distributed-fs-overview.md): allows access to files across devices, which include not only the local device and its external storage devices, but also the devices connected over a computer network.
**Figure 1** Files in an OS
diff --git a/en/application-dev/file-management/manage-external-storage.md b/en/application-dev/file-management/manage-external-storage.md
index bd5c01712cb48d6b8ac151b67a5b747967882870..b26a17455725e769f41cf1eb2cdc6d214ee3a0e9 100644
--- a/en/application-dev/file-management/manage-external-storage.md
+++ b/en/application-dev/file-management/manage-external-storage.md
@@ -1,8 +1,8 @@
# Managing External Storage Devices (for System Applications Only)
-External storage devices are pluggable. OpenHarmony provides the functions of listening for the device insertion and removal events and mounting/unmounting an external storage device.
+Because external storage devices are pluggable, OpenHarmony provides functions for listening for the device insertion/removal events and mounting/unmounting an external storage device.
-External storage devices are managed by the StorageManager and StorageDaemon services. StorageDaemon implements the underlying listening and mount/unmount functions. StorageManager provides status change notifications, query, and management capabilities for system applications.
+External storage devices are managed by the StorageManager and StorageDaemon services. StorageDaemon implements underlying listening and mount/unmount functions. StorageManager provides status change notifications and query and management of external storage devices for system applications.
**Figure 1** External storage device management
@@ -10,12 +10,12 @@ External storage devices are managed by the StorageManager and StorageDaemon ser
- When an external storage device is inserted, the StorageDaemon process obtains an insertion event over netlink and creates a disk device and volume. The created volume is in the **UNMOUNTED** state.
-- Then, the StorageDaemon process checks the volume. During the check process, the volume is in the **CHECKING** state.
+- Then, the StorageDaemon process checks the volume. The volume transits to the **CHECKING** state.
- The StorageDaemon process mounts the volume if the check is successful. If the mount operation is successful, the volume state changes to **MOUNTED** and StorageManager is instructed to send the COMMON_EVENT_VOLUME_MOUNTED broadcast.
- If the check fails, the volume state changes to **UNMOUNTED**.
- For a volume in the **MOUNTED** state:
- - If the device is directly removed, the volume information will be deleted and COMMON_EVENT_VOLUME_BAD_REMOVAL is broadcast.
+ - If the device is directly removed, the volume information is deleted and COMMON_EVENT_VOLUME_BAD_REMOVAL is broadcast.
- If the user chooses **Eject device**, the volume state changes to **EJECTING** and the COMMON_EVENT_VOLUME_EJECT is broadcast. After StorageDaemon unmounts the volume, the volume state changes to **UNMOUNTED** and COMMON_EVENT_VOLUME_UNMOUNTED is broadcast.
- For a volume in the **UNMOUNTED** state, removing the device will delete the volume information and broadcast COMMON_EVENT_VOLUME_REMOVED.
@@ -38,13 +38,13 @@ The following table describes the broadcast related parameters.
## How to Develop
-Subscribe to broadcast events to notify the insertion and removal of external storage devices. The volumes can be queried and managed based on the volume information obtained from the broadcast.
+You can subscribe to broadcast events to observe the insertion and removal of external storage devices, and query or manage volumes based on the volume information obtained from the broadcast.
-1. Apply for permissions.
+1. Apply for permissions.
Apply for the **ohos.permission.STORAGE_MANAGER** permission for subscribing to volume broadcast events. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
-2. Subscribe to broadcast events.
- Subscribe to the following events:
+2. Subscribe to broadcast events.
+ You can subscribe to the following events:
- "usual.event.data.VOLUME_REMOVED": The device is removed.
- "usual.event.data.VOLUME_UNMOUNTED": The volume is unmounted.
@@ -68,7 +68,7 @@ Subscribe to broadcast events to notify the insertion and removal of external st
let subscriber = await CommonEvent.createSubscriber(subscribeInfo);
```
-3. Obtain the volume information from the broadcast.
+3. Obtain volume information from the broadcast.
```ts
CommonEvent.subscribe(subscriber, function (err, data) {
diff --git a/en/application-dev/file-management/photoAccessHelper-notify-guidelines.md b/en/application-dev/file-management/photoAccessHelper-notify-guidelines.md
index 6e85789e72b92b991a654482a232100017cc0cbd..b5a7f381053593a806b40d2214a5bb4777a1b83d 100644
--- a/en/application-dev/file-management/photoAccessHelper-notify-guidelines.md
+++ b/en/application-dev/file-management/photoAccessHelper-notify-guidelines.md
@@ -1,11 +1,11 @@
-# Media Asset (Image, Video, and Album) Change Notification Management
+# Managing Media Asset Change Notifications
-The **photoAccessHelper** module provides APIs for listening for media asset changes.
+The **photoAccessHelper** module provides APIs for listening for media asset (image, video, and album) changes.
> **NOTE**
>
-> Before you start, refer to [photoAccessHelper Overview](photoAccessHelper-overview.md) to learn how to obtain a **photoAccessHelper** instance and apply for permissions required.
-> By default, the **photoAccessHelper** instance obtained in [photoAccessHelper Overview](photoAccessHelper-overview.md) is used when **photoAccessHelper** APIs are used. If the code for obtaining the **photoAccessHelper** instance is not added, an error indicating that **photoAccessHelper** is not defined is reported.
+> Before you start, you need to obtain a **PhotoAccessHelper** instance and apply for required permissions. For details, see [photoAccessHelper Overview](photoAccessHelper-overview.md).
+> By default, the **PhotoAccessHelper** instance obtained in [photoAccessHelper Overview](photoAccessHelper-overview.md) is used when **photoAccessHelper** APIs are used. If the code for obtaining the **PhotoAccessHelper** instance is not added, an error indicating that **photoAccessHelper** is not defined is reported.
The APIs related to media asset change notifications can be called asynchronously only in callback mode. This topic describes how to use some APIs. For more information about the APIs, see [Album Management](../reference/apis/js-apis-photoAccessHelper.md).
Unless otherwise specified, all the media assets to be obtained in this document exist in the database. If no media asset is obtained when the sample code is executed, check whether the media assets exist in the database.
@@ -16,14 +16,14 @@ Use [registerChange](../reference/apis/js-apis-photoAccessHelper.md#registerchan
### Registering a Listener for a File Asset
-Registers a listener for the specified file asset. When the observed file asset changes, the listener callback will be invoked to return the change.
+Register a listener for the specified file asset. When the observed file asset changes, the listener callback will be invoked to return the change.
**Prerequisites**
-- A **photoAccessHelper** instance is obtained.
+- A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions.
-Example: Register a listener for an image. When the image is favorited, the listener callback will be invoked.
+Example: Listener for changes of an image. When the image is favorited, the listener callback will be invoked.
**How to Develop**
@@ -60,18 +60,18 @@ try {
### Registering a Listener for an Album
-Registers a listener for an album. When the observed album changes, the listener callback will be invoked to return the change.
+Register a listener for an album. When the observed album changes, the listener callback will be invoked to return the change.
**Prerequisites**
-- A **photoAccessHelper** instance is obtained.
+- A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions.
-Example: Register a listener for a user album. When the album is renamed, the listener callback will be invoked.
+Example: Listener for a user album. When the album is renamed, the listener callback will be invoked.
**How to Develop**
-1. [Obtain the user album](photoAccessHelper-userAlbum-guidelines.md#obtaining-a-use-album].
+1. [Obtain a user album](photoAccessHelper-userAlbum-guidelines.md#obtaining-a-user-album).
2. Register a listener for the user album.
3. Rename the user album.
@@ -106,24 +106,30 @@ try {
## Fuzzy Listening
-You can set **forChildUris** to **true** to register fuzzy listening. When **uri** is an album URI, the value **true** of **forChildUris** listens for the changes of the files in the album, and the value **false** listens for only the changes of the album itself. If **uri** is the URI of a **fileAsset**, there is no difference between **true** and **false** for **forChildUris**. If **uri** is **DefaultChangeUri**, **forChildUris** must be set to **true**. If **forChildUris** is **false**, the URI cannot be found and no message can be received.
+You can set **forChildUris** to **true** to enable fuzzy listening.
-### Registering a Listener for All FileAssets
+If **uri** is an album URI, the value **true** of **forChildUris** enables listening for the changes of the files in the album, and the value **false** enables listening for only the changes of the album itself.
-Register listening for all FileAssets. When an observed FileAsset changes, the listener callback will be invoked.
+If **uri** is the URI of a file asset, there is no difference between **true** and **false** for **forChildUris**.
+
+If **uri** is **DefaultChangeUri**, **forChildUris** must be set to **true**. If **forChildUris** is **false**, the URI cannot be found and no notification can be received.
+
+### Registering a Listener for All File Assets
+
+Register listening for all file assets. When an observed file asset changes, the listener callback will be invoked.
**Prerequisites**
-- A **photoAccessHelper** instance is obtained.
+- A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions.
-Example: Register a listener for all FileAssets. When an observed FileAsset is favorited, the listener callback will be invoked.
+Example: Register a listener for all file assets. When an observed file asset is favorited, the listener callback will be invoked.
**How to Develop**
-1. Register a listener for all FileAssets.
+1. Register a listener for all file assets.
2. [Obtain a media asset](photoAccessHelper-resource-guidelines.md#obtaining-the-specified-media-assets).
-3. Add the media asset obtained to **Favorites**.
+3. Add the obtained media asset to **Favorites**.
```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
@@ -150,22 +156,22 @@ try {
}
```
-## Unregistering the Listening for a URI
+## Unregistering Listening for a URI
Use [unRegisterChange](../reference/apis/js-apis-photoAccessHelper.md#unregisterchange) to unregister the listening for the specified URI. Multiple listeners can be registered for a URI. If multiple listener callbacks exist, you can unregister a listener callback registered. If callback is not specified, all listeners of the URI will be unregistered.
**Prerequisites**
-- A **photoAccessHelper** instance is obtained.
+- A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions.
-Example: Unregister the listening for an image. After that, the corresponding listener callback is not triggered when the image favorites status is changed.
+Example: Unregister listening for an image. After that, the unregistered listener callback will not be invoked when the image favorite status is changed.
**How to Develop**
1. [Obtain a media asset](photoAccessHelper-resource-guidelines.md#obtaining-the-specified-media-assets).
-2. Unregister the listening for the URI of the media asset obtained.
-3. Add the media asset obtained to **Favorites**.
+2. Unregister listening for the URI of the media asset obtained.
+3. Add the obtained media asset to **Favorites**.
```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
diff --git a/en/application-dev/file-management/photoAccessHelper-overview.md b/en/application-dev/file-management/photoAccessHelper-overview.md
index 48bb753cf4c1b5d10132c4bb1b12e7cf9290fd4c..8c66669b4e5992b1a23dd60e9c5f3ae4fe5fc5f0 100644
--- a/en/application-dev/file-management/photoAccessHelper-overview.md
+++ b/en/application-dev/file-management/photoAccessHelper-overview.md
@@ -1,14 +1,14 @@
# PhotoAccessHelper Overview
-**PhotoAccessHelper** provides album management capabilities, including creating and accessing an album and accessing and modifying media data in albums. You can use the APIs provided by **PhotoAccessHelper** to manage:
+**PhotoAccessHelper** provides album management capabilities, including creating and accessing an album and accessing and modifying media data in albums. You can use the APIs provided by **PhotoAccessHelper** to:
-- [Media assets (images and videos)](photoAccessHelper-resource-guidelines.md), including:
+- [Manage media assets (images and videos)](photoAccessHelper-resource-guidelines.md), including:
- Obtaining the specified media assets.
- - Obtaining an image or video thumbnail.
+ - Obtaining image and video thumbnails.
- Creating a media asset.
- Renaming a media asset.
- Moving a media asset to the trash.
-- [User Albums](photoAccessHelper-userAlbum-guidelines.md), including:
+- [Manage user albums](photoAccessHelper-userAlbum-guidelines.md), including:
- Creating a user album.
- Obtaining a user album.
- Renaming a user album.
@@ -16,39 +16,38 @@
- Obtaining images and videos from a user album.
- Removing images and videos from a user album.
- Deleting a user album.
-- [System albums](photoAccessHelper-systemAlbum-guidelines.md), including:
+- [Manage system albums](photoAccessHelper-systemAlbum-guidelines.md), including:
- Favorites
- - Video album
- - Screenshot album
-- [Media asset (image, video, and album) change notifications](photoAccessHelper-notify-guidelines.md), including:
- - Registering listening for a specified URI.
- - Unregistering the listening for a specified URI.
+ - Videos
+ - Screenshots
+- [Manage media asset (image, video, and album) change notifications](photoAccessHelper-notify-guidelines.md), including:
+ - Registering listening for the specified URI.
+ - Unregistering the listening for the specified URI.
> **NOTE**
->
-> The **PhotoAccessHelper** development guides apply only to API version 10 based on the stage model.
+> This development guide applies only to API version 10 based on the stage model.
-An application needs to obtain a **photoAccessHelper** instance before accessing and modifying the media data in an album. User personal data is involved in the **photoAccessHelper** module. Therefore, the application needs to apply for the related read and write permissions. Unless otherwise specified, the APIs of the **photoAccessHelper** module apply to **pages/index.ets** of the project or other customized .ets files by default.
+An application needs to obtain a **PhotoAccessHelper** instance before accessing and modifying the media data in an album. User personal data is involved in the **photoAccessHelper** module. Therefore, the application needs to apply for the related read and write permissions. Unless otherwise specified, the APIs of the **photoAccessHelper** module are used in **pages/index.ets** of the project or other customized .ets files by default.
Before using the **PhotoAccessHelper** APIs, you need to:
-- [Obtain a **photoAccessHelper** instance.](#obtaining-a-photoaccesshelper-instance)
-- [Apply for permissions.](#applying-for-permissions)
+- [Obtain a **PhotoAccessHelper** instance](#obtaining-a-photoaccesshelper-instance).
+- [Apply for permissions](#applying-for-permissions).
-## Obtaining a photoAccessHelper Instance
+## Obtaining a PhotoAccessHelper Instance
-The application needs to call [getPhotoAccessHelper](../reference/apis/js-apis-photoAccessHelper.md#photoaccesshelpergetphotoaccesshelper) to obtain a **photoAccessHelper** instance based on the application context. The instance obtained can be used to access or modify the media data (such as image and videos) in an album.
+The application needs to call [getPhotoAccessHelper](../reference/apis/js-apis-photoAccessHelper.md#photoaccesshelpergetphotoaccesshelper) to obtain a **PhotoAccessHelper** instance based on the application context. The instance obtained can be used to access or modify the media data (such as images and videos) in an album.
**How to Develop**
1. Import the **photoAccessHelper** module.
2. Use **getContext** to obtain the application context.
-3. Obtain a **photoAccessHelper** instance.
+3. Obtain a **PhotoAccessHelper** instance.
```ts
import photoAccessHelper from '@ohos.file.photoAccessHelper';
-// The phAccessHelper instance obtained here is a global object. By default, the object obtained here is used in subsequent operations. If the code is not added, an undefined error will be reported.
+// The phAccessHelper instance obtained here is a global object. By default, the object obtained here is used in subsequent operations in this document. If an undefined error is reported, add the code snippet here.
const context = getContext(this);
let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
```
@@ -59,16 +58,16 @@ Before applying for permission, ensure that the [basic principles for permission
| Permission | Description | Authorization Mode |
| ------------------------------ | ------------------------------------------ | ---------- |
-| ohos.permission.READ_IMAGEVIDEO | Allows an app to read image and video file information from a user's external storage.| user_grant |
-| ohos.permission.WRITE_IMAGEVIDEO | Allows an app to read and write image and video file information on a user's external storage.| user_grant |
+| ohos.permission.READ_IMAGEVIDEO | Allows an application to read image and video file information from a user's external storage.| user_grant |
+| ohos.permission.WRITE_IMAGEVIDEO | Allows an application to read and write image and video file information on a user's external storage.| user_grant |
-The required permissions must be authorized by the user (user_grant). You need to add the permissions in the **module.json5** file, and use [abilityAccessCtrl.requestPermissionsFromUser](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) to check whether the required permissions are granted by the user. If yes, the application can access the data. Otherwise, a dialog box will be displayed to request user authorization.
+The required permissions must be authorized by the user (user_grant). After adding the permissions in the **module.json5** file, use [abilityAccessCtrl.requestPermissionsFromUser](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) to check whether the required permissions are granted by the user. If yes, the application can access the data. Otherwise, a dialog box will be displayed to request user authorization.
> **NOTE** Even if the user has granted the permission, the permission will still be checked before an API protected by the permission is called. The permission granted status should not be persisted, because the user can revoke the permission through the system application **Settings**.
**How to Develop**
-1. Declare the permissions in the **module.json5** file. Add **requestPermissions** under **module** in the file, and add the required permissions. For details, see [Applying for Permissions](../security/accesstoken-guidelines.md).
+1. Declare the required permissions in the **module.json5** file. Add **requestPermissions** under **module** in the file, and add the required permissions. For details, see [Applying for Permissions](../security/accesstoken-guidelines.md).
```json
{
@@ -99,7 +98,7 @@ The required permissions must be authorized by the user (user_grant). You need t
}
```
-2. Call **requestPermissionsFromUser** in the **onWindowStageCreate** callback of **Ability.ts** to check for the required permissions. If the permissions are not granted, display a dialog box to request user authorization dynamically.
+2. Call **requestPermissionsFromUser** in the **onWindowStageCreate** callback of **Ability.ts** to check the required permissions. If the permissions are not granted, display a dialog box to request user authorization dynamically.
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
diff --git a/en/application-dev/file-management/photoAccessHelper-resource-guidelines.md b/en/application-dev/file-management/photoAccessHelper-resource-guidelines.md
index 4934fca1c911c104c04f47f16505f989b5d1ba3a..a0557bcb2c264b2e1a641e489d2f62bf50deaf54 100644
--- a/en/application-dev/file-management/photoAccessHelper-resource-guidelines.md
+++ b/en/application-dev/file-management/photoAccessHelper-resource-guidelines.md
@@ -1,17 +1,17 @@
-# Media Asset Management
+# Managing Media Assets
Applications can call **photoAccessHelper** APIs to manage media assets (images and videos).
> **NOTE**
>
-> Before you start, refer to [photoAccessHelper Overview](photoAccessHelper-overview.md) to learn how to obtain a **photoAccessHelper** instance and apply for permissions required.
-> By default, the **photoAccessHelper** instance obtained in [photoAccessHelper Overview](photoAccessHelper-overview.md) is used when **photoAccessHelper** APIs are used. If the code for obtaining the **photoAccessHelper** instance is not added, an error indicating that **photoAccessHelper** is not defined is reported.
+> Before you start, you need to obtain a **PhotoAccessHelper** instance and apply for required permissions. For details, see [photoAccessHelper Overview](photoAccessHelper-overview.md).
+> By default, the **PhotoAccessHelper** instance obtained in [photoAccessHelper Overview](photoAccessHelper-overview.md) is used when **photoAccessHelper** APIs are used. If the code for obtaining the **PhotoAccessHelper** instance is not added, an error indicating that **photoAccessHelper** is not defined is reported.
-To ensure application running efficiency, most **PhotoAccessHelper** calls are asynchronous in callback or promise mode. The following code samples use promise-based APIs. For details about the APIs, see [Album Management](../reference/apis/js-apis-photoAccessHelper.md).
+To ensure application running efficiency, most **photoAccessHelper** APIs are asynchronously implemented in callback or promise mode. The following code samples use promise-based APIs. For details about the APIs, see [Album Management](../reference/apis/js-apis-photoAccessHelper.md).
## Obtaining the Specified Media Assets
-You can query media assets by media type, date, or album name.
+You can obtain media assets by media type, date, or album name.
Use [PhotoAccessHelper.getAssets](../reference/apis/js-apis-photoAccessHelper.md#getassets) with the [FetchOptions](../reference/apis/js-apis-photoAccessHelper.md#fetchoptions) object to specify search criteria. Unless otherwise specified, all the media assets to be obtained in this document exist in the database. If no media asset is obtained when the sample code is executed, check whether the media assets exist in the database.
@@ -19,7 +19,7 @@ To obtain the object at the specified position (for example, the first, the last
**Prerequisites**
-- A **photoAccessHelper** instance is obtained.
+- A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** permission.
- The [dataSharePredicates](../reference/apis/js-apis-data-dataSharePredicates.md) module is imported.
@@ -29,7 +29,7 @@ Example: Obtain the image **test.jpg**.
**How to Develop**
-Create a **FetchOptions** object and specify **test.jpg**.
+1. Create a **FetchOptions** object and specify **test.jpg**.
```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
@@ -42,7 +42,7 @@ let fetchOptions = {
};
```
-Call **PhotoAccessHelper.getAssets** to obtain image assets.
+2. Call **PhotoAccessHelper.getAssets** to obtain image assets.
```ts
try {
@@ -55,7 +55,7 @@ try {
}
```
-### Obtaining an Image or Video Asset by URI
+### Obtaining an Image or Video by URI
Example: Obtain the image with the file URI **file://media/Photo/1**.
@@ -86,7 +86,7 @@ try {
### Obtaining Images or Videos by Time
-Example: Obtain the media assets added from 2022-06-01 to 2023-06-01.
+Example: Obtain the media assets added between 2022-06-01 and 2023-06-01.
```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
@@ -96,7 +96,7 @@ let startTime = Date.parse(new Date('2022-06-01').toString()) / 1000; // The val
let endTime = Date.parse(new Date('2023-06-01').toString()) / 1000; // The value of the end time is the number of seconds elapsed since the Epoch time.
let date_added = photoAccessHelper.PhotoKeys.DATE_ADDED;
predicates.between(date_added, startTime, endTime);
-predicates.orderByDesc(date_added); // The query results are sorted in descending order.
+predicates.orderByDesc(date_added); // Sort the obtained records in descending order.
let fetchOptions = {
fetchColumns: [date_added], // The date_added attribute is not a default option and needs to be added.
predicates: predicates
@@ -123,7 +123,7 @@ Use [FileAsset.getThumbnail](../reference/apis/js-apis-photoAccessHelper.md#gett
**Prerequisites**
-- A **photoAccessHelper** instance is obtained.
+- A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** permission.
- The [dataSharePredicates](../reference/apis/js-apis-data-dataSharePredicates.md) module is imported.
@@ -169,10 +169,10 @@ Use [createAsset](../reference/apis/js-apis-photoAccessHelper.md#createasset) to
**Prerequisites**
-- A **photoAccessHelper** instance is obtained.
+- A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.WRITE_IMAGEVIDEO** permission.
-### Creating an Image or Video Asset
+### Creating an Image or Video
Example: Create an image asset.
@@ -197,15 +197,15 @@ try {
## Renaming a Media Asset
+Before renaming a file, use [FetchResult](../reference/apis/js-apis-photoAccessHelper.md#fetchresult) to obtain the file.
+
Set the **FileAsset.displayName** attribute to modify the file name (including the file name extension) displayed.
After the modification, use [FileAsset.commitModify](../reference/apis/js-apis-photoAccessHelper.md#commitmodify) to update the modification to the database.
-Before renaming a file, use [FetchResult](../reference/apis/js-apis-photoAccessHelper.md#fetchresult) to obtain the file.
-
**Prerequisites**
-- A **photoAccessHelper** instance is obtained.
+- A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.WRITE_IMAGEVIDEO** and **ohos.permission.READ_IMAGEVIDEO** permissions.
Example: Rename the first file in the obtained image assets.
@@ -246,11 +246,11 @@ try {
You can use [deleteAssets](../reference/apis/js-apis-photoAccessHelper.md#deleteassets) to move files to the trash.
-The files moved to the trash will be retained for 30 days, and deleted permanently after 30 days. Before a file is deleted permanently from the trash, the user can restore it using the system application **File Manager** or **Gallery**.
+The files moved to the trash will be retained for 30 days, and deleted permanently after 30 days. Before a file is deleted permanently from the trash, the user can restore it using the system application **FileManager** or **Gallery**.
**Prerequisites**
-- A **photoAccessHelper** instance is obtained.
+- A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.WRITE_IMAGEVIDEO** and **ohos.permission.READ_IMAGEVIDEO** permissions.
Example: Move the first file in the result set to the trash.
diff --git a/en/application-dev/file-management/photoAccessHelper-systemAlbum-guidelines.md b/en/application-dev/file-management/photoAccessHelper-systemAlbum-guidelines.md
index c88fc6536d5119a1bb6e994c4abd41270bc2d78a..e42d7bab28aa84d141bcc4fe385618bfd16114ca 100644
--- a/en/application-dev/file-management/photoAccessHelper-systemAlbum-guidelines.md
+++ b/en/application-dev/file-management/photoAccessHelper-systemAlbum-guidelines.md
@@ -1,18 +1,18 @@
-# System Album Management
+# Managing System Albums
-The **photoAccessHelper** module provides APIs for managing system albums, including the **Favorites**, video album, and screenshot album.
+The **photoAccessHelper** module provides APIs for managing system albums, including the **Favorites**, **Videos**, **Screenshots**.
> **NOTE**
>
-> Before you start, refer to [photoAccessHelper Overview](photoAccessHelper-overview.md) to learn how to obtain a **photoAccessHelper** instance and apply for permissions required.
-> By default, the **PhotoAccessHelper** instance obtained in [photoAccessHelper Overview](photoAccessHelper-overview.md) is used when **PhotoAccessHelper** APIs are used. If the code for obtaining the **PhotoAccessHelper** instance is not added, an error indicating that **PhotoAccessHelper** is not defined is reported.
+> Before you start, you need to obtain a **PhotoAccessHelper** instance and apply for required permissions. For details, see [photoAccessHelper Overview](photoAccessHelper-overview.md).
+> By default, the **PhotoAccessHelper** instance obtained in [photoAccessHelper Overview](photoAccessHelper-overview.md) is used when **photoAccessHelper** APIs are used. If the code for obtaining the **PhotoAccessHelper** instance is not added, an error indicating that **PhotoAccessHelper** is not defined is reported.
-To ensure application running efficiency, most **photoAccessHelper** calls are asynchronous in callback or promise mode. The following code samples use promise-based APIs. For details about the APIs, see [Album Management](../reference/apis/js-apis-photoAccessHelper.md).
+To ensure application running efficiency, most **photoAccessHelper** APIs are asynchronously implemented in callback or promise mode. The following code samples use promise-based APIs. For details about the APIs, see [Album Management](../reference/apis/js-apis-photoAccessHelper.md).
Unless otherwise specified, all the media assets to be obtained in this document exist in the database. If no media asset is obtained when the sample code is executed, check whether the media assets exist in the database.
## Favorites
-The **Favorites** is a system album. When you favorite a photo or video, the photo or video is added to **Favorites**. When you favorite a photo or video, the photo or video is removed from **Favorites**.
+**Favorites** is a system album. Favoriting a photo or video adds the photo or video to **Favorites**; unfavoriting a photo or video removes the photo or video from **Favorites**.
### Obtaining a Favorites Object
@@ -20,7 +20,7 @@ Use [getAlbums](../reference/apis/js-apis-photoAccessHelper.md#getalbums) to obt
**Prerequisites**
-- A **photoAccessHelper** instance is obtained.
+- A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** permission.
**How to Develop**
@@ -41,11 +41,11 @@ try {
### Favoriting an Image or Video
-Use [setFavorite](../reference/apis/js-apis-photoAccessHelper.md#setfavorite) to add images or videos to **Favorites**.
+Use [setFavorite](../reference/apis/js-apis-photoAccessHelper.md#setfavorite) to add an image or video to **Favorites**.
**Prerequisites**
-- A **photoAccessHelper** instance is obtained.
+- A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions.
Example: Favorite an image.
@@ -54,7 +54,7 @@ Example: Favorite an image.
1. [Obtain media assets](photoAccessHelper-resource-guidelines.md#obtaining-the-specified-media-assets).
2. Set **favoriteState** to **true** to favorite the image.
-3. Use **FileAsset.setFavorite** to add the image to **Favorites**.
+3. Call **FileAsset.setFavorite** to add the image to **Favorites**.
```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
@@ -83,7 +83,7 @@ try {
**Prerequisites**
-- A **photoAccessHelper** instance is obtained.
+- A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** permission.
Example: Obtain an image from **Favorites**.
@@ -121,20 +121,20 @@ try {
### Unfavoriting an Image or Video
-Use [setFavorite](../reference/apis/js-apis-photoAccessHelper.md#setfavorite) to remove an image or video from **Favorites**.
+Use [setFavorite](../reference/apis/js-apis-photoAccessHelper.md#setfavorite) to remove images or videos from **Favorites**.
**Prerequisites**
-- A **photoAccessHelper** instance is obtained.
+- A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions.
Example: Unfavorite an image.
**How to Develop**
-1. [Obtain the image and videos in **Favorites**](#obtaining-images-and-videos-in-favorites).
+1. [Obtain the images and videos in **Favorites**](#obtaining-images-and-videos-in-favorites).
2. Set **favoriteState** to **false**.
-3. Use **FileAsset.setFavorite** to remove the image from **Favorites**.
+3. Call **FileAsset.setFavorite** to unfavorite an image or video.
```ts
@@ -163,9 +163,9 @@ try {
}
```
-## Video Album
+## Videos
-The video album is a system album. The media assets of the video type in user files are automatically added to the video album.
+**Videos** is a system album that holds media assets of the video type in user files.
### Obtaining a Video Album Object
@@ -173,7 +173,7 @@ Use [getAlbums](../reference/apis/js-apis-photoAccessHelper.md#getalbums) to obt
**Prerequisites**
-- A **photoAccessHelper** instance is obtained.
+- A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** permission.
**How to Develop**
@@ -192,16 +192,16 @@ try {
}
```
-### Obtaining Videos from the Video Album
+### Obtaining a Video from Videos
-[Obtain a video album object](#obtaining-a-video-album-object). Use [Album.getAssets](../reference/apis/js-apis-photoAccessHelper.md#getassets-2) to obtain video assets in the video album.
+[Obtain a video album object](#obtaining-a-video-album-object), and use [Album.getAssets](../reference/apis/js-apis-photoAccessHelper.md#getassets-2) to obtain video assets in **Videos**.
**Prerequisites**
-- A **photoAccessHelper** instance is obtained.
+- A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** permission.
-Example: Obtain a video in the video album.
+Example: Obtain a video in **Videos**.
**How to Develop**
@@ -234,17 +234,17 @@ try {
}
```
-## Screenshot Album
+## Screenshots
-The screenshot album is a system album. The user's screenshots and screen recording files are automatically added to this album.
+**Screenshots** is a system album that holds user's screenshots and screen recording files.
### Obtaining a Screenshot Album Object
-Use [getAlbums](../reference/apis/js-apis-photoAccessHelper.md#getalbums) to obtain a screenshot album.
+Use [getAlbums](../reference/apis/js-apis-photoAccessHelper.md#getalbums) to obtain a screenshot album object.
**Prerequisites**
-- A **photoAccessHelper** instance is obtained.
+- A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** permission.
**How to Develop**
@@ -263,16 +263,16 @@ try {
}
```
-### Obtaining Media Assets in the Screenshot Album
+### Obtaining Media Assets in Screenshots
[Obtain a screenshot album object](#obtaining-a-screenshot-album-object), and call [Album.getAssets](../reference/apis/js-apis-photoAccessHelper.md#getassets-2) to obtain the media assets in the album.
**Prerequisites**
-- A **photoAccessHelper** instance is obtained.
+- A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** permission.
-Example: Obtain a media asset from the screenshot album.
+Example: Obtain a media asset from **Screenshots**.
**How to Develop**
diff --git a/en/application-dev/file-management/photoAccessHelper-userAlbum-guidelines.md b/en/application-dev/file-management/photoAccessHelper-userAlbum-guidelines.md
index 57bed20da0011c46f9172a87c121adc5f5c37f41..87d0fa3517e1ca3fcc6e4e494b5e0bcff229b80a 100644
--- a/en/application-dev/file-management/photoAccessHelper-userAlbum-guidelines.md
+++ b/en/application-dev/file-management/photoAccessHelper-userAlbum-guidelines.md
@@ -1,13 +1,13 @@
-# User Album Management
+# Managing User Albums
The **photoAccessHelper** module provides APIs for user album management, including creating or deleting a user album, adding images and videos to a user album, and deleting image and videos from a user album.
> **NOTE**
>
-> Before you start, refer to [photoAccessHelper Overview](photoAccessHelper-overview.md) to learn how to obtain a **photoAccessHelper** instance and apply for permissions required.
-> By default, the **photoAccessHelper** instance obtained in [photoAccessHelper Overview](photoAccessHelper-overview.md) is used when **photoAccessHelper** APIs are used. If the code for obtaining the **photoAccessHelper** instance is not added, an error indicating that **photoAccessHelper** is not defined is reported.
+> Before you start, you need to obtain a **PhotoAccessHelper** instance and apply for required permissions. For details, see [photoAccessHelper Overview](photoAccessHelper-overview.md).
+> By default, the **PhotoAccessHelper** instance obtained in [photoAccessHelper Overview](photoAccessHelper-overview.md) is used when **photoAccessHelper** APIs are used. If the code for obtaining the **PhotoAccessHelper** instance is not added, an error indicating that **photoAccessHelper** is not defined is reported.
-To ensure application running efficiency, most **PhotoAccessHelper** calls are asynchronous in callback or promise mode. The following code samples use promise-based APIs. For details about the APIs, see [Album Management](../reference/apis/js-apis-photoAccessHelper.md).
+To ensure application running efficiency, most **photoAccessHelper** APIs are asynchronously implemented in callback or promise mode. The following code samples use promise-based APIs. For details about the APIs, see [Album Management](../reference/apis/js-apis-photoAccessHelper.md).
Unless otherwise specified, all the media assets to be obtained in this document exist in the database. If no media asset is obtained when the sample code is executed, check whether the media assets exist in the database.
## Creating a User Album
@@ -23,14 +23,14 @@ The album name must meet the following requirements:
**Prerequisites**
-- A **photoAccessHelper** instance is obtained.
+- A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.WRITE_IMAGEVIDEO** permission.
Example: Create a user album.
**How to Develop**
-1. Set the name of the album to create.
+1. Set the name of the album.
2. Use **createAlbum** to create an album.
```ts
@@ -49,10 +49,10 @@ Use [getAlbums](../reference/apis/js-apis-photoAccessHelper.md#getalbums) to obt
**Prerequisites**
-- A **photoAccessHelper** instance is obtained.
+- A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** permission.
-Example: Obtain a user album named **albumName**.
+Example: Obtain the user album named **albumName**.
**How to Develop**
@@ -83,17 +83,15 @@ try {
## Renaming a User Album
-Modify the **Albums.albumName** attribute of the album,
+Modify the **Albums.albumName** attribute of the album, and use [Album.commitModify](../reference/apis/js-apis-photoAccessHelper.md#commitmodify-2) to update the modification to the database.
-and use [Album.commitModify](../reference/apis/js-apis-photoAccessHelper.md#commitmodify-2) to update the modification to the database.
-
-Before renaming a user album, you need to obtain an album object. You can use the [FetchResult](../reference/apis/js-apis-photoAccessHelper.md#fetchresult) APIs to obtain the user album of the corresponding location.
+Before renaming a user album, you need to obtain an album object. You can use the [FetchResult](../reference/apis/js-apis-photoAccessHelper.md#fetchresult) APIs to obtain the user album of the specified location.
The new user album names must also comply with the user name requirements in [Creating a User Album](#creating-a-user-album).
**Prerequisites**
-- A **photoAccessHelper** instance is obtained.
+- A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions.
Example: Rename an album named **albumName**.
@@ -104,7 +102,7 @@ Example: Rename an album named **albumName**.
2. Call **getAlbums** to obtain user albums.
3. Call [FetchResult.getFirstObject](../reference/apis/js-apis-photoAccessHelper.md#getfirstobject) to obtain the first user album.
4. Set a new album name.
-5. Call **Album.commitModify** to update the modified album attributes to the database.
+5. Call **Album.commitModify** to update the new album name to the database.
```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
@@ -129,16 +127,16 @@ try {
}
```
-## Adding Images and Videos to a User Album
+## Adding Images or Videos to a User Album
-[Obtain a user album](#obtaining-a-user-album) and the array of the images or videos to be added to the album, and then call [Album.addAssets](../reference/apis/js-apis-photoAccessHelper.md#addassets) to add the images or videos to the user album.
+[Obtain the user album](#obtaining-a-user-album) and the images or videos to be added to the album, and then call [Album.addAssets](../reference/apis/js-apis-photoAccessHelper.md#addassets) to add the images or videos to the user album.
**Prerequisites**
-- A **photoAccessHelper** instance is obtained.
+- A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions.
-Example: Add an image to the album named **albumName**.
+Example: Add an image to the album **albumName**.
**How to Develop**
@@ -184,14 +182,14 @@ try {
## Obtaining Images and Videos in a User Album
-[Obtain the user album](#obtaining-a-user-album) object, and call [Album.getAssets](../reference/apis/js-apis-photoAccessHelper.md#getassets-2) to obtain the media assets in the user album.
+[Obtain the user album](#obtaining-a-user-album), and call [Album.getAssets](../reference/apis/js-apis-photoAccessHelper.md#getassets-2) to obtain the media assets in the user album.
**Prerequisites**
-- A **photoAccessHelper** instance is obtained.
+- A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions.
-Example: Obtain an image in a user album named **albumName**.
+Example: Obtain an image in the user album **albumName**.
**How to Develop**
@@ -235,13 +233,13 @@ try {
## Removing Images and Videos from a User Album
-[Obtain the user album](#obtaining-a-user-album) object, and call [Album.getAssets](../reference/apis/js-apis-photoAccessHelper.md#getassets-2) to obtain the media assets in the user album.
+[Obtain the user album](#obtaining-a-user-album), and call [Album.getAssets](../reference/apis/js-apis-photoAccessHelper.md#getassets-2) to obtain the media assets in the user album.
-Use [Album.removeAssets](../reference/apis/js-apis-photoAccessHelper.md#removeassets) to remove the specified images.
+Use [Album.removeAssets](../reference/apis/js-apis-photoAccessHelper.md#removeassets) to remove the specified media assets.
**Prerequisites**
-- A **photoAccessHelper** instance is obtained.
+- A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions.
Example: Remove an image from the album named **albumName**.
@@ -290,11 +288,11 @@ try {
## Deleting a User Album
-[Obtain the user album](#obtaining-a-user-album) object, and call [deleteAlbums](../reference/apis/js-apis-photoAccessHelper.md#deletealbums) to delete the user album.
+[Obtain the user album](##obtaining-a-user-album), and call [deleteAlbums](../reference/apis/js-apis-photoAccessHelper.md#deletealbums) to delete the user album.
**Prerequisites**
-- A **photoAccessHelper** instance is obtained.
+- A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions.
Example: Delete a user album named **albumName**.
diff --git a/en/application-dev/file-management/save-user-file.md b/en/application-dev/file-management/save-user-file.md
index f0fadf5b62dd836c7d2c2f1508c8f0828ced86e9..a5cc3306c680ec9f5d1463de940e1844c5692a19 100644
--- a/en/application-dev/file-management/save-user-file.md
+++ b/en/application-dev/file-management/save-user-file.md
@@ -2,9 +2,9 @@
When a user needs to download a file from the network to a local directory or save a user file into another directory, use **FilePicker** to save the file.
-The operations for saving images, audio or video clips, and documents are similar. Call **save()** of the corresponding picker instance and pass in **saveOptions**. No permission is required if **FilePicker** is used to access files.
+The operations for saving images, audio or video clips, and documents are similar. Call **save()** of the corresponding picker instance and pass in **saveOptions**. No permission is required if your application uses **FilePicker** to access files.
-The **save()** method saves the file in the file manager, not in the Gallery.
+The **save()** method saves files in the file manager, not in **Gallery**.
## Saving Images or Video Files
@@ -53,9 +53,9 @@ For example, select an image from **Gallery** and save it to the file manager.
}
```
-3. Create a **photoViewPicker** instance and call [save()](../reference/apis/js-apis-file-picker.md#save) to open the **FilePicker** page to save the image. After the user selects the target folder, the file saving operation is complete. After the image is saved successfully, the URI of the saved image is returned.
+3. Create a **photoViewPicker** instance and call [save()](../reference/apis/js-apis-file-picker.md#save) to open the **FilePicker** page to save the image. After the user selects the destination folder, the image is saved and the URI of the saved image is returned.
- The permission on the URI returned by **save()** is read/write. Further operations can be performed based on the URI in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
+ The permission on the URI returned by **save()** is read/write. Further operations on the file can be performed based on the URI in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
```ts
let uri:string;
@@ -81,9 +81,9 @@ For example, select an image from **Gallery** and save it to the file manager.
}
```
-4. Use a button to trigger invocation of other functions. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_WRITE**.
+4. After the UI is returned from the **FilePicker** page, use a button to trigger API calling. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_WRITE**.
- Use [fs.write](../reference/apis/js-apis-file-fs.md#fswrite) to edit and modify the file based on the FD. After the modification is complete, close the FD.
+ Then, use [fs.write](../reference/apis/js-apis-file-fs.md#fswrite) to modify the file based on the FD, and close the FD after the modification is complete.
```ts
async writeOnly(uri) {
@@ -100,7 +100,7 @@ For example, select an image from **Gallery** and save it to the file manager.
## Saving Documents
-1. Import the **picker** module and **fs** module.
+1. Import the **picker** and **fs** modules.
```ts
import picker from '@ohos.file.picker';
@@ -111,12 +111,12 @@ For example, select an image from **Gallery** and save it to the file manager.
```ts
const documentSaveOptions = new picker.DocumentSaveOptions(); // Create a documentSaveOptions instance.
- documentSaveOptions.newFileNames = ["DocumentViewPicker01.txt"]; // (Optional) Set the names of the documents to save.
+ documentSaveOptions.newFileNames = ["DocumentViewPicker01.txt"]; // (Optional) Set the name of the document to save.
```
-3. Create a **documentViewPicker** instance, and call [save()](../reference/apis/js-apis-file-picker.md#save-3) to open the **FilePicker** page to save the documents. After the user selects the target folder, the file saving operation is complete. After the files are saved successfully, the URIs of the files saved are returned.
+3. Create a **documentViewPicker** instance, and call [save()](../reference/apis/js-apis-file-picker.md#save-3) to open the **FilePicker** page to save the document. After the user selects the destination folder, the document is saved and the URI of the document saved is returned.
- The permission on the URIs returned by **save()** is read/write. Further file operations can be performed based on the URIs in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
+ The permission on the URI returned by **save()** is read/write. Further operations on the file can be performed based on the URI in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
```ts
let uri = null;
@@ -129,14 +129,14 @@ For example, select an image from **Gallery** and save it to the file manager.
})
```
-4. Use a button to trigger invocation of other functions. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_WRITE**.
+4. After the UI is returned from the **FilePicker** page, use a button to trigger API calling. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_WRITE**.
```ts
let file = fs.openSync(uri, fs.OpenMode.READ_WRITE);
console.info('file fd: ' + file.fd);
```
-5. Use [fs.writeSync()](../reference/apis/js-apis-file-fs.md#writesync) to edit the file based on the FD, and then close the FD.
+5. Use [fs.writeSync()](../reference/apis/js-apis-file-fs.md#writesync) to edit the document based on the FD, and then close the FD.
```ts
let writeLen = fs.writeSync(file.fd, 'hello, world');
@@ -146,7 +146,7 @@ For example, select an image from **Gallery** and save it to the file manager.
## Saving Audio Files
-1. Import the **picker** module and **fs** module.
+1. Import the **picker** and **fs** modules.
```ts
import picker from '@ohos.file.picker';
@@ -157,12 +157,12 @@ For example, select an image from **Gallery** and save it to the file manager.
```ts
const audioSaveOptions = new picker.AudioSaveOptions(); // Create an audioSaveOptions instance.
- audioSaveOptions.newFileNames = ['AudioViewPicker01.mp3']; // (Optional) Set the names of the files to save.
+ audioSaveOptions.newFileNames = ['AudioViewPicker01.mp3']; // (Optional) Set the name of the audio file to save.
```
-3. Create an **audioViewPicker** instance, and call [save()](../reference/apis/js-apis-file-picker.md#save-6) to open the **FilePicker** page to save the files. After the user selects the target folder, the file saving operation is complete. After the files are saved successfully, the URIs of the files saved are returned.
+3. Create an **audioViewPicker** instance, and call [save()](../reference/apis/js-apis-file-picker.md#save-6) to open the **FilePicker** page to save the file. After the user selects the destination folder, the audio file is saved and the URI of the file saved is returned.
- The permission on the URIs returned by **save()** is read/write. Further file operations can be performed based on the URIs in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
+ The permission on the URI returned by **save()** is read/write. Further operations on the file can be performed based on the URI in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
```ts
let uri = null;
@@ -175,7 +175,7 @@ For example, select an image from **Gallery** and save it to the file manager.
})
```
-4. Use a button to trigger invocation of other functions. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_WRITE**.
+4. After the UI is returned from the **FilePicker** page, use a button to trigger API calling. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_WRITE**.
```ts
let file = fs.openSync(uri, fs.OpenMode.READ_WRITE);
diff --git a/en/application-dev/file-management/select-user-file.md b/en/application-dev/file-management/select-user-file.md
index af4bae83b13b50eb64e0063012dcaea4a51234bd..041d20f308e47b7757de53a4735958e54bba6f2e 100644
--- a/en/application-dev/file-management/select-user-file.md
+++ b/en/application-dev/file-management/select-user-file.md
@@ -1,18 +1,18 @@
# Selecting User Files
-If your application needs to support share and saving of user files (such as images and videos), you can use OpenHarmony [FilePicker](../reference/apis/js-apis-file-picker.md) to implement selection and saving of user files.
+If your application needs to support share and saving of user files (such as images and videos), you can use OpenHarmony [FilePicker](../reference/apis/js-apis-file-picker.md) to implement selection and saving of user files. No permission is required if your application uses **FilePicker** to access files.
The **FilePicker** provides the following interfaces by file type:
-- [**PhotoViewPicker**](../reference/apis/js-apis-file-picker.md#photoviewpicker): used to select and save images or video files.
+- [PhotoViewPicker](../reference/apis/js-apis-file-picker.md#photoviewpicker): used to select and save images or video files.
-- [**DocumentViewPicker**](../reference/apis/js-apis-file-picker.md#documentviewpicker): used to select and save documents.
+- [DocumentViewPicker](../reference/apis/js-apis-file-picker.md#documentviewpicker): used to select and save documents.
-- [**AudioViewPicker**](../reference/apis/js-apis-file-picker.md#audioviewpicker): used to select and save audio files.
+- [AudioViewPicker](../reference/apis/js-apis-file-picker.md#audioviewpicker): used to select and save audio files.
## Selecting Images or Video Files
-1. Import the **picker** module and **fs** module.
+1. Import the **picker** and **fs** modules.
```ts
import picker from '@ohos.file.picker';
@@ -25,8 +25,8 @@ The **FilePicker** provides the following interfaces by file type:
const photoSelectOptions = new picker.PhotoSelectOptions();
```
-3. Set the file type and the maximum number of media files to select.
- For example, select a maximum of five images. For details about the media file type, see [PhotoViewMIMETypes](../reference/apis/js-apis-file-picker.md#photoviewmimetypes).
+3. Set the file type and the maximum number of media files to select.
+ For example, select a maximum of five images. For details about the media file types, see [PhotoViewMIMETypes](../reference/apis/js-apis-file-picker.md#photoviewmimetypes).
```ts
photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE; // Select images.
@@ -48,14 +48,14 @@ The **FilePicker** provides the following interfaces by file type:
})
```
-5. Use a button to trigger invocation of other functions. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_ONLY**.
+5. After the UI is returned from the **FilePicker** page, use a button to trigger API calling. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the file descriptor (FD). Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_ONLY**.
```ts
let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
console.info('file fd: ' + file.fd);
```
-6. Use [fs.readSync()](../reference/apis/js-apis-file-fs.md#readsync) to read the file data based on the FD. After the data is read, close the FD.
+6. Use [fs.readSync()](../reference/apis/js-apis-file-fs.md#readsync) to read the file based on the FD. After the data is read, close the FD.
```ts
let buffer = new ArrayBuffer(4096);
@@ -66,7 +66,7 @@ The **FilePicker** provides the following interfaces by file type:
## Selecting Documents
-1. Import the **picker** module and **fs** module.
+1. Import the **picker** and **fs** modules.
```ts
import picker from '@ohos.file.picker';
@@ -83,7 +83,7 @@ The **FilePicker** provides the following interfaces by file type:
The permission on the URIs returned by **select()** is read-only. Further file operations can be performed based on the URIs in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
- For example, you can use [file management APIs](../reference/apis/js-apis-file-fs.md) to obtain file attribute information, such as the file size, access time, and last modification time, based on the URI. If you need to obtain the file name, use [startAbilityForResult](../../application-dev/application-models/uiability-intra-device-interaction.md).
+ For example, you can use [file management APIs](../reference/apis/js-apis-file-fs.md) to obtain file attributes, such as the file size, access time, and last modification time, based on the URI. If you need to obtain the file name, use [startAbilityForResult](../../application-dev/application-models/uiability-intra-device-interaction.md).
> **NOTE**
>
@@ -102,7 +102,7 @@ The **FilePicker** provides the following interfaces by file type:
> **NOTE**
>
- > Currently, **DocumentSelectOptions** does not provide the method for obtaining the file name. To obtain the file name, use **startAbilityForResult()**.
+ > Currently, **DocumentSelectOptions** cannot be used to obtain the file name. To obtain the file name, use **startAbilityForResult()**.
```ts
let config = {
@@ -126,14 +126,14 @@ The **FilePicker** provides the following interfaces by file type:
}
```
-4. Use a button to trigger invocation of other functions. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_ONLY**.
+4. After the UI is returned from the **FilePicker** page, use a button to trigger API calling. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_ONLY**.
```ts
let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
console.info('file fd: ' + file.fd);
```
-5. Use [fs.readSync()](../reference/apis/js-apis-file-fs.md#readsync) to read the file data based on the FD. After the data is read, close the FD.
+5. Use [fs.readSync()](../reference/apis/js-apis-file-fs.md#readsync) to read the file based on the FD. After the data is read, close the FD.
```ts
let buffer = new ArrayBuffer(4096);
@@ -143,9 +143,9 @@ The **FilePicker** provides the following interfaces by file type:
```
-## Selecting an Audio File
+## Selecting Audio Files
-1. Import the **picker** module and **fs** module.
+1. Import the **picker** and **fs** modules.
```ts
import picker from '@ohos.file.picker';
@@ -179,14 +179,14 @@ The **FilePicker** provides the following interfaces by file type:
})
```
-4. Use a button to trigger invocation of other functions. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_ONLY**.
+4. After the UI is returned from the **FilePicker** page, use a button to trigger API calling. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_ONLY**.
```ts
let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
console.info('file fd: ' + file.fd);
```
-5. Use [fs.readSync()](../reference/apis/js-apis-file-fs.md#readsync) to read the file data based on the FD. After the data is read, close the FD.
+5. Use [fs.readSync()](../reference/apis/js-apis-file-fs.md#readsync) to read the file based on the FD. After the data is read, close the FD.
```ts
let buffer = new ArrayBuffer(4096);
diff --git a/en/application-dev/file-management/send-file-to-app-sandbox.md b/en/application-dev/file-management/send-file-to-app-sandbox.md
index fdcee889e0ce2a8c51fb9db66a0c1d3e414a0d1b..af3dde8be74d5f2ddc40d2f78672d5801a09ec89 100644
--- a/en/application-dev/file-management/send-file-to-app-sandbox.md
+++ b/en/application-dev/file-management/send-file-to-app-sandbox.md
@@ -1,10 +1,10 @@
-# Sending Files to an Application Sandbox
+# Pushing Files to an Application Sandbox
-During the development and debugging process of an application, you may need to place some files to the application sandbox for intra-application access or for testing purposes. In this case, you can use either of the following methods:
+During the development and debugging process of an application, you may need to push files to the application sandbox for intra-application access or for testing purposes. In this case, you can use either of the following methods:
-1. Use DevEco Studio to place the files to the application installation directory. For details, see [Application Installation Resource Access](../quick-start/resource-categories-and-access.md# resource-access).
+- Use DevEco Studio to push the files to the application installation directory. For details, see [Application Installation Resource Access](../quick-start/resource-categories-and-access.md#resource-access).
-2. Use the hdc tool to send files to the application sandbox directory on the device. This section describes the second method.
+- Use the hdc tool to push files to the application sandbox directory on the device. This section describes the second method.
However, the file directories visible to the debugged process in the hdc shell are different from the application sandbox directories visible to the application. You need to understand the mappings between the application sandbox directories and the physical (real) directories.
@@ -27,15 +27,15 @@ The read and write operations performed based on the application sandbox paths v
The following uses the application bundle **com.ohos.example** as an example. If the application sandbox path is **/data/storage/el1/bundle**, the physical path is **/data/app/el1/bundle/public/**, that is, **/data/app/el1/bundle/public/com.ohos.example**.
-Run the following command to send the file:
+Run the following command to push files:
```
-hdc file send ${Path of the local file to send} /data/app/el1/bundle/public/com.ohos.example/
+hdc file send ${Path of the local files to send} /data/app/el1/bundle/public/com.ohos.example/
```
## Switching to the Application View
-During the debugging process, if you do not have the permission or the file does not exist, you need to switch from the process view to the application view and further analyze permission and directory problems. To switch to the application view, run the following commands:
+During the debugging process, if the required permission is unavailable or the file does not exist, you need to switch from the process view to the application view and further analyze permission and directory problems. To switch to the application view, run the following commands:
```
hdc shell // Switch to shell.
diff --git a/en/application-dev/file-management/set-security-label.md b/en/application-dev/file-management/set-security-label.md
index af819fba397d47f81b0ebe005e67f9e6c8ebef39..2bf82ab58daa28d82b3c9a7ec2c38162a6ad210c 100644
--- a/en/application-dev/file-management/set-security-label.md
+++ b/en/application-dev/file-management/set-security-label.md
@@ -1,6 +1,6 @@
# Setting the Security Level of a Distributed File
-The security capabilities vary with devices. For example, small embedded devices provide fewer security capabilities than tablets. The security requirements also vary with data. For example, personal health information and bank card information are not expected to be accessed by devices of lower security levels. OpenHarmony provides a complete set of standards for data and device classification and custom data transfer policies for different devices. For details, see [Data Security Labels and Device Security Levels](../database/access-control-by-device-and-data-level.md).
+The security capabilities vary with devices. For example, small embedded devices provide fewer security capabilities than tablets. The security requirements also vary with data. For example, personal health information and bank card information are not expected to be accessed by devices of lower security levels. OpenHarmony provides a complete set of data and device classification standards and custom data transfer policies for different devices. For details, see [Access Control by Device and Data Level](../database/access-control-by-device-and-data-level.md).
## Available APIs
@@ -8,26 +8,26 @@ For details about the APIs, see [ohos.file.securityLabel](../reference/apis/js-a
**Table 1** APIs
-| API| Description| Type| Synchronous Programming| Asynchronous Programming|
+| API| Description| Type| Synchronous Programming| Asynchronous Programming|
| -------- | -------- | -------- | -------- | -------- |
-| setSecurityLabel | Sets a security label for a file.| Method| √ | √ |
-| getSecurityLabel | Obtains the security label of a file.| Method| √ | √ |
+| setSecurityLabel | Sets a security label for a file.| Method| √ | √ |
+| getSecurityLabel | Obtains the security label of a file.| Method| √ | √ |
-> **NOTICE**
+> **NOTE**
>
-> 1. In distributed networking, a device can view the files that do not match its security level but cannot access them.
+> - In distributed networking, a device can view the files that do not match its security level but cannot access them.
>
-> 2. The default security level of the distributed file system data is S3. Applications can set the security level of files.
+> - The default security level of the distributed file system data is S3. Applications can set the security level of files.
## Development Example
-Obtain the sandbox path of the file and set the data security label. For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
+Obtain the sandbox path of a file and set the data security label. For details about how to obtain the context, see [Obtaining the Context of UIAbility](../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
+
-
```ts
import securityLabel from '@ohos.file.securityLabel';
-//Obtain the sandbox path of the file.
+// Obtain the sandbox path of the file.
let context =...; // Obtain UIAbilityContext information.
let pathDir = context.filesDir;
let filePath = pathDir + '/test.txt';
diff --git a/en/application-dev/file-management/share-app-file.md b/en/application-dev/file-management/share-app-file.md
index c2f8f8d12f5ff056e043fb632cff9752c95256ce..76dbcab2a74b6b6a4afdcee72c4535939cf3e0a0 100644
--- a/en/application-dev/file-management/share-app-file.md
+++ b/en/application-dev/file-management/share-app-file.md
@@ -1,10 +1,10 @@
# Sharing an Application File
-The file of an application can be shared with another application based on the file descriptor (FD) or uniform resource identifier (URI) of the file. However, if the FD of a shared file is closed, the file cannot be opened. Therefore, the file sharing based on the FD is not recommended. This section describes how to share an application file based on its URI.
+An application can share its file with another application based on the file descriptor (FD) or uniform resource identifier (URI) of the file. However, if the FD of a shared file is closed, the file is no longer opened. Therefore, the FD-based file sharing is not recommended. This section describes how to share an application file based on its URI.
-- You can use **wantConstant.Flags()** of the [ohos.app.ability.wantConstant](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantflags) module to share an application file in read or read/write mode based on its URI with another application. The target application can use **open()** of the [ohos.file.fs](../reference/apis/js-apis-file-fs.md#fsopen) module to open the URI and then perform read and/or write operations based on the permissions granted. Currently, OpenHarmony API version 9 supports only temporary authorization. The permission on shared file is revoked once the target application exits.
+- You can use [wantConstant.Flags](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantflags) to share a single application file in read or read/write mode based on its URI with another application. The target application can use **open()** of the [ohos.file.fs](../reference/apis/js-apis-file-fs.md#fsopen) module to open the URI and then perform read and/or write operations based on the permissions granted. OpenHarmony API version 9 supports only temporary authorization. The permission on the shared file is revoked once the target application exits.
-- You can also use **open()** of the ohos.file.fs module to share an application file with the specified permissions to another application based on the FD. After parsing the FD from **Want**, the target application can read and write the file by using **read()** and **write()** APIs of ohos.file.fs.
+- You can also use **open()** of the ohos.file.fs module to share a single application file with the specified permissions to another application based on the FD. After parsing the FD from **Want**, the target application can read and write the file by using **read()** and **write()** APIs of ohos.file.fs.
You can use the related APIs to [share a file with another application](#sharing-a-file-with-another-application) or [use shared application files](#using-shared-files).
@@ -12,7 +12,7 @@ You can use the related APIs to [share a file with another application](#sharing
The file URIs are in the following format:
- file://<bundleName>/<path>
+ **file**://<*bundleName*>/<*path*>
- **file**: indicates a file URI.
@@ -22,7 +22,7 @@ The file URIs are in the following format:
## Sharing a File with Another Application
-Before sharing application files, you need to [obtain the application file path](../application-models/application-context-stage.md#obtaining-the-application-development-path).
+Before sharing application files, you need to [obtain the application file path](../application-models/application-context-stage.md#obtaining-application-file-paths).
1. Obtain the application sandbox path of the file and convert it into the file URI.
@@ -43,7 +43,7 @@ Before sharing application files, you need to [obtain the application file path]
```
2. Set the target application, with which you want to share the file, and grant permissions on the file.
- Use [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to share the file with the target application. You need to pass in the URI obtained in **uri** of the **want** parameter, set the type of the file to share, set **action** to **ohos.want.action.sendData**, and set the granted permission on the file in **flags**. For details, see [Want](../reference/apis/js-apis-app-ability-want.md#attributes).
+ Use [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to share the file with the target application. You need to pass in the obtained URI in **uri** of the **want** parameter, set the type of the file to share, set **action** to **ohos.want.action.sendData**, and set the granted permission on the file in **flags**. For details, see [Want](../reference/apis/js-apis-app-ability-want.md#attributes).
> **NOTE**
>
@@ -85,7 +85,7 @@ Before sharing application files, you need to [obtain the application file path]
## Using Shared Files
In the [**module.json5** file](../quick-start/module-configuration-file.md) of the application, which wants to use the shared file, set **actions** to **ohos.want.action.sendData** to allow the application to receive files shared by another application and set **uris** to the type of the URI to receive. In the following example, the application receives only .txt files with **scheme** of **file**.
-
+
```json
{
"module": {
@@ -115,7 +115,7 @@ In the [**module.json5** file](../quick-start/module-configuration-file.md) of t
After **UIAbility** of the application starts, the application obtains **want** information from [**onCreate()**](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) or [**onNewWant()**](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonnewwant).
-After obtaining the URI of the shared file through **want**, the application can call **fs.open()** to open the file, and then read and write the file after obtaining the related file object.
+After obtaining the URI of the shared file from **want**, the application can call **fs.open()** to open the file, and then read and write the file after obtaining the related file object.
```ts
// xxx.ets
diff --git a/en/application-dev/file-management/user-file-overview.md b/en/application-dev/file-management/user-file-overview.md
index 599da1024166be5c00619aa71f19f6f10fd73f7f..034eabb1bce098e548a4a2fd95c8b1b62d5ceb42 100644
--- a/en/application-dev/file-management/user-file-overview.md
+++ b/en/application-dev/file-management/user-file-overview.md
@@ -1,60 +1,61 @@
# User File Overview
-User files are the private images, video and audio clips, and documents of the user who logs in to the device.
+User files are the private images, video and audio clips, and documents of the user who has logged in to the device.
-1. User files are stored in a directory, whose owner is the user who logs in to the device.
+- User files are stored in a directory, whose owner is the user who has logged in to the device.
-2. User files can be stored in [built-in storage](#built-in-storage) and [external storage](#external-storage).
+- User files can be stored in [built-in storage](#built-in-storage) and [external storage](#external-storage) of the device.
-3. An application cannot access user files without user authorization, or the operations on user files must be performed by the user.
+- An application cannot access user files without user authorization, or the operations on user files must be performed by the user.
-OpenHarmony provides the [user file access framework](#user-file-access-framework) for developers to access and manage user files, which will be described in detail below.
+OpenHarmony provides the [user file access framework](#user-file-access-framework) for developers to access and manage user files.
## User File Storage
### Built-in Storage
-Built-in storage refers to the internal storage device (space) of a device. The built-in storage device cannot be removed. The following files can be stored in the built-in storage of a device:
+Built-in storage is the internal storage device (space) of a device. The built-in storage device cannot be removed. The following files can be stored in the built-in storage of a device:
-- Files owned by a user: The files belong to the user who logs in to the device. Different users who log in to a device can view only their own files.
+- Files of a user: The files belong to the user who has logged in to the device. Different login users on a device can view their own files only.
These user files can be classified into the following types based on file attributes and access habits of users/applications:
- - Image/Video files
- The files have attributes, such as the shooting time, location, rotation angle, and file width and height information, and are stored in media file formats. The files are usually presented as media files or albums, without the specific location in the system.
+ - Image/Video files
+ The files have attributes, such as the shooting time, location, rotation angle, and file width and height information, and are stored in media file formats. Generally, these files are presented as media files or albums, without the specific storage location in the system.
- - Audio files
- The files have attributes, such as the album, creator, and shooting duration information, and are stored in media file formats. Generally, the files are presented by file, album, or creator, without the specific location in the system.
+ - Audio files
+ The files have attributes, such as the album, artist, and duration information, and are stored in media file formats. Generally, audio files are presented by file, album, or artist, without the specific storage location in the system.
- - Documents
- The files are stored as common files, including common text files, compressed files, and images, videos and audio clips stored as common files. These files are presented in a directory tree.
+ - Other files (documents)
+ The files are stored as common files, including common text files, compressed files, and images, videos and audio clips stored as common files. Generally, these files are presented in a directory tree.
-- Files shared by users: The files are stored in a directory for share and shared by multiple users.
- The files in the shared directory are stored as common files and presented in a directory tree.
+- Files shared by users: The files are stored in a share directory to enable access from multiple users.
+ The files in the share directory are stored as common files and presented in a directory tree.
### External Storage
-External storage is not inside a device's main storage or memory. Common external storage devices include pluggable devices, such as SD cards and USB flash drives. Same as the files in the shared directory of the built-in storage device, the files in an external storage device can be viewed by all the users who log in to the system.
+External storage is not inside a device's main storage or memory. Common external storage devices include pluggable devices, such as SD cards and USB flash drives. Same as the files in the share directory of the built-in storage device, the files in an external storage device can be viewed by all the users who has logged in to the system.
-External storage devices are pluggable. OpenHarmony provides the functions of listening for the device insertion and removal events and mounting/unmounting an external storage device. For details, see [Managing External Storage Devices)](manage-external-storage.md).
+External storage devices are pluggable. OpenHarmony provides listening for the device insertion/removal events and mount/unmount of an external storage device. For details, see [Managing External Storage Devices](manage-external-storage.md).
-The files on external storage devices are presented as common files in a directory tree, like the documents stored in built-in storage.
+The files on external storage devices are presented as common files in a directory tree, like the documents in built-in storage.
## User File Access Framework
OpenHarmony provides the user file access framework for developers to access and manage user files. This framework leverages the ExtensionAbility of OpenHarmony to provide a set of methods and interfaces for accessing user files.
-**Figure 1** User file access framework
+**Figure 1** User file access framework
+

-- To access user files, for example, select a photo or save multiple documents, a system application or third-party application (file access client in **Figure 1**) starts the **FilePicker** application.
+- The file access client (a system application or third-party application) can access user files, for example, select a photo or save multiple documents, by starting the **FilePicker** application.
- OpenHarmony is prebuilt with the **FilePicker** and **FileManager** applications.
- - **FilePicker**: provides APIs for a file access client to select and save user files without any permission. For details, see [Selecting User Files](select-user-file.md).
- - **FileManager**: allows users to view and modify files, and delete, rename, move, and create files or directories by using a system FileManager.
+ - **FilePicker**: allows a file access client to select and save user files without any permission. For details, see [Selecting User Files](select-user-file.md).
+ - **FileManager**: allows users to view and modify files, and delete, rename, move, and create files or directories.
- You can also develop your own FilePicker or FileManager applications as required. FilePicker is a subset of FileManager. For details about how to develop a FileManager application, see [Developing a FileManager Application)](dev-user-file-manager.md).
+ You can also develop your own file picker or file manager applications as required. File picker is a subset of file manager. For details about how to develop a file manager application, see [Developing a File Manager Application](dev-user-file-manager.md).
-- The user file access framework provides the following functional modules:
+- The user file access framework consists of the following functional modules:
- **File Access Helper**: provides APIs for the **FileManager** and **FilePicker** to access user files.
- - **File Access ExtensionAbility**: provides a file access framework to implement file access functions. The **File Access ExtensionAbility** consists of the following:
- - **UserFileManager**: implements management of the files stored on the built-in storage.
- - **ExternalFileManager**: implements management of the files stored on the external storage.
+ - **File Access ExtensionAbility**: implements file access via the following services:
+ - **UserFileManager**: implements management of the files on the built-in storage based on the File Access ExtensionAbility framework.
+ - **ExternalFileManager**: implements management of the files on the external storage based on the File Access ExtensionAbility framework.
diff --git a/en/application-dev/media/Readme-EN.md b/en/application-dev/media/Readme-EN.md
index e118468c6f24d6815d36c3b72a9d0ddc641ba468..b1ab8672c0a6ed63c781027c41541657b39e31ee 100755
--- a/en/application-dev/media/Readme-EN.md
+++ b/en/application-dev/media/Readme-EN.md
@@ -31,6 +31,7 @@
- [Developing Audio Call](audio-call-development.md)
- [Video Playback](video-playback.md)
- [Video Recording](video-recording.md)
+ - [Screen Capture](avscreen-capture.md)
- Audio and Video Codecs
- [Obtaining Supported Codecs](obtain-supported-codecs.md)
- [Audio Encoding](audio-encoding.md)
@@ -61,6 +62,7 @@
- Best Practices
- [Camera Photographing Sample](camera-shooting-case.md)
- [Camera Recording Sample](camera-recording-case.md)
+ - [Using Performance Improvement Features (for System Applications Only)](camera-performance-improvement.md)
- Image
- [Image Overview](image-overview.md)
- [Image Decoding](image-decoding.md)
diff --git a/en/application-dev/media/audio-encoding.md b/en/application-dev/media/audio-encoding.md
index 607c89560a052ce98b4170d098840f84df3286f7..df7c4f51023a915583b44a3e8260593a2b64d546 100644
--- a/en/application-dev/media/audio-encoding.md
+++ b/en/application-dev/media/audio-encoding.md
@@ -28,8 +28,7 @@ Read [AudioEncoder](../reference/native-apis/_audio_encoder.md) for the API refe
Refer to the code snippet below to complete the entire audio encoding process, including creating an encoder, setting encoding parameters (such as the sampling rate, bit rate, and number of audio channels), and starting, refreshing, resetting, and destroying the encoder.
-
-During application development, you must call the APIs in the defined sequence. Otherwise, an exception or undefined behavior may occur.
+During application development, you must call the APIs in the defined sequence. Otherwise, an exception or undefined behavior may occur.
For details about the complete code, see [Sample](https://gitee.com/openharmony/multimedia_av_codec/blob/master/test/nativedemo/audio_demo/avcodec_audio_aac_encoder_demo.cpp).
@@ -41,37 +40,34 @@ The figure below shows the call relationship of audio encoding.
You can create an encoder by name or MIME type.
- ```cpp
- // Create an encoder by name.
- OH_AVCapability *capability = OH_AVCodec_GetCapability(OH_AVCODEC_MIMETYPE_AUDIO_AAC, true);
- const char *name = OH_AVCapability_GetName(capability);
- OH_AVCodec *audioEnc = OH_AudioEncoder_CreateByName(name);
- ```
-
- ```cpp
- // Create an encoder by MIME type.
- OH_AVCodec *audioEnc = OH_AudioEncoder_CreateByMime(OH_AVCODEC_MIMETYPE_AUDIO_AAC);
- ```
-
- ```cpp
- // Initialize the queues.
- class AEncSignal {
- public:
- std::mutex inMutex_;
- std::mutex outMutex_;
- std::mutex startMutex_;
- std::condition_variable inCond_;
- std::condition_variable outCond_;
- std::condition_variable startCond_;
- std::queue inQueue_;
- std::queue outQueue_;
- std::queue inBufferQueue_;
- std::queue outBufferQueue_;
- std::queue attrQueue_;
- };
- AEncSignal *signal_ = new AEncSignal();
- ```
-
+ ```cpp
+ // Create an encoder by name.
+ OH_AVCapability *capability = OH_AVCodec_GetCapability(OH_AVCODEC_MIMETYPE_AUDIO_AAC, true);
+ const char *name = OH_AVCapability_GetName(capability);
+ OH_AVCodec *audioEnc = OH_AudioEncoder_CreateByName(name);
+ ```
+ ```cpp
+ // Create an encoder by MIME type.
+ OH_AVCodec *audioEnc = OH_AudioEncoder_CreateByMime(OH_AVCODEC_MIMETYPE_AUDIO_AAC);
+ ```
+ ```cpp
+ // Initialize the queues.
+ class AEncSignal {
+ public:
+ std::mutex inMutex_;
+ std::mutex outMutex_;
+ std::mutex startMutex_;
+ std::condition_variable inCond_;
+ std::condition_variable outCond_;
+ std::condition_variable startCond_;
+ std::queue inQueue_;
+ std::queue outQueue_;
+ std::queue inBufferQueue_;
+ std::queue outBufferQueue_;
+ std::queue attrQueue_;
+ };
+ AEncSignal *signal_ = new AEncSignal();
+ ```
2. Call **OH_AudioEncoder_SetCallback()** to set callback functions.
Register the **OH_AVCodecAsyncCallback** struct that defines the following callback function pointers:
@@ -83,126 +79,122 @@ The figure below shows the call relationship of audio encoding.
You need to process the callback functions to ensure that the encoder runs properly.
- ```cpp
- // Implement the OH_AVCodecOnError callback function.
- static void OnError(OH_AVCodec *codec, int32_t errorCode, void *userData)
- {
- (void)codec;
- (void)errorCode;
- (void)userData;
- }
- // Implement the OH_AVCodecOnStreamChanged callback function.
- static void OnStreamChanged(OH_AVCodec *codec, OH_AVFormat *format, void *userData)
- {
- (void)codec;
- (void)format;
- (void)userData;
- }
- // Implement the OH_AVCodecOnNeedInputData callback function.
- static void OnNeedInputData(OH_AVCodec *codec, uint32_t index, OH_AVMemory *data, void *userData)
- {
- (void)codec;
- // The input stream is sent to the InputBuffer queue.
- AEncSignal *signal = static_cast(userData);
- unique_lock lock(signal->inMutex_);
- signal->inQueue_.push(index);
- signal->inBufferQueue_.push(data);
- signal->inCond_.notify_all();
- }
- // Implement the OH_AVCodecOnNewOutputData callback function.
- static void OnNeedOutputData(OH_AVCodec *codec, uint32_t index, OH_AVMemory *data, OH_AVCodecBufferAttr *attr,
- void *userData)
- {
- (void)codec;
- // The index of the output buffer is sent to OutputQueue_.
- // The encoded data is sent to the outBuffer queue.
- AEncSignal *signal = static_cast(userData);
- unique_lock lock(signal->outMutex_);
- signal->outQueue_.push(index);
- signal->outBufferQueue_.push(data);
- if (attr) {
- signal->attrQueue_.push(*attr);
- }
- }
- OH_AVCodecAsyncCallback cb = {&OnError, &OnStreamChanged, &OnNeedInputData, &OnNeedOutputData};
- // Set the asynchronous callbacks.
- int32_t ret = OH_AudioEncoder_SetCallback(audioEnc, cb, userData);
- ```
-
+ ```cpp
+ // Implement the OH_AVCodecOnError callback function.
+ static void OnError(OH_AVCodec *codec, int32_t errorCode, void *userData)
+ {
+ (void)codec;
+ (void)errorCode;
+ (void)userData;
+ }
+ // Implement the OH_AVCodecOnStreamChanged callback function.
+ static void OnStreamChanged(OH_AVCodec *codec, OH_AVFormat *format, void *userData)
+ {
+ (void)codec;
+ (void)format;
+ (void)userData;
+ }
+ // Implement the OH_AVCodecOnNeedInputData callback function.
+ static void OnNeedInputData(OH_AVCodec *codec, uint32_t index, OH_AVMemory *data, void *userData)
+ {
+ (void)codec;
+ // The input stream is sent to the InputBuffer queue.
+ AEncSignal *signal = static_cast(userData);
+ unique_lock lock(signal->inMutex_);
+ signal->inQueue_.push(index);
+ signal->inBufferQueue_.push(data);
+ signal->inCond_.notify_all();
+ }
+ // Implement the OH_AVCodecOnNewOutputData callback function.
+ static void OnNeedOutputData(OH_AVCodec *codec, uint32_t index, OH_AVMemory *data, OH_AVCodecBufferAttr *attr,
+ void *userData)
+ {
+ (void)codec;
+ // The index of the output buffer is sent to OutputQueue_.
+ // The encoded data is sent to the outBuffer queue.
+ AEncSignal *signal = static_cast(userData);
+ unique_lock lock(signal->outMutex_);
+ signal->outQueue_.push(index);
+ signal->outBufferQueue_.push(data);
+ if (attr) {
+ signal->attrQueue_.push(*attr);
+ }
+ }
+ OH_AVCodecAsyncCallback cb = {&OnError, &OnStreamChanged, &OnNeedInputData, &OnNeedOutputData};
+ // Set the asynchronous callbacks.
+ int32_t ret = OH_AudioEncoder_SetCallback(audioEnc, cb, userData);
+ ```
3. Call **OH_AudioEncoder_Configure** to configure the encoder.
The following options are mandatory: sampling rate, bit rate, number of audio channels, audio channel type, and bit depth. The maximum input length is optional.
For FLAC encoding, the compliance level and sampling precision are also mandatory.
- ```cpp
- enum AudioFormatType : int32_t {
- TYPE_AAC = 0,
- TYPE_FLAC = 1,
- };
- int32_t ret;
- // (Mandatory) Configure the audio sampling rate.
- constexpr uint32_t DEFAULT_SMAPLERATE = 44100;
- // (Mandatory) Configure the audio bit rate.
- constexpr uint32_t DEFAULT_BITRATE = 32000;
- // (Mandatory) Configure the number of audio channels.
- constexpr uint32_t DEFAULT_CHANNEL_COUNT = 2;
- // (Mandatory) Configure the audio channel type.
- constexpr AudioChannelLayout CHANNEL_LAYOUT =AudioChannelLayout::STEREO;
- // (Mandatory) Configure the audio bit depth. Only SAMPLE_S16LE and SAMPLE_S32LE are available for FLAC encoding.
- constexpr OH_BitsPerSample SAMPLE_FORMAT =OH_BitsPerSample::SAMPLE_S32LE;
- // (Mandatory) Configure the audio bit depth. Only SAMPLE_S32P is available for AAC encoding.
- constexpr OH_BitsPerSample SAMPLE_AAC_FORMAT =OH_BitsPerSample::SAMPLE_S32P;
- // Configure the audio compliance level. The default value is 0, and the value ranges from -2 to 2.
- constexpr int32_t COMPLIANCE_LEVEL = 0;
- // (Mandatory) Configure the audio sampling precision. SAMPLE_S16LE, SAMPLE_S24LE, and SAMPLE_S32LE are available.
- constexpr BITS_PER_CODED_SAMPLE BITS_PER_CODED_SAMPLE =OH_BitsPerSample::SAMPLE_S24LE;
- // (Optional) Configure the maximum input length.
- constexpr uint32_t DEFAULT_MAX_INPUT_SIZE = 1024*DEFAULT_CHANNEL_COUNT *sizeof(float);//aac
- OH_AVFormat *format = OH_AVFormat_Create();
- // Set the format.
- OH_AVFormat_SetIntValue(format,MediaDescriptionKey::MD_KEY_SAMPLE_RATE.data(),DEFAULT_SMAPLERATE);
- OH_AVFormat_SetIntValue(format,MediaDescriptionKey::MD_KEY_BITRATE.data(), DEFAULT_BITRATE);
- OH_AVFormat_SetIntValue(format,MediaDescriptionKey::MD_KEY_CHANNEL_COUNT.data(),DEFAULT_CHANNEL_COUNT);
- OH_AVFormat_SetIntValue(format,MediaDescriptionKey::MD_KEY_MAX_INPUT_SIZE.data(),DEFAULT_MAX_INPUT_SIZE);
- OH_AVFormat_SetLongValue(format,MediaDescriptionKey::MD_KEY_CHANNEL_LAYOUT.data(),CHANNEL_LAYOUT);
- OH_AVFormat_SetIntValue(format,MediaDescriptionKey::MD_KEY_AUDIO_SAMPLE_FORMAT.data(),SAMPLE_FORMAT);
- if(audioType == TYPE_AAC){
- OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_AUDIO_SAMPLE_FORMAT.data(), SAMPLE_AAC_FORMAT);
- }
- if (audioType == TYPE_FLAC) {
- OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_BITS_PER_CODED_SAMPLE.data(), BITS_PER_CODED_SAMPLE);
- OH_AVFormat_SetLongValue(format, MediaDescriptionKey::MD_KEY_COMPLIANCE_LEVEL.data(), COMPLIANCE_LEVEL);
- }
- // Configure the encoder.
- ret = OH_AudioEncoder_Configure(audioEnc, format);
- if (ret != AV_ERR_OK) {
- // Exception handling.
- }
- ```
-
+ ```cpp
+ enum AudioFormatType : int32_t {
+ TYPE_AAC = 0,
+ TYPE_FLAC = 1,
+ };
+ int32_t ret;
+ // (Mandatory) Configure the audio sampling rate.
+ constexpr uint32_t DEFAULT_SMAPLERATE = 44100;
+ // (Mandatory) Configure the audio bit rate.
+ constexpr uint64_t DEFAULT_BITRATE = 32000;
+ // (Mandatory) Configure the number of audio channels.
+ constexpr uint32_t DEFAULT_CHANNEL_COUNT = 2;
+ // (Mandatory) Configure the audio channel type.
+ constexpr AudioChannelLayout CHANNEL_LAYOUT =AudioChannelLayout::STEREO;
+ // (Mandatory) Configure the audio bit depth. Only SAMPLE_S16LE and SAMPLE_S32LE are available for FLAC encoding.
+ constexpr OH_BitsPerSample SAMPLE_FORMAT =OH_BitsPerSample::SAMPLE_S32LE;
+ // (Mandatory) Configure the audio bit depth. Only SAMPLE_F32P is available for AAC encoding.
+ constexpr OH_BitsPerSample SAMPLE_AAC_FORMAT = OH_BitsPerSample::SAMPLE_F32LE;
+ // Configure the audio compliance level. The default value is 0, and the value ranges from -2 to 2.
+ constexpr int32_t COMPLIANCE_LEVEL = 0;
+ // (Mandatory) Configure the audio sampling precision. SAMPLE_S16LE, SAMPLE_S24LE, and SAMPLE_S32LE are available.
+ constexpr BITS_PER_CODED_SAMPLE BITS_PER_CODED_SAMPLE =OH_BitsPerSample::SAMPLE_S24LE;
+ // (Optional) Configure the maximum input length.
+ constexpr uint32_t DEFAULT_MAX_INPUT_SIZE = 1024*DEFAULT_CHANNEL_COUNT *sizeof(float);//aac
+ OH_AVFormat *format = OH_AVFormat_Create();
+ // Set the format.
+ OH_AVFormat_SetIntValue(format,MediaDescriptionKey::MD_KEY_SAMPLE_RATE.data(),DEFAULT_SMAPLERATE);
+ OH_AVFormat_SetLongValue(format,MediaDescriptionKey::MD_KEY_BITRATE.data(), DEFAULT_BITRATE);
+ OH_AVFormat_SetIntValue(format,MediaDescriptionKey::MD_KEY_CHANNEL_COUNT.data(),DEFAULT_CHANNEL_COUNT);
+ OH_AVFormat_SetIntValue(format,MediaDescriptionKey::MD_KEY_MAX_INPUT_SIZE.data(),DEFAULT_MAX_INPUT_SIZE);
+ OH_AVFormat_SetLongValue(format,MediaDescriptionKey::MD_KEY_CHANNEL_LAYOUT.data(),CHANNEL_LAYOUT);
+ OH_AVFormat_SetIntValue(format,MediaDescriptionKey::MD_KEY_AUDIO_SAMPLE_FORMAT.data(),SAMPLE_FORMAT);
+ if(audioType == TYPE_AAC){
+ OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_AUDIO_SAMPLE_FORMAT.data(), SAMPLE_AAC_FORMAT);
+ }
+ if (audioType == TYPE_FLAC) {
+ OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_BITS_PER_CODED_SAMPLE.data(), BITS_PER_CODED_SAMPLE);
+ OH_AVFormat_SetLongValue(format, MediaDescriptionKey::MD_KEY_COMPLIANCE_LEVEL.data(), COMPLIANCE_LEVEL);
+ }
+ // Configure the encoder.
+ ret = OH_AudioEncoder_Configure(audioEnc, format);
+ if (ret != AV_ERR_OK) {
+ // Exception handling.
+ }
+ ```
4. Call **OH_AudioEncoder_Prepare()** to prepare internal resources for the encoder.
- ```c++
- OH_AudioEncoder_Prepare(audioEnc);
- ```
-
+ ```c++
+ OH_AudioEncoder_Prepare(audioEnc);
+ ```
5. Call **OH_AudioEncoder_Start()** to start the encoder.
- ```c++
- inputFile_ = std::make_unique();
- // Open the path of the binary file to be encoded.
- inputFile_->open(inputFilePath.data(), std::ios::in |std::ios::binary);
- // Configure the path of the output file.
- outFile_ = std::make_unique();
- outFile_->open(outputFilePath.data(), std::ios::out |std::ios::binary);
- // Start encoding.
- ret = OH_AudioEncoder_Start(audioEnc);
- if (ret != AV_ERR_OK) {
- // Exception handling.
- }
- ```
-
+ ```c++
+ inputFile_ = std::make_unique();
+ // Open the path of the binary file to be encoded.
+ inputFile_->open(inputFilePath.data(), std::ios::in |std::ios::binary);
+ // Configure the path of the output file.
+ outFile_ = std::make_unique();
+ outFile_->open(outputFilePath.data(), std::ios::out |std::ios::binary);
+ // Start encoding.
+ ret = OH_AudioEncoder_Start(audioEnc);
+ if (ret != AV_ERR_OK) {
+ // Exception handling.
+ }
+ ```
6. Call **OH_AudioEncoder_PushInputData()** to write the data to encode.
To indicate the End of Stream (EOS), pass in the **AVCODEC_BUFFER_FLAGS_EOS** flag.
@@ -213,64 +205,64 @@ The figure below shows the call relationship of audio encoding.
| Sampling Rate| FRAME_SIZE|
| :----: | :----: |
- | 8000 | 576 |
- | 16000 | 1152 |
- | 22050 | 2304 |
- | 24000 | 2304 |
- | 32000 | 2304 |
- | 44100 | 4608 |
- | 48000 | 4608 |
- | 88200 | 8192 |
- | 96000 | 8192 |
+ | 8000 | 576 |
+ | 16000 | 1152 |
+ | 22050 | 2304 |
+ | 24000 | 2304 |
+ | 32000 | 2304 |
+ | 44100 | 4608 |
+ | 48000 | 4608 |
+ | 88200 | 8192 |
+ | 96000 | 8192 |
**NOTE**: If **FRAME_SIZE** is not set to **1024** for AAC encoding, an error code is returned. In the case of FLAC encoding, if **FRAME_SIZE** is set to a value greater than the value listed in the table for a given sampling rate, an error code is returned; if **FRAME_SIZE** is set to a value less than the value listed, the encoded file may be damaged.
-
- ```c++
- constexpr int32_t FRAME_SIZE = 1024; // AAC encoding
- constexpr int32_t DEFAULT_CHANNEL_COUNT =2;
- constexpr int32_t INPUT_FRAME_BYTES = DEFAULT_CHANNEL_COUNT * FRAME_SIZE * sizeof(float); // AAC encoding
- // Configure the buffer information.
- OH_AVCodecBufferAttr info;
- // Set the package size, offset, and timestamp.
- info.size = pkt_->size;
- info.offset = 0;
- info.pts = pkt_->pts;
- info.flags = AVCODEC_BUFFER_FLAGS_CODEC_DATA;
- auto buffer = signal_->inBufferQueue_.front();
- if (inputFile_->eof()){
- info.size = 0;
- info.flags = AVCODEC_BUFFER_FLAGS_EOS;
- }else{
- inputFile_->read((char *)OH_AVMemory_GetAddr(buffer), INPUT_FRAME_BYTES);
- }
- uint32_t index = signal_->inQueue_.front();
- // Send the data to the input queue for encoding. The index is the subscript of the queue.
- int32_t ret = OH_AudioEncoder_PushInputData(audioEnc, index,info);
- if (ret != AV_ERR_OK) {
- // Exception handling.
- }
- ```
-
+
+
+ ```c++
+ constexpr int32_t FRAME_SIZE = 1024; // AAC encoding
+ constexpr int32_t DEFAULT_CHANNEL_COUNT =2;
+ constexpr int32_t INPUT_FRAME_BYTES = DEFAULT_CHANNEL_COUNT * FRAME_SIZE * sizeof(float); // AAC encoding
+ // Configure the buffer information.
+ OH_AVCodecBufferAttr info;
+ // Set the package size, offset, and timestamp.
+ info.size = pkt_->size;
+ info.offset = 0;
+ info.pts = pkt_->pts;
+ info.flags = AVCODEC_BUFFER_FLAGS_CODEC_DATA;
+ auto buffer = signal_->inBufferQueue_.front();
+ if (inputFile_->eof()){
+ info.size = 0;
+ info.flags = AVCODEC_BUFFER_FLAGS_EOS;
+ }else{
+ inputFile_->read((char *)OH_AVMemory_GetAddr(buffer), INPUT_FRAME_BYTES);
+ }
+ uint32_t index = signal_->inQueue_.front();
+ // Send the data to the input queue for encoding. The index is the subscript of the queue.
+ int32_t ret = OH_AudioEncoder_PushInputData(audioEnc, index,info);
+ if (ret != AV_ERR_OK) {
+ // Exception handling.
+ }
+ ```
+
7. Call **OH_AudioEncoder_FreeOutputData()** to output the encoded stream.
- ```c++
- OH_AVCodecBufferAttr attr = signal_->attrQueue_.front();
- OH_AVMemory *data = signal_->outBufferQueue_.front();
- uint32_t index = signal_->outQueue_.front();
- // Write the encoded data (specified by data) to the output file.
- outFile_->write(reinterpret_cast(OH_AVMemory_GetAdd(data)), attr.size);
- // Release the output buffer.
- ret = OH_AudioEncoder_FreeOutputData(audioEnc, index);
- if (ret != AV_ERR_OK) {
- // Exception handling.
- }
- if (attr.flags == AVCODEC_BUFFER_FLAGS_EOS) {
- cout << "decode eos" << endl;
- isRunning_.store(false);
- break;
- }
- ```
-
+ ```c++
+ OH_AVCodecBufferAttr attr = signal_->attrQueue_.front();
+ OH_AVMemory *data = signal_->outBufferQueue_.front();
+ uint32_t index = signal_->outQueue_.front();
+ // Write the encoded data (specified by data) to the output file.
+ outFile_->write(reinterpret_cast(OH_AVMemory_GetAdd(data)), attr.size);
+ // Release the output buffer.
+ ret = OH_AudioEncoder_FreeOutputData(audioEnc, index);
+ if (ret != AV_ERR_OK) {
+ // Exception handling.
+ }
+ if (attr.flags == AVCODEC_BUFFER_FLAGS_EOS) {
+ cout << "decode eos" << endl;
+ isRunning_.store(false);
+ break;
+ }
+ ```
8. (Optional) Call **OH_AudioEncoder_Flush()** to refresh the encoder.
After **OH_AudioEncoder_Flush()** is called, the current encoding queue is cleared.
@@ -282,19 +274,18 @@ The figure below shows the call relationship of audio encoding.
* The EOS of the file is reached.
* An error with **OH_AudioEncoder_IsValid** set to **true** (indicating that the execution can continue) occurs.
- ```c++
- // Refresh the encoder.
- ret = OH_AudioEncoder_Flush(audioEnc);
- if (ret != AV_ERR_OK) {
- // Exception handling.
- }
- // Start encoding again.
- ret = OH_AudioEncoder_Start(audioEnc);
- if (ret != AV_ERR_OK) {
- // Exception handling.
- }
- ```
-
+ ```c++
+ // Refresh the encoder.
+ ret = OH_AudioEncoder_Flush(audioEnc);
+ if (ret != AV_ERR_OK) {
+ // Exception handling.
+ }
+ // Start encoding again.
+ ret = OH_AudioEncoder_Start(audioEnc);
+ if (ret != AV_ERR_OK) {
+ // Exception handling.
+ }
+ ```
9. (Optional) Call **OH_AudioEncoder_Reset()** to reset the encoder.
After **OH_AudioEncoder_Reset()** is called, the encoder returns to the initialized state. To continue encoding, you must call **OH_AudioEncoder_Configure()** and then **OH_AudioEncoder_Start()**.
@@ -334,4 +325,4 @@ The figure below shows the call relationship of audio encoding.
audioEnc = NULL; // The encoder cannot be destroyed repeatedly.
}
return ret;
- ```
+ ```
\ No newline at end of file
diff --git a/en/application-dev/media/avscreen-capture.md b/en/application-dev/media/avscreen-capture.md
new file mode 100644
index 0000000000000000000000000000000000000000..b435311c0697c90f2ae1e59d1235caecd7a9ef26
--- /dev/null
+++ b/en/application-dev/media/avscreen-capture.md
@@ -0,0 +1,236 @@
+# Screen Capture
+
+Screen capture is mainly used to record the main screen.
+
+You can call the native APIs of the **AVScreenCapture** module to record the screen and collect audio and video source data output by the device and microphone. When developing a live streaming or an office application, you can call the APIs to obtain original audio and video streams and transfer the streams to other modules for processing. In this way, the home screen can be shared during live streaming.
+
+The **AVScreenCapture**, **Window**, and **Graphics** modules together implement the entire video capture process.
+
+By default, the main screen is captured, and the **Graphics** module generates the screen capture frame data based on the main screen and places the data to the display data buffer queue. The screen capture framework obtains the data from the display data buffer queue for consumption processing.
+
+## Development Guidelines
+
+The full screen capture process involves creating an **AVScreenCapture** instance, configuring audio and video capture parameters, starting and stopping screen capture, and releasing the instance. This topic describes how to use the **AVScreenCapture** module to carry out one-time screen capture. For details about the API reference, see [AVScreenCapture](../reference/native-apis/_a_v_screen_capture.md).
+
+After an **AVScreenCapture** instance is created, different APIs can be called to switch the AVScreenCapture to different states and trigger the required behavior. If an API is called when the AVScreenCapture is not in the given state, the system may throw an exception or generate other undefined behavior. Therefore, you are advised to check the AVScreenCapture state before triggering state transition.
+
+### Permission Description
+
+Before development, configure the following permissions for your application. For details about permission configuration, see [Permission Application Guide](../security/accesstoken-guidelines.md).
+
+| Permission| Description| Authorization Mode| APL|
+| ------ | ----- | --------| ------- |
+| ohos.permission.CAPTURE_SCREEN | Allows an application to take screenshots.| system_grant | system_core |
+| ohos.permission.MICROPHONE | Allows an application to access the microphone. This permission is required only when you need to record the audio output by the microphone.| user_grant | normal |
+
+### How to Develop
+
+The following walks you through how to implement simple screen capture:
+
+1. Create an **AVScreenCapture** instance, named **capture** in this example.
+
+ ```c++
+ OH_AVScreenCapture* capture = AVScreenCapture_Create();
+ ```
+
+2. Set screen capture parameters.
+
+ After creating the **capture** instance, you can set the parameters required for screen capture.
+
+ ```c++
+ OH_AudioCaptureInfo miccapinfo = {
+ .audioSampleRate = 16000,
+ .audioChannels = 2,
+ .audioSource = OH_MIC
+ };
+
+ OH_VideoCaptureInfo videocapinfo = {
+ .videoFrameWidth = display->GetWidth(),
+ .videoFrameHeight = display->Height(),
+ .videoSource = OH_VIDEO_SOURCE_SURFACE_RGBA
+ };
+
+ OH_AudioInfo audioinfo = {
+ .micCapInfo = miccapinfo,
+ };
+
+ OH_VideoInfo videoinfo = {
+ .videoCapInfo = videocapinfo
+ };
+
+ OH_RecorderInfo recorderinfo = {
+ .url = name
+ };
+
+ OH_AVScreenCaptureConfig config = {
+ .captureMode = OH_CAPTURE_HOME_SCREEN,
+ .dataType = OH_ORIGINAL_STREAM,
+ .audioInfo = audioinfo,
+ .videoInfo = videoinfo,
+ .recorderInfo = recorderinfo
+ };
+
+ OH_AVScreenCapture_Init(capture, config);
+ ```
+
+3. Enable the microphone.
+
+ ```c++
+ bool isMic = true;
+ OH_AVScreenCapture_SetMicrophoneEnabled(capture, isMic);
+ ```
+
+4. Set callback functions, which are used to listen for errors that may occur during screen capture and the generation of audio and video stream data.
+
+ ```c++
+ OH_AVScreenCaptureCallback callback;
+ callback.onAudioBufferAvailable = OnAudioBufferAvailable;
+ callback.onVideoBufferAvailable = OnVideoBufferAvailable;
+ OH_AVScreenCapture_SetCallback(capture, callback);
+ ```
+
+5. Call **StartScreenCapture** to start screen capture.
+
+ ```c++
+ OH_AVScreenCapture_StartScreenCapture(capture);
+ ```
+
+6. Call **StopScreenCapture()** to stop screen capture.
+
+ ```c++
+ OH_AVScreenCapture_StopScreenCapture(capture_);
+ ```
+
+7. Call **AcquireAudioBuffer()** to obtain an audio buffer.
+
+ ```c++
+ OH_AVScreenCapture_AcquireAudioBuffer(capture, &audiobuffer, type);
+ ```
+
+8. Call **AcquireVideoBuffer()** to obtain a video buffer.
+
+ ```c++
+ OH_NativeBuffer* buffer = OH_ScreenCapture_AcquireVideoBuffer(capture, &fence, ×tamp, &damage);
+ ```
+
+9. Call **ReleaseAudioBuffer()** to release the audio buffer.
+
+ ```c++
+ OH_ScreenCapture_ReleaseAudioBuffer(capture, type);
+ ```
+
+10. Call **ReleaseVideoBuffer()** to release the video buffer.
+
+ ```c++
+ OH_ScreenCapture_ReleaseVideoBuffer(capture);
+ ```
+
+11. Call **release()** to release the instance.
+
+ ```c++
+ OH_AVScreenCapture_Release(capture);
+ ```
+
+### Sample Code
+
+Refer to the sample code below to implement screen capture using **AVScreenCapture**.
+Currently, the buffer holds original streams, which can be encoded and saved in MP4 format for playback. The encoding format and file format are reserved and will be implemented in later versions.
+
+```c++
+
+#include "multimedia/player_framework/native_avscreen_capture.h"
+#include "multimedia/player_framework/native_avscreen_capture_base.h"
+#include "multimedia/player_framework/native_avscreen_capture_errors.h"
+
+void OnError(struct OH_AVScreenCapture *capture, int32_t errorCode)
+{
+ (void) capture;
+ (void) errorCode;
+}
+
+void OnAudioBufferAvailable(struct OH_AVScreenCapture *capture, bool isReady, OH_AudioCapSourceType type)
+{
+ if (isReady) {
+ OH_AudioBuffer *audiobuffer = (struct OH_AudioBuffer*) malloc (sizeof(OH_AudioBuffer));
+ // Obtain an audio buffer.
+ int32_t ret = OH_AVScreenCapture_AcquireAudioBuffer(capture, &audiobuffer, type);
+ /* Obtain a buffer. */
+ (void)audiobuffer->buf;
+ /* Obtain the buffer size. */
+ (void)audiobuffer->size;
+ /* Obtain the timestamp of the audio buffer. */
+ (void)audiobuffer->timestamp;
+ free(audiobuffer);
+ audiobuffer = nullptr;
+ // Release the audio buffer.
+ int32_t ret = OH_ScreenCapture_ReleaseAudioBuffer(capture, type);
+ }
+}
+
+void OnVideoBufferAvailable(struct OH_ScreenCapture *capture, bool isReady)
+{
+ if (isReady) {
+ int32_t fence = 0;
+ int64_t timestamp = 0;
+ struct OH_Rect damage;
+ // Obtain a video buffer.
+ OH_NativeBuffer* buffer = OH_ScreenCapture_AcquireVideoBuffer(capture, &fence, ×tamp, &damage);
+ void *virAddr = nullptr;
+ OH_NativeBuffer_Map (buffer, &virAddr); // Obtain a buffer.
+ OH_NativeBuffer_Config config;
+ OH_NativeBuffer_GetNativeBufferConfig(buffer, config); // Obtain the width, height, and format.
+ // Obtain the fence, timestamp, and coordinate information.
+ OH_NativeBuffer_UnMap (buffer); // Release the buffer.
+ // Release the video buffer.
+ int32_t ret = OH_ScreenCapture_ReleaseVideoBuffer(capture);
+ }
+}
+
+int main()
+{
+ // Instantiate AVScreenCapture.
+ struct OH_AVScreenCapture* capture = OH_AVScreenCapture_Create(void);
+ // Set the callbacks.
+ struct OH_AVScreenCaptureCallback callback;
+ callback.onError = OnError;
+ callack.onAudioBufferAvailable = OnAudioBufferAvailable ;
+ callack.onVideoBufferAvailable = OnVideoBufferAvailable;
+ int32_t ret = OH_AVScreenCapture_SetCallback(capture, callback);
+ // Initialize AVScreenCapture and pass in an OH_AVScreenRecorderConfig struct.
+ OH_AudioCaptureInfo miccapinfo = {
+ .audioSampleRate = 16000,
+ .audioChannels = 2,
+ .audioSource = OH_MIC
+ };
+ OH_VideoCaptureInfo videocapinfo = {
+ .videoFrameWidth = 720,
+ .videoFrameHeight = 1280,
+ .videoSource = OH_VIDEO_SOURCE_SURFACE_RGBA
+ };
+ OH_AudioInfo audioinfo = {
+ .micCapInfo = miccapinfo,
+ };
+ OH_VideoInfo videoinfo = {
+ .videoCapInfo = videocapinfo
+ };
+ OH_AVScreenCaptureConfig config = {
+ .captureMode = OH_CAPTURE_HOME_SCREEN,
+ .dataType = OH_ORIGINAL_STREAM,
+ .audioInfo = audioinfo,
+ .videoInfo = videoinfo,
+ .recorderInfo = recorderinfo
+ };
+ OH_AVScreenCapture_Init(capture, config);
+ int32_t ret = OH_AVScreenCapture_Init(capture, &config);
+ // Start screen capture.
+ int32_t ret = OH_AVScreenCapture_StartScreenCapture(capture);
+ // Enable the microphone.
+ int32_t ret = OH_ScreenCapture_SetMicrophoneEnable(capture, true);
+ sleep(10); // Capture the screen for 10s.
+ // Stop screen capture.
+ int32_t ret = OH_ScreenCapture_StopScreenCapture(capture);
+ // Release the AVScreenCapture instance.
+ int32_t ret = OH_ScreenCapture_Realease(capture);
+ return 0;
+}
+```
diff --git a/en/application-dev/media/camera-performance-improvement.md b/en/application-dev/media/camera-performance-improvement.md
new file mode 100644
index 0000000000000000000000000000000000000000..f5bdeb76c4abdb54aa15e113e4ce950ae9ea6539
--- /dev/null
+++ b/en/application-dev/media/camera-performance-improvement.md
@@ -0,0 +1,168 @@
+# Using Performance Improvement Features (for System Applications Only)
+
+The camera startup performance is affected by time-consuming operations such as power-on of underlying components and initialization of the process pipeline. To improve the camera startup speed and thumbnail display speed, OpenHarmony introduces some features. The capabilities of these features are related to underlying components. You need to check whether these capabilities are supported before using them.
+
+These features are involved in the processes of starting the camera device, configuring streams, and taking photos. This topic describes the three scenarios.
+
+## Deferred Stream Configuration
+
+A typical camera startup process includes starting the camera device, configuring a data stream, and starting the data stream. Before configuring the data stream, you need to obtain the surface ID of the **\**.
+
+The deferred stream configuration feature decouples stream configuration and start from the surface. Before the **\** provides the surface for the camera application, the system configures and starts the stream. This way, the surface only needs to be available before the stream is started. This improves the startup speed and prevents the implementation of other startup optimization schemas from being affected.
+
+
+
+Before optimization: Stream configuration depends on a **Surface** object, which is available after UI loading is complete. In other words, you can create a session, configure input and output streams, and start the session only after the UI is loaded. The camera HDI is responsible for stream configuration.
+
+After optimization: Stream configuration does not depend on the **Surface** object. UI loading and stream configuration are executed concurrently. After the parameters are prepared, you can create a session.
+
+### Available APIs
+
+Read [Camera](../reference/apis/js-apis-camera.md) for the API reference.
+
+| API| Description|
+| ---- | ---- |
+| createDeferredPreviewOutput(profile: Profile): Promise\ | Creates a deferred **PreviewOutput** instance and adds it to the data stream instead of a common **PreviewOutput** instance during stream configuration.|
+| addDeferredSurface(surfaceId: string): Promise\ | Adds a surface for delayed preview. This API can run after **session.commitConfig()** or **session.start()** is called.|
+
+### Development Example
+
+The figure below shows the recommended API call process.
+
+
+
+```js
+import camera from '@ohos.multimedia.camera';
+
+function async preview(context: Context, cameraInfo: camera.Device, previewProfile: camera.Profile, photoProfile: camera.Profile, surfaceId: string): Promise {
+ const cameraManager: camera.CameraManager = camera.getCameraManager(context);
+ const cameraInput camera.CameraInput = await cameraManager.createCameraInput(cameraInfo)
+ const previewOutput: camera.PreviewOutput = await cameraManager.createDeferredPreviewOutput(previewProfile);
+ const photoOutput: camera.PhotoOutput = await cameraManager.createPhotoOutput(photoProfile);
+ const session: camera.CaptureSession = await this.mCameraManager.createCaptureSession();
+ await session.beginConfig();
+ await session.addInput(cameraInput);
+ await session.addOutput(previewOutput);
+ await session.addOutput(photoOutput);
+ await session.commitConfig();
+ await session.start();
+ await previewOutput.addDeferredSurface(surfaceId);
+}
+```
+
+## Quick Thumbnail
+
+The photographing performance depends on the algorithm processing speed. A complex algorithm chain provides better image effect while requiring longer processing time.
+
+To improve the photographing speed perceived by end users, the quick thumbnail feature is introduced. When the user takes a photo, a thumbnail is output and reported to the camera application for display before a real image is reported.
+
+In this way, the photographing process is optimized, which fulfills the processing requirements of the post-processing algorithm without blocking the photographing speed of the foreground.
+
+### Available APIs
+
+Read [Camera](../reference/apis/js-apis-camera.md) for the API reference.
+
+| API| Description|
+| ---- | ---- |
+| isQuickThumbnailSupported() : boolean | Checks whether the quick thumbnail feature is supported.|
+| enableQuickThumbnail(enabled:bool): void | Enables or disables the quick thumbnail feature.|
+| on(type: 'quickThumbnail', callback: AsyncCallback\): void | Listens for camera thumbnails.|
+
+> **NOTE**
+>
+> - **isQuickThumbnailSupported** and **enableQuickThumbnail** must be called after **CaptureSession.addOutput** and **CaptureSession.addInput** but before **CaptureSession.commitConfig()**.
+> - **on()** takes effect after **enableQuickThumbnail(true)** is called.
+
+### Development Example
+
+The figure below shows the recommended API call process.
+
+
+
+```js
+import camera from '@ohos.multimedia.camera'
+
+this.cameraManager = camera.getCameraManager(globalThis.abilityContext);
+let cameras = this.cameraManager.getSupportedCameras()
+// Create a CaptureSession instance.
+this.captureSession = await this.cameraManager.createCaptureSession()
+// Start configuration for the session.
+await this.captureSession.beginConfig()
+// Add a CameraInput instance to the session.
+this.cameraInput = await this.cameraManager.createCameraInput(cameras[0])
+await this.cameraInput.open()
+await this.captureSession.addInput(this.cameraInput)
+// Add a PhotoOutput instance to the session.
+this.photoOutPut = await this.cameraManager.createPhotoOutput(photoProfile, surfaceId)
+await this.captureSession.addOutput(this.photoOutPut)
+boolean isSupported = this.photoOutPut.isQuickThumbnailSupported()
+if (isSupported) {
+ // Enable the quick thumbnail feature.
+ this.photoOutPut.enableQuickThumbnail(true)
+ this.photoOutPut.on('quickThumbnail', (err, pixelmap) => {
+ if (err || pixelmap === undefined) {
+ Logger.error(this.tag, 'photoOutPut on thumbnail failed ')
+ return
+ }
+ // Display or save the PixelMap instance.
+ this.showOrSavePicture(pixelmap)
+ })
+}
+```
+
+## Prelaunch
+
+Generally, the startup of the camera application is triggered when the user touches the camera icon on the home screen. The home screen senses the touch event and instructs the application manager to start the camera application. This takes a relatively long time. After the camera application is started, the camera startup process starts. A typical camera startup process includes starting the camera device, configuring a data stream, and starting the data stream, which is also time-consuming.
+
+The prelaunch feature triggers the action of starting the camera device before the camera application is started. In other words, when the user touches the camera icon on the home screen, the system starts the camera device. At this time, the camera application is not started yet. The figure below shows the camera application process before and after the prelaunch feature is introduced.
+
+
+
+### Available APIs
+
+Read [Camera](../reference/apis/js-apis-camera.md) for the API reference.
+
+| API| Description|
+| ---- | ---- |
+| isPrelaunchSupported(camera: CameraDevice) : boolean | Checks whether the camera supports prelaunch.|
+| setPrelaunchConfig(prelaunchConfig: PrelaunchConfig) : void | Sets the prelaunch parameters.|
+| prelaunch() : void | Prelaunches the camera. This API is called when a user clicks the system camera icon to start the camera application.|
+
+### Development Example
+
+The figure below shows the recommended API call process.
+
+
+
+- **Home screen**
+
+ ```js
+ import camera from '@ohos.multimedia.camera'
+
+ this.cameraManager = camera.getCameraManager(globalThis.abilityContext);
+ try {
+ this.cameraManager.prelaunch();
+ } catch (error) {
+ console.error(`catch error: Code: ${error.code}, message: ${error.message}`)
+ }
+ ```
+
+- **Camera application**
+
+ To use the prelaunch feature, the camera application must configure the **ohos.permission.CAMERA** permission.
+
+ For details about how to request and verify the permissions, see [Permission Application Guide](../security/accesstoken-guidelines.md).
+
+ ```js
+ import camera from '@ohos.multimedia.camera'
+
+ this.cameraManager = camera.getCameraManager(globalThis.abilityContext);
+ let cameras = this.cameraManager.getSupportedCameras()
+ if(this.cameraManager.isPrelaunchSupported(cameras[0])) {
+ try {
+ this.cameraManager.setPrelaunchConfig({cameraDevice: cameras[0]});
+ } catch (error) {
+ console.error(`catch error: Code: ${error.code}, message: ${error.message}`)
+ }
+ }
+ ```
diff --git a/en/application-dev/media/camera-recording-case.md b/en/application-dev/media/camera-recording-case.md
index e92b8d80d5289071b507f59dcee1389733c498bb..783c35ab1f93158e511f9765b0f76c703e95e9ca 100644
--- a/en/application-dev/media/camera-recording-case.md
+++ b/en/application-dev/media/camera-recording-case.md
@@ -72,7 +72,7 @@ let AVRecorderConfig = {
audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC,
videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV,
profile : AVRecorderProfile,
- url : 'fd://', // Before passing in a file descriptor to this parameter, the file must be created by the caller and granted with the read and write permissions. Example value: eg.fd://45--file:///data/media/01.mp4.
+ url : 'fd://', // Before passing in a file descriptor to this parameter, the file must be created by the caller and granted with the read and write permissions. Example value: fd://45--file:///data/media/01.mp4.
rotation: 0, // The value can be 0, 90, 180, or 270. If any other value is used, prepare() reports an error.
location : { latitude : 30, longitude : 130 }
}
diff --git a/en/application-dev/media/camera-recording.md b/en/application-dev/media/camera-recording.md
index 9d872d6b323f84718ac045be83cebda268b08d8c..88f5f6913cebf9b20c3adce3c0da9d849764651a 100644
--- a/en/application-dev/media/camera-recording.md
+++ b/en/application-dev/media/camera-recording.md
@@ -104,7 +104,7 @@ Read [Camera](../reference/apis/js-apis-camera.md) for the API reference.
avRecorder.start().then(() => {
console.info('avRecorder start success');
- }
+ });
```
5. Stop video recording.
@@ -114,7 +114,7 @@ Read [Camera](../reference/apis/js-apis-camera.md) for the API reference.
```ts
videoRecorder.stop().then(() => {
console.info('stop success');
- }
+ });
videoOutput.stop((err) => {
if (err) {
diff --git a/en/application-dev/media/figures/deferred-surface-scene.png b/en/application-dev/media/figures/deferred-surface-scene.png
new file mode 100644
index 0000000000000000000000000000000000000000..fac0141a196abf281b41b4df7b40aff15a95fe12
Binary files /dev/null and b/en/application-dev/media/figures/deferred-surface-scene.png differ
diff --git a/en/application-dev/media/figures/deferred-surface-sequence-diagram.png b/en/application-dev/media/figures/deferred-surface-sequence-diagram.png
new file mode 100644
index 0000000000000000000000000000000000000000..14f27fe8bcaf190b60da741bdd9092bc0929e1a1
Binary files /dev/null and b/en/application-dev/media/figures/deferred-surface-sequence-diagram.png differ
diff --git a/en/application-dev/media/figures/prelaunch-scene.png b/en/application-dev/media/figures/prelaunch-scene.png
new file mode 100644
index 0000000000000000000000000000000000000000..25139365b0a66170bc7d9e4bdff41c8aeaa023fd
Binary files /dev/null and b/en/application-dev/media/figures/prelaunch-scene.png differ
diff --git a/en/application-dev/media/figures/prelaunch-sequence-diagram.png b/en/application-dev/media/figures/prelaunch-sequence-diagram.png
new file mode 100644
index 0000000000000000000000000000000000000000..b28c3ffdd6fa7aeb2c4d3d22a267a982504370cf
Binary files /dev/null and b/en/application-dev/media/figures/prelaunch-sequence-diagram.png differ
diff --git a/en/application-dev/media/figures/quick-thumbnail-sequence-diagram.png b/en/application-dev/media/figures/quick-thumbnail-sequence-diagram.png
new file mode 100644
index 0000000000000000000000000000000000000000..9c05f247683566c2e37b3a2b8797e7e487b3376f
Binary files /dev/null and b/en/application-dev/media/figures/quick-thumbnail-sequence-diagram.png differ
diff --git a/en/application-dev/media/using-ohaudio-for-playback.md b/en/application-dev/media/using-ohaudio-for-playback.md
index d63468342a25627e95e3e82b210b36a3dedff685..a90cfe257371c7a0b35c2e2f5b843a69fe1ac155 100644
--- a/en/application-dev/media/using-ohaudio-for-playback.md
+++ b/en/application-dev/media/using-ohaudio-for-playback.md
@@ -90,3 +90,16 @@ The following walks you through how to implement simple playback:
```c++
OH_AudioStreamBuilder_Destroy(builder);
```
+
+## Setting the Low Latency Mode
+
+If the device supports the low-latency channel, you can use the low-latency mode to create a player for a higher-quality audio experience.
+
+The development process is similar to that in the common playback scenario. The only difference is that you need to set the low delay mode by calling [OH_AudioStreamBuilder_SetLatencyMode()](../reference/native-apis/_o_h_audio.md#oh_audiostreambuilder_setlatencymode) when creating an audio stream builder.
+
+The code snippet is as follows:
+
+```C
+OH_AudioStream_LatencyMode latencyMode = AUDIOSTREAM_LATENCY_MODE_FAST;
+OH_AudioStreamBuilder_SetLatencyMode(builder, latencyMode);
+```
diff --git a/en/application-dev/media/video-playback.md b/en/application-dev/media/video-playback.md
index 30e3a98f9858baf7d3a6cbaf5c826792322417b4..40c754219cf35dc234be37635fcb8a27bfb86027 100644
--- a/en/application-dev/media/video-playback.md
+++ b/en/application-dev/media/video-playback.md
@@ -46,7 +46,7 @@ Read [AVPlayer](../reference/apis/js-apis-media.md#avplayer9) for the API refere
>
> The URL in the code snippet below is for reference only. You need to check the media asset validity and set the URL based on service requirements.
>
- > - If local files are used for playback, ensure that the files are available and the application sandbox path is used for access. For details about how to obtain the application sandbox path, see [Obtaining the Application Development Path](../application-models/application-context-stage.md#obtaining-the-application-development-path). For details about the application sandbox and how to push files to the application sandbox, see [File Management](../file-management/app-sandbox-directory.md).
+ > - If local files are used for playback, ensure that the files are available and the application sandbox path is used for access. For details about how to obtain the application sandbox path, see [Obtaining Application File Paths](../application-models/application-context-stage.md#obtaining-application-file-paths). For details about the application sandbox and how to push files to the application sandbox, see [File Management](../file-management/app-sandbox-directory.md).
>
> - If a network playback path is used, you must request the ohos.permission.INTERNET [permission](../security/accesstoken-guidelines.md).
>
diff --git a/en/application-dev/napi/native-buffer-guidelines.md b/en/application-dev/napi/native-buffer-guidelines.md
index b45c43f77e6d63aac676327bc971d9eeb0609259..fae8927caa9563c9fd459906d9fb9ecf2e166297 100644
--- a/en/application-dev/napi/native-buffer-guidelines.md
+++ b/en/application-dev/napi/native-buffer-guidelines.md
@@ -26,6 +26,13 @@ For details about the APIs, see [native_buffer](../reference/native-apis/_o_h___
The following describes how to use the native APIs provided by **NativeBuffer** to create an **OH_NativeBuffer** instance, obtain memory properties, and map the corresponding ION memory to the process address space.
+**Adding Dynamic Link Libraries**
+
+Add the following library to **CMakeLists.txt**:
+```txt
+libnative_buffer.so
+```
+
**Header File**
```c++
#include
@@ -51,14 +58,14 @@ The following describes how to use the native APIs provided by **NativeBuffer**
if (ret != 0) {
std::cout << "OH_NativeBuffer_Map Failed" << std::endl;
}
-
- // Unmap the ION memory from the process address space when it is no longer needed.
+
+// Unmap the ION memory from the process address space when it is no longer needed.
ret = OH_NativeBuffer_Unmap(buffer);
if (ret != 0) {
std::cout << "OH_NativeBuffer_Unmap Failed" << std::endl;
}
```
-
+
3. Obtain the memory properties.
```c++
// Obtain the properties of the OH_NativeBuffer instance.
diff --git a/en/application-dev/napi/native-image-guidelines.md b/en/application-dev/napi/native-image-guidelines.md
index 10142f438059908cef4320b5d01e2029cf6cfe16..46518e0985b2b8ab8403456fced4d16f69b1fcb9 100644
--- a/en/application-dev/napi/native-image-guidelines.md
+++ b/en/application-dev/napi/native-image-guidelines.md
@@ -27,6 +27,17 @@ For details about the APIs, see [native_image](../reference/native-apis/_o_h___n
The following steps describe how to use the native APIs provided by **NativeImage** to create an **OH_NativeImage** instance as the consumer and update the data to a OpenGL external texture.
+**Adding Dynamic Link Libraries**
+
+Add the following libraries to **CMakeLists.txt**:
+```txt
+libEGL.so
+libGLESv3.so
+libnative_image.so
+libnative_window.so
+libnative_buffer.so
+```
+
**Header File**
```c++
#include
@@ -159,41 +170,48 @@ The following steps describe how to use the native APIs provided by **NativeImag
4. Write the produced content to a **NativeWindowBuffer** instance.
1. Obtain a NativeWindowBuffer instance from the NativeWindow instance.
- ```c++
- OHNativeWindowBuffer* buffer = nullptr;
- int fenceFd;
- // Obtain a NativeWindowBuffer instance by calling OH_NativeWindow_NativeWindowRequestBuffer.
- OH_NativeWindow_NativeWindowRequestBuffer(nativeWindow, &buffer, &fenceFd);
- BufferHandle *handle = OH_NativeWindow_GetBufferHandleFromNative(buffer);
- int code = SET_BUFFER_GEOMETRY;
- int32_t width = 0x100;
- int32_t height = 0x100;
- ret = OH_NativeWindow_NativeWindowHandleOpt(nativeWindow, code, width, height);
- ```
- 3. Write the produced content to the **NativeWindowBuffer** instance.
- ```c++
- static uint32_t value = 0x00;
- value++;
- uint32_t *pixel = static_cast(handle->virAddr);
- for (uint32_t x = 0; x < width; x++) {
- for (uint32_t y = 0; y < height; y++) {
- *pixel++ = value;
- }
- }
- ```
- 4. Flush the **NativeWindowBuffer** to the **NativeWindow**.
- ```c++
- // Set the refresh region. If Rect in Region is a null pointer or rectNumber is 0, all contents in the NativeWindowBuffer are changed.
- Region region{nullptr, 0};
- // Flush the buffer to the consumer through OH_NativeWindow_NativeWindowFlushBuffer, for example, by displaying it on the screen.
- OH_NativeWindow_NativeWindowFlushBuffer(nativeWindow, buffer, fenceFd, region);
- ```
- 5. Destroy the **NativeWindow** instance when it is no longer needed.
- ```c++
- OH_NativeWindow_DestroyNativeWindow(nativeWindow);
- ```
-
+ ```c++
+ OHNativeWindowBuffer* buffer = nullptr;
+ int fenceFd;
+ // Obtain a NativeWindowBuffer instance by calling OH_NativeWindow_NativeWindowRequestBuffer.
+ OH_NativeWindow_NativeWindowRequestBuffer(nativeWindow, &buffer, &fenceFd);
+
+ BufferHandle *handle = OH_NativeWindow_GetBufferHandleFromNative(buffer);
+ int code = SET_BUFFER_GEOMETRY;
+ int32_t width = 0x100;
+ int32_t height = 0x100;
+ ret = OH_NativeWindow_NativeWindowHandleOpt(nativeWindow, code, width, height);
+ ```
+
+ 2. Write the produced content to the **NativeWindowBuffer** instance.
+
+ ```c++
+ static uint32_t value = 0x00;
+ value++;
+ uint32_t *pixel = static_cast(handle->virAddr);
+ for (uint32_t x = 0; x < width; x++) {
+ for (uint32_t y = 0; y < height; y++) {
+ *pixel++ = value;
+ }
+ }
+ ```
+
+ 3. Flush the **NativeWindowBuffer** to the **NativeWindow**.
+
+ ```c++
+ // Set the refresh region. If Rect in Region is a null pointer or rectNumber is 0, all contents in the NativeWindowBuffer are changed.
+ Region region{nullptr, 0};
+ // Flush the buffer to the consumer through OH_NativeWindow_NativeWindowFlushBuffer, for example, by displaying it on the screen.
+ OH_NativeWindow_NativeWindowFlushBuffer(nativeWindow, buffer, fenceFd, region);
+ ```
+
+ 4. Destroy the **NativeWindow** instance when it is no longer needed.
+
+ ```c++
+ OH_NativeWindow_DestroyNativeWindow(nativeWindow);
+ ```
+
5. Update the content to the OpenGL texture.
```c++
// Update the content to the OpenGL texture.
diff --git a/en/application-dev/napi/native-vsync-guidelines.md b/en/application-dev/napi/native-vsync-guidelines.md
index 548a791e97ee75a1ee4ad83123893c5495181b59..f43495857483fc529ce03b565011a59e98fc07a7 100644
--- a/en/application-dev/napi/native-vsync-guidelines.md
+++ b/en/application-dev/napi/native-vsync-guidelines.md
@@ -6,12 +6,12 @@ The **NativeVSync** module is used to obtain virtual synchronization (VSync) sig
## Available APIs
-| API| Description:|
+| API| Description|
| -------- | -------- |
-| OH_NativeVSync_Create (const char \*name, unsigned int length) | Creates an **OH_NativeVSync** instance. A new **OH_NativeVSync** instance is created each time this function is called.|
-| OH_NativeVSync_Destroy (OH_NativeVSync \*nativeVsync) | Destroys an **OH_NativeVSync** instance.|
-| OH_NativeVSync_FrameCallback (long long timestamp, void \*data) | Sets a callback function. **timestamp** indicates the timestamp, and **data** indicates the input parameter of the callback function. |
-| OH_NativeVSync_RequestFrame (OH_NativeVSync \*nativeVsync, OH_NativeVSync_FrameCallback callback, void \*data) | Requests the next VSync signal. When the signal arrives, a callback function is invoked.|
+| OH_NativeVSync_Create (const char \*name, unsigned int length) | Creates an **OH_NativeVSync** instance. A new **OH_NativeVSync** instance is created each time this function is called.|
+| OH_NativeVSync_Destroy (OH_NativeVSync \*nativeVsync) | Destroys an **OH_NativeVSync** instance.|
+| OH_NativeVSync_FrameCallback (long long timestamp, void \*data) | Sets a callback function. **timestamp** indicates the timestamp, and **data** indicates the input parameter of the callback function.|
+| OH_NativeVSync_RequestFrame (OH_NativeVSync \*nativeVsync, OH_NativeVSync_FrameCallback callback, void \*data) | Requests the next VSync signal. When the signal arrives, a callback function is invoked.|
For details about the APIs, see [native_vsync](../reference/native-apis/_native_vsync.md).
@@ -19,6 +19,13 @@ For details about the APIs, see [native_vsync](../reference/native-apis/_native_
The following steps describe how to use the native APIs provided by **NativeVSync** to create and destroy an **OH_NativeVSync** instance and set the VSync callback function.
+**Adding Dynamic Link Libraries**
+
+Add the following library to **CMakeLists.txt**:
+```txt
+libnative_vsync.so
+```
+
**Header File**
```c++
#include
@@ -33,12 +40,12 @@ The following steps describe how to use the native APIs provided by **NativeVSyn
std::cout << "OnVSync: " << timestamp << std::endl;
}
OH_NativeVSync_FrameCallback callback = OnVSync; // The callback function must be of the OH_NativeVSync_FrameCallback type.
- ```
+ ```
2. Create an **OH_NativeVSync** instance.
```c++
char name[] = "hello_vsync";
OH_NativeVSync* nativeVSync = OH_NativeVSync_Create(name, strlen(name));
- ```
+ ```
3. Set the VSync callback function through the **OH_NativeVSync** instance.
```c++
diff --git a/en/application-dev/napi/native-window-guidelines.md b/en/application-dev/napi/native-window-guidelines.md
index f6f4e44b5edd8f40757105b4c050d4c9b2b0363d..5c5a62ab3d256689d1d467595797e3f2c605b679 100644
--- a/en/application-dev/napi/native-window-guidelines.md
+++ b/en/application-dev/napi/native-window-guidelines.md
@@ -11,11 +11,11 @@ The following scenarios are common for NativeWindow development:
## Available APIs
-| API| Description|
+| API| Description|
| -------- | -------- |
-| OH_NativeWindow_NativeWindowRequestBuffer (OHNativeWindow \*window, OHNativeWindowBuffer \*\*buffer, int \*fenceFd) | Requests an **OHNativeWindowBuffer** through an **OHNativeWindow** instance for content production.|
-| OH_NativeWindow_NativeWindowFlushBuffer (OHNativeWindow \*window, OHNativeWindowBuffer \*buffer, int fenceFd, Region region) | Flushes the **OHNativeWindowBuffer** filled with the content to the buffer queue through an **OHNativeWindow** instance for content consumption.|
-| OH_NativeWindow_NativeWindowHandleOpt (OHNativeWindow \*window, int code,...) | Sets or obtains the attributes of an **OHNativeWindow**, including the width, height, and content format.|
+| OH_NativeWindow_NativeWindowRequestBuffer (OHNativeWindow \*window, OHNativeWindowBuffer \*\*buffer, int \*fenceFd) | Requests an **OHNativeWindowBuffer** through an **OHNativeWindow** instance for content production.|
+| OH_NativeWindow_NativeWindowFlushBuffer (OHNativeWindow \*window, OHNativeWindowBuffer \*buffer, int fenceFd, Region region) | Flushes the **OHNativeWindowBuffer** filled with the content to the buffer queue through an **OHNativeWindow** instance for content consumption.|
+| OH_NativeWindow_NativeWindowHandleOpt (OHNativeWindow \*window, int code,...) | Sets or obtains the attributes of an **OHNativeWindow**, including the width, height, and content format.|
For details about the APIs, see [native_window](../reference/native-apis/_native_window.md).
@@ -37,7 +37,7 @@ libnative_window.so
#include
```
-1. Obtain an **OHNativeWindow** instance.
+1. Obtain an **OHNativeWindow** instance.
You can call the APIs provided by [OH_NativeXComponent_Callback](../reference/native-apis/_o_h___native_x_component___callback.md) to obtain an **OHNativeWindow** instance. An example code snippet is provided below. For details about how to use the **\**, see [XComponent Development](xcomponent-guidelines.md).
1. Add an **\** to the .ets file.
@@ -159,5 +159,3 @@ libnative_window.so
// munmap failed
}
```
-
-
\ No newline at end of file
diff --git a/en/application-dev/napi/vulkan-guidelines.md b/en/application-dev/napi/vulkan-guidelines.md
index e55b53cd38d44fb5d5a893cdbc21d175b9b0c8df..6ce31b8e1339633bcaa45f47637204f3b4ecef84 100644
--- a/en/application-dev/napi/vulkan-guidelines.md
+++ b/en/application-dev/napi/vulkan-guidelines.md
@@ -18,6 +18,15 @@ For details about the APIs, see [Vulkan](../reference/native-lib/third_party_vul
The following steps illustrate how to create a **VkSurfaceKHR** instance.
+**Adding Dynamic Link Libraries**
+
+Add the following libraries to **CMakeLists.txt**:
+```txt
+libace_ndk.z.so
+libnative_window.so
+libvulkan.so
+```
+
**Header File**
```c++
#include
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 9548ad942cbd5ba3a24e4bcfe57ab71a0fb37043..45efde654b917c333e52d1f0d294282569622c45 100644
--- a/en/application-dev/quick-start/arkts-create-custom-components.md
+++ b/en/application-dev/quick-start/arkts-create-custom-components.md
@@ -70,8 +70,6 @@ To fully understand the preceding example, a knowledge of the following concepts
- [Universal Style of a Custom Component](#universal-style-of-a-custom-component)
-- [Custom Attribute Methods](#custom-attribute-methods)
-
## Basic Structure of a Custom Component
@@ -106,6 +104,8 @@ To fully understand the preceding example, a knowledge of the following concepts
> **NOTE**
>
> Since API version 9, this decorator is supported in ArkTS widgets.
+ >
+ > Since API version 10, the \@Entry decorator accepts an optional parameter of type [LocalStorage](arkts-localstorage.md) or type [EntryOptions](#entryoptions10).
```ts
@Entry
@@ -114,6 +114,23 @@ To fully understand the preceding example, a knowledge of the following concepts
}
```
+ ### EntryOptions10+
+
+ Describes the named route options.
+
+ | Name | Type | Mandatory| Description |
+ | ------ | ------ | ---- | ------------------------------------------------------------ |
+ | routeName | string | No| Name of the target named route.|
+ | storage | [LocalStorage](arkts-localstorage.md) | No| Storage of page-level UI state.|
+
+ ```ts
+ @Entry({ routeName : 'myPage' })
+ @Component
+ struct MyComponent {
+ }
+ ```
+
+
- \@Recycle: A custom component decorated with \@Recycle can be reused.
> **NOTE**
@@ -328,68 +345,4 @@ struct MyComponent {
>
> When ArkUI sets styles for custom components, an invisible container component is set for **MyComponent2**. These styles are set on the container component instead of the **\** component of **MyComponent2**. As seen from the rendering result, the red background color is not directly applied to the button. Instead, it is applied to the container component that is invisible to users where the button is located.
-
-## Custom Attribute Methods
-
-Custom components do not support custom attribute methods. You can use the Controller capability to implement custom APIs.
-
-
-```ts
-// Custom controller
-export class MyComponentController {
- item: MyComponent = null;
-
- setItem(item: MyComponent) {
- this.item = item;
- }
-
- changeText(value: string) {
- this.item.value = value;
- }
-}
-
-// Custom component
-@Component
-export default struct MyComponent {
- public controller: MyComponentController = null;
- @State value: string = 'Hello World';
-
- build() {
- Column() {
- Text(this.value)
- .fontSize(50)
- }
- }
-
- aboutToAppear() {
- if (this.controller)
- this.controller.setItem (this); // Link to the controller.
- }
-}
-
-// Processing logic
-@Entry
-@Component
-struct StyleExample {
- controller = new MyComponentController();
-
- build() {
- Column() {
- MyComponent({ controller: this.controller })
- }
- .onClick(() => {
- this.controller.changeText('Text');
- })
- }
-}
-```
-
-In the preceding example:
-
-1. The **aboutToAppear** method of the **MyComponent** child component passes the current **this** pointer to the **item** member variable of **MyComponentController**.
-
-2. The **StyleExample** parent component holds a **Controller** instance and with which calls the **changeText** API of **Controller**. That is, the value of the state variable **value** of **MyComponent** is changed through the **this** pointer of the **MyComponent** child component held by the controller.
-
-Through the encapsulation of the controller, **MyComponent** exposes the **changeText** API. All instances that hold the controller can call the **changeText** API to change the value of the **MyComponent** state variable **value**.
-
diff --git a/en/application-dev/quick-start/arkts-persiststorage.md b/en/application-dev/quick-start/arkts-persiststorage.md
index 303402ac5a2dffe2537fa4b252a21fcfe31631ad..fdbacd4235dcd50ea2777e8e3695227ff02be70c 100644
--- a/en/application-dev/quick-start/arkts-persiststorage.md
+++ b/en/application-dev/quick-start/arkts-persiststorage.md
@@ -92,7 +92,7 @@ struct Index {
1. The state variable **\@StorageLink('aProp') aProp** is updated, triggering the **\** component to be re-rendered.
2. The two-way synchronization between the \@StorageLink decorated variable and AppStorage results in the change of the **\@StorageLink('aProp') aProp** being synchronized back to AppStorage.
3. The change of the **aProp** attribute in AppStorage triggers any other one-way or two-way bound variables to be updated. (In this example, there are no such other variables.)
- 4. Because the attribute corresponding to **aProp** has been persisted, the change of the **aProp** attribute in AppStorage triggers PersistentStorage to write the attribute and its changed value to the device disk.
+ 4. Because the attribute corresponding to **aProp** has been persisted, the change of the **aProp** attribute in AppStorage triggers PersistentStorage to write the attribute and its new value to the device disk.
- Subsequent application running:
1. **PersistentStorage.PersistProp('aProp', 47)** is called. A search for the **aProp** attribute on the PersistentStorage disk succeeds.
diff --git a/en/application-dev/quick-start/arkts-rendering-control-lazyforeach.md b/en/application-dev/quick-start/arkts-rendering-control-lazyforeach.md
index 95b6665c834a4bdf281b4712717e71f51659c112..30ca2da92bbe84a9f5dd5a7882afac9927c9913e 100644
--- a/en/application-dev/quick-start/arkts-rendering-control-lazyforeach.md
+++ b/en/application-dev/quick-start/arkts-rendering-control-lazyforeach.md
@@ -34,8 +34,8 @@ interface DataChangeListener {
| Name | Type | Mandatory | Description |
| ------------- | --------------------------------------- | ---- | ---------------------------------------- |
| dataSource | IDataSource | Yes | **LazyForEach** data source. You need to implement related APIs. |
-| itemGenerator | (item: any) => void | Yes | Child component generation function, which generates a child component for each data item in the array. **NOTE** The function body of **itemGenerator** must be included in braces {...}. **itemGenerator** can and must generate only one child component for each iteration. The **if** statement is allowed in **itemGenerator**, but you must ensure that each branch of the **if** statement creates a child component of the same type. **ForEach** and **LazyForEach** statements are not allowed in **itemGenerator**.|
-| keyGenerator | (item: any) => string | No | ID generation function, which generates a unique and fixed ID for each data item in the data source. This ID must remain unchanged for the data item even when the item is relocated in the array. When the item is replaced by a new item, the ID of the new item must be different from that of the replaced item. This ID generation function is optional. However, for performance reasons, it is strongly recommended that the ID generation function be provided, so that the framework can better identify array changes. For example, if no ID generation function is provided, a reverse of an array will result in rebuilding of all nodes in **LazyForEach**. **NOTE** The ID generated for each data item in the data source must be unique.|
+| itemGenerator | (item: any) => void | Yes | Child component generation function, which generates a child component for each data item in the array. **NOTE** The function body of **itemGenerator** must be included in braces {...}. **itemGenerator** can and must generate only one child component for each iteration. The **if** statement is allowed in **itemGenerator**, but you must ensure that each branch of the **if** statement creates a child component of the same type. **ForEach** and **LazyForEach** statements are not allowed in **itemGenerator**.|
+| keyGenerator | (item: any) => string | No | ID generation function, which generates a unique and fixed ID for each data item in the data source. This ID must remain unchanged for the data item even when the item is relocated in the array. When the item is replaced by a new item, the ID of the new item must be different from that of the replaced item. This ID generation function is optional. However, for performance reasons, it is strongly recommended that the ID generation function be provided, so that the framework can better identify array changes. For example, if no ID generation function is provided, a reverse of an array will result in rebuilding of all nodes in **LazyForEach**. **NOTE** The ID generated for each data item in the data source must be unique.|
## Description of IDataSource
@@ -52,10 +52,10 @@ interface IDataSource {
| Declaration | Parameter Type | Description |
| ---------------------------------------- | ------------------ | ------------------------------------- |
-| totalCount(): number | - | Obtains the total number of data records. |
-| getData(index: number): any | number | Obtains the data record corresponding to the specified index. **index**: index of the data record to obtain.|
-| registerDataChangeListener(listener:DataChangeListener): void | DataChangeListener | Registers a listener for data changes. **listener**: listener for data changes. |
-| unregisterDataChangeListener(listener:DataChangeListener): void | DataChangeListener | Deregisters the listener for data changes. **listener**: listener for data changes. |
+| totalCount(): number | - | Obtains the total number of data records. |
+| getData(index: number): any | number | Obtains the data record corresponding to the specified index. **index**: index of the data record to obtain.|
+| registerDataChangeListener(listener:DataChangeListener): void | DataChangeListener | Registers a listener for data changes. **listener**: listener for data changes. |
+| unregisterDataChangeListener(listener:DataChangeListener): void | DataChangeListener | Deregisters the listener for data changes. **listener**: listener for data changes. |
## Description of DataChangeListener
@@ -77,20 +77,20 @@ interface DataChangeListener {
| Declaration | Parameter Type | Description |
| ------------------------------------------------------------ | -------------------------------------- | ------------------------------------------------------------ |
-| onDataReloaded(): void | - | Invoked when all data is reloaded. |
-| onDataAdded(index: number):void(deprecated) | number | Invoked when data is added to the position indicated by the specified index. This API is deprecated since API version 8. You are advised to use **onDataAdd** instead. **index**: index of the position where data is added.|
-| onDataMoved(from: number, to: number): void(deprecated) | from: number, to: number | Invoked when data is moved. This API is deprecated since API version 8. You are advised to use **onDataMove** instead. **from**: original position of data; **to**: target position of data. **NOTE** The ID must remain unchanged before and after data movement. If the ID changes, APIs for deleting and adding data must be called.|
-| onDataDeleted(index: number):void(deprecated) | number | Invoked when data is deleted from the position indicated by the specified index. LazyForEach will update the displayed content accordingly. This API is deprecated since API version 8. You are advised to use **onDataDelete** instead. **index**: index of the position where data is deleted.|
-| onDataChanged(index: number): void(deprecated) | number | Invoked when data in the position indicated by the specified index is changed. This API is deprecated since API version 8. You are advised to use **onDataChange** instead. **index**: listener for data changes.|
-| onDataAdd(index: number): void8+ | number | Invoked when data is added to the position indicated by the specified index. **index**: index of the position where data is added.|
-| onDataMove(from: number, to: number): void8+ | from: number, to: number | Invoked when data is moved. **from**: original position of data; **to**: target position of data. **NOTE** The ID must remain unchanged before and after data movement. If the ID changes, APIs for deleting and adding data must be called.|
+| onDataReloaded(): void | - | Invoked when all data is reloaded. |
+| onDataAdd(index: number): void8+ | number | Invoked when data is added to the position indicated by the specified index. **index**: index of the position where data is added.|
+| onDataMove(from: number, to: number): void8+ | from: number, to: number | Invoked when data is moved. **from**: original position of data; **to**: target position of data. **NOTE** The ID must remain unchanged before and after data movement. If the ID changes, APIs for deleting and adding data must be called.|
| onDataDelete(index: number):void8+ | number | Invoked when data is deleted from the position indicated by the specified index. LazyForEach will update the displayed content accordingly. **index**: index of the position where data is deleted. **NOTE** Before **onDataDelete** is called, ensure that the corresponding data in **dataSource** has been deleted. Otherwise, undefined behavior will occur during page rendering.|
-| onDataChange(index: number): void8+ | number | Invoked when data in the position indicated by the specified index is changed. **index**: index of the position where data is changed.|
+| onDataChange(index: number): void8+ | number | Invoked when data in the position indicated by the specified index is changed. **index**: index of the position where data is changed.|
+| onDataAdded(index: number):void(deprecated) | number | Invoked when data is added to the position indicated by the specified index. This API is deprecated since API version 8. You are advised to use **onDataAdd** instead. **index**: index of the position where data is added.|
+| onDataMoved(from: number, to: number): void(deprecated) | from: number, to: number | Invoked when data is moved. This API is deprecated since API version 8. You are advised to use **onDataMove** instead. **from**: original position of data; **to**: target position of data. **NOTE** The ID must remain unchanged before and after data movement. If the ID changes, APIs for deleting and adding data must be called.|
+| onDataDeleted(index: number):void(deprecated) | number | Invoked when data is deleted from the position indicated by the specified index. LazyForEach will update the displayed content accordingly. This API is deprecated since API version 8. You are advised to use **onDataDelete** instead. **index**: index of the position where data is deleted.|
+| onDataChanged(index: number): void(deprecated) | number | Invoked when data in the position indicated by the specified index is changed. This API is deprecated since API version 8. You are advised to use **onDataChange** instead. **index**: listener for data changes.|
## Restrictions
-- **LazyForEach** must be used in the container component. Only the **\**, **\**, and **\** components support lazy loading (that is, only the visible part and a small amount of data before and after the visible part are loaded for caching). For other components, all data is loaded at the same time.
+- LazyForEach must be used in the container component. Only the [\](../reference/arkui-ts/ts-container-list.md), [\](../reference/arkui-ts/ts-container-grid.md), and [\](../reference/arkui-ts/ts-container-swiper.md) components support lazy loading (that is, only the visible part and a small amount of data before and after the visible part are loaded for caching). For other components, all data is loaded at the same time.
- **LazyForEach** must create one and only one child component in each iteration.
@@ -177,7 +177,7 @@ class BasicDataSource implements IDataSource {
}
class MyDataSource extends BasicDataSource {
- private dataArray: string[] = ['/path/image0', '/path/image1', '/path/image2', '/path/image3'];
+ private dataArray: string[] = [];
public totalCount(): number {
return this.dataArray.length;
@@ -201,6 +201,12 @@ class MyDataSource extends BasicDataSource {
@Entry
@Component
struct MyComponent {
+ aboutToAppear() {
+ for (var i = 100; i >= 80; i--) {
+ this.data.pushData(`Hello ${i}`)
+ }
+ }
+
private data: MyDataSource = new MyDataSource();
build() {
@@ -208,15 +214,17 @@ struct MyComponent {
LazyForEach(this.data, (item: string) => {
ListItem() {
Row() {
- Image(item).width('30%').height(50)
- Text(item).fontSize(20).margin({ left: 10 })
+ Text(item).fontSize(50)
+ .onAppear(() => {
+ console.info("appear:" + item)
+ })
}.margin({ left: 10, right: 10 })
}
.onClick(() => {
- this.data.pushData('/path/image' + this.data.totalCount());
+ this.data.pushData(`Hello ${this.data.totalCount()}`);
})
}, item => item)
- }
+ }.cachedCount(5)
}
}
```
diff --git a/en/application-dev/quick-start/arkts-state.md b/en/application-dev/quick-start/arkts-state.md
index be3260d6855bdb72a8e38fbaea31307117ec091b..ccbf348f847f61efc034d2a6347f7390d4b6f558 100644
--- a/en/application-dev/quick-start/arkts-state.md
+++ b/en/application-dev/quick-start/arkts-state.md
@@ -25,21 +25,21 @@ An @State decorated variable, like all other decorated variables in the declarat
## Rules of Use
-| \@State Decorator| Description |
-| ------------ | ---------------------------------------- |
-| Decorator parameters | None. |
-| Synchronization type | Does not synchronize with any type of variable in the parent component. |
-| Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types. For details about the scenarios of nested types, see [Observed Changes](#observed-changes). The type must be specified. **any** is not supported. A combination of simple and complex types is not supported. The **undefined** and **null** values are not allowed. **NOTE** Avoid using this decorator to decorate the Date type, as doing so may lead to unexpected behavior of the application. The Length, ResourceStr, and ResourceColor types are a combination of simple and complex types and therefore not supported.|
-| Initial value for the decorated variable | Mandatory. |
+| \@State Decorator | Description |
+| ------------------ | ------------------------------------------------------------ |
+| Decorator parameters | None. |
+| Synchronization type | Does not synchronize with any type of variable in the parent component. |
+| Allowed variable types| Object, class, string, number, Boolean, enum, and array of these types. Date type. For details about the scenarios of supported types, see [Observed Changes](#observed-changes). The type must be specified. **any** is not supported. A combination of simple and complex types is not supported. The **undefined** and **null** values are not allowed. **NOTE** The Length, ResourceStr, and ResourceColor types are a combination of simple and complex types and therefore not supported.|
+| Initial value for the decorated variable| Local initialization is required. |
## Variable Transfer/Access Rules
-| Transfer/Access | Description |
-| --------- | ---------------------------------------- |
-| Initialization from the parent component | Optional. Initialization from the parent component or local initialization can be used. An \@State decorated variable can be initialized from a regular variable or an \@State, \@Link, \@Prop, \@Provide, \@Consume, \@ObjectLink, \@StorageLink, \@StorageProp, \@LocalStorageLink, or \@LocalStorageProp decorated variable in its parent component.|
-| Subnode initialization | Supported. An \@State decorated variable can be used to initialize a regular variable or \@State, \@Link, \@Prop, or \@Provide decorated variable in the child component.|
-| Access| Private, accessible only within the component. |
+| Transfer/Access | Description |
+| ------------------ | ------------------------------------------------------------ |
+| Initialization from the parent component | Optional. Initialization from the parent component or local initialization can be used. The initial value specified in the parent component will overwrite the one defined locally. An \@State decorated variable can be initialized from a regular variable or an \@State, \@Link, \@Prop, \@Provide, \@Consume, \@ObjectLink, \@StorageLink, \@StorageProp, \@LocalStorageLink, or \@LocalStorageProp decorated variable in its parent component.|
+| Subnode initialization | Supported. An \@State decorated variable can be used to initialize a regular variable or \@State, \@Link, \@Prop, or \@Provide decorated variable in the child component.|
+| Access| Private, accessible only within the component. |
**Figure 1** Initialization rule
@@ -153,6 +153,45 @@ Not all changes to state variables cause UI updates. Only changes that can be ob
this.title.push(new Model(12))
```
+- When the decorated variable is of the Date type, the overall value assignment of the Date object can be observed, and the following APIs can be called to update Date attributes: **setFullYear**, **setMonth**, **setDate**, **setHours**, **setMinutes**, **setSeconds**, **setMilliseconds**, **setTime**, **setUTCFullYear**, **setUTCMonth**, **setUTCDate**, **setUTCHours**, **setUTCMinutes**, **setUTCSeconds**, and **setUTCMilliseconds**.
+
+ ```ts
+ @Entry
+ @Component
+ struct DatePickerExample {
+ @State selectedDate: Date = new Date('2021-08-08')
+
+ build() {
+ Column() {
+ Button('set selectedDate to 2023-07-08')
+ .margin(10)
+ .onClick(() => {
+ this.selectedDate = new Date('2023-07-08')
+ })
+ Button('increase the year by 1')
+ .margin(10)
+ .onClick(() => {
+ this.selectedDate.setFullYear(this.selectedDate.getFullYear() + 1)
+ })
+ Button('increase the month by 1')
+ .margin(10)
+ .onClick(() => {
+ this.selectedDate.setMonth(this.selectedDate.getMonth() + 1)
+ })
+ Button('increase the day by 1')
+ .margin(10)
+ .onClick(() => {
+ this.selectedDate.setDate(this.selectedDate.getDate() + 1)
+ })
+ DatePicker({
+ start: new Date('1970-1-1'),
+ end: new Date('2100-1-1'),
+ selected: this.selectedDate
+ })
+ }.width('100%')
+ }
+ }
+ ```
### Framework Behavior
@@ -168,9 +207,9 @@ Not all changes to state variables cause UI updates. Only changes that can be ob
### Decorating Variables of Simple Types
-In this example, \@State is used to decorate the **count** variable of the simple type and turns it into a state variable. The change of **count** causes the update of the **\** component.
+In this example, \@State is used to decorate the **count** variable of the simple type, turning it into a state variable. The change of **count** causes the update of the **\** component.
-- When the state variable **count** changes, the framework searches for components that depend on this state variable, which include only the **\** component in this example.
+- When **count** changes, the framework searches for components bound to it, which include only the **\** component in this example.
- The framework executes the update method of the **\** component to implement on-demand update.
diff --git a/en/application-dev/quick-start/figures/chooseStageModel.png b/en/application-dev/quick-start/figures/chooseStageModel.png
index b7dd96b6b7c5d2afd241e0c6fd9ee91977692115..dffb66f40999c09e20edfa1b094aee8e62952f61 100644
Binary files a/en/application-dev/quick-start/figures/chooseStageModel.png and b/en/application-dev/quick-start/figures/chooseStageModel.png differ
diff --git a/en/application-dev/quick-start/figures/deleteRuntimeOS.png b/en/application-dev/quick-start/figures/deleteRuntimeOS.png
index 8087b03be057d646ae6e3348abae73c1e840b781..c75770635cb1bb3ab927968afe97664ff8c2ebde 100644
Binary files a/en/application-dev/quick-start/figures/deleteRuntimeOS.png and b/en/application-dev/quick-start/figures/deleteRuntimeOS.png differ
diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001364054489.png b/en/application-dev/quick-start/figures/en-us_image_0000001364054489.png
deleted file mode 100644
index bcc45efdddb87a39201661c5f6d3ccbce9bfd3e6..0000000000000000000000000000000000000000
Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001364054489.png and /dev/null differ
diff --git a/en/application-dev/quick-start/figures/project.png b/en/application-dev/quick-start/figures/project.png
new file mode 100644
index 0000000000000000000000000000000000000000..e1f2db2da30489fa3c4b64587db203a2ef173533
Binary files /dev/null and b/en/application-dev/quick-start/figures/project.png differ
diff --git a/en/application-dev/quick-start/figures/secondPage.png b/en/application-dev/quick-start/figures/secondPage.png
index 2c08d85c610336a71b06407800603ed5c101606d..efca1a48d38136c2a09c3d36e6b4a8b54785cf70 100644
Binary files a/en/application-dev/quick-start/figures/secondPage.png and b/en/application-dev/quick-start/figures/secondPage.png differ
diff --git a/en/application-dev/quick-start/har-package.md b/en/application-dev/quick-start/har-package.md
index 587af49e108ed1cfedbd9a190ea7858bc470073c..1ba7b3402a34a40b7a01c7df261b9362852b55ff 100644
--- a/en/application-dev/quick-start/har-package.md
+++ b/en/application-dev/quick-start/har-package.md
@@ -2,7 +2,17 @@
A Harmony Archive (HAR) is a static shared package that can contain code, C++ libraries, resources, and configuration files. It enables modules and projects to share code related to ArkUI components, resources, and more. Unlike a Harmony Ability Package (HAP), a HAR cannot be independently installed on a device. Instead, it can be referenced only as the dependency of an application module.
## Creating a HAR Module
-You can [create a HAR module in DevEco Studio](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/creating_har_api9-0000001518082393-V3#section143510369612). To better protect your source code, enable obfuscation for the HAR module so that DevEco Studio compiles, obfuscates, and compresses code during HAR building. To enable obfuscation, open the **build-profile.json5** file of the HAR module and set **artifactType** to **obfuscation** as follows:
+You can [create a HAR module in DevEco Studio](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/creating_har_api9-0000001518082393-V3#section143510369612).
+
+To better protect your source code, enable obfuscation for the HAR module so that DevEco Studio compiles, obfuscates, and compresses code during HAR building.
+
+> **NOTE**
+>
+> Obfuscation is only available for ArkTS projects in the stage model.
+
+### Obfuscation in API Version 9
+
+In API version 9, obfuscation is disabled by default, and can be enabled by setting **artifactType** to **obfuscation** in the **build-profile.json5** file of the HAR module. The configuration is as follows:
```json
{
@@ -16,9 +26,43 @@ The value options of **artifactType** are as follows, with the default value bei
- **original**: Code is not obfuscated.
- **obfuscation**: Code is obfuscated using Uglify.
-> **NOTE**
->
-> Obfuscation is available only in the stage model. Therefore, if **artifactType** is set to **obfuscation**, **apiType** must be set to **stageMode**.
+### Obfuscation in API Version 10
+
+In API version 10, obfuscation is enabled by default, and can be set through the **enable** field under **ruleOptions** in the **build-profile.json5** file of the HAR module. The configuration is as follows:
+
+```json
+{
+ "apiType": "stageMode",
+ "buildOption": {
+ },
+ "buildOptionSet": [
+ {
+ "name": "release",
+ "arkOptions": {
+ "obfuscation": {
+ "ruleOptions": {
+ "enable": true,
+ "files": [
+ "./obfuscation-rules.txt"
+ ]
+ },
+ "consumerFiles": [
+ "./consumer-rules.txt"
+ ]
+ }
+ }
+ },
+ ],
+ "targets": [
+ {
+ "name": "default"
+ }
+ ]
+}
+```
+### Adaptation Guide
+
+The **artifactType** field is forward compatible, and the original function is not affected. Yet, it is deprecated since API version 10, and you are advised to use the substitute as soon as possible.
## Precautions for HAR Development
- The HAR does not support the declaration of **abilities** and **extensionAbilities** in its configuration file.
@@ -95,10 +139,10 @@ To start with, [configure dependency](https://developer.harmonyos.com/cn/docs/do
### Reference ArkUI Components in the HAR
-After configuring the dependency on the HAR, you can reference ArkUI components exported from the HAR by using **import**. The sample code is as follows:
+After configuring the dependency on the HAR, you can reference ArkUI components exported from the HAR by using **import**. The code snippet is as follows:
```js
// entry/src/main/ets/pages/index.ets
-import { MainPage } from "@ohos/library"
+import { MainPage } from "library"
@Entry
@Component
@@ -123,8 +167,8 @@ struct Index {
To reference the TS classes and methods exported from the HAR, use **import** as follows:
```js
// entry/src/main/ets/pages/index.ets
-import { Log } from "@ohos/library"
-import { func } from "@ohos/library"
+import { Log } from "library"
+import { func } from "library"
@Entry
@Component
diff --git a/en/application-dev/quick-start/introduction-to-arkts.md b/en/application-dev/quick-start/introduction-to-arkts.md
index 88a0cb306220caf5f5ebcb0fea8eaf0c9db6f674..b3bbd6671524a508d881c3d5245d0a1958d59c63 100644
--- a/en/application-dev/quick-start/introduction-to-arkts.md
+++ b/en/application-dev/quick-start/introduction-to-arkts.md
@@ -48,12 +48,17 @@ applications in ArkTS.
## Declarations
-Declarations in ArkTS introduce variables, constants, functions and types.
+Declarations in ArkTS introduce:
+
+- variables,
+- constants,
+- functions, and
+- types.
### Variable Declaration
-Declaration started with keyword `let` introduces a variable which can have different values
-during program execution.
+A declaration starting with the keyword `let` introduces a variable which
+can have different values during program execution.
```typescript
let hi: string = "hello"
@@ -62,18 +67,19 @@ hi = "hello, world"
### Constant Declaration
-Declaration started with keyword `const` introduces a read-only constant that can be assigned only once.
+A declaration starting with the keyword `const` introduces a read-only
+constant that can be assigned only once.
```typescript
const hello: string = "hello"
```
-Assigning a new value to a constant is a compile-time error.
+A compile-time error occurs if a new value is assigned to a constant.
### Automatic Type Inference
As ArkTS is a statically typed language, the types of all entities, like
-variables and constants have to be known at compile time.
+variables and constants, have to be known at compile time.
However, developers do not need to explicitly specify the type of a declared
entity if a variable or a constant declaration contains an initial value.
@@ -90,8 +96,8 @@ let hi2 = "hello, world"
## Types
-`Class`, `interface`, `function`, `enum`, `union` types and type `aliases` are
-described in the corresponding sections.
+`Class`, `interface`, `function`, `enum`, `union` types, and type
+`aliases` are described in the corresponding sections.
### Numeric Types
@@ -104,9 +110,9 @@ with the decimal base.
Integer literals include the following:
* decimal integers that consist of a sequence of digits. For example: `0`, `117`, `-345`;
-* hexadecimal integers that start with 0x (or 0X) and can contain digits (0-9) and letters a-f or A-F. For example: `0x1123`, `0x00111`, `-0xF1A7`;
+* hexadecimal integers that start with 0x (or 0X), and can contain digits (0-9) and letters a-f or A-F. For example: `0x1123`, `0x00111`, `-0xF1A7`;
* octal integers that start with 0o (or 0O) and can only contain digits (0-7). For example: `0o777`;
-* binary integers that start with 0b (or 0B) and can only contain the digits 0 and 1. For example: `0b11`, `0b0011`, `-0b11`.
+* binary integers that start with 0b (or 0B), and can only contain the digits 0 and 1. For example: `0b11`, `0b0011`, `-0b11`.
A floating-point literal includes the following:
@@ -150,13 +156,12 @@ if (isDone) {
### `String`
-A `string` is a sequence of characters; some characters can be set using
-escape-sequences.
+A `string` is a sequence of characters; some characters can be set by using
+escape sequences.
-A `string` literal consists of zero or more characters
-enclosed between single (’) or
-double quotes (“). The special form of a string literals are template literals
-enclosed in backtick quotes (\`).
+A `string` literal consists of zero or more characters enclosed in single
+(’) or double quotes (“). The special form of string literals are template
+literals enclosed in backtick quotes (\`).
```typescript
let s1 = "Hello, world!\n"
@@ -168,9 +173,8 @@ let s3 = `The result is ${a}`
### `Void` Type
The `void` type is used to specify that a function does not return a value.
-This type has the only one value,
-which is also `void`. As `void` is reference type, it can be used as type
-argument for generic types.
+This type has the only one value which is also `void`. As `void` is
+a reference type, it can be used as type argument for generic types.
```typescript
class Class {
@@ -181,19 +185,18 @@ let instance: Class
### `Object` Type
-An `Object` class type is a base type for all reference types. Any value, including
-values of primitive types (they will be automatically boxed), can be directly assigned
-to variables of type `Object`.
+An `Object` class type is a base type for all reference types. Any value,
+including values of primitive types (they will be automatically boxed), can
+be directly assigned to variables of the type `Object`.
### `Array` Type
An `array` is an object comprised of elements of data types assignable to
the element type specified in the array declaration.
-A value of an `array` is set using *array composite literal*, that is a list
-of zero or more expressions
-enclosed in square brackets ([]). Each expression represents an element of the
-`array`. The length of the `array` is set by the number of expressions. Index of
-the first array element is 0.
+A value of an `array` is set by using *array composite literal*, that is a
+list of zero or more expressions enclosed in square brackets ([]). Each
+expression represents an element of the `array`. The length of the `array`
+is set by the number of expressions. Index of the first array element is 0.
The following example creates the `array` with three elements:
@@ -205,15 +208,16 @@ let names: string[] = ["Alice", "Bob", "Carol"]
An `enum` type is a value type with a defined set of named values called
enum constants.
-To be used, an `enum` constant must be prefixed with an enum `type` name.
+In order to be used, an `enum` constant must be prefixed with an enum
+`type` name.
```typescript
enum Color { Red, Green, Blue }
let c: Color = Color.Red
```
-A constant expression can be
-used to explicitly set the value of an enum constant.
+A constant expression can be used to explicitly set the value of an `enum`
+constant.
```typescript
enum Color { White = 0xFF, Grey = 0x7F, Black = 0x00 }
@@ -222,8 +226,9 @@ let c: Color = Color.Black
### `Union` Type
-An `union` type is a reference type which is created as a combination of other types. Values of the union types
-can be valid values of all types union was created from.
+A `union` type is a reference type which is created as a combination
+of other types. Values of union types can be valid values of all types
+a union was created from.
```typescript
class Cat {
@@ -244,7 +249,8 @@ animal = 42
// One may assign the variable of the union type with any valid value
```
-There are different mechanisms how to get a value of the particular type from the union.
+There are different mechanisms to get a value of a particular type from a union.
+
For example
```typescript
@@ -267,8 +273,8 @@ animal.sleep () // Any animal can sleep
### Type `Aliases`
-Type `aliases` provide names for anonymous types (array, function, object literal or union
-types) or alternative names for existing types.
+Type `aliases` provide names for anonymous types (array, function, object
+literal or union types) or alternative names for existing types.
```typescript
type Matrix = number[][]
@@ -284,7 +290,7 @@ type NullableObject = Object | null
Simple assignment operator ‘=’ is used as in “x = y”.
Compound assignment operators combine an assignment with an operator, where
-`x op = y` equals to `x = x op y`.
+`x op = y` equals `x = x op y`.
Compound assignment operators are as follows: `+=`, `-=`, `*=`, `/=`,
`%=`, `<<=`, `>>=`, `>>>=`, `&=`, `|=`, `^=`.
@@ -299,10 +305,9 @@ Compound assignment operators are as follows: `+=`, `-=`, `*=`, `/=`,
| `>=` | returns true if the left operand is greater than or equal to the right |
| `<` | returns true if the left operand is less then the right |
| `<=` | returns true if the left operand is less than or equal to the right |
-
### Arithmetic Operators
-Unary operators are `-`, `+`, `--`, `++`.
+Unary operators are `-`, `+`, `--` and `++`.
Binary operators are as follows:
@@ -313,7 +318,6 @@ Binary operators are as follows:
| `*` | multiplication |
| `/` | division |
| `%` | remainder after division |
-
### Bitwise Operators
| Operator | Description |
@@ -325,7 +329,6 @@ Binary operators are as follows:
| `a << b` | Shift left: shifts the binary representation of *a* to the left by *b* bits. |
| `a >> b` | Arithmetic right shift: shifts the binary representation of *a* to the right by *b* bits with sign-extension. |
| `a >>> b` | Logical right shift: shifts the binary representation of *a* to the right by *b* bits with zero-extension. |
-
### Logical Operators
| Operator | Description |
@@ -333,16 +336,15 @@ Binary operators are as follows:
| `a && b` | logical AND |
| `a \|\| b` | logical OR |
| `! a` | logical NOT |
-
## Control Flow
### `If` Statements
-Use `if` statement to execute a sequence of statements when a logical
-condition is true, or another set of statements (if provided) otherwise.
-`else` part may contain more `if` statements as well.
+An `if` statement is used to execute a sequence of statements when a logical
+condition is `true`, or another set of statements (if provided) otherwise.
+The `else` part can also contain more `if` statements.
-The `if` statement looks as follows:
+An `if` statement looks as follows:
```typescript
if (condition1) {
@@ -354,7 +356,7 @@ if (condition1) {
}
```
-All conditional expressions should be of the type `boolean` or other types
+All conditional expressions must be of the type `boolean` or other types
(`string`, `number`, etc.). For types other than `boolean`, implicit
conversion rules apply:
@@ -372,10 +374,10 @@ if (s2.length != 0) {
### `Switch` Statements
-Use `switch` statement to execute a sequence of statements that match the
-value of the switch expression.
+A `switch` statement is used to execute a sequence of statements that match
+the value of a switch expression.
-The `switch` statement looks as follows:
+A `switch` statement looks as follows:
```typescript
switch (expression) {
@@ -396,7 +398,7 @@ default:
```
The `switch` expression type must be of `number`, `enum` or `string`
-type.
+types.
Each label must be either a constant expression or the name of an enum constant.
@@ -409,14 +411,15 @@ default statements are executed.
An optional `break` statement allows to break out of the `switch` and
continue executing the statement that follows the `switch`.
-If there is no break, then the next statements in the `switch` is executed.
+If there is no `break`, then the next statements in the `switch` is
+executed.
### Conditional Expressions
-The conditional expression `?` : uses the `boolean` value of the first
+The conditional expression `? :` uses the `boolean` value of the first
expression to decide which of two other expressions to evaluate.
-It looks as follows:
+A conditional expression looks as follows:
```typescript
condition ? expression1 : expression2
@@ -435,8 +438,10 @@ let message = isValid ? 'Valid' : 'Failed'
### `For` Statements
-A `for` statement is executed repeatedly until the specified loop exit condition
-is `false`. A `for` statement looks as follows:
+A `for` statement is executed repeatedly until the specified loop exit
+condition is `false`.
+
+A `for` statement looks as follows:
```typescript
for ([init]; [condition]; [update]) {
@@ -446,10 +451,15 @@ for ([init]; [condition]; [update]) {
When a `for` statement is executed, the following process takes place:
-1. An `init` expression is executed, if any. This expression usually initializes one or more loop counters.
-2. The condition is evaluated. If the value of condition is `true`, or if the conditional expression is omitted, then the statements in the for body are to be executed. If the value of condition is `false`, the `for` loop terminates.
+1. An `init` expression is executed, if any. This expression usually
+ initializes one or more loop counters.
+2. The condition is evaluated. If the value of condition is `true`, or
+ if the conditional expression is omitted, then the statements in the
+ `for` body are to be executed. If the value of condition is `false`,
+ then the `for` loop terminates.
3. The statements of the `for` body are executed.
-4. If there is an `update` expression, the `update` expression is executed.
+4. If there is an `update` expression, then the `update` expression
+ is executed.
5. Go back to step 2.
Example:
@@ -463,8 +473,9 @@ for (let i = 0; i < 10; i += 2) {
### `For-of` Statements
-Use `for-of` statements to iterate over an array or string. A `for-of`
-statement looks as follows:
+`for-of` statements are used to iterate over an array or string.
+
+A `for-of` statement looks as follows:
```typescript
for (forVar of expression) {
@@ -480,8 +491,10 @@ for (let ch of "a string object") { /* process ch */ }
### `While` Statements
-A `while` statement has its body statements executed as long as the specified condition
-evaluates to `true`. It looks as follows:
+A `while` statement has its body statements executed as long as the
+specified condition evaluates to `true`.
+
+A `while` statement looks as follows:
```typescript
while (condition) {
@@ -504,8 +517,10 @@ while (n < 3) {
### `Do-while` Statements
-The `do-while` statements are executed repetitively until the specified
-condition evaluates to false. It looks as follows:
+`do-while` statements are executed repetitively until a specified
+condition evaluates to false.
+
+A `do-while` statement looks as follows:
```typescript
do {
@@ -526,7 +541,7 @@ do {
### `Break` Statements
-Use a `break` statement to terminate any `loop` statement or `switch`.
+A `break` statement is used to terminate any `loop` statement or `switch`.
Example:
@@ -558,8 +573,8 @@ label: while (true) {
### `Continue` Statements
-A `continue` statement stops the execution of the current loop iteration and
-passes control to the next iteration.
+A `continue` statement stops the execution of the current loop iteration
+and passes control to the next iteration.
Example:
@@ -575,13 +590,13 @@ for (let x = 0; x < 100; x++) {
### `Throw` and `Try` Statements
-A `throw` statement is used to throw an exception or error:
+A `throw` statement is used to throw an exception or an error:
```typescript
throw new Error("this error")
```
-A `try` statement is used to catch and handle an exception or error:
+A `try` statement is used to catch and handle an exception or an error:
```typescript
try {
@@ -672,7 +687,7 @@ function hello(name?: string) {
Another form contains an expression that specifies a default value.
If the corresponding argument to such parameter is omitted in a function call,
-then this parameter has the default value.
+then this parameter’s value is default.
```typescript
function multiply(n: number, coeff: number = 2): number {
@@ -701,7 +716,8 @@ sum(1, 2, 3) // returns 6
## Return Types
-If function return type can be inferred from its body content then it can be omitted from the function declaration.
+If function return type can be inferred from its body content, then it can
+be omitted from the function declaration.
```typescript
// Explicit return type
@@ -711,7 +727,9 @@ function foo(): string { return "foo" }
function goo() { return "goo" }
```
-The return type of a function that does not need to return a value may be explicitly specified as `void` or omitted altogether. No return statement is needed for such functions.
+The return type of a function that does not need to return a value can be
+explicitly specified as `void` or omitted altogether. No return statement
+is needed for such functions.
Both notations below are valid:
@@ -722,13 +740,16 @@ function hi2(): void { console.log("hi") }
## Function Scope
-Variables and other entities defined in a function are local to the function and cannot be accessed outside.
+Variables and other entities defined in a function are local to the function
+and cannot be accessed from the outside.
-If the name of a variable defined in the function is equal to the name of an entity in the outer scope, then the local definition shadows outer entity.
+If the name of a variable defined in the function is equal to the name of an
+entity in the outer scope, then the local definition shadows the outer entity.
## Function Calls
-Calling a function actually leads to its body execution while arguments of the call are assigned to function parameters.
+Calling a function actually leads to the execution of its body, while
+the arguments of the call are assigned to the function parameters.
If the function is defined as follows:
@@ -770,9 +791,11 @@ let sum = (x: number, y: number): number => {
}
```
-An arrow function return type may be omitted; in this case it is inferred from the function body.
+An arrow function return type can be omitted; in such case, it is inferred
+from the function body.
-An expression can be specified as an arrow function, making notation shorter, so the following two notations are equivalent:
+An expression can be specified as an arrow function to make the notation
+shorter, i.e., the following two notations are equivalent:
```typescript
let sum1 = (x: number, y: number) => { return x + y }
@@ -781,10 +804,12 @@ let sum2 = (x: number, y: number) => x + y
## Closure
-An arrow function is usually defined inside another function. As an inner function, it can access all variables and functions defined in the outer functions.
+An arrow function is usually defined inside another function. As an inner
+function, it can access all variables and functions defined in the outer
+functions.
To capture the context, an inner function forms a closure of its environment.
-The closure allows accessing such inner function outside its own environment.
+The closure allows accessing such an inner function outside its own environment.
```typescript
function f(): () => number {
@@ -801,7 +826,10 @@ In the sample above, the arrow function closure captures the `count` variable.
## Function Overload Signatures
-A function can be specified to be called in different ways by writing overload signatures. To do so, several functions headers are written that they have the same name but different signatures, immediately followed by the single implementing function.
+A function can be specified to be called in different ways by writing
+overload signatures. To do so, several functions’ headers that have the
+same name but different signatures are written and immediately followed
+by the single implementation function.
```typescript
function foo(): void; /* 1st signature */
@@ -814,13 +842,15 @@ foo() // ok, 1st signature is used
foo("aa") // ok, 2nd signature is used
```
-It is an error if two overload signatures have identical parameter lists.
+An error occurs if two overload signatures have identical parameter lists.
# Classes
-A class declaration introduces a new type and defines its fields, methods and constructors.
+A class declaration introduces a new type and defines its fields, methods
+and constructors.
-In the following example, class `Person` is defined, which has fields ‘name’ and ‘surname’, constructor and a method `fullName`:
+In the following example, class `Person` is defined, which has fields
+‘name’ and ‘surname’, constructor, and a method `fullName`:
```typescript
class Person {
@@ -836,21 +866,22 @@ class Person {
}
```
-After the class is defined, its instances can be created using the keyword `new`:
+After the class is defined, its instances can be created by using
+the keyword `new`:
```typescript
let p = new Person("John", "Smith")
console.log(p.fullName())
```
-Or an instance can be created using object literals:
+or an instance can be created by using object literals:
```typescript
class Point {
x: number = 0
y: number = 0
}
-let p: Point = {42 ,42}
+let p: Point = {x: 42, y: 42}
```
## Fields
@@ -877,7 +908,7 @@ let p1 = new Person("Alice", 25)
let p2 = new Person("Bob", 28)
```
-To access an instance field, use an instance of the class:
+An instance of the class is used to access an instance field:
```typescript
p1.name
@@ -886,10 +917,11 @@ this.name
### Static Fields
-Use the keyword `static` to declare a field as static. Static fields belong
-to the class itself, and all instances of the class share one static field.
+The keyword `static` is used to declare a field as static. Static fields
+belong to the class itself, and all instances of the class share one static
+field.
-To access a static field, use the class name:
+The class name is used to access a static field:
```typescript
class Person {
@@ -906,9 +938,11 @@ console.log(Person.numberOfPersons)
### Getters and Setters
-Setters and getters can be used to provide controlled access to object properties.
+Setters and getters can be used to provide controlled access to object
+properties.
-In the following example, a setter is used to forbid setting invalid values of the ‘age’ property:
+In the following example, a setter is used to forbid setting invalid
+values of the ‘age’ property:
```typescript
class Person {
@@ -928,19 +962,22 @@ console.log (p.age) // 0 will be printed out
p.age = -42 // Error will be thrown as an attempt to set incorrect age
```
-A class may define a getter, a setter or both.
+A class can define a getter, a setter or both.
## Methods
A method is a function that belongs to a class.
A class can define instance methods, static methods or both.
-A static method belongs to the class itself, and can have access to static fields only.
-While instance method has access to both static (class) fields and instance fields including private ones of its class.
+A static method belongs to the class itself, and can have access to static
+fields only.
+A `while` instance method has access to both static (class) fields and
+instance fields including private ones of its class.
### Instance Methods
-Example below illustrates how instanced methods work.
-The `calculateArea` method calculates the area of a rectangle by multiplying the height by the width:
+The example below illustrates how instanced methods work.
+The `calculateArea` method calculates the area of a rectangle by
+multiplying the height by the width:
```typescript
class Rectangle {
@@ -955,20 +992,21 @@ class Rectangle {
}
```
-To use an instance method, call it on an instance of the class:
+To use an instance method, it must be called on an instance of the class:
```typescript
-let r = new Rectangle(10, 10)
+let square = new Rectangle(10, 10)
console.log(square.calculateArea()) // output: 100
```
### Static Methods
-Use the keyword `static` to declare a method as static. Static methods belong to the class itself and have access to static fields only.
+The keyword `static` is used to declare a method as static. Static methods
+belong to the class itself and have access to static fields only.
A static method defines a common behavior of the class as a whole.
All instances have access to static methods.
-To call a static method, use the class name:
+The class name is used to call a static method:
```typescript
class Cl {
@@ -981,7 +1019,8 @@ console.log(Cl.staticMethod())
### Inheritance
-A class can extend another class (called base class) and implement several interfaces using the following syntax:
+A class can extend another class (called base class) and implement several
+interfaces by using the following syntax:
```typescript
class [extends BaseClassName] [implements listOfInterfaces] {
@@ -989,9 +1028,12 @@ class [extends BaseClassName] [implements listOfInterfaces] {
}
```
-The extended class inherits fields and methods from the base class, but not constructors, and can add its own fields and methods as well as override methods defined by the base class.
+The extended class inherits fields and methods from the base class, but
+not constructors, and can add its own fields and methods as well as override
+methods defined by the base class.
-The base class is also called ‘parent class’ or ‘superclass’. The extended class also called ‘derived class’ or ‘subclass’.
+The base class is also called ‘parent class’ or ‘superclass’.
+The extended class also called ‘derived class’ or ‘subclass’.
Example:
@@ -1011,7 +1053,9 @@ class Employee extends Person {
}
```
-A class containing the `implements` clause must implement all methods defined in all listed interfaces, except the methods defined with default implementation.
+A class containing the `implements` clause must implement all methods
+defined in all listed interfaces, except the methods defined with default
+implementation.
```typescript
interface DateInterface {
@@ -1027,9 +1071,11 @@ class MyDate implements DateInterface {
### Access to Super
-The keyword `super` can be used to access instance fields, instance methods and constructors from the super class.
+The keyword `super` can be used to access instance fields, instance methods
+and constructors from the super class.
-It is often used to extend basic functionality of subclass with the required behavior taken from the super class:
+It is often used to extend basic functionality of subclass with the required
+behavior taken from the super class:
```typescript
class Rectangle {
@@ -1062,9 +1108,11 @@ class FilledRectangle extends Rectangle {
### Override Methods
-A subclass may override implementation of a method defined in its superclass.
-An overridden method may be marked with the keyword `override`, to improve readability.
-An overridden method must have the same types of parameters and same or derived return type as the original method.
+A subclass can override implementation of a method defined in its superclass.
+An overridden method can be marked with the keyword `override` to improve
+readability.
+An overridden method must have the same types of parameters, and same or
+derived return type as the original method.
```typescript
class Rectangle {
@@ -1084,7 +1132,10 @@ class Square extends Rectangle {
### Method Overload Signatures
-A method can be specified to can be called in different ways by writing overload signatures. To do so, several method headers are written that have the same name but different signatures, immediately followed by the single implementation method.
+A method can be specified to be called in different ways by writing overload
+signatures. To do so, several method headers that have the same name but
+different signatures are written and immediately followed by the single
+implementation method.
```typescript
class C {
@@ -1099,13 +1150,15 @@ c.foo() // ok, 1st signature is used
c.foo("aa") // ok, 2nd signature is used
```
-It is an error if two overload signatures have the same name and identical parameter lists.
+An error occurs if two overload signatures have the same name and identical
+parameter lists.
## Constructors
-A class declaration may contain a constructor that is used to initialize object state.
+A class declaration may contain a constructor that is used to initialize
+object state.
-Constructor is defined as follows:
+A constructor is defined as follows:
```typescript
constructor ([parameters]) {
@@ -1113,7 +1166,8 @@ constructor ([parameters]) {
}
```
-If no constructor is defined, then a default constructor with an empty parameter list is created automatically, for example:
+If no constructor is defined, then a default constructor with an empty
+parameter list is created automatically, for example:
```typescript
class Point {
@@ -1123,11 +1177,13 @@ class Point {
let p = new Point()
```
-In this case the default constructor fills the instance fields with default values for the field types.
+In this case the default constructor fills the instance fields with
+default values for the field types.
### Constructors in Derived Class
-The first statement of a constructor body can use the keyword `super` to explicitly call a constructor of the direct superclass.
+The first statement of a constructor body can use the keyword `super`
+to explicitly call a constructor of the direct superclass.
```typescript
class Rectangle {
@@ -1142,11 +1198,16 @@ class Square extends Rectangle {
}
```
-If a constructor body does not begin with such an explicit call of a superclass constructor, then the constructor body implicitly begins with a superclass constructor call `super()`.
+If a constructor body does not begin with such an explicit call of a
+superclass constructor, then the constructor body implicitly begins
+with a superclass constructor call `super()`.
### Constructor Overload Signatures
-A constructor can be specified to can be called in different ways by writing overload signatures. To do so, several constructor headers are written that have the same name but different signatures, immediately followed by the single implementation constructor.
+A constructor can be specified to be called in different ways by writing
+overload signatures. To do so, several constructor headers that have the
+same name but different signatures are written and immediately followed
+by the single implementation constructor.
```typescript
class C {
@@ -1160,23 +1221,33 @@ let c1 = new C() // ok, 1st signature is used
let c2 = new C("abc") // ok, 2nd signature is used
```
-It is an error if two overload signatures have the same name and identical parameter lists.
+An error occurs if two overload signatures have the same name and
+identical parameter lists.
## Visibility Modifiers
Both methods and properties of a class can have visibility modifiers.
-There are several visibility modifiers: `private`, `protected`,
-`public`, and `internal`. The default visibility is `public`.
-`internal` allows to limit visibility within the current package.
+There are several visibility modifiers:
+
+- `private`,
+- `protected`,
+- `public`, and
+- `internal`.
+
+The default visibility is `public`.
+The modifier `internal` allows to limit visibility within
+the current package.
### Public Visibility
-The `public` members (fields, methods, constructors) of a class are visible in any part of the program, where their class is visible.
+The `public` members (fields, methods, constructors) of a class are
+visible in any part of the program, where their class is visible.
### Private Visibility
-A `private` member cannot be accessed outside the class in which it is declared, for example:
+A `private` member cannot be accessed outside the class it is declared in,
+for example:
```typescript
class C {
@@ -1193,8 +1264,8 @@ c.y = "b" // compile-time error: 'y' is not visible
### Protected Visibility
-The `protected` modifier acts much like the `private` modifier, but
-`protected` members are also accessible in derived classes, for example:
+The modifier `protected` acts much like the modifier `private`, but
+the `protected` members are also accessible in derived classes, for example:
```typescript
class Base {
@@ -1211,9 +1282,12 @@ class Derived extends Base {
## Object Literals
-An object literal is an expression that can be used to create a class instance and provide some initial values. It can be used instead of `new` expression as it is more convenient in some cases.
+An object literal is an expression that can be used to create a class instance
+and provide some initial values. It can be used instead of the expression
+`new` as it is more convenient in some cases.
-A class composite is written as a comma-separated list of name-value pairs enclosed in ‘{’ and ‘}’.
+A class composite is written as a comma-separated list of name-value pairs
+enclosed in ‘{’ and ‘}’.
```typescript
class C {
@@ -1224,7 +1298,9 @@ class C {
let c: C = {n: 42, s: "foo"}
```
-Due to static typing of the ArkTS the object literals can be used in context where the class or interface type of the object literal can be inferred as in the example above. Other valid cases:
+Due to the static typing of the ArkTS, object literals can be used in a
+context where the class or interface type of the object literal can be
+inferred as in the example above. Other valid cases are illustrated below:
```typescript
class C {
@@ -1244,7 +1320,7 @@ function bar(): C {
}
```
-Type of an array element or a type of a class field also can be used:
+The type of an array element or of a class field can also be used:
```typescript
class C {
@@ -1254,10 +1330,12 @@ class C {
let cc: C[] = [{n: 1, s: "a"}, {n: 2, s: "b"}]
```
-### Object Literals of the Record Type
+### Object Literals of Record Type
+
+The generic Record type is used to map the properties of a type
+(Key type) to another type (Value type).
-The generic Record type is used to map the properties of a type (Key type) to another type (Value type).
-A special form of an object literal is used to initialize the value of such type:
+A special form of object literal is used to initialize the value of such type:
```typescript
let map: Record = {
@@ -1283,9 +1361,11 @@ let map: Record = {
# Interfaces
-An interface declaration introduces a new type. Interfaces are a common way of defining contracts between various part of codes.
+An interface declaration introduces a new type. Interfaces are a common way
+of defining contracts between various part of codes.
-Interfaces are used to write polymorphic code, which can be applied to any class instances that implement a particular interface.
+Interfaces are used to write polymorphic code, which can be applied to any
+class instances that implement a particular interface.
An interface usually contains properties and method headers.
@@ -1326,9 +1406,11 @@ class Rectangle implements Area {
## Interface Properties
-An interface property can be in a form of field, getter, setter or both getter and setter.
+An interface property can be in a form of field, getter, setter, or both
+getter and setter.
-A property field is just a shortcut notation of a getter/setter pair, and the following notations are equal:
+A property field is just a shortcut notation of a getter/setter pair, and
+the following notations are equal:
```typescript
interface Style {
@@ -1381,28 +1463,31 @@ interface ExtendedStyle extends Style {
}
```
-An extended interface contains all properties and methods of the interface it extends and may also add its own properties and methods.
+An extended interface contains all properties and methods of the
+interface it extends, and can also add its own properties and methods.
## Interface Visibility Modifiers
Properties and methods are `public`.
-Only methods with default implementation may be defined as `private`.
+Only methods with default implementation can be defined as `private`.
# Generic Types and Functions
-Generic types and functions allow creating the code capable to work over a variety of types rather than a single one.
+Generic types and functions allow creating the code capable to work over a
+variety of types rather than a single type.
## Generic Classes and Interfaces
-A class and an interface can be defined as generics, adding parameters to the type definition, like the type parameter `Element` in the following example:
+A class and an interface can be defined as generics, adding parameters to the
+type definition, like the type parameter `Element` in the following example:
```typescript
class Stack {
public pop(): Element {
// ...
}
- public push(e: Element) {
+ public push(e: Element): void {
// ...
}
}
@@ -1415,7 +1500,8 @@ let s = new Stack
s.push("hello")
```
-Compiler ensures type safety while working with generic types and functions. See below
+Compiler ensures type safety while working with generic types and functions.
+See below:
```typescript
let s = new Stack
@@ -1424,7 +1510,9 @@ s.push(55) // That will be a compile-time error
## Generic Constraints
-Type parameters of generic types can be bounded. For example, the `Key` type parameter in the `HashMap` container must have a hash method, i.e., it should be hashable.
+Type parameters of generic types can be bounded. For example, the `Key`
+type parameter in the `HashMap` container must have a hash
+method, i.e., it must be hashable.
```typescript
interface Hashable {
@@ -1438,11 +1526,13 @@ class HasMap {
}
```
-In the above example, the `Key` type extends `Hashable`, and all methods of `Hashable` interface can be called for keys.
+In the above example, the `Key` type extends `Hashable`, and all methods
+of `Hashable` interface can be called for keys.
## Generic Functions
-Use a generic function to create a more universal code. Consider a function that returns the last element of the array:
+Use a generic function to create a more universal code. Consider a function
+that returns the last element of the array:
```typescript
function last(x: number[]): number {
@@ -1451,7 +1541,8 @@ function last(x: number[]): number {
console.log(last([1, 2, 3])) // output: 3
```
-If the same function needs to be defined for any array, define it as generic with a type parameter:
+If the same function needs to be defined for any array, then define it as
+a generic with a type parameter:
```typescript
function last(x: T[]): T {
@@ -1461,7 +1552,7 @@ function last(x: T[]): T {
Now, the function can be used with any array.
-In a function call, type argument may be set explicitly or implicitly:
+In a function call, type argument can be set explicitly or implicitly:
```typescript
// Explicit type argument
@@ -1476,7 +1567,8 @@ console.log(last([1, 2, 3]))
## Generic Defaults
Type parameters of generic types can have defaults.
-It allows not specifying the actual type arguments but using just the generic type name.
+It allows using just the generic type name instead of specifying the actual
+type arguments.
Example below illustrates this for both classes and functions.
```typescript
@@ -1497,9 +1589,10 @@ foo()
# Null Safety
-All types in ArkTS by default are non-nullable, so the value of a type cannot be null.
+All types in ArkTS by default are non-nullable, so the value of a type
+cannot be null.
It is similar to TypeScript behavior in strict null checking mode
-(`strictNullChecks`), but the rules are stricter, and the there is no `undefined` type in ArkTS.
+(`strictNullChecks`), but the rules are stricter.
In the example below, all lines cause a compile-time error:
@@ -1522,7 +1615,8 @@ if (x != null) { /* do something */ }
A postfix operator `!` can be used to assert that its operand is non-null.
-If applied to a null value, the operator throws an error. Otherwise, the type of the value is changed from `T | null` to `T`:
+If applied to a null value, the operator throws an error. Otherwise, the
+type of the value is changed from `T | null` to `T`:
```typescript
let x: number | null = 1
@@ -1533,12 +1627,15 @@ y = x! + 1 // ok
## Null-Coalescing Operator
-The null-coalescing binary operator `??` checks whether the evaluation of the left-hand-side expression is equal to null.
-If it is, then the result of the expression is the right-hand-side expression; otherwise, it is the left-hand-side expression.
+The null-coalescing binary operator `??` checks whether the evaluation
+of the left-hand-side expression is equal to null.
+If it is, then the result of the expression is the right-hand-side expression;
+otherwise, it is the left-hand-side expression.
In other words, `a ?? b` equals the ternary operator `a != null ? a : b`.
-In the following example, the method `getNick` returns a nickname if it is set; otherwise, empty string is returned:
+In the following example, the method `getNick` returns a nickname if it is
+set; otherwise, an empty string is returned:
```typescript
class Person {
@@ -1552,46 +1649,72 @@ class Person {
## Optional Chaining
-Optional chaining operator `?.` allows writing code where the evaluation stops of an expression that is partially evaluated to `null`.
+Optional chaining operator `?.` allows writing code where the evaluation
+stops at an expression that is partially evaluated to `null` or `undefined`.
```typescript
class Person {
- // ...
- spouse: Person | null = null
- nick: string | null = null
- getSpouseNick(): string | null {
+ nick : string | null = null
+ spouse ?: Person
+
+ setSpouse(spouse: Person) : void {
+ this.spouse = spouse
+ }
+
+ getSpouseNick(): string | null | undefined {
return this.spouse?.nick
}
+
+ constructor(nick: string) {
+ this.nick = nick
+ this.spouse = undefined
+ }
}
```
-**Note**: that the return type of `getSpouseNick` must be `string | null`, as the method may return null.
+**Note**: the return type of `getSpouseNick` must be `string | null | undefined`, as
+the method can return null or undefined.
-An optional chain may be of any length and contain any number of `?.`
+An optional chain can be of any length and contain any number of `?.`
operators.
-In the following sample, the output is a person’s spouse nickname if the person has a spouse, and the spouse has a nickname.
+In the following sample, the output is a person’s spouse nickname if that
+person has a spouse, and the spouse has a nickname.
-Otherwise, the output is `null`:
+Otherwise, the output is `undefined`:
```typescript
-let p: Person = ...
-console.log(p?.spouse?.nick)
+class Person {
+ nick : string | null = null
+ spouse ?: Person
+
+ constructor(nick: string) {
+ this.nick = nick
+ this.spouse = undefined
+ }
+}
+
+let p: Person = new Person("Alice")
+console.log(p.spouse?.nick) // print: undefined
```
# Modules
Programs are organized as sets of compilation units or modules.
-Each module creates its own scope, i.e., any declarations (variables, functions, classes, etc.) declared in the module are not visible outside that module unless they are explicitly exported.
+Each module creates its own scope, i.e., any declarations (variables,
+functions, classes, etc.) declared in the module are not visible outside
+that module unless they are explicitly exported.
-Conversely, a variable, function, class, interface, etc. exported from another module must first be imported to a module.
+Conversely, a variable, function, class, interface, etc. exported from
+another module must first be imported to a module.
## Export
A top-level declaration can be exported by using the keyword `export`.
-A declared name that is not exported is considered private and can be used only in the module where it is declared.
+A declared name that is not exported is considered private and can be used
+only in the module where it is declared.
```typescript
export class Point {
@@ -1610,16 +1733,21 @@ export function Distance(p1: Point, p2: Point): number {
## Import
-Import declarations are used to import entities exported from other modules and provide their bindings in the current module. An import declaration consists of two parts:
+Import declarations are used to import entities exported from other modules
+and provide their bindings in the current module. An import declaration
+consists of two parts:
* Import path that determines the module to import from;
-* Import bindings that define the set of usable entities in the imported module and the form of use i.e., qualified or unqualified use.
+* Import bindings that define the set of usable entities in the imported
+ module, and the form of use (i.e., qualified or unqualified use).
Import bindings may have several forms.
Let’s assume a module has the path ‘./utils’ and export entities ‘X’ and ‘Y’.
-An import binding of the form `* as A` binds the name ‘A’, and all entities exported from the module defined by the import path can be accessed by using the qualified name `A.name`:
+An import binding of the form `* as A` binds the name ‘A’, and all entities
+exported from the module defined by the import path can be accessed by using
+the qualified name `A.name`:
```typescript
import * as Utils from "./utils"
@@ -1627,7 +1755,8 @@ Utils.X // denotes X from Utils
Utils.Y // denotes Y from Utils
```
-An import binding of the form `{ ident1, ..., identN }` binds an exported entity with a specified name, which can be used as a simple name:
+An import binding of the form `{ ident1, ..., identN }` binds an exported
+entity with a specified name, which can be used as a simple name:
```typescript
import { X, Y } from "./utils"
@@ -1635,7 +1764,8 @@ X // denotes X from Utils
Y // denotes Y from Utils
```
-If a list of identifiers contains aliasing of the form `ident as alias`, then entity `ident` is bound under the name `alias`:
+If a list of identifiers contains aliasing of the form `ident as alias`,
+then entity `ident` is bound under the name `alias`:
```typescript
import { X as Z, Y } from "./utils"
@@ -1648,12 +1778,17 @@ X // Compile-time error: 'X' is not visible
A module can contain any statements at the module level, except `return` ones.
-If a module contains a `main` function (program entry point) then top-level statements of the module are executed immediately before the body of this function.
-Otherwise, they are executed before execution of any other function of the module.
+If a module contains a `main` function (program entry point), then
+top-level statements of the module are executed immediately before
+the body of this function.
+Otherwise, they are executed before execution of any other function
+of the module.
## Program Entry Point
-An entry point of a program (application) is the top-level `main` function. The `main` function should have either an empty parameter list or a single parameter of `string[]` type.
+An entry point of a program (application) is the top-level `main` function.
+The `main` function must have either an empty parameter list or a single
+parameter of `string[]` type.
```typescript
function main() {
@@ -1664,16 +1799,16 @@ function main() {
# Support for ArkUI
This section demonstrates mechanisms that ArkTS provides for
-creating graphical user interface (GUI) programs. The section is based on the
-ArkUI declarative framework. ArkUI provides a set of extensions of the standard
-TypeScript to declaratively describe the GUI of the applications and the interaction
-between the GUI components.
+creating graphical user interface (GUI) programs. The section is based on
+the ArkUI declarative framework. ArkUI provides a set of extensions of
+the standard TypeScript to declaratively describe the GUI of the applications
+and the interaction between the GUI components.
## ArkUI Example
The following example provides a complete ArkUI-based application as an
-illustration of GUI programming capabilities. For more details about ArkUI
-features, please refer to the ArkUI
+illustration of GUI programming capabilities. For more details of the
+ArkUI features, refer to the ArkUI
[tutorial](arkts-get-started.md).
```typescript
diff --git a/en/application-dev/quick-start/start-with-ets-stage.md b/en/application-dev/quick-start/start-with-ets-stage.md
index 789f4c05e28730d4f2851fc507af6bc4a8af1d9b..2205e71621f27e3c779dbe27d4f0bca4efc9cbaf 100644
--- a/en/application-dev/quick-start/start-with-ets-stage.md
+++ b/en/application-dev/quick-start/start-with-ets-stage.md
@@ -1,11 +1,11 @@
# Building the First ArkTS Application in Stage Model
-> **NOTE**
->
-> To use ArkTS, your DevEco Studio must be V3.0.0.900 Beta3 or later.
->
-> In this document, DevEco Studio 4.0 Beta1 is used. You can download it [here](../../release-notes/OpenHarmony-v4.0-beta1.md#version-mapping).
+> **NOTE**
+>
+> To use ArkTS, your DevEco Studio must be V3.0.0.900 Beta3 or later.
+>
+> In this document, DevEco Studio 4.0 Beta2 is used. You can download it [here](../../release-notes/OpenHarmony-v4.0-beta2.md#version-mapping).
## Creating an ArkTS Project
@@ -21,16 +21,18 @@ The following describes how to create the OpenHarmony projects of API 10 and API

-3. On the project configuration page, set **Compile SDK** to **3.1.0(API 9** and retain the default values for other parameters.
+3. On the project configuration page, set **Compile SDK** to **3.1.0(API 9)** and retain the default values for other parameters.
+
+ The **Node** parameter sets the Node.js version to use for the project. You can use an existing version or download a new one.

> **NOTE**
>
> You can use the low-code development mode apart from the traditional coding approach.
- >
+ >
> On the low-code development pages, you can design your application UI in an efficient, intuitive manner, with a wide array of UI editing features.
- >
+ >
> To use the low-code development mode, turn on **Enable Super Visual** on the page shown above.
4. Click **Finish**. DevEco Studio will automatically generate the sample code and resources that match your project type. Wait until the project is created.
@@ -43,12 +45,13 @@ The following describes how to create the OpenHarmony projects of API 10 and API

-7. Delete the **runtimeOS** configuration from the **targets** field in all module-level **build-profile.json5** files.
+7. Delete the **runtimeOS** configuration from the **targets** field in the module-level **build-profile.json5** files.

8. Click **Sync Now** and wait until the synchronization is complete. A project of API version 10 is now created.
+
### Creating a Project of API Version 9
1. If you are opening DevEco Studio for the first time, click **Create Project**. If a project is already open, choose **File** > **New** > **Create Project** from the menu bar.
@@ -57,16 +60,18 @@ The following describes how to create the OpenHarmony projects of API 10 and API

-3. On the project configuration page, set **Compile SDK** to **3.1.0(API 9** and retain the default values for other parameters.
+3. On the project configuration page, set **Compile SDK** to **3.1.0(API 9)** and retain the default values for other parameters.
+
+ The **Node** parameter sets the Node.js version to use for the project. You can use an existing version or download a new one.

> **NOTE**
>
> You can use the low-code development mode apart from the traditional coding approach.
- >
+ >
> On the low-code development pages, you can design your application UI in an efficient, intuitive manner, with a wide array of UI editing features.
- >
+ >
> To use the low-code development mode, turn on **Enable Super Visual** on the page shown above.
4. Click **Finish**. DevEco Studio will automatically generate the sample code and resources that match your project type. Wait until the project is created.
@@ -78,11 +83,11 @@ The following describes how to create the OpenHarmony projects of API 10 and API
## ArkTS Project Directory Structure (Stage Model, API Version 10)
-
+
- **AppScope > app.json5**: application-level configuration information.
-- **entry**: OpenHarmony project module, which can be built into an OpenHarmony Ability Package ([HAP](../../glossary.md#hap)).
+- **entry**: OpenHarmony project module, which can be built into an ability package (HAP).
- **src > main > ets**: a collection of ArkTS source code.
- **src > main > ets > entryability**: entry to your application/service.
@@ -99,17 +104,18 @@ The following describes how to create the OpenHarmony projects of API 10 and API
- **oh_modules**: third-party library dependency information. For details about how to adapt a historical npm project to ohpm, see [Manually Migrating Historical Projects](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/project_overview-0000001053822398-V3#section108143331212).
-- **build-profile.json5**: application-level configuration options, including **signingConfigs** and **products**. The **runtimeOS** field in **products** indicates the runtime OS. Its default value is **HarmonyOS**. If you are developing an OpenHarmony application, change the value to **OpenHarmony**.
+- **build-profile.json5**: application-level configuration information, including the **signingConfigs** and **products** configuration. The **runtimeOS** field in **products** indicates the runtime OS. Its default value is **HarmonyOS**. If you are developing an OpenHarmony application, change the value to **OpenHarmony**.
- **hvigorfile.ts**: application-level build script.
+
## ArkTS Project Directory Structure (Stage Model, API Version 9)
-
+
- **AppScope > app.json5**: application-level configuration information.
-- **entry**: OpenHarmony project module, which can be built into an OpenHarmony Ability Package ([HAP](../../glossary.md#hap)).
+- **entry**: OpenHarmony project module, which can be built into an ability package (HAP).
- **src > main > ets**: a collection of ArkTS source code.
- **src > main > ets > entryability**: entry to your application/service.
@@ -267,7 +273,7 @@ You can implement page redirection through the [page router](../reference/apis/j
1. Implement redirection from the first page to the second page.
- In the **index.ets** file of the first page, bind the **onClick** event to the **Next** button so that clicking the button redirects the user to the second page. The sample code in the **Index.ets** file is shown below:
+ In the **Index.ets** file of the first page, bind the **onClick** event to the **Next** button so that clicking the button redirects the user to the second page. The sample code in the **Index.ets** file is shown below:
```ts
// Index.ets
diff --git a/en/application-dev/quick-start/typescript-to-arkts-migration-guide.md b/en/application-dev/quick-start/typescript-to-arkts-migration-guide.md
index 8239982de59eca3128a864092571f3af18657dfd..eb3a47adb6545ddb001689b8374b206703a0b9b3 100644
--- a/en/application-dev/quick-start/typescript-to-arkts-migration-guide.md
+++ b/en/application-dev/quick-start/typescript-to-arkts-migration-guide.md
@@ -12,22 +12,24 @@ categories:
2. **Partially supported features**: some minor code refactoring is needed.
Example: The keyword `let` must be used in place of `var` to declare
variables. Please note that your code will still remain a valid TypeScript code
- after rewriting according to our recipes.
+ after rewriting by our recipes.
3. **Unsupported features**: a greater code refactoring effort can be required.
Example: The type `any` is unsupported, and you are to introduce explicit
typing to your code everywhere `any` is used.
+PageBreak
+
# How to Use The Cookbook
The main goal of this cookbook is to provide recipes for all partially
supported features and explicitly list all unsupported features.
-The document is built on the feature-by-feature basis, and if you do not find
-some feature, you can safely consider it **supported**. Otherwise, a recipe
-will give you a suggestion on how to rewrite your code and work around an
-unsupported case.
+The document is built on the feature-by-feature basis, and if you do not
+find some feature, then you can safely consider it **supported**. Otherwise,
+a recipe will give you a suggestion on how to rewrite your code and work
+around an unsupported case.
-## Recipe explained
+## Recipe Explained
The original TypeScript code containing the keyword `var`:
@@ -38,7 +40,7 @@ function addTen(x: number): number {
}
```
-This code must be rewritten as follows:
+must be rewritten as follows:
```typescript
// Important! This is still valid TypeScript.
@@ -50,40 +52,40 @@ function addTen(x: number): number {
## Status of Unsupported Features
-Currently unsupported are mainly the features which
+Currently unsupported are mainly the features which:
- relate to dynamic typing that degrades runtime performance, or
- require extra support in the compiler, thus degrading project build time.
However, the ArkTS team reserves the right to reconsider the list and
-**shrink** it in the future releases based on the feedback from the developers
-and more real-world data experiments.
+**shrink** it in the future releases based on the feedback from the developers,
+and on more real-world data experiments.
+
+PageBreak
# Recipes Summarized
-This documents provides an informal summary of TypeScript features that ArkTS either
-does not support or supports with limitations. For the full list, with more
-detailed code examples and workaround suggestions, please see
-[this section](#recipes).
+This document provides an informal summary of TypeScript features that ArkTS either
+can support with limitations, or cannot support. See [Recipes](#recipes) for the
+full list with more detailed code examples and workaround suggestions.
-## Static typing is enforced
+## Static Typing is Enforced
-ArkTS was designed with following goals in mind:
+ArkTS was designed with the following goals in mind:
-- It should be easy for developers to read and understand ArkTS programs,
- because the code is read more often than written;
-- ArkTS should execute fast with as little power consumption as possible,
- which is critical for mobile devices which ArkTS targets.
+- ArkTS programs must be easy for developers to read and understand because
+ the code is read more often than written;
+- ArkTS must execute fast and consume as little power as possible because
+ it is particularly critical on mobile devices which ArkTS targets.
-Static typing is one of the most important features of ArkTS, which helps
-achieve both goals. Indeed, if your program is statically typed, i.e. all
-types are known at the compile time, it’s much easier to understand which data
-structures are used in the code. At the same time, since all types are known
-before the program actually runs, code correctness can be verified by the
-compiler, which eliminates many runtime type checks and improves the
-performance.
+One of the most important features of ArkTS that helps achieving both goals
+is static typing. Indeed, if a program is statically typed, i.e. all types
+are known at compile time, then it is much easier to understand what data
+structures are used in the code. That all types are known before the program
+actually runs results in the compiler to verify code correctness, thus
+eliminating many runtime type checks and improving performance.
-Therefore, it was decided to prohibit usage of the type `any`.
+Therefore, the usage of the type `any` in ArkTS is prohibited.
### Example
@@ -112,26 +114,27 @@ if (!res.succeeded()) {
}
```
-### Rationale and impact
+### Rationale and Impact
-Our research and experiments let us conclude that this feature is already
-not welcome in the modern TypeScript. According to our measurements, it is used
-in approximately 1% of TypeScript code bases. Moreover, code linters (e.g., ESLint)
-already include a set of rules that prohibit usage of `any`. Thus, although
-prohibiting `any` requires code refactoring, we consider it a low-effort
-change with the high impact result.
+Our research and experiments let us conclude that `any` is already not welcome
+in TypeScript. According to our measurements, `any` is used in approximately 1% of
+TypeScript codebases. Moreover, today’s code linters (e.g., ESLint) include a set
+of rules that prohibit the usage of `any`.
-## Changing object layout in runtime is prohibited
+Prohibiting `any` results in a strong positive impact on performance at the
+cost of low-effort code refactoring.
-To achieve maximum performance benefits, ArkTS requires that layout of objects
-does not change during program execution. In other words, it is prohibited to:
+## Changing Object Layout in Runtime Is Prohibited
-- add new properties or methods to the objects;
-- delete existing properties or methods from the objects;
+To achieve maximum performance benefits, ArkTS requires the layout of objects
+to not change during program execution. In other words, it is prohibited to:
+
+- add new properties or methods to objects;
+- delete existing properties or methods from objects;
- assign values of arbitrary types to object properties.
-It’s worth noticing that many such operations are already prohibited by the TypeScript
-compiler. However, it still can be “tricked” by e.g. `as any` casts, wchich
+It is noteworthy that many such operations are already prohibited by the TypeScript
+compiler. However, it still can be “tricked”, e.g., by `as any` casts that
ArkTS does not support (see the detailed example below).
### Example
@@ -193,29 +196,27 @@ let p6 = new Point(6.0, 6.0)
console.log("Distance between p5 and p6: " + distance(p5, p6))
```
-### Rationale and impact
+### Rationale and Impact
Unpredictable changing of object layout contradicts both good readability and
-good performance of the code. Indeed, having class definition at one place and
+good performance of code. Indeed, having class definition at one place and
modifying actual object layout elsewhere is confusing and error-prone from the
-developer’s point of view. Additionally, it requires extra runtime support,
-which brings undesired execution overhead. Moreover, it contradicts the idea of
-static typing. If we want to make typing as explicit as possible, why would we
-need to add or remove additional properties?
+developer’s point of view. It opposes the idea of static typing (why adding
+or removing additional properties if typing is to be as explicit as possible?)
+and requires extra runtime support that causes undesired execution overhead.
-At the same time, according to our observations and experiments, this feature
-is already not welcome in the modern TypeScript. It is used in the marginal number of
-cases in real-world projects and state of the art linters have rules to
-prohibit its usage.
+According to our observations and experiments, this feature is already not
+welcome in TypeScript: it is used in a marginal number of real-world projects,
+and state-of-the-art linters have rules to prohibit its usage.
-Thus, we conclude that prohibiting runtime changes to objects’ layout results
-in low-effort refactoring with the high positive impact on performance.
+We conclude that prohibiting runtime changes to object layouts results in a
+strong positive impact on performance at the cost of low-effort refactoring.
-## Semantics of operators is restricted
+## Semantics of Operators Is Restricted
To achieve better performance and encourage developers write clearer code,
-ArkTS restricts semantics of some operators. A couple of examples are given
-below, and the full list of restrictions is outlined [here](#recipes).
+ArkTS restricts the semantics of some operators. A couple of examples are
+given below, and the full list of restrictions is outlined in [Recipes](#recipes).
### Example
@@ -229,24 +230,23 @@ let c2 : C = new C()
console.log(c1 + c2) // Compile-time error
```
-### Rationale and impact
+### Rationale and Impact
-Overloading language operators with extra semantics complicates language
-specification and makes developers remember about all possible corner cases
-and their handling rules. Besides, in certain cases it incurs some runtime
-overhead, which is undesired.
+Loading language operators with extra semantics complicates the language
+specification, and forces developers to remember all possible corner cases with
+appropriate handling rules. Besides, in certain cases it causes some undesired
+runtime overhead.
At the same time, according to our observations and experiments, this feature
-is not popular in the modern TypeScript. It is used in less than 1% of real-world
-code bases. Besides, such cases are very easy to refactor.
+is not popular in TypeScript. It is used in less than 1% of real-world codebases,
+and such cases are easy to refactor.
-Thus, although restricting semantics of operators requires changing the code,
-this is a low-effort change which results in a clearer and more performant code.
+Restricting the operator semantics results in a clearer and more performant
+at the cost of low-effort changes in code.
-## Structural typing is not supported (yet)
+## Structural Typing Is Not Supported (Yet)
-Let’s consider a situation when two unrelated classes `T` and `U` have the
-same public API:
+Assuming that two unrelated classes `T` and `U` have the same public API:
```typescript
class T {
@@ -284,31 +284,34 @@ let t : T = new T()
greeter(t) // Is this allowed?
```
-Or, in other words, which approach will we take:
+In other words, which approach will we take:
- `T` and `U` are not related by inheritance or any common interface, but
- since they have the same public API, they are “somewhat equivalent”, so the
- answer to both questions above is “yes”;
+ they are “somewhat equivalent” since they have the same public API, and so
+ the answer to both questions above is “yes”;
- `T` and `U` are not related by inheritance or any common interface, and
- should always be considered as totally different types, so the
- answer to both questions above is “no”.
-
-Languages that take the first approach are said to support structural typing,
-while languages that take the second approach do not support it. Currently,
-TypeScript supports structural typing, and ArkTS does not.
-
-It is debatable if structural typing helps produce clear and
-understandable code, arguments can be found both for and against it.
-Moreover, structural typing does not harm program performance (at least in some
-cases). Why is it not supported then?
-
-The answer is that support for structural typing is a major feature which needs
-lots of consideration and careful implementation in language specification,
-compiler and runtime. Safe and efficient implementation requires that other
-aspects (static typing, restrictions on changing object layout) are also
-taken into account. That’s why support for this feature is postponed. The team
-will be ready to reconsider based on real-world scenarios and feedback. More
-cases and suggested workarounds can be found in [Recipes](#recipes).
+ always must be considered as totally different types, so that the answer to
+ both questions above is “no”.
+
+The languages that take the first approach are said to support structural
+typing, while the languages that take the second approach do not support it.
+Currently, TypeScript supports structural typing, and ArkTS does not.
+
+It is debatable whether or not structural typing helps to produce code that
+is clearer and more understandable, and both *pro* and *contra* arguments can
+be found. Moreover, structural typing does not harm program performance (at
+least in some cases). Why not support it then?
+
+The answer is that supporting structural typing is a major feature that needs
+a lot of consideration and careful implementation in language specification,
+compiler and runtime. As safe and efficient implementation requires taking
+other aspects (static typing, restrictions on changing object layout) into
+account, the support to this feature is postponed.
+
+The ArkTS team is ready to reconsider based on real-world scenarios and
+feedback. More cases and suggested workarounds can be found in [Recipes](#recipes).
+
+PageBreak
# Recipes
@@ -335,9 +338,9 @@ console.log(x[2])
```typescript
class X {
- public name: number
+ public name: number = 0
}
-let x = {name: 1}
+let x:X = {name: 1}
console.log(x.name)
let y = [1, 2, 3]
@@ -372,7 +375,7 @@ console.log(z.get(2))
TypeScript has `Symbol()` API, which can be used among other things to generate
unique property names at runtime. ArkTS does not support `Symbol()` API
because its most popular use cases make no sense in the statically typed
-environment. In particular, the object layout is defined at compile time
+environment. In particular, the object layout is defined at compile time,
and cannot be changed at runtime.
**TypeScript**
@@ -388,7 +391,7 @@ let o = {
```typescript
class SomeClass {
- public someProperty : string
+ public someProperty : string = ""
}
let o = new SomeClass()
```
@@ -410,15 +413,18 @@ let o = new SomeClass()
**Severity: error**
-ArkTS does not private identifiers started with `#` symbol, use `private`
-keyword instead.
+ArkTS does not use private identifiers starting with the symbol `#`. Use
+the keyword `private` instead.
**TypeScript**
```typescript
+/*
+ * Such notation for private fields is not supported:
class C {
#foo: number = 42
}
+*/
```
**ArkTS**
@@ -458,7 +464,7 @@ type T = number[] // X is not allowed here to avoid name collisions
**Severity: error**
-ArkTS does not support `var`, always use `let` instead.
+ArkTS does not support `var`. Use `let` instead.
**TypeScript**
@@ -507,59 +513,40 @@ scoped_var = 5
scoped_let = 5 // Compile-time error
```
-## Recipe: Use explicit types instead of `any`, `undefined`, `unknown`
+## Recipe: Use explicit types instead of `any`, `unknown`
-**Rule `arkts-no-any-undefined-unknown`**
+**Rule `arkts-no-any-unknown`**
**Severity: error**
-ArkTS does not support `any`, `undefined`, and `unknown` types.
-Specify types explicitly.
+ArkTS does not support the types `any` and `unknown`. Specify
+types explicitly.
**TypeScript**
```typescript
-var x
-console.log(x) // undefined
+let value1 : any
+value1 = true
+value1 = 42
-var y: any
-console.log(y) // undefined
+let value2 : unknown
+value2 = true
+value2 = 42
```
**ArkTS**
```typescript
-// All variables should have their types specified explicitly:
-let x: Object = {}
-console.log(x) // {}
+let value_b: boolean = true // OR: let value_b = true
+let value_n: number = 42 // OR: let value_n = 42
+let value_o1: Object = true
+let value_o2: Object = 42
```
**See also**
* Recipe: Use Object[] instead of tuples
-
-## Recipe: `bigint` is not a builtin type, suffix `n` for numeric literals is not supported
-
-**Rule `arkts-no-n-suffix`**
-
-**Severity: error**
-
-ArkTS supports `bigint` as a part of the standard library, not as a builtin
-type. `n` suffix for numeric literals is not supported, `BigInt` factory
-function can be used to produce values of `bigint` type.
-
-**TypeScript**
-
-```typescript
-let a: bigint = 1n
-```
-
-**ArkTS**
-
-```typescript
-let a = BigInt(1)
-let b: bigint = BigInt(2)
-```
+* Recipe: Strict type checking is enforced
## Recipe: Use `Object[]` instead of tuples
@@ -567,7 +554,7 @@ let b: bigint = BigInt(2)
**Severity: error**
-Currently, ArkTS does not support tuples. You can use arrays of `Object`
+Currently, ArkTS does not support tuples. Use arrays of `Object`
(`Object[]`) to emulate tuples.
**TypeScript**
@@ -679,8 +666,8 @@ function fn(s: string): SomeObject {
**Severity: error**
-ArkTS does not allow to have sevaral static block for class initialization,
-combine static blocks statements to the one static block.
+ArkTS does not allow having sevaral static blocks for class initialization.
+Combine static block statements into one static block.
**TypeScript**
@@ -716,7 +703,7 @@ class C {
**Severity: error**
-ArkTS does not allow indexed signatures, use arrays instead.
+ArkTS does not allow indexed signatures. Use arrays instead.
**TypeScript**
@@ -738,7 +725,7 @@ const secondItem = myArray[1]
```typescript
class X {
- public f: string[]
+ public f: string[] = []
}
let myArray: X = new X()
@@ -751,8 +738,8 @@ const secondItem = myArray.f[1]
**Severity: error**
-Currently, ArkTS does not support intersection types. You can use inheritance
-as a work-around.
+Currently, ArkTS does not support intersection types. Use inheritance
+as a workaround.
**TypeScript**
@@ -764,7 +751,7 @@ interface Identity {
interface Contact {
email: string
- phone: string
+ phoneNumber: string
}
type Employee = Identity & Contact
@@ -780,15 +767,15 @@ interface Identity {
interface Contact {
email: string
- phone: string
+ phoneNumber: string
}
interface Employee extends Identity, Contact {}
```
-## Recipe: Returning `this` type is not supported
+## Recipe: Type notation using `this` is not supported
-**Rule `arkts-no-this-as-return-type`**
+**Rule `arkts-no-typing-with-this`**
**Severity: error**
@@ -800,6 +787,14 @@ ArkTS does not support the returning `this` type. Use explicit type instead.
interface ListItem {
getHead(): this
}
+
+class C {
+ n: number = 0
+
+ m(c: this) {
+ console.log(c)
+ }
+}
```
**ArkTS**
@@ -808,6 +803,14 @@ interface ListItem {
interface ListItem {
getHead(): ListItem
}
+
+class C {
+ n: number = 0
+
+ m(c: C) {
+ console.log(c)
+ }
+}
```
## Recipe: Conditional types are not supported
@@ -817,8 +820,8 @@ interface ListItem {
**Severity: error**
ArkTS does not support conditional type aliases. Introduce a new type with
-constraints explicitly or rewrite logic with use of `Object`. `infer`
-keyword is not supported.
+constraints explicitly, or rewrite logic using `Object`. The keyword
+`infer` is not supported.
**TypeScript**
@@ -842,44 +845,6 @@ type X2 = Object
type YI- > = Item
```
-## Recipe: Optional parameters are not supported for primitive types
-
-**Rule `arkts-no-opt-params`**
-
-**Severity: error**
-
-ArkTS does not support optional parameters of primitive types.
-You can use default parameter values or reference types. For reference types,
-non-specified optional parameter is set to `null`.
-
-**TypeScript**
-
-```typescript
-// x is an optional parameter:
-function f(x?: number) {
- console.log(x) // log undefined or number
-}
-
-// x is a required parameter with the default value:
-function g(x: number = 1) {
- console.log(x)
-}
-```
-
-**ArkTS**
-
-```typescript
-// You can use reference type (will be set to null if missing):
-function f(x?: Number) {
- console.log(x) // log null or some number
-}
-
-// You can use a required parameter with the default value:
-function g(x: number = 1) {
- console.log(x)
-}
-```
-
## Recipe: Declaring fields in `constructor` is not supported
**Rule `arkts-no-ctor-prop-decls`**
@@ -887,7 +852,7 @@ function g(x: number = 1) {
**Severity: error**
ArkTS does not support declaring class fields in the `constructor`.
-You must declare them inside the `class` declaration instead.
+Declare class fields inside the `class` declaration instead.
**TypeScript**
@@ -929,7 +894,7 @@ class Person {
}
```
-## Recipe: Construct signatures not supported in interfaces
+## Recipe: Construct signatures are not supported in interfaces
**Rule `arkts-no-ctor-signatures-iface`**
@@ -1019,11 +984,11 @@ let x = p.x
**Severity: error**
Currently, ArkTS does not support structural identity, i.e., the compiler
-cannot compare two types’ public APIs and decide whether such types are
+cannot compare public APIs of two types and decide whether such types are
identical. Use other mechanisms (inheritance, interfaces or type aliases)
instead.
-For the examples below, types `X` and `Y` are equivalent (interchangeble)
+In the examples below, types `X` and `Y` are equivalent (interchangeble)
in TypeScript, while in ArkTS they are not.
**TypeScript**
@@ -1061,7 +1026,7 @@ type Y = X // Y is equal to X
**Severity: error**
Currently, ArkTS does not check structural equivalence for type inference,
-i.e., the compiler cannot compare two types’ public APIs and decide whether
+i.e., the compiler cannot compare public APIs of two types and decide whether
such types are identical. Use other mechanisms (inheritance or interfaces)
instead.
@@ -1135,8 +1100,8 @@ x = y // ok, X is the super class of Y
**Severity: error**
Currently, ArkTS does not check structural equivalence when checking if types
-are assignable to each other, i.e., the compiler cannot compare two types’
-public APIs and decide whether such types are identical. Use other mechanisms
+are assignable to each other, i.e., the compiler cannot compare public APIs of
+two types and decide whether such types are identical. Use other mechanisms
(inheritance or interfaces) instead.
**TypeScript**
@@ -1208,56 +1173,6 @@ x = y // ok, both are of the same type
* Recipe: Structural typing is not supported for subtyping / supertyping
* Recipe: Structural typing is not supported for type inference
-## Recipe: Optional properties are not supported for primitive types
-
-**Rule `arkts-no-opt-props`**
-
-**Severity: error**
-
-ArkTS does not support optional properties of primitive types. You can use
-properties with default values or reference types. For reference types,
-non-specified optional property is set to `null`. This rule applies both to
-classes and interfaces.
-
-**TypeScript**
-
-```typescript
-class CompilerOptions {
- strict?: boolean
- sourcePath?: string
- targetPath?: string
-}
-
-let options: CompilerOptions = {
- strict: true,
- sourcePath: "./src"
-}
-
-if (options.targetPath == undefined) {
- // Some logic
-}
-```
-
-**ArkTS**
-
-```typescript
-class CompilerOptions {
- strict: boolean = false
- sourcePath: string = ""
- targetPath?: string
-}
-
-let options: CompilerOptions = {
- strict: true,
- sourcePath: "./src"
- // targetPath is implicitly set to null
-}
-
-if (options.targetPath == null) {
- // Some logic
-}
-```
-
## Recipe: Type inference in case of generic function calls is limited
**Rule `arkts-no-inferred-generic-params`**
@@ -1265,8 +1180,8 @@ if (options.targetPath == null) {
**Severity: error**
ArkTS allows to omit generic type parameters if it is possible to infer
-the concrete types from the parameters passed to the function. Otherwise a
-compile-time error occurs. In particular, inference of generic type parameters
+the concrete types from the parameters passed to the function. A compile-time
+error occurs otherwise. In particular, inference of generic type parameters
based only on function return types is prohibited.
**TypeScript**
@@ -1282,7 +1197,7 @@ let y = choose("10", 20) // Compile-time error
function greet
(): T {
return "Hello" as T
}
-let z = greet() // Type of x is inferred as "unknown"
+let z = greet() // Type of T is inferred as "unknown"
```
**ArkTS**
@@ -1308,7 +1223,7 @@ let z = greet()
**Severity: error**
Currently, ArkTS does not support structural typing, i.e., the compiler cannot
-compare two types’ public APIs and decide whether such types are identical.
+compare public APIs of two types and decide whether such types are identical.
Use inheritance and interfaces to specify the relation between the types
explicitly.
@@ -1402,8 +1317,8 @@ bar(new Y(2))
**Severity: error**
-Currently, ArkTS does not support RegExp literals. Use library call with string
-literals instead.
+Currently, ArkTS does not support RegExp literals. Use library call with
+string literals instead.
**TypeScript**
@@ -1424,9 +1339,9 @@ let regex: RegExp = new RegExp("/bc*d/")
**Severity: error**
ArkTS supports usage of object literals if the compiler can infer to what
-classes or interfaces such literals correspond to. Otherwise, a compile-time
-error occurs. Specifically, using literals to initialize classes and interfaces
-is not supported in following contexts:
+classes or interfaces such literals correspond to. A compile-time error
+occurs otherwise. Using literals to initialize classes and interfaces is
+specifically not supported in the following contexts:
* Initialization of anything that has `any`, `Object`, or `object` type
* Initialization of classes or interfaces with methods
@@ -1579,8 +1494,8 @@ type S = Set<{x: number, y: number}>
```typescript
class O {
- x: number
- y: number
+ x: number = 0
+ y: number = 0
}
let o: O = {x: 2, y: 3}
@@ -1600,8 +1515,8 @@ type S = Set
**Severity: error**
Basically, ArkTS infers the type of an array literal as a union type of its
-contents. But if there is at least one element with a non-inferrable type
-(e.g. untyped object literal), a compile-time error occurs.
+contents. However, a compile-time error occurs if there is at least one
+element with a non-inferrable type (e.g. untyped object literal).
**TypeScript**
@@ -1638,7 +1553,8 @@ to be explicitly specified.
**TypeScript**
```typescript
-let f = (s) => { // type any is assumed
+// Compile-time error only with noImplicitAny:
+let f = (s /* type any is assumed */) => {
console.log(s)
}
```
@@ -1658,8 +1574,8 @@ let f = (s: string) => {
**Severity: error**
-ArkTS does not support function expressions, use arrow functions instead
-to be explicitly specified.
+ArkTS does not support function expressions. Use arrow functions instead
+to specify explicitly.
**TypeScript**
@@ -1710,19 +1626,19 @@ generic_func("string")
**Severity: error**
-ArkTS does not support class literals. A new named class type must be
-introduced explicitly.
+ArkTS does not support class literals. Introduce new named class types
+explicitly.
**TypeScript**
```typescript
const Rectangle = class {
constructor(height: number, width: number) {
- this.heigth = height
+ this.height = height
this.width = width
}
- heigth
+ height
width
}
@@ -1734,11 +1650,11 @@ const rectangle = new Rectangle(0.0, 0.0)
```typescript
class Rectangle {
constructor(height: number, width: number) {
- this.heigth = height
+ this.height = height
this.width = width
}
- heigth: number
+ height: number
width: number
}
@@ -1770,7 +1686,7 @@ class C1 implements C {
```typescript
interface C {
- foo()
+ foo(): void
}
class C1 implements C {
@@ -1786,7 +1702,7 @@ class C1 implements C {
ArkTS supports accessing only those class properties that are either declared
in the class, or accessible via inheritance. Accessing any other properties is
-prohibited and causes compile-time errors. Use proper types to check property
+prohibited, and causes compile-time errors. Use proper types to check property
existence during compilation.
**TypeScript**
@@ -1796,7 +1712,7 @@ let person = {name: "Bob", isEmployee: true}
let n = person["name"]
let e = person["isEmployee"]
-let s = person["office"] // undefined
+let s = person["office"] // Compile-time error only with noImplicitAny
```
**ArkTS**
@@ -1835,10 +1751,13 @@ let s = person.office // Compile-time error
**Severity: error**
-ArkTS supports `as` keyword as the only syntax for type casts.
+ArkTS supports the keyword `as` as the only syntax for type casts.
Incorrect cast causes a compile-time error or runtime `ClassCastException`.
`` syntax for type casts is not supported.
+Use the expression `new ...` instead of `as` if a **primitive** type
+(e.g., a `number` or a `boolean`) must be cast to the reference type.
+
**TypeScript**
```typescript
@@ -1858,6 +1777,14 @@ let c2 = createShape() as Circle
// nor during runtime if cast is wrong:
let c3 = createShape() as Square
console.log(c3.y) // undefined
+
+// Important corner case for casting primitives to the boxed counterparts:
+// The left operand is not properly boxed here in in runtime
+// because "as" has no runtime effect in TypeScript
+let e1 = (5.0 as Number) instanceof Number // false
+
+// Number object is created and instanceof works as expected:
+let e2 = (new Number(5.0)) instanceof Number // true
```
**ArkTS**
@@ -1875,6 +1802,9 @@ let c2 = createShape() as Circle
// ClassCastException during runtime is thrown:
let c3 = createShape() as Square
+
+// Number object is created and instanceof works as expected:
+let e2 = (new Number(5.0)) instanceof Number // true
```
## Recipe: JSX expressions are not supported
@@ -1899,45 +1829,14 @@ be done explicitly.
**TypeScript**
```typescript
-let a = +5 // 5 as number
-let b = +"5" // 5 as number
-let c = -5 // -5 as number
-let d = -"5" // -5 as number
-let e = ~5 // -6 as number
-let f = ~"5" // -6 as number
+let a = +5 // 5 as number
+let b = +"5" // 5 as number
+let c = -5 // -5 as number
+let d = -"5" // -5 as number
+let e = ~5 // -6 as number
+let f = ~"5" // -6 as number
let g = +"string" // NaN as number
-```
-
-**ArkTS**
-
-```typescript
-let a = +5 // 5 as number
-let b = +"5" // Compile-time error
-let c = -5 // -5 as number
-let d = -"5" // Compile-time error
-let e = ~5 // -6 as number
-let f = ~"5" // Compile-time error
-let g = +"string" // Compile-time error
-```
-
-**See also**
-
-* Recipe: Binary operators \*, /, %, -, <<, >>, >>>, &, ^ and | work only on numeric types
-* Recipe: Binary + operator supports implicit casts only for numbers and strings
-
-## Recipe: Unary `+` cannot be used for casting to `number`
-
-**Rule `arkts-no-unary-plus-cast`**
-
-**Severity: error**
-
-ArkTS does not support casting from any type to a numeric type
-by using the unary `+` operator, which can be applied only to
-numeric types.
-
-**TypeScript**
-```typescript
function returnTen(): string {
return "-10"
}
@@ -1946,13 +1845,21 @@ function returnString(): string {
return "string"
}
-let a = +returnTen() // -10 as number
-let b = +returnString() // NaN
+let x = +returnTen() // -10 as number
+let y = +returnString() // NaN
```
**ArkTS**
```typescript
+let a = +5 // 5 as number
+let b = +"5" // Compile-time error
+let c = -5 // -5 as number
+let d = -"5" // Compile-time error
+let e = ~5 // -6 as number
+let f = ~"5" // Compile-time error
+let g = +"string" // Compile-time error
+
function returnTen(): string {
return "-10"
}
@@ -1961,16 +1868,10 @@ function returnString(): string {
return "string"
}
-let a = +returnTen() // Compile-time error
-let b = +returnString() // Compile-time error
+let x = +returnTen() // Compile-time error
+let y = +returnString() // Compile-time error
```
-**See also**
-
-* Recipe: Unary operators +, - and ~ work only on numbers
-* Recipe: Binary operators \*, /, %, -, <<, >>, >>>, &, ^ and | work only on numeric types
-* Recipe: Binary + operator supports implicit casts only for numbers and strings
-
## Recipe: `delete` operator is not supported
**Rule `arkts-no-delete`**
@@ -1999,8 +1900,8 @@ delete p.y
// and assign null to mark value absence:
class Point {
- x: number | null
- y: number | null
+ x: number | null = 0
+ y: number | null = 0
}
let p = new Point()
@@ -2023,8 +1924,8 @@ p.y = null
**Severity: error**
-ArkTS supports `typeof` operator only in the expression context. Specifying
-type notations using `typeof` is not supported.
+ArkTS supports `typeof` operator only in the expression context. Using
+`typeof` to specify type notations is not supported.
**TypeScript**
@@ -2059,77 +1960,19 @@ let s2: string
* Recipe: Dynamic property declaration is not supported
* Recipe: Usage of standard library is restricted
-## Recipe: Binary operators `*`, `/`, `%`, `-`, `<<`, `>>`, `>>>`, `&`, `^` and `|` work only on numeric types
-
-**Rule `arkts-no-polymorphic-binops`**
-
-**Severity: error**
-
-ArkTS allows applying binary operators `*`, `/`, `%`, `-`, `<<`,
-`>>`, `>>>`, `&`, `^` and `|` only to values of numeric types.
-Implicit casts from other types to numeric types are prohibited and cause
-compile-time errors.
-
-**TypeScript**
-
-```typescript
-let a = (5 & 5) // 5
-let b = (5.5 & 5.5) // 5, not 5.5
-let c = (5 | 5) // 5
-let d = (5.5 | 5.5) // 5, not 5.5
-
-enum Direction {
- Up = -1,
- Down
-}
-let e = Direction.Up >> 1 // -1
-let f = Direction.Up >>> 1 // 2147483647
-
-let g = ("10" as any) << 1 // 20
-let h = ("str" as any) << 1 // 0
-
-let i = 10 * 5
-let j = 10 / 5
-let k = 10 % 5
-let l = 10 - 5
-```
-
-**ArkTS**
-
-```typescript
-let a = (5 & 5) // 5
-let b = (5.5 & 5.5) // Compile-time error
-let c = (5 | 5) // 5
-let d = (5.5 | 5.5) // Compile-time error
-
-enum Direction {
- Up,
- Down
-}
-
-let e = Direction.Up >> 1 // 0
-let f = Direction.Up >>> 1 // 0
-
-let i = 10 * 5
-let j = 10 / 5
-let k = 10 % 5
-let l = 10 - 5
-```
-
-**See also**
-
-* Recipe: Unary operators +, - and ~ work only on numbers
-* Recipe: Unary + cannot be used for casting to number
-* Recipe: Binary + operator supports implicit casts only for numbers and strings
-
-## Recipe: Binary `+` operator supports implicit casts only for numbers and strings
+## Recipe: Binary `+` operator supports implicit casts only for numbers, enums and strings
**Rule `arkts-no-polymorphic-plus`**
**Severity: error**
-ArkTS supports implicit casts for `+` only for strings and numbers.
-Elsewhere, any form of an explicit cast to string is required.
+If one of the operands of the binary `+` operator is of the string type
+(including enum string constant), then the other operand can be of any type,
+and its value is implicitly converted to string.
+Otherwise, ArkTS supports implicit casts with `+` only for numbers and
+numeric enum constants.
+ArkTS, like TypeScript, does not support the operator `+` for the booleans.
+Elsewhere, any form of an explicit cast is required.
**TypeScript**
@@ -2145,6 +1988,10 @@ let e = "Hello, " + "world!" // "Hello, world!"
let f = "string" + true // "stringtrue"
let g = (new Object()) + "string" // "[object Object]string"
+
+let i = true + true // JS: 2, TS: compile-time error
+let j = true + 2 // JS: 3, TS: compile-time error
+let k = E.E1 + true // JS: 1, TS: compile-time error
```
**ArkTS**
@@ -2161,13 +2008,16 @@ let e = "Hello, " + "world!" // "Hello, world!"
let f = "string" + true // "stringtrue"
let g = (new Object()).toString() + "string"
+
+
+let i = true + true // compile-time error
+let j = true + 2 // compile-time error
+let k = E.E1 + true // compile-time error
```
**See also**
* Recipe: Unary operators +, - and ~ work only on numbers
-* Recipe: Unary + cannot be used for casting to number
-* Recipe: Binary operators \*, /, %, -, <<, >>, >>>, &, ^ and | work only on numeric types
## Recipe: `instanceof` operator is partially supported
@@ -2175,40 +2025,38 @@ let g = (new Object()).toString() + "string"
**Severity: error**
-In TypeScript, the left-hand side of an `instanceof` expression must be of type
-`any`, an object type or a type parameter, otherwise the result is `false`.
-In ArkTS, the left-hand side expression may be of any reference type, otherwise
-a compile-time error occurs. In addition, the left operand in ArkTS cannot be
-a type.
+In TypeScript, the left-hand side of an `instanceof` expression must be of the type
+`any`, an object type or a type parameter; the result is `false` otherwise.
+In ArkTS, the left-hand side expression may be of any reference type;
+a compile-time error occurs otherwise. In addition, the left operand in ArkTS
+cannot be a type.
**TypeScript**
```typescript
-class X {}
+class X {
+ // ...
+}
let a = (new X()) instanceof Object // true
-let b = (new X()) instanceof X // true
-// left operand is a type:
-let c = X instanceof Object // true
-let d = X instanceof X // false
+let b = (new X()) instanceof X // true
-// left operand is not of type any
-let e = (5.0 as Number) instanceof Number // false
+let c = X instanceof Object // true, left operand is a type
+let d = X instanceof X // false, left operand is a type
```
**ArkTS**
```typescript
-class X {}
+class X {
+ // ...
+}
let a = (new X()) instanceof Object // true
-let b = (new X()) instanceof X // true
-// left operand is a type:
-let c = X instanceof Object // Compile-time error
-let d = X instanceof X // Compile-time error
+let b = (new X()) instanceof X // true
-// left operand may be of any reference type, like number
-let e = (5.0 as Number) instanceof Number // true
+let c = X instanceof Object // Compile-time error, left operand is a type
+let d = X instanceof X // Compile-time error, left operand is a type
```
## Recipe: `in` operator is not supported
@@ -2217,9 +2065,9 @@ let e = (5.0 as Number) instanceof Number // true
**Severity: error**
-ArkTS does not support the `in` operator. However, this operator makes
-little sense since the object layout is known at compile time and cannot
-be modified at runtime. Use `instanceof` as a work-around if you still need
+ArkTS does not support the operator `in`. However, this operator makes
+little sense since the object layout is known at compile time, and cannot
+be modified at runtime. Use `instanceof` as a workaround if you still need
to check whether certain class members exist.
**TypeScript**
@@ -2261,8 +2109,8 @@ let b = p instanceof Person // true, and "name" is guaranteed to be present
**Severity: error**
-ArkTS does not support destructuring assignment. Other idioms (e.g.,
-using a temporary variable, where applicable) can be used for replacement.
+ArkTS does not support destructuring assignment. Use other idioms (e.g.,
+a temporary variable, where applicable) for replacement.
**TypeScript**
@@ -2285,11 +2133,11 @@ let tmp = one
one = two
two = tmp
-let data: Number[] = [1,2,3,4]
+let data: Number[] = [1, 2, 3, 4]
let head = data[0]
-let tail = new Number[data.length - 1]
+let tail: Number[] = []
for (let i = 1; i < data.length; ++i) {
- tail[i - 1] = data[i]
+ tail.push(data[i])
}
```
@@ -2378,9 +2226,9 @@ let y = zp.y
**Severity: error**
-Currently, ArkTS does not support inference of implied types. Use explicit
-type notation instead. Use `Object[]` if you need containers that hold
-data of mixed types.
+Currently, ArkTS does not support inference of implied types.
+Use explicit type notation instead.
+Use `Object[]` if you need containers that hold data of mixed types.
**TypeScript**
@@ -2407,9 +2255,8 @@ let c1 = arr[2]
**Severity: error**
-In TypeScript catch clause variable type annotation must be `any` or `unknown`
-if specified. As ArkTS does not support these types, a type annotation should
-be omitted.
+In TypeScript, catch clause variable type annotation must be `any` or `unknown`
+if specified. As ArkTS does not support these types, omit type annotations.
**TypeScript**
@@ -2417,7 +2264,9 @@ be omitted.
try {
// some code
}
-catch (a: unknown) {}
+catch (a: unknown) {
+ // handle error
+}
```
**ArkTS**
@@ -2426,7 +2275,9 @@ catch (a: unknown) {}
try {
// some code
}
-catch (a) {}
+catch (a) {
+ // handle error
+}
```
**See also**
@@ -2441,8 +2292,8 @@ catch (a) {}
ArkTS does not support the iteration over object contents by the
`for .. in` loop. For objects, iteration over properties at runtime is
-considered redundant because object layout is known at compile time and cannot
-change at runtime. For arrays, you can iterate with the regular `for` loop.
+considered redundant because object layout is known at compile time, and
+cannot change at runtime. For arrays, iterate with the regular `for` loop.
**TypeScript**
@@ -2469,7 +2320,7 @@ for (let i = 0; i < a.length; ++i) {
## Recipe: Iterable interfaces are not supported
-**Rule `arkts-noiterable`**
+**Rule `arkts-no-iterable`**
**Severity: error**
@@ -2505,7 +2356,7 @@ for (let s of a) {
```typescript
let a: Set = new Set([1, 2, 3])
-let numbers = a.values()
+let numbers = Array.from(a.values())
for (let n of numbers) {
console.log(n)
}
@@ -2523,7 +2374,7 @@ for (let n of numbers) {
**Severity: error**
ArkTS does not support mapped types. Use other language idioms and regular
-classes to achieve the same behaviour.
+classes to achieve that same behaviour.
**TypeScript**
@@ -2558,7 +2409,23 @@ class CFlags {
**Severity: error**
ArkTS does not support the `with` statement. Use other language idioms
-(including fully qualified names of functions) to achieve the same behaviour.
+(including fully qualified names of functions) to achieve that same behaviour.
+
+**TypeScript**
+
+```typescript
+with (Math) { // Compile-time error, but JavaScript code still emitted
+ let r: number = 42
+ console.log("Area: ", PI * r * r)
+}
+```
+
+**ArkTS**
+
+```typescript
+let r: number = 42
+console.log("Area: ", Math.PI * r * r)
+```
## Recipe: Values computed at runtime are not supported in `case` statements
@@ -2688,6 +2555,7 @@ explicitly.
**TypeScript**
```typescript
+// Compile-time error with noImplicitAny
function f(x: number) {
if (x <= 0) {
return x
@@ -2695,6 +2563,7 @@ function f(x: number) {
return g(x)
}
+// Compile-time error with noImplicitAny
function g(x: number) {
return f(x - 1)
}
@@ -2718,8 +2587,8 @@ function f(x: number) : number {
return g(x)
}
-// Explicit return type is required:
-function g(x: number) : number {
+// Return type may be omitted, it is inferred from f's explicit type:
+function g(x: number) {
return f(x - 1)
}
@@ -2738,8 +2607,8 @@ console.log(doOperation(2, 3))
**Severity: error**
-ArkTS requires that parameters must be passed directly to the function, and
-local names must be assigned manually.
+ArkTS requires parameters to be passed directly to the function, and
+local names to be assigned manually.
**TypeScript**
@@ -2824,7 +2693,7 @@ ArkTS does not support the usage of `this` inside stand-alone functions.
```typescript
function foo(i: number) {
- this.count = i
+ this.count = i // Compile-time error only with noImplicitThis
}
class A {
@@ -2983,7 +2852,7 @@ function main(): void {
**Severity: error**
ArkTS has no keyof operator because the object layout is defined
-at compile time and cannot be changed at runtime. Object fields can only be
+at compile time, and cannot be changed at runtime. Object fields can only be
accessed directly.
**TypeScript**
@@ -3021,7 +2890,6 @@ function getPropertyValue(obj: Point, key: string): number {
return obj.y
}
throw new Error() // No such property
- return 0
}
function main(): void {
@@ -3038,7 +2906,7 @@ function main(): void {
**Severity: error**
The only supported scenario for the spread operator is to spread an array into
-the rest parameter. Otherwise manually “unpack” data from arrays and objects,
+the rest parameter. Otherwise, manually “unpack” data from arrays and objects,
where necessary.
**TypeScript**
@@ -3097,15 +2965,15 @@ console.log(p3d.x, p3d.y, p3d.z)
## Recipe: Interface declarations (extends same property)
-**Rule `arkts-no-extend-same-property`**
+**Rule `arkts-no-extend-same-prop`**
**Severity: error**
-In TypeScript, an interface that extends two other interfaces with the same method,
+In TypeScript, an interface that extends two other interfaces with the same method
must declare that method with a combined result type. It is not allowed in
ArkTS because ArkTS does not allow an interface to contain two methods with
signatures that are not distinguishable, e.g., two methods that have the same
-parameter lists, but different return types.
+parameter lists but different return types.
**TypeScript**
@@ -3198,8 +3066,8 @@ class C implements Mover, Shaker {
**Severity: error**
-ArkTS does not support merging declratations. All definitions of classes,
-interfaces and so on must be kept compact in the code base.
+ArkTS does not support merging declratations. Keep all definitions of classes,
+interfaces and so on compact in the codebase.
**TypeScript**
@@ -3270,11 +3138,13 @@ interface SelectableControl extends Control {
**Severity: error**
-ArkTS requires that object layout is determined in compile-time and cannot
-be changed at runtime. There for no runtime property-based checks are supported.
-If you need to do a type cast, use `as` operator and use desired properties
-and methods. If some property doesn’t exist then an attempt to reference it
-will result in a compile-time error.
+ArkTS requires that object layout is determined at compile time, and cannot
+be changed at runtime. Therefore, property-based runtime checks are not
+supported.
+If you need to do a type cast, use the operator `as` with desired properties
+and methods.
+If some property does not exist, then an attempt to refer to it causes a
+compile-time error.
**TypeScript**
@@ -3385,10 +3255,10 @@ const person = createPerson(Impersonizer, "John", 30)
**Severity: error**
-ArkTS does not support dynamic property declaration. All object properties must
-be declared immediately in the class. While it can be replaced with an array
-of objects, it is still better to adhere to the static language paradigm and
-declare fields, their names and types explicitly.
+ArkTS does not support dynamic property declaration. Declare all object
+properties immediately in the class. While replacement for an array of
+objects is possible, it is still better to adhere to the static language
+paradigm, and declare fields, their names and types explicitly.
**TypeScript**
@@ -3403,7 +3273,7 @@ const person: Person = {
name: "John",
age: 30,
email: "john@example.com",
- phone: 1234567890,
+ phoneNumber: 1234567890,
}
```
@@ -3414,13 +3284,13 @@ class Person {
name: string
age: number
email: string
- phone: number
+ phoneNumber: number
- constructor(name: string, age: number, email: string, phone: number) {
+ constructor(name: string, age: number, email: string, phoneNumber: number) {
this.name = name
this.age = age
this.email = email
- this.phone = phone
+ this.phoneNumber = phoneNumber
}
}
@@ -3448,7 +3318,7 @@ function main(): void {
ArkTS does not support initializing members of enumerations with expressions
that are evaluated during program runtime. Besides, all explicitly set
-initializers must be of the same time.
+initializers must be of the same type.
**TypeScript**
@@ -3494,8 +3364,8 @@ enum E2 {
**Severity: error**
-ArkTS does not support merging declratations for `enum`.
-The declaration of each `enum` must be kept compact in the code base.
+ArkTS does not support merging declratations for `enum`. Keep the
+declaration of each `enum` compact in the codebase.
**TypeScript**
@@ -3555,26 +3425,6 @@ namespace MyNamespace {
MyNamespace.x = 2
```
-## Recipe: Scripts and modules
-
-**Rule `arkts-no-scripts`**
-
-**Severity: error**
-
-In general, scripts and modules in ArkTS are very close to TypeScript.
-Differences are described in separate recipes.
-
-**See also**
-
-* Recipe: Special import type declarations are not supported
-* Recipe: Importing a module for side-effects only is not supported
-* Recipe: import default as ... is not supported
-* Recipe: require is not supported
-* Recipe: Renaming in export declarations is not supported
-* Recipe: Export list declaration is not supported
-* Recipe: Re-exporting is not supported
-* Recipe: export = ... assignment is not supported
-
## Recipe: Non-declaration statements in namespaces are not supported
**Rule `arkts-no-ns-statements`**
@@ -3621,23 +3471,23 @@ Use ordinary import instead.
```typescript
// Re-using the same import
-import { APIResponseType } from "./api"
+import { APIResponseType } from "api"
// Explicitly use import type
-import type { APIResponseType } from "./api"
+import type { APIResponseType } from "api"
```
**ArkTS**
```typescript
-import { APIResponseType } from "./api"
+import { APIResponseType } from "api"
```
**See also**
* Recipe: Importing a module for side-effects only is not supported
* Recipe: import default as ... is not supported
-* Recipe: require is not supported
+* Recipe: require and import assignment are not supported
## Recipe: Importing a module for side-effects only is not supported
@@ -3689,13 +3539,15 @@ import { default as d } from "mod"
import d from "mod"
```
-## Recipe: `require` is not supported
+## Recipe: `require` and `import` assignment are not supported
**Rule `arkts-no-require`**
**Severity: error**
-ArkTS does not support importing via `require`. Use `import` instead.
+ArkTS does not support importing via `require`.
+`import` assignments are not supported either.
+Use regular `import` instead.
**TypeScript**
@@ -3709,139 +3561,59 @@ import m = require("mod")
import * as m from "mod"
```
-## Recipe: Renaming in export declarations is not supported
-
-**Rule `arkts-no-export-renaming`**
-
-**Severity: error**
-
-ArkTS does not support renaming in export declarations. Similar effect
-can be achieved through setting an alias for the exported entity.
-
-**TypeScript**
-
-```typescript
-// file1.ts
-class MyClass {
- // ...
-}
-
-export { MyClass as RenamedClass }
-
-// file2.ts
-import { RenamedClass } from "./file1"
-
-function main(): void {
- const myObject = new RenamedClass()
- // ...
-}
-```
-
-**ArkTS**
-
-```typescript
-// module1
-class MyClass {
- // ...
-}
-
-export type RenamedClass = MyClass
-
-// module2
-import { RenamedClass } from "./module1"
-
-function main(): void {
- const myObject = new RenamedClass()
- // ...
-}
-```
-
**See also**
-* Recipe: Export list declaration is not supported
-* Recipe: Re-exporting is not supported
* Recipe: export = ... assignment is not supported
-## Recipe: Export list declaration is not supported
+## Recipe: Re-exporting is supported with restrictions
-**Rule `arkts-no-export-list-decl`**
+**Rule `arkts-limited-reexport`**
**Severity: error**
-ArkTS does not support syntax of export list declarations. All exported
-entities must be explicitly annotated with the `export` keyword.
-
-**TypeScript**
-
-```typescript
-export { x }
-export { x } from "mod"
-export { x, y as b, z as c }
-```
-
-**ArkTS**
-
-```typescript
-let x = 1
-class MyClass {}
-export let y = x, z: number = 2
-export RenamedClass = MyClass
-```
-
-**See also**
-
-* Recipe: Renaming in export declarations is not supported
-* Recipe: Re-exporting is not supported
-* Recipe: export = ... assignment is not supported
-
-## Recipe: Re-exporting is not supported
-
-**Rule `arkts-no-reexport`**
-
-**Severity: error**
-
-ArkTS does not support re-exporting. All desired entities must be
-imported explicitly from the modules that export them.
+ArkTS supports re-exporting syntax which covers most common cases of re-export:
+re-exporting imported entities and re-exporting which is combined with renaming.
+Other syntax flavors like `export * as ...` are not supported.
**TypeScript**
```typescript
// module1
-export class MyClass {
+export class Class1 {
+ // ...
+}
+export class Class2 {
// ...
}
// module2
-export { MyClass } from "module1"
+export * as utilities from "module1"
// consumer module
-import { MyClass } from "module2"
-
-const myInstance = new MyClass()
+import { utilities } from "module2"
```
**ArkTS**
```typescript
// module1
-export class MyClass {
- // ...
+export class Class1 {
+ // ...
+}
+export class C2 {
+ // ...
}
// module2
-// some stuff
+export { Class1 } from "module1"
+export { C2 as Class2 } from "module1"
// consumer module
-import { MyClass } from "module1"
-import * from "module2"
-
-const myInstance = new MyClass()
+import { Class1, Class2 } from "module2"
```
**See also**
-* Recipe: Renaming in export declarations is not supported
-* Recipe: Export list declaration is not supported
* Recipe: export = ... assignment is not supported
## Recipe: `export = ...` assignment is not supported
@@ -3887,30 +3659,47 @@ let p = Pt.origin
**See also**
-* Recipe: Renaming in export declarations is not supported
-* Recipe: Export list declaration is not supported
-* Recipe: Re-exporting is not supported
+* Recipe: require and import assignment are not supported
+* Recipe: Re-exporting is supported with restrictions
-## Recipe: Special export type declarations are not supported
+## Recipe: Special `export type` declarations are not supported
**Rule `arkts-no-special-exports`**
**Severity: error**
-ArkTS does not have a special notation for exporting types.
-Use ordinary export instead.
+ArkTS does not have a special notation for exporting types through
+`export type ...`. Use ordinary export instead.
**TypeScript**
```typescript
-class C {}
-export type { C }
+// Explicitly exported class:
+export class Class1 {
+ // ...
+}
+
+// Declared class later exported through export type ...
+class Class2 {
+ // ...
+}
+
+// This is not supported:
+export type { Class2 }
```
**ArkTS**
```typescript
-export class C {}
+// Explicitly exported class:
+export class Class1 {
+ // ...
+}
+
+// Explicitly exported class:
+export class Class2 {
+ // ...
+}
```
## Recipe: Ambient module declaration is not supported
@@ -3934,7 +3723,7 @@ declare module "someModule" {
```typescript
// Import what you need from the original module
-import { normalize } from "../someModule"
+import { normalize } from "someModule"
```
**See also**
@@ -3948,16 +3737,34 @@ import { normalize } from "../someModule"
**Severity: error**
-ArkTS does not supported wildcards in module names because in ArkTS, import
-is a compile-time, not a runtime feature. Use ordinary export syntax instead.
+ArkTS does not support wildcards in module names because in the language
+import is a compile-time, not a runtime feature.
+Use ordinary export syntax instead.
**TypeScript**
```typescript
+// Declaration:
declare module "*!text" {
const content: string
export default content
}
+
+// Consuming code:
+import fileContent from "some.txt!text"
+```
+
+**ArkTS**
+
+```typescript
+// Declaration:
+declare namespace N {
+ function foo(x: number): number
+}
+
+// Consuming code:
+import * from "module"
+console.log("N.foo called: ", N.foo(42))
```
**See also**
@@ -3972,10 +3779,10 @@ declare module "*!text" {
**Severity: error**
-ArkTS does not support universal module definitions (UMD) because in ArkTS
-there is no concept of “script” (as opposed to “module”). Besides, in ArkTS
-import is a compile-time, not a runtime feature. Use ordinary syntax for
-`export` and `import` instead.
+ArkTS does not support universal module definitions (UMD) because in the
+language there is no concept of “script” (as opposed to “module”).
+Besides, in ArkTS import is a compile-time, not a runtime feature.
+Use ordinary syntax for `export` and `import` instead.
**TypeScript**
@@ -3997,7 +3804,7 @@ namespace mathLib {
}
// in program
-import { mathLib } from "./math-lib"
+import { mathLib } from "math-lib"
mathLib.isPrime(2)
```
@@ -4011,19 +3818,19 @@ mathLib.isPrime(2)
**Severity: error**
-ArkTS does not allow to use `.js` extension in module identifiers because it
-has its own mechanisms for interoperating with JavaScript.
+ArkTS does not allow using `.js` extension in module identifiers because
+it has its own mechanisms for interoperating with JavaScript.
**TypeScript**
```typescript
-import { something } from "./module.js"
+import { something } from "module.js"
```
**ArkTS**
```typescript
-import { something } from "./module"
+import { something } from "module"
```
**See also**
@@ -4039,7 +3846,7 @@ import { something } from "./module"
ArkTS does not support `new.target` because there is no concept of runtime
prototype inheritance in the language. This feature is considered not applicable
-to the statically typing.
+to static typing.
**TypeScript**
@@ -4055,6 +3862,20 @@ class CustomError extends Error {
}
```
+**ArkTS**
+
+```typescript
+class CustomError extends Error {
+ constructor(message?: string) {
+ // Call parent's constructor, inheritance chain is static and
+ // cannot be modified in runtime
+ super(message)
+ console.log(this instanceof Error) // true
+ }
+}
+let ce = new CustomError()
+```
+
**See also**
* Recipe: Prototype assignment is not supported
@@ -4066,19 +3887,19 @@ class CustomError extends Error {
**Severity: error**
ArkTS does not support such “runtime” import expressions as `await import...`
-because in ArkTS import is a compile-time, not a runtime feature. Use regular
-import syntax instead.
+because in the language import is a compile-time, not a runtime feature.
+Use regular import syntax instead.
**TypeScript**
```typescript
-const zipUtil = await import("./utils/create-zip-file")
+const zipUtil = await import("utils/create-zip-file")
```
**ArkTS**
```typescript
-import { zipUtil } from "./utils/create-zip-file"
+import { zipUtil } from "utils/create-zip-file"
```
**See also**
@@ -4094,8 +3915,8 @@ import { zipUtil } from "./utils/create-zip-file"
**Severity: error**
ArkTS does not support definite assignment assertions `let v!: T` because
-they are considered an excessive compiler hint. Use declaration with
-initialization instead.
+they are considered an excessive compiler hint.
+Use declaration with initialization instead.
**TypeScript**
@@ -4129,17 +3950,18 @@ console.log("x = " + x)
**Severity: error**
-ArkTS does not support IIFEs as namespace declarations because in ArkTS,
-anonymous functions cannot serve as namespaces. Use regular syntax for
-namespaces instead.
+ArkTS does not support IIFEs as namespace declarations because anonymous
+functions in the language cannot serve as namespaces.
+Use regular syntax for namespaces instead.
**TypeScript**
```typescript
var C = (function() {
- function C(n) {
- this.p = n
+ function C(n: number) {
+ this.p = n // Compile-time error only with noImplicitThis
}
+ C.staticProperty = 0
return C
})()
C.staticProperty = 1
@@ -4161,13 +3983,14 @@ namespace C {
ArkTS does not support prototype assignment because there is no concept of
runtime prototype inheritance in the language. This feature is considered not
-applicable to the static typing.
+applicable to static typing. Mechanism of classes and / or interfaces must
+be used instead to statically “combine” methods to data together.
**TypeScript**
```typescript
-var C = function(p) {
- this.p = p
+var C = function(p: number) {
+ this.p = p // Compile-time error only with noImplicitThis
}
C.prototype = {
@@ -4176,8 +3999,22 @@ C.prototype = {
}
}
-C.prototype.q = function(r) {
- return this.p === r
+C.prototype.q = function(r: number) {
+ return this.p == r
+}
+```
+
+**ArkTS**
+
+```typescript
+class C {
+ p: number = 0
+ m() {
+ console.log(this.p)
+ }
+ q(r: number) {
+ return this.p == r
+ }
}
```
@@ -4211,7 +4048,7 @@ globalThis.abc = 200
export let abc : number = 0
// file2
-import * as M from "../file1"
+import * as M from "file1"
M.abc = 200
```
@@ -4221,15 +4058,18 @@ M.abc = 200
* Recipe: Declaring properties on functions is not supported
* Recipe: Usage of standard library is restricted
-## Recipe: Utility types are not supported
+## Recipe: Some of utility types are not supported
**Rule `arkts-no-utility-types`**
**Severity: error**
Currently ArkTS does not support utility types from TypeScript extensions to the
-standard library (`Omit`, `Partial`, `Readonly`, `Record`, `Pick`,
-etc.).
+standard library (`Omit`, `Pick`, etc.). Exceptions are: `Partial`,
+`Record`.
+
+For the type *Record*, the type of an indexing expression *rec[index]* is
+of the type *V | undefined*.
**TypeScript**
@@ -4241,20 +4081,55 @@ type Person = {
}
type QuantumPerson = Omit
+
+let persons : Record = {
+ "Alice": {
+ name: "Alice",
+ age: 32,
+ location: "Shanghai"
+ },
+ "Bob": {
+ name: "Bob",
+ age: 48,
+ location: "New York"
+ }
+}
+console.log(persons["Bob"].age)
+console.log(persons["Rob"].age) // Runtime exception
```
**ArkTS**
```typescript
class Person {
- name: string
- age: number
- location: string
+ name: string = ""
+ age: number = 0
+ location: string = ""
}
class QuantumPerson {
- name: string
- age: number
+ name: string = ""
+ age: number = 0
+}
+
+type OptionalPerson = Person | undefined
+let persons : Record = {
+// Or:
+// let persons : Record = {
+ "Alice": {
+ name: "Alice",
+ age: 32,
+ location: "Shanghai"
+ },
+ "Bob": {
+ name: "Bob",
+ age: 48,
+ location: "New York"
+ }
+}
+console.log(persons["Bob"]!.age)
+if (persons["Rob"]) { // Explicit value check, no runtime exception
+ console.log(persons["Rob"].age)
}
```
@@ -4303,15 +4178,17 @@ class MyImage {
// ...
}
-function readImage(
+async function readImage(
path: string, callback: (err: Error, image: MyImage) => void
) : Promise
{
- // async implementation
+ // In real world, the implementation is more complex,
+ // involving real network / DB logic, etc.
+ return await new MyImage()
}
function readImageSync(path: string) : MyImage {
- // sync implementation
+ return new MyImage()
}
```
@@ -4325,12 +4202,12 @@ function readImageSync(path: string) : MyImage {
**Severity: error**
-ArkTS does not allow to use standard library functions `Function.apply`,
-`Function.bind`, `Function.call`. These APIs are needed in the standard
+ArkTS does not allow using standard library functions `Function.apply`,
+`Function.bind` and `Function.call`. These APIs are needed in the standard
library to explicitly set `this` parameter for the called function.
-In ArkTS semantics of `this` is restricted to the conventional OOP style,
-and usage of `this` in stand-alone functions is prohibited. Thus these
-functions are excessive.
+In ArkTS the semantics of `this` is restricted to the conventional OOP
+style, and the usage of `this` in stand-alone functions is prohibited.
+Thus these functions are excessive.
**TypeScript**
@@ -4382,7 +4259,7 @@ console.log(person1.fullName())
**Severity: error**
-Currently ArkTS supports `readonly` for properties, but not for parameters.
+Currently, ArkTS supports `readonly` for properties, but not for parameters.
**TypeScript**
@@ -4435,7 +4312,7 @@ let x : string = "hello"
let y : number[] = [10, 20]
class Label {
- text : string
+ text : string = ""
}
// Type 'Label':
@@ -4450,7 +4327,7 @@ let z : Label = {
**Severity: error**
-ArkTS does not support import assertions because in ArkTS, import is a
+ArkTS does not support import assertions because in the language import is a
compile-time, not a runtime feature. So asserting correctness of imported APIs
in runtime does not make sense for the statically typed language. Use ordinary
`import` syntax instead.
@@ -4458,14 +4335,14 @@ in runtime does not make sense for the statically typed language. Use ordinary
**TypeScript**
```typescript
-import { obj } from "./something.json" assert { type: "json" }
+import { obj } from "something.json" assert { type: "json" }
```
**ArkTS**
```typescript
// Correctness of importing T will be checked in compile-time:
-import { something } from "./module"
+import { something } from "module"
```
**See also**
@@ -4480,10 +4357,10 @@ import { something } from "./module"
**Severity: error**
-ArkTS does not allow usage of some APIs from the TypeScript/JavaScript standard library.
-The most part of the restricted APIs relates to manipulating objects in
-dynamic manner, which is not compatible with the static typing. Following APIs
-are prohibited from usage:
+ArkTS does not allow using some APIs from the TypeScript/JavaScript standard library.
+The most part of the restricted APIs relates to manipulating objects in a
+dynamic manner, which is not compatible with static typing. The usage of
+the following APIs is prohibited:
Properties and functions of the global object: `eval`,
`Infinity`, `NaN`, `isFinite`, `isNaN`, `parseFloat`, `parseInt`,
@@ -4526,3 +4403,161 @@ Properties and functions of the global object: `eval`,
* Recipe: Dynamic property declaration is not supported
* Recipe: globalThis is not supported
+## Recipe: Strict type checking is enforced
+
+**Rule `arkts-strict-typing`**
+
+**Severity: error**
+
+Type checker in ArkTS is not optional, the code must be explicitly and
+correctly types to be compiled and run. When porting from the standard TypeScript,
+turn on the following flags: `noImplicitReturns`, `strictFunctionTypes`,
+`strictNullChecks`, `strictPropertyInitialization`.
+
+**TypeScript**
+
+```typescript
+class C {
+ n: number // Compile-time error only with strictPropertyInitialization
+ s: string // Compile-time error only with strictPropertyInitialization
+}
+
+// Compile-time error only with noImplicitReturns
+function foo(s: string): string {
+ if (s != "") {
+ console.log(s)
+ return s
+ } else {
+ console.log(s)
+ }
+}
+
+let n: number = null // Compile-time error only with strictNullChecks
+```
+
+**ArkTS**
+
+```typescript
+class C {
+ n: number = 0
+ s: string = ""
+}
+
+function foo(s: string): string {
+ console.log(s)
+ return s
+}
+
+let n1: number | null = null
+let n2: number = 0
+```
+
+**See also**
+
+* Recipe: Use explicit types instead of any, unknown
+* Recipe: Switching off type checks with in-place comments is not allowed
+
+## Recipe: Switching off type checks with in-place comments is not allowed
+
+**Rule `arkts-strict-typing-required`**
+
+**Severity: error**
+
+Type checker in ArkTS is not optional, the code must be explicitly and
+correctly typed to be compiled and run. “Suppressing” type checker in-place
+with special comments is not allowed. In particular, `@ts-ignore` and
+`@ts-nocheck` annotations are not supported.
+
+**TypeScript**
+
+```typescript
+// @ts-nocheck
+// ...
+// Some code with switched off type checker
+// ...
+
+let s1: string = null // No error, type checker suppressed
+
+// @ts-ignore
+let s2: string = null // No error, type checker suppressed
+```
+
+**ArkTS**
+
+```typescript
+let s1: string | null = null // No error, properly types
+let s2: string = null // Compile-time error
+```
+
+**See also**
+
+* Recipe: Use explicit types instead of any, unknown
+* Recipe: Strict type checking is enforced
+
+## Recipe: No dependencies on TypeScript code are currently allowed
+
+**Rule `arkts-no-ts-deps`**
+
+**Severity: error**
+
+Currently, the codebase implemented in the standard TypeScript language must not
+depend on ArkTS through importing the ArkTS codebase. Imports in reverse
+direction are supported.
+
+**TypeScript**
+
+```typescript
+// app.ets
+export class C {
+ // ...
+}
+
+// lib.ts
+import { C } from "app"
+```
+
+**ArkTS**
+
+```typescript
+// lib1.ets
+export class C {
+ // ...
+}
+
+// lib2.ets
+import { C } from "lib1"
+```
+
+## Recipe: No decorators except ArkUI decorators are currently allowed
+
+**Rule `arkts-no-decorators-except-arkui`**
+
+**Severity: error**
+
+Currently, only ArkUI decorators are allowed in the ArkTS.
+Any other decorator will cause a compile-time error.
+
+**TypeScript**
+
+```typescript
+function classDecorator(x: any, y: any): void {
+ //
+}
+
+@classDecorator
+class BugReport {
+}
+```
+
+**ArkTS**
+
+```typescript
+function classDecorator(x: any, y: any): void {
+ //
+}
+
+@classDecorator // compile-time error: unsupported decorator
+class BugReport {
+}
+```
+
diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md
index 4fc3fb5005d7ac0208b083be1a084bd5c66b4865..cf433ae09b9c8575f2d126a465a5053049a69141 100644
--- a/en/application-dev/reference/apis/Readme-EN.md
+++ b/en/application-dev/reference/apis/Readme-EN.md
@@ -205,12 +205,13 @@
- [@ohos.curves (Interpolation Calculation)](js-apis-curve.md)
- [@ohos.font (Custom Font Registration)](js-apis-font.md)
- [@ohos.matrix4 (Matrix Transformation)](js-apis-matrix4.md)
+ - [@ohos.measure (Text Measurement)](js-apis-measure.md)
- [@ohos.mediaquery (Media Query)](js-apis-mediaquery.md)
- [@ohos.pluginComponent (PluginComponentManager)](js-apis-plugincomponent.md)
- [@ohos.promptAction (Prompt)](js-apis-promptAction.md)
- [@ohos.router (Page Routing)](js-apis-router.md)
- - [@ohos.measure (Text Measurement)](js-apis-measure.md)
- [@ohos.uiAppearance (UI Appearance)](js-apis-uiappearance.md)
+
- Graphics
- [@ohos.animation.windowAnimationManager (Window Animation Management)](js-apis-windowAnimationManager.md)
- [@ohos.application.WindowExtensionAbility (WindowExtensionAbility)](js-apis-application-windowExtensionAbility.md)
@@ -225,12 +226,15 @@
- [WebGL2](js-apis-webgl2.md)
- Multimedia
+ - [@ohos.app.ability.MediaControlExtensionAbility (ExtensionAbility for Media Playback Control)](js-apis-app-ability-MediaControlExtensionAbility.md)
- [@ohos.multimedia.audio (Audio Management)](js-apis-audio.md)
- [@ohos.multimedia.avsession (AVSession Management)](js-apis-avsession.md)
- [@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)
+ - application
+ - [MediaControlExtensionContext (ExtensionAbility Context for Media Playback Control)](js-apis-inner-application-MediaControlExtensionContext.md)
- multimedia
- [ringtonePlayer (Ringtone Player)](js-apis-inner-multimedia-ringtonePlayer.md)
@@ -315,18 +319,19 @@
- [@ohos.net.statistics (Traffic Management)](js-apis-net-statistics.md)
- [@ohos.net.webSocket (WebSocket Connection)](js-apis-webSocket.md)
- [@ohos.request (Upload and Download)](js-apis-request.md)
+ - [@ohos.net.vpn (VPN Management)](js-apis-net-vpn.md)
- Connectivity
- - [@ohos.bluetooth.a2dp (Bluetooth a2dp Module)(Recommended)](js-apis-bluetooth-a2dp.md)
- - [@ohos.bluetooth.access (Bluetooth access Module)(Recommended)](js-apis-bluetooth-access.md)
- - [@ohos.bluetooth.baseProfile (Bluetooth baseProfile Module)(Recommended)](js-apis-bluetooth-baseProfile.md)
- - [@ohos.bluetooth.ble (Bluetooth ble Module)(Recommended)](js-apis-bluetooth-ble.md)
- - [@ohos.bluetooth.connection (Bluetooth connection Module)(Recommended)](js-apis-bluetooth-connection.md)
- - [@ohos.bluetooth.constant (Bluetooth constant Module)(Recommended)](js-apis-bluetooth-constant.md)
- - [@ohos.bluetooth.hfp (Bluetooth hfp Module)(Recommended)](js-apis-bluetooth-hfp.md)
- - [@ohos.bluetooth.hid (Bluetooth hid Module)(Recommended)(js-apis-bluetooth-hid.md)
- - [@ohos.bluetooth.pan (Bluetooth pan Module)(Recommended)](js-apis-bluetooth-pan.md)
- - [@ohos.bluetooth.socket (Bluetooth socket Module)(Recommended)](js-apis-bluetooth-socket.md)
+ - [@ohos.bluetooth.a2dp (Bluetooth A2DP Module) (Recommended)](js-apis-bluetooth-a2dp.md)
+ - [@ohos.bluetooth.access (Bluetooth Access Module) (Recommended)](js-apis-bluetooth-access.md)
+ - [@ohos.bluetooth.baseProfile (Bluetooth baseProfile Module) (Recommended)](js-apis-bluetooth-baseProfile.md)
+ - [@ohos.bluetooth.ble (Bluetooth BLE Module) (Recommended)](js-apis-bluetooth-ble.md)
+ - [@ohos.bluetooth.connection (Bluetooth connection Module) (Recommended)](js-apis-bluetooth-connection.md)
+ - [@ohos.bluetooth.constant (Bluetooth constant Module) (Recommended)](js-apis-bluetooth-constant.md)
+ - [@ohos.bluetooth.hfp (Bluetooth hfp Module) (Recommended)](js-apis-bluetooth-hfp.md)
+ - [@ohos.bluetooth.hid (Bluetooth hid Module) (Recommended)](js-apis-bluetooth-hid.md)
+ - [@ohos.bluetooth.pan (Bluetooth pan Module) (Recommended)](js-apis-bluetooth-pan.md)
+ - [@ohos.bluetooth.socket (Bluetooth socket Module) (Recommended)](js-apis-bluetooth-socket.md)
- [@ohos.bluetooth (Bluetooth) (To Be Deprecated Soon)](js-apis-bluetooth.md)
- [@ohos.bluetoothManager (Bluetooth) (To Be Deprecated Soon)](js-apis-bluetoothManager.md)
- [@ohos.connectedTag (Active Tags)](js-apis-connectedTag.md)
@@ -385,6 +390,7 @@
- [@ohos.charger (Charging Type)](js-apis-charger.md)
- [@ohos.cooperate (Screen Hopping)](js-apis-devicestatus-cooperate.md)
- [@ohos.deviceAttest (Device Attestation)](js-apis-deviceAttest.md)
+ - [@ohos. deviceStatus.dragInteraction (Drag)](js-apis-devicestatus-draginteraction.md)
- [@ohos.deviceInfo (Device Information)](js-apis-device-info.md)
- [@ohos.distributedDeviceManager (Device Management)](js-apis-distributedDeviceManager.md)
- [@ohos.distributedHardware.deviceManager (Device Management)](js-apis-device-manager.md)
@@ -405,6 +411,7 @@
- [@ohos.multimodalInput.touchEvent (Touch Event)](js-apis-touchevent.md)
- [@ohos.multimodalInput.shortKey (Shortcut Key)](js-apis-shortKey.md)
- [@ohos.power (System Power Management)](js-apis-power.md)
+ - [@ohos.resourceschedule.deviceStandby (Device Standby)](js-apis-resourceschedule-deviceStandby.md)
- [@ohos.runningLock (Runninglock)](js-apis-runninglock.md)
- [@ohos.sensor (Sensor)](js-apis-sensor.md)
- [@ohos.settings (Data Item Settings)](js-apis-settings.md)
@@ -420,7 +427,6 @@
- Account Management
- [@ohos.account.appAccount (App Account Management)](js-apis-appAccount.md)
- - [@ohos.account.appAccount.AuthorizationExtensionAbility (App AuthorizationExtensionAbility)](js-apis-appAccount-authorizationExtensionAbility.md)
- [@ohos.account.distributedAccount (Distributed Account Management)](js-apis-distributed-account.md)
- [@ohos.account.osAccount (OS Account Management)](js-apis-osAccount.md)
diff --git a/en/application-dev/reference/apis/js-apis-ability-featureAbility.md b/en/application-dev/reference/apis/js-apis-ability-featureAbility.md
index b5ea0c253dba532a22c1e090f40e51656f64b27d..deae2f81c8347f379daf3aada06e51f9377ae450 100644
--- a/en/application-dev/reference/apis/js-apis-ability-featureAbility.md
+++ b/en/application-dev/reference/apis/js-apis-ability-featureAbility.md
@@ -161,7 +161,7 @@ startAbilityForResult(parameter: StartAbilityParameter, callback: AsyncCallback\
Starts an ability. This API uses an asynchronous callback to return the result when the ability is terminated. The following situations may be possible for a started ability:
- Normally, you can call [terminateSelfWithResult](#featureabilityterminateselfwithresult7) to terminate the ability. The result is returned to the caller.
- If an exception occurs, for example, the ability is killed, an exception message, in which **resultCode** is **-1**, is returned to the caller.
- - If different applications call this API to start an ability that uses the sington mode and then call [terminateSelfWithResult](#featureabilityterminateselfwithresult7) to terminate the ability, the normal result is returned to the last caller, and an exception message, in which **resultCode** is **-1**, is returned to others.
+ - If different applications call this API to start an ability that uses the singleton mode and then call [terminateSelfWithResult](#featureabilityterminateselfwithresult7) to terminate the ability, the normal result is returned to the last caller, and an exception message, in which **resultCode** is **-1**, is returned to others.
Observe the following when using this API:
- If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission.
@@ -214,7 +214,7 @@ startAbilityForResult(parameter: StartAbilityParameter): Promise\
Starts an ability. This API uses a promise to return the result when the ability is terminated. The following situations may be possible to an ability after it is started:
- Normally, you can call [terminateSelfWithResult](#featureabilityterminateselfwithresult7) to terminate the ability. The result is returned to the caller.
- If an exception occurs, for example, the ability is killed, an exception message, in which **resultCode** is **-1**, is returned to the caller.
- - If different applications call this API to start an ability that uses the sington mode and then call [terminateSelfWithResult](#featureabilityterminateselfwithresult7) to terminate the ability, the normal result is returned to the last caller, and an exception message, in which **resultCode** is **-1**, is returned to others.
+ - If different applications call this API to start an ability that uses the singleton mode and then call [terminateSelfWithResult](#featureabilityterminateselfwithresult7) to terminate the ability, the normal result is returned to the last caller, and an exception message, in which **resultCode** is **-1**, is returned to others.
Observe the following when using this API:
- If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission.
diff --git a/en/application-dev/reference/apis/js-apis-animator.md b/en/application-dev/reference/apis/js-apis-animator.md
index 1818bfc13dd6859894cf122f96b2171d0ce70e47..829355f9eecdfd2ccc9a889a478a9c8c575ee52a 100644
--- a/en/application-dev/reference/apis/js-apis-animator.md
+++ b/en/application-dev/reference/apis/js-apis-animator.md
@@ -257,7 +257,7 @@ Defines animator options.
| Name | Type | Mandatory| Description |
| ---------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
| duration | number | Yes | Duration for playing the animation, in milliseconds. |
-| easing | string | Yes | Animation interpolation curve. Only the following values are supported: **"linear"**: The animation speed keeps unchanged. **"ease"**: The animation starts slowly, accelerates, and then slows down towards the end. The cubic-bezier curve (0.25, 0.1, 0.25, 1.0) is used. **"ease-in"**: The animation starts at a low speed and then picks up speed until the end. The cubic-bezier curve (0.42, 0.0, 1.0, 1.0) is used. **"ease-out"**: The animation ends at a low speed. The cubic-bezier curve (0.0, 0.0, 0.58, 1.0) is used. **"ease-in-out"**: The animation starts and ends at a low speed. The cubic-bezier curve (0.42, 0.0, 0.58, 1.0) is used. **"fast-out-slow-in"**: The animation uses the standard cubic-bezier curve (0.4, 0.0, 0.2, 1.0). **"linear-out-slow-in"**: The animation uses the deceleration cubic-bezier curve (0.0, 0.0, 0.2, 1.0). **"friction"**: The animation uses the damping cubic-bezier curve (0.2, 0.0, 0.2, 1.0). **"extreme-deceleration"**: The animation uses the extreme deceleration cubic-bezier curve (0.0, 0.0, 0.0, 1.0). **"rhythm"**: The animation uses the rhythm cubic-bezier curve (0.7, 0.0, 0.2, 1.0). **"sharp"**: The animation uses the sharp cubic-bezier curve (0.33, 0.0, 0.67, 1.0). **"smooth"**: The animation uses the smooth cubic-bezier curve (0.4, 0.0, 0.4, 1.0). **cubic-bezier(x1, y1, x2, y2)**: The animation uses the defined cubic-bezier curve, where the value of the input parameters must range from 0 to 1. **steps(number, step-position)**: The animation uses a step curve. The **number** must be set and only an integer is supported. **step-position** is optional. It can be set to **start** or **end**. The default value is **end**.|
+| easing | string | Yes | Animation interpolation curve. Only the following values are supported: **"linear"**: The animation speed keeps unchanged. **"ease"**: The animation starts slowly, accelerates, and then slows down towards the end. The cubic-bezier curve (0.25, 0.1, 0.25, 1.0) is used. **"ease-in"**: The animation starts at a low speed and then picks up speed until the end. The cubic-bezier curve (0.42, 0.0, 1.0, 1.0) is used. **"ease-out"**: The animation ends at a low speed. The cubic-bezier curve (0.0, 0.0, 0.58, 1.0) is used. **"ease-in-out"**: The animation starts and ends at a low speed. The cubic-bezier curve (0.42, 0.0, 0.58, 1.0) is used. **"fast-out-slow-in"**: The animation uses the standard cubic-bezier curve (0.4, 0.0, 0.2, 1.0). **"linear-out-slow-in"**: The animation uses the deceleration cubic-bezier curve (0.0, 0.0, 0.2, 1.0). **"friction"**: The animation uses the damping cubic-bezier curve (0.2, 0.0, 0.2, 1.0). **"extreme-deceleration"**: The animation uses the extreme deceleration cubic-bezier curve (0.0, 0.0, 0.0, 1.0). **"rhythm"**: The animation uses the rhythm cubic-bezier curve (0.7, 0.0, 0.2, 1.0). **"sharp"**: The animation uses the sharp cubic-bezier curve (0.33, 0.0, 0.67, 1.0). **"smooth"**: The animation uses the smooth cubic-bezier curve (0.4, 0.0, 0.4, 1.0). **"cubic-bezier(x1,y1,x2,y2)"**: The animation uses the defined cubic bezier curve, where the value of **x1** and **x2** must range from 0 to 1. For example, **"cubic-bezier(0.42,0.0,0.58,1.0)"**. **"steps(number,step-position)"**: The animation uses a step curve. The **number** parameter is mandatory and must be set to a positive integer. The **step-position** parameter is optional and can be set to **start** or **end** (default value). For example, **"steps(3,start)"**.|
| delay | number | Yes | Animation delay duration, in milliseconds. Value **0** means that there is no delay. |
| fill | "none" \| "forwards" \| "backwards" \| "both" | Yes | State of the animated target after the animation is executed. **"none"**: No style is applied to the target before or after the animation is executed. **"forwards"**: The target keeps the state at the end of the animation (defined in the last key frame) after the animation is executed. **"backwards"**: The animation uses the value defined in the first key frame during the **animation-delay**. When **animation-direction** is set to **normal** or **alternate**, the value in the **from** key frame is used. When **animation-direction** is set to **reverse** or **alternate-reverse**, the value in the **to** key frame is used. **"both"**: The animation follows the **forwards** and **backwards** rules.|
| direction | "normal" \| "reverse" \| "alternate" \| "alternate-reverse" | Yes | Animation playback mode. **"normal"**: plays the animation in forward loop mode. **"reverse"**: plays the animation in reverse loop mode. **"alternate"**: plays the animation in alternating loop mode. When the animation is played for an odd number of times, the playback is in forward direction. When the animation is played for an even number of times, the playback is in reverse direction. **"alternate-reverse"**: plays the animation in reverse alternating loop mode. When the animation is played for an odd number of times, the playback is in reverse direction. When the animation is played for an even number of times, the playback is in forward direction.|
diff --git a/en/application-dev/reference/apis/js-apis-app-ability-MediaControlExtensionAbility.md b/en/application-dev/reference/apis/js-apis-app-ability-MediaControlExtensionAbility.md
new file mode 100644
index 0000000000000000000000000000000000000000..6660aa2e1f10722a23fad1ea77d3df80109cf37e
--- /dev/null
+++ b/en/application-dev/reference/apis/js-apis-app-ability-MediaControlExtensionAbility.md
@@ -0,0 +1,17 @@
+# @ohos.app.ability.MediaControlExtensionAbility (ExtensionAbility for Media Playback Control)
+
+The **MediaControlExtensionAbility** module, inherited from [UIExtensionAbility](js-apis-app-ability-uiExtensionAbility.md), provides ExtensionAbilities for media playback control. No APIs are added. During actual development, you need to implement the APIs in the parent class to use the lifecycle and capabilities of UIExtensionAbilities. You cannot directly call the base class.
+
+**System capability**: SystemCapability.Multimedia.AVSession.Core
+
+> **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 of this module can be used only in the stage model.
+> - The APIs provided by this module are system APIs.
+
+## Modules to Import
+
+```js
+import MediaControlExtensionAbility from @ohos.app.ability.MediaControlExtensionAbility;
+```
diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md
index 334d1f36db45e2ad9c5fc4aa15748bc05b579de8..14ef27dab2c6063f5e3f67acfdb5f8d53d7f3226 100644
--- a/en/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md
+++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md
@@ -39,7 +39,7 @@ Enumerates the initial ability launch reasons. You can use it together with [onC
| CALL | 2 | The ability is started by calling [startAbilityByCall](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartabilitybycall).|
| CONTINUATION | 3 | The ability is started by means of cross-device migration.|
| APP_RECOVERY | 4 | The ability is automatically started when the application is restored from a fault.|
-| SHARE10+ | 5 | The ability is started by calling [acquireShareData](js-apis-app-ability-abilityManager.md#acquiresharedata).|
+| SHARE10+ | 5 | The ability is started by means of atomic service sharing.|
**Example**
diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityManager.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityManager.md
index a19759144290c86e6af1f6812569683e39d74bae..20a2d3fa934663ead33140c413754b3deff69bdc 100644
--- a/en/application-dev/reference/apis/js-apis-app-ability-abilityManager.md
+++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityManager.md
@@ -392,6 +392,8 @@ Called by a system dialog box to obtain shared data, which is set by the target
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
+**System API**: This is a system API and cannot be called by third-party applications.
+
**Parameters**
| Name | Type | Mandatory | Description |
@@ -433,6 +435,8 @@ Called by a system dialog box to obtain shared data, which is set by the target
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
+**System API**: This is a system API and cannot be called by third-party applications.
+
**Parameters**
| Name | Type | Mandatory | Description |
diff --git a/en/application-dev/reference/apis/js-apis-app-ability-driverExtensionAbility.md b/en/application-dev/reference/apis/js-apis-app-ability-driverExtensionAbility.md
index 769c14e71f4fc11339c36aa848a60d1a719a9624..b403e44db08e3c8367b95174b27d6ff7e12f0a06 100644
--- a/en/application-dev/reference/apis/js-apis-app-ability-driverExtensionAbility.md
+++ b/en/application-dev/reference/apis/js-apis-app-ability-driverExtensionAbility.md
@@ -21,7 +21,6 @@ None.
**System capability**: SystemCapability.Driver.ExternalDevice
-**System API**: This is a system API and cannot be called by third-party applications.
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
@@ -36,8 +35,6 @@ Called when a DriverExtensionAbility is created to initialize the service logic.
**System capability**: SystemCapability.Driver.ExternalDevice
-**System API**: This is a system API and cannot be called by third-party applications.
-
**Parameters**
| Name| Type| Mandatory| Description|
@@ -63,8 +60,6 @@ Called when this DriverExtensionAbility is destroyed to clear resources.
**System capability**: SystemCapability.Driver.ExternalDevice
-**System API**: This is a system API and cannot be called by third-party applications.
-
**Example**
```ts
@@ -84,8 +79,6 @@ Called following **onCreate()** when a DriverExtensionAbility is started by call
**System capability**: SystemCapability.Driver.ExternalDevice
-**System API**: This is a system API and cannot be called by third-party applications.
-
**Parameters**
| Name| Type| Mandatory| Description|
@@ -106,7 +99,7 @@ Called following **onCreate()** when a DriverExtensionAbility is started by call
constructor(des) {
super(des);
}
- onRemoteRequest(code, data, reply, option) {
+ onRemoteMessageRequest(code, data, reply, option) {
}
}
class DriverExt extends DriverExtension {
@@ -125,7 +118,7 @@ class StubTest extends rpc.RemoteObject{
constructor(des) {
super(des);
}
- onRemoteRequest(code, data, reply, option) {
+ onRemoteMessageRequest(code, data, reply, option) {
}
}
async function getDescriptor() {
@@ -149,8 +142,6 @@ Called when a client is disconnected from this DriverExtensionAbility.
**System capability**: SystemCapability.Driver.ExternalDevice
-**System API**: This is a system API and cannot be called by third-party applications.
-
**Parameters**
| Name| Type| Mandatory| Description|
@@ -187,8 +178,6 @@ Dumps client information.
**System capability**: SystemCapability.Driver.ExternalDevice
-**System API**: This is a system API and cannot be called by third-party applications.
-
**Parameters**
| Name| Type| Mandatory| Description|
diff --git a/en/application-dev/reference/apis/js-apis-app-ability-uiAbility.md b/en/application-dev/reference/apis/js-apis-app-ability-uiAbility.md
index 0ce9d75fbc5983a7670a16645ee50816914520c7..41f32713e0de5e611cec98753f439c345b3cbbe1 100644
--- a/en/application-dev/reference/apis/js-apis-app-ability-uiAbility.md
+++ b/en/application-dev/reference/apis/js-apis-app-ability-uiAbility.md
@@ -1,6 +1,6 @@
# @ohos.app.ability.UIAbility (UIAbility)
-UIAbility is an application component that has the UI. The **UIAbility** module provides lifecycle callback such as component creation, destruction, and foreground/background switching. It also provides the following capabilities related to component collaboration:
+UIAbility is an application component that has the UI. The **UIAbility** module provides lifecycle callbacks such as component creation, destruction, and foreground/background switching. It also provides the following capabilities related to component collaboration:
- [Caller](#caller): an object returned by [startAbilityByCall](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartabilitybycall). The CallerAbility (caller) uses this object to communicate with the CalleeAbility (callee).
- [Callee](#callee): an internal object of UIAbility. The CalleeAbility (callee) uses this object to communicate with the CallerAbility (caller).
@@ -141,7 +141,7 @@ Called when this UIAbility is destroyed to clear resources.
}
```
-After the **onDestroy** lifecycle callback is executed, the application may exit. As a result, the asynchronous function in **onDestroy** may fail to be executed correctly, for example, asynchronously writing data to the database. The asynchronous lifecycle can be used to ensure that the subsequent lifecycle continues after the asynchronous **onDestroy** is complete.
+After the **onDestroy()** lifecycle callback is executed, the application may exit. Consequently, the asynchronous function (for example, asynchronously writing data to the database) in **onDestroy()** may fail to be executed. You can use the asynchronous lifecycle to ensure that the subsequent lifecycle continues only after the asynchronous function in **onDestroy()** finishes the execution.
```ts
class MyUIAbility extends UIAbility {
@@ -202,7 +202,7 @@ Called to save data during the ability migration preparation process.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| wantParam | {[key: string]: any} | Yes| **want** parameter.|
+| wantParam | {[key: string]: Object} | Yes| **want** parameter.|
**Return value**
@@ -289,7 +289,7 @@ Called when the framework automatically saves the UIAbility state in the case of
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| reason | [AbilityConstant.StateType](js-apis-app-ability-abilityConstant.md#abilityconstantstatetype) | Yes| Reason for triggering the callback to save the UIAbility state.|
-| wantParam | {[key: string]: any} | Yes| **want** parameter.|
+| wantParam | {[key: string]: Object} | Yes| **want** parameter.|
**Return value**
@@ -315,7 +315,7 @@ class MyUIAbility extends UIAbility {
onShare(wantParam:{ [key: string]: Object }): void;
-Called when this UIAbility sets data to share. **ohos.extra.param.key.contentTitle** indicates the title of the content to share in the sharing box, **ohos.extra.param.key.shareAbstract** provides an abstract description of the content, and **ohos.extra.param.key.shareUrl** indicates the online address of the service. You need to set these three items as objects, with the key set to **title**, **abstract**, and **url**, respectively.
+Called by this UIAbility to set data to share. **ohos.extra.param.key.shareUrl** indicates the online address of the service.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
@@ -332,9 +332,7 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant';
class MyUIAbility extends UIAbility {
onShare(wantParams) {
console.log('onShare');
- wantParams['ohos.extra.param.key.contentTitle'] = {title: "OA"};
- wantParams['ohos.extra.param.key.shareAbstract'] = {abstract: "communication for company employee"};
- wantParams['ohos.extra.param.key.shareUrl'] = {url: "oa.example.com"};
+ wantParams['ohos.extra.param.key.shareUrl'] = 'example.com';
}
}
```
diff --git a/en/application-dev/reference/apis/js-apis-app-ability-uiExtensionAbility.md b/en/application-dev/reference/apis/js-apis-app-ability-uiExtensionAbility.md
new file mode 100644
index 0000000000000000000000000000000000000000..27b81231e21b8e5f1c561270e6451be502677e74
--- /dev/null
+++ b/en/application-dev/reference/apis/js-apis-app-ability-uiExtensionAbility.md
@@ -0,0 +1,85 @@
+# @ohos.app.ability.UIExtensionAbility (Base Class for ExtensionAbilities with UI)
+
+**UIExtensionAbility**, inherited from [ExtensionAbility](js-apis-app-ability-extensionAbility.md), is a base class for ExtensionAbilities with UI in specific scenarios. It provides attributes and APIs related to ExtensionAbilities with UI. You cannot inherit from this base class.
+
+> **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 of this module can be used only in the stage model.
+
+## Modules to Import
+
+```ts
+import UIExtensionAbility from '@ohos.app.ability.UIExtensionAbility';
+```
+
+## Attributes
+
+**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
+
+| Name| Type| Readable| Writable| Description|
+| -------- | -------- | -------- | -------- | -------- |
+| context | [UIExtensionContext](js-apis-inner-application-uiExtensionContext.md) | Yes| No| Context.|
+
+## UIExtensionAbility.onCreate
+
+onCreate(): void
+
+Called to initialize the service logic when a UIExtensionAbility is created.
+
+**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
+
+## UIExtensionAbility.onSessionCreate
+
+onSessionCreate(want: Want, session: UIExtensionContentSession): void
+
+Called when a **UIExtensionContentSession** instance is created.
+
+**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
+
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| want | [Want](js-apis-app-ability-want.md) | Yes| Want information related to this UIExtensionAbility, including the ability name and bundle name.|
+| session | [UIExtensionContentSession](js-apis-app-ability-uiExtensionContentSession.md) | Yes| UI content information related to this UIExtensionAbility.|
+
+## UIExtensionAbility.onSessionDestroy
+
+onSessionDestroy(session: UIExtensionContentSession): void
+
+Called when a **UIExtensionContentSession** instance is destroyed.
+
+**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
+
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| session | [UIExtensionContentSession](js-apis-app-ability-uiExtensionContentSession.md) | Yes| UI content information related to this UIExtensionAbility.|
+
+## UIExtensionAbility.onForeground
+
+onForeground(): void;
+
+Called when this UIExtensionAbility is switched from the background to the foreground.
+
+**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
+
+## UIExtensionAbility.onBackground
+
+onBackground(): void;
+
+Called when this UIExtensionAbility is switched from the foreground to the background.
+
+**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
+
+## UIExtensionAbility.onDestroy
+
+onDestroy(): void | Promise<void>;
+
+Called to clear resources when this UIExtensionAbility is destroyed.
+
+After the **onDestroy()** lifecycle callback is executed, the application may exit. Consequently, the asynchronous function (for example, asynchronously writing data to the database) in **onDestroy()** may fail to be executed. You can use the asynchronous lifecycle to ensure that the subsequent lifecycle continues only after the asynchronous function in **onDestroy()** finishes the execution.
+
+**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
diff --git a/en/application-dev/reference/apis/js-apis-app-ability-uiExtensionContentSession.md b/en/application-dev/reference/apis/js-apis-app-ability-uiExtensionContentSession.md
new file mode 100644
index 0000000000000000000000000000000000000000..112e55092e2d4f8abf1793dd3525f59f11b64a6d
--- /dev/null
+++ b/en/application-dev/reference/apis/js-apis-app-ability-uiExtensionContentSession.md
@@ -0,0 +1,215 @@
+# @ohos.app.ability.UIExtensionContentSession (UI Operation Class for ExtensionAbilities with UI)
+
+**UIExtensionContentSession** is an instance created when the [UIExtensionAbility](js-apis-app-ability-uiExtensionAbility.md) loads UI content. When the UIExtensionComponent starts a UIExtensionAbility, the UIExtensionAbility creates a UIExtensionContentSession instance and returns it through the [onSessionCreate](js-apis-app-ability-uiExtensionAbility.md#uiextensionabilityonsessioncreate) callback. One UIExtensionComponent corresponds to one **UIExtensionContentSession** instance, which provides methods such as UI loading and result notification. The **UIExtensionContentSession** instances of multiple UIExtensionAbilities are operated separately.
+
+> **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 of this module can be used only in the stage model.
+
+## Modules to Import
+
+```ts
+import UIExtensionContentSession from '@ohos.app.ability.UIExtensionContentSession';
+```
+
+## UIExtensionContentSession.sendData
+
+sendData(data: { [key: string]: Object }): void
+
+Sends data to the UIExtensionComponent.
+
+**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
+
+**System API**: This is a system API and cannot be called by third-party applications.
+
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| data | {[key: string]: Object} | Yes| Data to send.|
+
+**Error codes**
+
+| ID| Error Message|
+| ------- | -------------------------------- |
+| 16000050 | Internal error. |
+
+For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
+
+## UIExtensionContentSession.setReceiveDataCallback
+
+setReceiveDataCallback(callback: (data: { [key: string]: Object }) => void): void
+
+Sets the callback used to receive data from the UIExtensionComponent.
+
+**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
+
+**System API**: This is a system API and cannot be called by third-party applications.
+
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| callback | (data: { [key: string]: Object }) => void | Yes| Callback used to receive data.|
+
+**Error codes**
+
+| ID| Error Message|
+| ------- | -------------------------------- |
+| 16000050 | Internal error. |
+
+For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
+
+## UIExtensionContentSession.loadContent
+
+loadContent(path: string, storage?: LocalStorage): Promise<void>
+
+Loads content from a page associated with a local storage to the window corresponding to the current UIExtensionComponent.
+
+**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
+
+**Parameters**
+
+| 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) | No | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.|
+
+**Error codes**
+
+| ID| Error Message|
+| ------- | -------------------------------- |
+| 16000050 | Internal error. |
+
+For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
+
+## UIExtensionContentSession.terminateSelf
+
+terminateSelf(callback: AsyncCallback<void>): void;
+
+Stops the window object corresponding to this **UIExtensionContentSession** instance. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Ability.AbilityRuntime.Core
+
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| callback | AsyncCallback<void> | Yes| Callback used to return the result.|
+
+## UIExtensionContentSession.terminateSelf
+
+terminateSelf(): Promise<void>;
+
+Stops the window object corresponding to this **UIExtensionContentSession** instance. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Ability.AbilityRuntime.Core
+
+**Return value**
+
+| Type| Description|
+| -------- | -------- |
+| Promise<void> | Promise used to return the result.|
+
+## UIExtensionContentSession.terminateSelfWithResult
+
+terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<void>): void;
+
+Stops the window object corresponding to this **UIExtensionContentSession** instance and returns the result to the UIExtensionComponent. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Ability.AbilityRuntime.Core
+
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes| Result returned to the UIExtensionComponent.|
+| callback | AsyncCallback<void> | Yes| Callback used to return the result.|
+
+## UIExtensionContentSession.terminateSelfWithResult
+
+terminateSelfWithResult(parameter: AbilityResult): Promise<void>;
+
+Stops the window object corresponding to this **UIExtensionContentSession** instance and returns the result to the UIExtensionComponent. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Ability.AbilityRuntime.Core
+
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes| Result returned to the UIExtensionComponent.|
+
+**Return value**
+
+| Type| Description|
+| -------- | -------- |
+| Promise<void> | Promise used to return the result.|
+
+## UIExtensionContentSession.setWindowBackgroundColor
+
+setWindowBackgroundColor(color: string): void
+
+Sets the background color for the loading page of the UIExtensionAbility. This API must be used after [loadContent()](#uiextensioncontentsessionloadcontent) takes effect.
+
+**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
+
+**System API**: This is a system API and cannot be called by third-party applications.
+
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| color | string | Yes| Background color to set. The value is a hexadecimal RGB or ARGB color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**.|
+
+**Error codes**
+
+| ID| Error Message|
+| ------- | -------------------------------- |
+| 16000050 | Internal error. |
+
+For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
+
+## UIExtensionContentSession.setWindowPrivacyMode
+
+setWindowPrivacyMode(isPrivacyMode: boolean): Promise<void>
+
+Sets whether the window is in privacy mode. This API uses a promise to return the result.
+
+A window in privacy mode cannot be captured or recorded.
+
+**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
+
+**Required permissions**: ohos.permission.PRIVACY_WINDOW
+
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| ------------- | ------- | -- | ----------------------------------------------------- |
+| isPrivacyMode | boolean | Yes| Whether the window is in privacy mode. The value **true** means that the window is in privacy mode, and **false** means the opposite.|
+
+**Return value**
+
+| Type| Description|
+| ------------------- | ------------------------ |
+| Promise<void> | Promise that returns no value.|
+
+## UIExtensionContentSession.setWindowPrivacyMode
+
+setWindowPrivacyMode(isPrivacyMode: boolean, callback: AsyncCallback<void>): void
+
+Sets whether the window is in privacy mode. This API uses an asynchronous callback to return the result.
+
+A window in privacy mode cannot be captured or recorded.
+
+**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
+
+**Required permissions**: ohos.permission.PRIVACY_WINDOW
+
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| ------------- | ------------------------- | -- | ------------------------------------------------------ |
+| isPrivacyMode | boolean | Yes| Whether the window is in privacy mode. The value **true** means that the window is in privacy mode, and **false** means the opposite. |
+| callback | AsyncCallback<void> | Yes| Callback used to return the result. |
diff --git a/en/application-dev/reference/apis/js-apis-app-form-formHost.md b/en/application-dev/reference/apis/js-apis-app-form-formHost.md
index dcbbe55a2a8121406e275df03dae90a9390e390a..ebb7e1afd22c0200a7d722003728b2073e836a9d 100644
--- a/en/application-dev/reference/apis/js-apis-app-form-formHost.md
+++ b/en/application-dev/reference/apis/js-apis-app-form-formHost.md
@@ -1202,97 +1202,6 @@ try {
}
```
-## getRunningFormInfos10+
-
-getRunningFormInfos(callback: AsyncCallback<Array<formInfo.RunningFormInfo>>, hostBundleName?: string): void
-
-Obtains information about all non-temporary widgets running on the device. This API uses an asynchronous callback to return the result.
-
-**Required permissions**: ohos.permission.REQUIRE_FORM
-
-**System capability**: SystemCapability.Ability.Form
-
-**Parameters**
-
-| Name| Type | Mandatory| Description |
-| ------ | ------ | ---- | ------- |
-| callback | AsyncCallback<Array<formInfo.RunningFormInfo>> | Yes| Callback used to return the result. If the widget information is obtained, **error** is undefined and **data** is the information obtained.|
-| hostBundleName | string | No| Name of the bundle that functions as the widget host. If this parameter is specified, only the information about the non-temporary widgets that are running under the widget host is returned. By default, information about all running non-temporary widgets on the device is returned.|
-
-**Error codes**
-
-For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
-
-| Error Code ID| Error Message|
-| -------- | -------- |
-| 16500050 | An IPC connection error happened. |
-| 16500060 | A service connection error happened, please try again later. |
-
-**Example**
-
-```ts
-import formHost from '@ohos.app.form.formHost';
-
-try {
- formHost.getRunningFormInfos((error, data) => {
- if (error) {
- console.error(`error, code: ${error.code}, message: ${error.message}`);
- } else {
- console.log('formHost getRunningFormInfos, data: ${JSON.stringify(data)}');
- }
- }, 'com.example.ohos.formjsdemo');
-} catch(error) {
- console.error(`catch error, code: ${error.code}, message: ${error.message}`);
-}
-```
-
-## getRunningFormInfos10+
-
-getRunningFormInfos(hostBundleName?: string): Promise<Array<formInfo.RunningFormInfo>>
-
-Obtains information about all non-temporary widgets running on the device. This API uses a promise to return the result.
-
-**Required permissions**: ohos.permission.REQUIRE_FORM
-
-**System capability**: SystemCapability.Ability.Form
-
-**Parameters**
-
-| Name| Type | Mandatory| Description |
-| ------ | ------ | ---- | ------- |
-| hostBundleName | string | No| Name of the bundle that functions as the widget host. If this parameter is specified, only the information about the non-temporary widgets that are running under the widget host is returned. By default, information about all running non-temporary widgets on the device is returned.|
-
-**Return value**
-
-| Type | Description |
-| :----------------------------------------------------------- | :---------------------------------- |
-| Promise<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | Promise used to return the information obtained.|
-
-**Error codes**
-
-For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
-
-| Error Code ID| Error Message|
-| -------- | -------- |
-| 16500050 | An IPC connection error happened. |
-| 16500060 | A service connection error happened, please try again later. |
-
-**Example**
-
-```ts
-import formHost from '@ohos.app.form.formHost';
-
-try {
- formHost.getRunningFormInfos('com.example.ohos.formjsdemo').then((data) => {
- console.log('formHost getRunningFormInfos, data: ${JSON.stringify(data)}');
- }).catch((error) => {
- console.error(`error, code: ${error.code}, message: ${error.message}`);
- });
-} catch(error) {
- console.error(`catch error, code: ${error.code}, message: ${error.message}`);
-}
-```
-
## deleteInvalidForms
deleteInvalidForms(formIds: Array<string>, callback: AsyncCallback<number>): void
@@ -1585,140 +1494,6 @@ let callback = function(formId) {
formHost.off('formUninstall', callback);
```
-## on('formAdd')10+
-
- on(type: 'formAdd', observerCallback: Callback<formInfo.RunningFormInfo>, bundleName?: string): void
-
-Subscribes to widget addition events. This API uses an asynchronous callback to return the result.
-
-**Required permissions**: ohos.permission.REQUIRE_FORM
-
-**System capability**: SystemCapability.Ability.Form
-
-**Parameters**
-
-| Name| Type | Mandatory| Description |
-| ------ | ------ | ---- | ------- |
-| type | string | Yes | Event type. The value **'formAdd'** indicates a widget addition event.|
-| callback | Callback<formInfo.RunningFormInfo> | Yes| Callback used to return **RunningFormInfo** of the new widget.|
-| bundleName | string | No| Name of the bundle that functions as the widget host. By default, widget addition events of all widget hosts are subscribed to.|
-
-**Example**
-
-```ts
-import formHost from '@ohos.app.form.formHost';
-let bundleName = 'ohos.samples.FormApplication';
-let callback = function(data) {
- console.log('a new form added, data: ${JSON.stringify(data)');
-}
-
-formHost.on('formAdd', callback);
-formHost.on('formAdd', callback, bundleName);
-```
-
-## off('formAdd')10+
-
- off(type: "formAdd", observerCallback?: Callback<formInfo.RunningFormInfo>, bundleName?: string): void
-
-Unsubscribes from widget addition events. This API uses an asynchronous callback to return the result.
-
-**Required permissions**: ohos.permission.REQUIRE_FORM
-
-**System capability**: SystemCapability.Ability.Form
-
-**Parameters**
-
-| Name| Type | Mandatory| Description |
-| ------ | ------ | ---- | ------- |
-| type | string | Yes | Event type. The value **'formAdd'** indicates a widget addition event.|
-| callback | Callback<formInfo.RunningFormInfo> | No| Callback used to return **RunningFormInfo**. By default, all the subscriptions to the specified event are canceled. To cancel the subscription with a given callback, this parameter must be set to the same value as **callback** in **on('formAdd')**.|
-| bundleName | string | No| Name of the bundle that functions as the widget host. To cancel the subscription for a given bundle name, this parameter must be set to the same value as **bundleName** in **on('formAdd')**. By default, the subscriptions for all the widget hosts are canceled.|
-
-**Example**
-
-```ts
-import formHost from '@ohos.app.form.formHost';
-let bundleName = 'ohos.samples.FormApplication';
-let callback = function(data) {
- console.log('a new form added, data: ${JSON.stringify(data)');
-}
-
-formHost.off('formAdd', callback);
-formHost.off('formAdd', callback, bundleName);
-```
-> **NOTE**
->
-> - **on('formAdd', callback)** and **off('formAdd', callback)** must be used in pairs.
-> - **on('formAdd', callback, bundleName)** and **off('formAdd', callback, bundleName)** must be used in pairs.
-> - To cancel the subscription with a given callback or for a given bundle name, the **callback** or **bundleName** parameter in **off()** must be set to the same value as that in **on()**.
-
-## on('formRemove')10+
-
- on(type: 'formRemove', observerCallback: Callback<formInfo.RunningFormInfo>, bundleName?: string): void
-
-Subscribes to widget removal events. This API uses an asynchronous callback to return the result.
-
-**Required permissions**: ohos.permission.REQUIRE_FORM
-
-**System capability**: SystemCapability.Ability.Form
-
-**Parameters**
-
-| Name| Type | Mandatory| Description |
-| ------ | ------ | ---- | ------- |
-| type | string | Yes | Event type. The value **'formRemove'** indicates a widget removal event.|
-| callback | Callback<formInfo.RunningFormInfo> | Yes| Callback used to return **RunningFormInfo** of the removed widget.|
-| bundleName | string | No| Name of the bundle that functions as the widget host. By default, widget removal events of all widget hosts are subscribed to.|
-
-**Example**
-
-```ts
-import formHost from '@ohos.app.form.formHost';
-let bundleName = 'ohos.samples.FormApplication';
-let callback = function(data) {
- console.log('a new form added, data: ${JSON.stringify(data)');
-}
-
-formHost.on('formRemove', callback);
-formHost.on('formRemove', callback, bundleName);
-```
-
-## off('formRemove')10+
-
-off(type: "formRemove", observerCallback?: Callback<formInfo.RunningFormInfo>, bundleName?: string): void
-
-Unsubscribes from widget removal events. This API uses an asynchronous callback to return the result.
-
-**Required permissions**: ohos.permission.REQUIRE_FORM
-
-**System capability**: SystemCapability.Ability.Form
-
-**Parameters**
-
-| Name| Type | Mandatory| Description |
-| ------ | ------ | ---- | ------- |
-| type | string | Yes | Event type. The value **'formRemove'** indicates a widget removal event.|
-| callback | Callback<formInfo.RunningFormInfo> | No| Callback used to return **RunningFormInfo**. By default, all the subscriptions to the specified event are canceled. To cancel the subscription with a given callback, this parameter must be set to the same value as **callback** in **on('formRemove')**.|
-| bundleName | string | No| Name of the bundle that functions as the widget host. To cancel the subscription for a given bundle name, this parameter must be set to the same value as **bundleName** in **on('formRemove')**. By default, the subscriptions for all the widget hosts are canceled.|
-
-**Example**
-
-```ts
-import formHost from '@ohos.app.form.formHost';
-let bundleName = 'ohos.samples.FormApplication';
-let callback = function(data) {
- console.log('a new form added, data: ${JSON.stringify(data)');
-}
-
-formHost.off('formRemove', callback);
-formHost.off('formRemove', callback, bundleName);
-```
-> **NOTE**
->
-> - **on('formRemove', callback)** and **off('formRemove', callback)** must be used in pairs.
-> - **on('formRemove', callback, bundleName)** and **off('formRemove', callback, bundleName)** must be used in pairs.
-> - To cancel the subscription with a given callback or for a given bundle name, the **callback** or **bundleName** parameter in **off()** must be set to the same value as that in **on()**.
-
## notifyFormsVisible
notifyFormsVisible(formIds: Array<string>, isVisible: boolean, callback: AsyncCallback<void>): void
@@ -2225,352 +2000,3 @@ try {
console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
-
-## getRunningFormInfosByFilter10+
-
-getRunningFormInfosByFilter(formProviderFilter: formInfo.FormProviderFilter): Promise<Array<formInfo.RunningFormInfo>>
-
-Obtains the information about widget hosts based on the widget provider information. This API uses a promise to return the result.
-
-**Required permissions**: ohos.permission.REQUIRE_FORM
-
-**System capability**: SystemCapability.Ability.Form
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| ----------- | --------------- | ---- | -------------------------------- |
-| formProviderFilter | [formInfo.FormProviderFilter](js-apis-app-form-formInfo.md#formProviderFilter) | Yes | Information about the widget provider.|
-
-**Return value**
-
-| Type | Description |
-| ------------------- | ------------------------- |
-| Promise<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md#RunningFormInfo)>> | Promise used to return the widget host information obtained.|
-
-**Error codes**
-
-For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
-
-| Error Code ID| Error Message|
-| -------- | -------- |
-| 201 | Permissions denied. |
-| 202 | The application is not a system application. |
-| 401 | If the input parameter is not valid parameter. |
-| 16500050 | An IPC connection error happened. |
-| 16500100 | Failed to obtain the configuration information. |
-| 16501000 | An internal functional error occurred. |
-
-
-```ts
-import formHost from '@ohos.app.form.formHost';
-
-let formInstanceFilter = {
- bundleName: "com.example.formprovide",
- abilityName: "EntryFormAbility",
- formName: "widget",
- moduleName: "entry"
-}
-try {
- formHost.getRunningFormInfosByFilter(formInstanceFilter).then(data1 => {
- console.info('formHost getRunningFormInfosByFilter return err :');
- }).catch((error) => {
- console.error(`error, code: ${error.code}, message: ${error.message}`);
- });
-} catch(error) {
- console.error(`catch error, code: ${error.code}, message: ${error.message}`);
-}
-```
-
-## getRunningFormInfosByFilter10+
-
-getRunningFormInfosByFilter(formProviderFilter: formInfo.FormProviderFilter, callback: AsyncCallback<Array<formInfo.RunningFormInfo>>): void
-
-Obtains the information about widget hosts based on the widget provider information. This API uses an asynchronous callback to return the result.
-
-**Required permissions**: ohos.permission.REQUIRE_FORM
-
-**System capability**: SystemCapability.Ability.Form
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| ----------- | --------------- | ---- | -------------------------------- |
-| formProviderFilter | [formInfo.FormProviderFilter](js-apis-app-form-formInfo.md#formProviderFilter) | Yes | Information about the widget provider.|
-| callback | AsyncCallback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the result. If the widget host information is obtained, **error** is **undefined** and **data** is the information obtained; otherwise, **error** is an error object.|
-
-**Error codes**
-
-For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
-
-| Error Code ID| Error Message|
-| -------- | -------- |
-| 201 | Permissions denied. |
-| 202 | The application is not a system application. |
-| 401 | If the input parameter is not valid parameter. |
-| 16500050 | An IPC connection error happened. |
-| 16500100 | Failed to obtain the configuration information. |
-| 16501000 | An internal functional error occurred. |
-
-
-```ts
-import formHost from '@ohos.app.form.formHost';
-
-let formInstanceFilter = {
- bundleName: "com.example.formprovide",
- abilityName: "EntryFormAbility",
- formName: "widget",
- moduleName: "entry"
-}
-try {
- formHost.getRunningFormInfosByFilter(formInstanceFilter,(error, data) => {
- if (error) {
- console.error(`error, code: ${error.code}, message: ${error.message}`);
- } else {
- console.log('formHost getRunningFormInfosByFilter, data: ${JSON.stringify(data)}');
- }
- });
-} catch(error) {
- console.error(`catch error, code: ${error.code}, message: ${error.message}`);
-}
-```
-
-## getRunningFormInfoById10+
-
-getRunningFormInfoById(formId: string): Promise<formInfo.RunningFormInfo>
-
-
-Obtains the information about widget hosts based on the widget ID. This API uses a promise to return the result.
-
-**Required permissions**: ohos.permission.REQUIRE_FORM
-
-**System capability**: SystemCapability.Ability.Form
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| ----------- | --------------- | ---- | -------------------------------- |
-| formId | string | Yes | Widget ID.|
-
-**Return value**
-
-| Type | Description |
-| ------------------- | ------------------------- |
-| Promise<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)> | Promise used to return the widget host information obtained.|
-
-**Error codes**
-
-For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
-
-| Error Code ID| Error Message|
-| -------- | -------- |
-| 201 | Permissions denied. |
-| 202 | The application is not a system application. |
-| 401 | If the input parameter is not valid parameter. |
-| 16500050 | An IPC connection error happened. |
-| 16500100 | Failed to obtain the configuration information. |
-| 16501000 | An internal functional error occurred. |
-
-
-```ts
-import formHost from '@ohos.app.form.formHost';
-let formId = '12400633174999288';
-try {
- formHost.getRunningFormInfoById(formId).then(data1 => {
- console.info('formHost getRunningFormInfoById return err :');
- }).catch((error) => {
- console.error(`error, code: ${error.code}, message: ${error.message}`);
- });
-} catch(error) {
- console.error(`catch error, code: ${error.code}, message: ${error.message}`);
-}
-```
-
-## getRunningFormInfoById10+
-
-getRunningFormInfoById(formId: string, callback: AsyncCallback<formInfo.RunningFormInfo>): void
-
-Obtains the information about widget hosts based on the widget ID. This API uses an asynchronous callback to return the result.
-
-**Required permissions**: ohos.permission.REQUIRE_FORM
-
-**System capability**: SystemCapability.Ability.Form
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| ----------- | --------------- | ---- | -------------------------------- |
-| formId | string | Yes | Widget ID.|
-| callback | AsyncCallback<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)> | Yes| Callback used to return the result. If the widget host information is obtained, **error** is **undefined** and **data** is the information obtained; otherwise, **error** is an error object.|
-
-**Error codes**
-
-For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
-
-| Error Code ID| Error Message|
-| -------- | -------- |
-| 201 | Permissions denied. |
-| 202 | The application is not a system application. |
-| 401 | If the input parameter is not valid parameter. |
-| 16500050 | An IPC connection error happened. |
-| 16500100 | Failed to obtain the configuration information. |
-| 16501000 | An internal functional error occurred. |
-
-```ts
-import formHost from '@ohos.app.form.formHost';
-
-let formId = '12400633174999288';
-try {
- formHost.getRunningFormInfoById(formId,(error, data) => {
- if (error) {
- console.error(`error, code: ${error.code}, message: ${error.message}`);
- } else {
- console.log('formHost getRunningFormInfoById, data: ${JSON.stringify(data)}');
- }
- });
-} catch(error) {
- console.error(`catch error, code: ${error.code}, message: ${error.message}`);
-}
-```
-
-## on('notifyVisible')10+
-
- on(type: 'notifyVisible', observerCallback: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>, bundleName?: string): void
-
-Subscribes to events indicating that a widget becomes visible.
-
-This event is triggered when **notifyVisibleForms** is called to make a widget visible.
-
-**Required permissions**: ohos.permission.REQUIRE_FORM
-
-**System capability**: SystemCapability.Ability.Form
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
-| type | string | Yes | Event type. This value **'notifyVisible'** indicates a widget visibility event. |
-| callback | Callback <Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | Yes | Callback used to return **RunningFormInfo** of the widget. |
-| bundleName | string | No | Name of the bundle that functions as the widget host, on which the widget visibility state changes are subscribed.|
-
-**Example**
-
-```ts
-import formHost from '@ohos.app.form.formHost';
-let bundleName = 'ohos.samples.FormApplication';
-let callback = function(data) {
- console.log('form change visibility, data: ${JSON.stringify(data)');
-}
-
-formHost.on('notifyVisible', callback);
-formHost.on('notifyVisible', callback, bundleName);
-```
-
-## off('notifyVisible')10+
-
- off(type: "notifyVisible", observerCallback?: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>, bundleName?: string): void
-
-Unsubscribes from events indicating that a widget becomes visible.
-
-**Required permissions**: ohos.permission.REQUIRE_FORM
-
-**System capability**: SystemCapability.Ability.Form
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
-| type | string | Yes | Event type. This value **'notifyVisible'** indicates a widget visibility event.|
-| callback | Callback <Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | No | Callback registered during the subscription. By default, all the subscriptions to the specified event are canceled. To cancel the subscription with a given callback, this parameter must be set to the same value as **callback** in **on('notifyVisible')**.|
-| bundleName | string | No | Name of the bundle that functions as the widget host, on which the widget visibility state changes are subscribed. To cancel the subscription for a given bundle name, this parameter must be set to the same value as **bundleName** in **on('notifyVisible')**.|
-
-**Example**
-
-```ts
-import formHost from '@ohos.app.form.formHost';
-let bundleName = 'ohos.samples.FormApplication';
-let callback = function(data) {
- console.log('form change visibility, data: ${JSON.stringify(data)');
-}
-
-formHost.off('notifyVisible', callback);
-formHost.off('notifyVisible', callback, bundleName);
-```
-
-> **NOTE**
->
-> - **on('notifyVisible', callback)** and **off('notifyVisible', callback)** must be used in pairs.
-> - **on('notifyVisible', callback, bundleName)** and **off('notifyVisible', callback, bundleName)** must be used in pairs.
-> - To cancel the subscription with a given callback or for a given bundle name, the **callback** or **bundleName** parameter in **off()** must be set to the same value as that in **on()**.
-
-
-
-## on('notifyInvisible')10+
-
- on(type: 'notifyInvisible', observerCallback: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>, bundleName?: string): void
-
-Subscribes to events indicating that a widget becomes invisible.
-
-This event is triggered when **notifyInvisibleForms** is called to make a widget invisible.
-
-**Required permissions**: ohos.permission.REQUIRE_FORM
-
-**System capability**: SystemCapability.Ability.Form
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
-| type | string | Yes | Event type. This value **'notifyInvisible'** indicates a widget invisibility event. |
-| callback | Callback <Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | Yes | Callback used to return **RunningFormInfo** of the widget. |
-| bundleName | string | No | Name of the bundle that functions as the widget host, on which the widget visibility state changes are subscribed.|
-
-**Example**
-
-```ts
-import formHost from '@ohos.app.form.formHost';
-let bundleName = 'ohos.samples.FormApplication';
-let callback = function(data) {
- console.log('form change invisibility, data: ${JSON.stringify(data)');
-}
-
-formHost.on('notifyInvisible', callback);
-formHost.on('notifyInvisible', callback, bundleName);
-```
-
-## off('notifyInvisible')10+
-
- off(type: "notifyInvisible", observerCallback?: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>, bundleName?: string): void
-
-Unsubscribes from events indicating that a widget becomes invisible.
-
-**Required permissions**: ohos.permission.REQUIRE_FORM
-
-**System capability**: SystemCapability.Ability.Form
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
-| type | string | Yes | Event type. This value **'notifyInvisible'** indicates a widget invisibility event. |
-| callback | Callback <Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | No | Callback registered during the subscription. By default, all the subscriptions to the specified event are canceled. To cancel the subscription with a given callback, this parameter must be set to the same value as **callback** in **on('notifyInvisible')**.|
-| bundleName | string | No | Name of the bundle that functions as the widget host, on which the widget visibility state changes are subscribed. To cancel the subscription for a given bundle name, this parameter must be set to the same value as **bundleName** in **on('notifyInvisible')**. |
-
-**Example**
-
-```ts
-import formHost from '@ohos.app.form.formHost';
-let bundleName = 'ohos.samples.FormApplication';
-let callback = function(data) {
- console.log('form change invisibility, data: ${JSON.stringify(data)');
-}
-
-formHost.off('notifyInvisible', callback);
-formHost.off('notifyInvisible', callback, bundleName);
-```
-
-> **NOTE**
->
-> - **on('notifyInvisible', callback)** and **off('notifyInvisible', callback)** must be used in pairs.
-> - **on('notifyInvisible', callback, bundleName)** and **off('notifyInvisible', callback, bundleName)** must be used in pairs.
-> - To cancel the subscription with a given callback or for a given bundle name, the **callback** or **bundleName** parameter in **off()** must be set to the same value as that in **on()**.
diff --git a/en/application-dev/reference/apis/js-apis-app-form-formObserver.md b/en/application-dev/reference/apis/js-apis-app-form-formObserver.md
new file mode 100644
index 0000000000000000000000000000000000000000..cba38112d1de95f16d476a62e0ae2af863bdc427
--- /dev/null
+++ b/en/application-dev/reference/apis/js-apis-app-form-formObserver.md
@@ -0,0 +1,699 @@
+# @ohos.app.form.formObserver (formObserver)
+
+The **formObserver** module provides APIs related to widget listeners. You can use the APIs to subscribe to and unsubscribe from widget addition, removal, and visibility change events, and obtain information about running widgets.
+
+> **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
+
+```ts
+import formObserver from '@ohos.app.form.formObserver';
+```
+
+## on('formAdd')
+
+ on(type: 'formAdd', observerCallback: Callback<formInfo.RunningFormInfo>): void
+
+Subscribes to widget addition events. This API uses an asynchronous callback to return the result.
+
+**Required permissions**: ohos.permission.OBSERVE_FORM_RUNNING
+
+**System capability**: SystemCapability.Ability.Form
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | ------ | ---- | ------- |
+| type | string | Yes | Event type. The value **'formAdd'** indicates a widget addition event.|
+| callback | Callback<formInfo.RunningFormInfo> | Yes| Callback used to return **RunningFormInfo** of the widget.|
+
+**Example**
+
+```ts
+import formObserver from '@ohos.app.form.formObserver';
+let callback = function(data) {
+ console.log('a new form added, data: ${JSON.stringify(data)');
+}
+
+formObserver.on('formAdd', callback);
+```
+
+## on('formAdd')
+
+ on(type: 'formAdd', bundleName: string, observerCallback: Callback<formInfo.RunningFormInfo>): void
+
+Subscribes to widget addition events for a given bundle that functions as the widget host. This API uses an asynchronous callback to return the result.
+
+**Required permissions**: ohos.permission.OBSERVE_FORM_RUNNING
+
+**System capability**: SystemCapability.Ability.Form
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | ------ | ---- | ------- |
+| type | string | Yes | Event type. The value **'formAdd'** indicates a widget addition event.|
+| bundleName | string | Yes| Name of the bundle that functions as the widget host. If no value is passed in, widget addition events of all widget hosts are subscribed to.|
+| callback | Callback<formInfo.RunningFormInfo> | Yes| Callback used to return **RunningFormInfo** of the widget.|
+
+
+**Example**
+
+```ts
+import formObserver from '@ohos.app.form.formObserver';
+let bundleName = 'ohos.samples.FormApplication';
+let callback = function(data) {
+ console.log('a new form added, data: ${JSON.stringify(data)');
+}
+
+formObserver.on('formAdd', bundleName, callback);
+```
+
+## off('formAdd')
+
+ off(type: "formAdd", bundleName?: string, observerCallback?: Callback<formInfo.RunningFormInfo>): void
+
+Unsubscribes from widget addition events. This API uses an asynchronous callback to return the result.
+
+**Required permissions**: ohos.permission.OBSERVE_FORM_RUNNING
+
+**System capability**: SystemCapability.Ability.Form
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | ------ | ---- | ------- |
+| type | string | Yes | Event type. The value **'formAdd'** indicates a widget addition event.|
+| bundleName | string | No| Name of the bundle that functions as the widget host. To cancel the subscription for a given bundle name, this parameter must be set to the same value as **bundleName** in **on('formAdd')**. If no value is passed in, the subscriptions for all the widget hosts are canceled. |
+| callback | Callback<formInfo.RunningFormInfo> | No| Callback used to return **RunningFormInfo** of the widget. If no value is passed in, all the subscriptions to the specified event are canceled. To cancel the subscription with a given callback, this parameter must be set to the same value as **callback** in **on('formAdd')**. |
+
+
+**Example**
+
+```ts
+import formObserver from '@ohos.app.form.formObserver';
+let bundleName = 'ohos.samples.FormApplication';
+let callback = function(data) {
+ console.log('a new form added, data: ${JSON.stringify(data)');
+}
+
+formObserver.off('formAdd', callback);
+formObserver.off('formAdd', bundleName, callback);
+```
+> **NOTE**
+> **on('formAdd', callback)** and **off('formAdd', callback)** must be used in pairs.
+> **on('formAdd', bundleName, callback)** and **off('formAdd', bundleName, callback)** must be used in pairs.
+> To cancel the subscription with a given callback or for a given bundle name, the **callback** or **bundleName** parameter in **off()** must be set to the same value as that in **on()**.
+
+## on('formRemove')
+
+ on(type: 'formRemove', observerCallback: Callback<formInfo.RunningFormInfo>): void
+
+Subscribes to widget removal events. This API uses an asynchronous callback to return the result.
+
+**Required permissions**: ohos.permission.OBSERVE_FORM_RUNNING
+
+**System capability**: SystemCapability.Ability.Form
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | ------ | ---- | ------- |
+| type | string | Yes | Event type. The value **'formRemove'** indicates a widget removal event.|
+| callback | Callback<formInfo.RunningFormInfo> | Yes| Callback used to return **RunningFormInfo** of the widget.|
+
+**Example**
+
+```ts
+import formObserver from '@ohos.app.form.formObserver';
+let callback = function(data) {
+ console.log('form deleted, data: ${JSON.stringify(data)');
+}
+
+formObserver.on('formRemove', callback);
+```
+
+## on('formRemove')
+
+ on(type: 'formRemove', bundleName: string, observerCallback: Callback<formInfo.RunningFormInfo>): void
+
+Subscribes to widget removal events for a given bundle, which functions as the widget host. This API uses an asynchronous callback to return the result.
+
+**Required permissions**: ohos.permission.OBSERVE_FORM_RUNNING
+
+**System capability**: SystemCapability.Ability.Form
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | ------ | ---- | ------- |
+| type | string | Yes | Event type. The value **'formRemove'** indicates a widget removal event.|
+| bundleName | string | Yes| Name of the bundle that functions as the widget host. If no value is passed in, widget removal events of all widget hosts are subscribed to.|
+| callback | Callback<formInfo.RunningFormInfo> | Yes| Callback used to return **RunningFormInfo** of the widget.|
+
+
+**Example**
+
+```ts
+import formObserver from '@ohos.app.form.formObserver';
+let bundleName = 'ohos.samples.FormApplication';
+let callback = function(data) {
+ console.log('form deleted, data: ${JSON.stringify(data)');
+}
+
+formObserver.on('formRemove', bundleName, callback);
+```
+
+## off('formRemove')
+
+off(type: "formRemove", bundleName?: string, observerCallback?: Callback<formInfo.RunningFormInfo>): void
+
+Unsubscribes from widget removal events. This API uses an asynchronous callback to return the result.
+
+**Required permissions**: ohos.permission.OBSERVE_FORM_RUNNING
+
+**System capability**: SystemCapability.Ability.Form
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | ------ | ---- | ------- |
+| type | string | Yes | Event type. The value **'formRemove'** indicates a widget removal event.|
+| bundleName | string | No| Name of the bundle that functions as the widget host. To cancel the subscription for a given bundle name, this parameter must be set to the same value as **bundleName** in **on('formRemove')**. If no value is passed in, the subscriptions for all the widget hosts are canceled. |
+| callback | Callback<formInfo.RunningFormInfo> | No| Callback used to return **RunningFormInfo** of the widget. If no value is passed in, all the subscriptions to the specified event are canceled. To cancel the subscription with a given callback, this parameter must be set to the same value as **callback** in **on('formRemove')**. |
+
+**Example**
+
+```ts
+import formObserver from '@ohos.app.form.formObserver';
+let bundleName = 'ohos.samples.FormApplication';
+let callback = function(data) {
+ console.log('a new form added, data: ${JSON.stringify(data)');
+}
+
+formObserver.off('formRemove', callback);
+formObserver.off('formRemove', bundleName, callback);
+```
+> **NOTE**
+> **on('formRemove', callback)** and **off('formRemove', callback)** must be used in pairs.
+> **on('formRemove', bundleName, callback)** and **off('formRemove', bundleName, callback)** must be used in pairs.
+> To cancel the subscription with a given callback or for a given bundle name, the **callback** or **bundleName** parameter in **off()** must be set to the same value as that in **on()**.
+
+## on('notifyVisible')
+
+ on(type: 'notifyVisible', observerCallback: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>): void
+
+Subscribes to events indicating that a widget becomes visible.
+
+This event is triggered when **notifyVisibleForms** is called to make a widget visible.
+
+**Required permissions**: ohos.permission.OBSERVE_FORM_RUNNING
+
+**System capability**: SystemCapability.Ability.Form
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
+| type | string | Yes | Event type. This value **'notifyVisible'** indicates a widget visibility event. |
+| callback | Callback <Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | Yes | Callback used to return **RunningFormInfo** of the widget. |
+
+**Example**
+
+```ts
+import formObserver from '@ohos.app.form.formObserver';
+let callback = function(data) {
+ console.log('form change visibility, data: ${JSON.stringify(data)');
+}
+
+formObserver.on('notifyVisible', callback);
+```
+
+## on('notifyVisible')
+
+ on(type: 'notifyVisible', bundleName: string, observerCallback: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>): void
+
+Subscribes to events indicating that a widget becomes visible for a given bundle, which functions as the widget host.
+
+This event is triggered when **notifyVisibleForms** is called to make a widget visible.
+
+**Required permissions**: ohos.permission.OBSERVE_FORM_RUNNING
+
+**System capability**: SystemCapability.Ability.Form
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
+| type | string | Yes | Event type. This value **'notifyVisible'** indicates a widget visibility event. |
+| bundleName | string | Yes | Name of the bundle that functions as the widget host, on which the widget visibility state changes are subscribed.|
+| callback | Callback <Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | Yes | Callback used to return **RunningFormInfo** of the widget. |
+
+
+**Example**
+
+```ts
+import formObserver from '@ohos.app.form.formObserver';
+let bundleName = 'ohos.samples.FormApplication';
+let callback = function(data) {
+ console.log('form change visibility, data: ${JSON.stringify(data)');
+}
+
+formObserver.on('notifyVisible', bundleName, callback);
+```
+
+## off('notifyVisible')
+
+ off(type: "notifyVisible", bundleName?: string, observerCallback?: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>): void
+
+Unsubscribes from events indicating that a widget becomes visible.
+
+**Required permissions**: ohos.permission.OBSERVE_FORM_RUNNING
+
+**System capability**: SystemCapability.Ability.Form
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
+| type | string | Yes | Event type. This value **'notifyVisible'** indicates a widget visibility event.|
+| bundleName | string | No | Name of the bundle that functions as the widget host, on which the widget visibility state changes are subscribed. To cancel the subscription for a given bundle name, this parameter must be set to the same value as **bundleName** in **on('notifyVisible')**. |
+| callback | Callback <Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | No | Callback registered during the subscription. If no value is passed in, all the subscriptions to the specified event are canceled. To cancel the subscription with a given callback, this parameter must be set to the same value as **callback** in **on('notifyVisible')**. |
+
+
+**Example**
+
+```ts
+import formObserver from '@ohos.app.form.formObserver';
+let bundleName = 'ohos.samples.FormApplication';
+let callback = function(data) {
+ console.log('form change visibility, data: ${JSON.stringify(data)');
+}
+
+formObserver.off('notifyVisible', callback);
+formObserver.off('notifyVisible', bundleName, callback);
+```
+
+> **NOTE**
+> **on('notifyVisible', callback)** and **off('notifyVisible', callback)** must be used in pairs.
+> **on('notifyVisible', bundleName, callback)** and **off('notifyVisible', bundleName, callback)** must be used in pairs.
+> To cancel the subscription with a given callback or for a given bundle name, the **callback** or **bundleName** parameter in **off()** must be set to the same value as that in **on()**.
+
+## on('notifyInvisible')
+
+ on(type: 'notifyInvisible', observerCallback: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>): void
+
+Subscribes to events indicating that a widget becomes invisible.
+
+This event is triggered when **notifyInvisibleForms** is called to make a widget invisible.
+
+**Required permissions**: ohos.permission.OBSERVE_FORM_RUNNING
+
+**System capability**: SystemCapability.Ability.Form
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
+| type | string | Yes | Event type. This value **'notifyInvisible'** indicates a widget invisibility event. |
+| callback | Callback <Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | Yes | Callback used to return **RunningFormInfo** of the widget. |
+
+**Example**
+
+```ts
+import formObserver from '@ohos.app.form.formObserver';
+let callback = function(data) {
+ console.log('form change invisibility, data: ${JSON.stringify(data)');
+}
+
+formObserver.on('notifyInvisible', callback);
+```
+
+
+## on('notifyInvisible')
+
+ on(type: 'notifyInvisible', bundleName: string, observerCallback: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>): void
+
+Subscribes to events indicating that a widget becomes invisible for a given bundle, which functions as the widget host.
+
+This event is triggered when **notifyInvisibleForms** is called to make a widget invisible.
+
+**Required permissions**: ohos.permission.OBSERVE_FORM_RUNNING
+
+**System capability**: SystemCapability.Ability.Form
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
+| type | string | Yes | Event type. This value **'notifyInvisible'** indicates a widget invisibility event. |
+| bundleName | string | Yes | Name of the bundle that functions as the widget host, on which the widget visibility state changes are subscribed.|
+| callback | Callback <Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | Yes | Callback used to return **RunningFormInfo** of the widget. |
+
+**Example**
+
+```ts
+import formObserver from '@ohos.app.form.formObserver';
+let bundleName = 'ohos.samples.FormApplication';
+let callback = function(data) {
+ console.log('form change invisibility, data: ${JSON.stringify(data)');
+}
+
+formObserver.on('notifyInvisible', bundleName, callback);
+```
+
+## off('notifyInvisible')
+
+ off(type: "notifyInvisible", bundleName?: string, observerCallback?: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>): void
+
+Unsubscribes from events indicating that a widget becomes invisible.
+
+**Required permissions**: ohos.permission.OBSERVE_FORM_RUNNING
+
+**System capability**: SystemCapability.Ability.Form
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
+| type | string | Yes | Event type. This value **'notifyInvisible'** indicates a widget invisibility event. |
+| bundleName | string | No | Name of the bundle that functions as the widget host, on which the widget visibility state changes are subscribed. To cancel the subscription for a given bundle name, this parameter must be set to the same value as **bundleName** in **on('notifyInvisible')**. |
+| callback | Callback <Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | No | Callback registered during the subscription. If no value is passed in, all the subscriptions to the specified event are canceled. To cancel the subscription with a given callback, this parameter must be set to the same value as **callback** in **on('notifyInvisible')**. |
+
+**Example**
+
+```ts
+import formObserver from '@ohos.app.form.formObserver';
+let bundleName = 'ohos.samples.FormApplication';
+let callback = function(data) {
+ console.log('form change invisibility, data: ${JSON.stringify(data)');
+}
+
+formObserver.off('notifyInvisible', callback);
+formObserver.off('notifyInvisible', bundleName, callback);
+```
+
+> **NOTE**
+> **on('notifyInvisible', callback)** and **off('notifyInvisible', callback)** must be used in pairs.
+> **on('notifyInvisible', bundleName, callback)** and **off('notifyInvisible', bundleName, callback)** must be used in pairs.
+> To cancel the subscription with a given callback or for a given bundle name, the **callback** or **bundleName** parameter in **off()** must be set to the same value as that in **on()**.
+
+
+## getRunningFormInfos
+
+getRunningFormInfos(callback: AsyncCallback<Array<formInfo.RunningFormInfo>>, hostBundleName?: string): void
+
+Obtains information about all non-temporary widgets running on the device. This API uses an asynchronous callback to return the result.
+
+**Required permissions**: ohos.permission.OBSERVE_FORM_RUNNING
+
+**System capability**: SystemCapability.Ability.Form
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | ------ | ---- | ------- |
+| callback | AsyncCallback<Array<formInfo.RunningFormInfo>> | Yes| Callback used to return the result. If the widget information is obtained, **error** is undefined and **data** is the information obtained.|
+| hostBundleName | string | No| Name of the bundle that functions as the widget host. If a value is passed in, only the information about the non-temporary widgets that are running under the widget host is returned. If no value is passed in, information about all running non-temporary widgets on the device is returned. |
+
+**Error codes**
+For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
+
+| ID| Error Message|
+| -------- | -------- |
+| 16500050 | An IPC connection error happened. |
+| 16500060 | A service connection error happened, please try again later. |
+
+**Example**
+
+```ts
+import formObserver from '@ohos.app.form.formObserver';
+
+try {
+ formObserver.getRunningFormInfos((error, data) => {
+ if (error) {
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
+ } else {
+ console.log('formObserver getRunningFormInfos, data: ${JSON.stringify(data)}');
+ }
+ }, 'com.example.ohos.formjsdemo');
+} catch(error) {
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
+}
+```
+
+## getRunningFormInfos
+
+getRunningFormInfos(hostBundleName?: string): Promise<Array<formInfo.RunningFormInfo>>
+
+Obtains information about all non-temporary widgets running on the device. This API uses a promise to return the result.
+
+**Required permissions**: ohos.permission.OBSERVE_FORM_RUNNING
+
+**System capability**: SystemCapability.Ability.Form
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | ------ | ---- | ------- |
+| hostBundleName | string | No| Name of the bundle that functions as the widget host. If a value is passed in, only the information about the non-temporary widgets that are running under the widget host is returned. If no value is passed in, information about all running non-temporary widgets on the device is returned. |
+
+**Return value**
+
+| Type | Description |
+| :----------------------------------------------------------- | :---------------------------------- |
+| Promise<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | Promise used to return the information obtained.|
+
+**Error codes**
+For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
+
+| ID| Error Message|
+| -------- | -------- |
+| 16500050 | An IPC connection error happened. |
+| 16500060 | A service connection error happened, please try again later. |
+
+**Example**
+
+```ts
+import formObserver from '@ohos.app.form.formObserver';
+
+try {
+ formObserver.getRunningFormInfos('com.example.ohos.formjsdemo').then((data) => {
+ console.log('formObserver getRunningFormInfos, data: ${JSON.stringify(data)}');
+ }).catch((error) => {
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
+ });
+} catch(error) {
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
+}
+```
+
+## getRunningFormInfosByFilter
+
+getRunningFormInfosByFilter(formProviderFilter: formInfo.FormProviderFilter): Promise<Array<formInfo.RunningFormInfo>>
+
+Obtains the information about widget hosts based on the widget provider information. This API uses a promise to return the result.
+
+**Required permissions**: ohos.permission.OBSERVE_FORM_RUNNING
+
+**System capability**: SystemCapability.Ability.Form
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ----------- | --------------- | ---- | -------------------------------- |
+| formProviderFilter | [formInfo.FormProviderFilter](js-apis-app-form-formInfo.md#formProviderFilter) | Yes | Information about the widget provider.|
+
+**Return value**
+
+| Type | Description |
+| ------------------- | ------------------------- |
+| Promise<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md#RunningFormInfo)>> | Promise used to return the widget host information obtained.|
+
+**Error codes**
+
+For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
+
+| ID| Error Message|
+| -------- | -------- |
+| 201 | Permissions denied. |
+| 202 | The application is not a system application. |
+| 401 | If the input parameter is not valid parameter. |
+| 16500050 | An IPC connection error happened. |
+| 16500100 | Failed to obtain the configuration information. |
+| 16501000 | An internal functional error occurred. |
+
+
+```ts
+import formObserver from '@ohos.app.form.formObserver';
+
+let formInstanceFilter = {
+ bundleName: "com.example.formprovide",
+ abilityName: "EntryFormAbility",
+ formName: "widget",
+ moduleName: "entry"
+}
+try {
+ formObserver.getRunningFormInfosByFilter(formInstanceFilter).then(data1 => {
+ console.info('formObserver getRunningFormInfosByFilter return err :');
+ }).catch((error) => {
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
+ });
+} catch(error) {
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
+}
+```
+
+## getRunningFormInfosByFilter
+
+getRunningFormInfosByFilter(formProviderFilter: formInfo.FormProviderFilter, callback: AsyncCallback<Array<formInfo.RunningFormInfo>>): void
+
+Obtains the information about widget hosts based on the widget provider information. This API uses an asynchronous callback to return the result.
+
+**Required permissions**: ohos.permission.OBSERVE_FORM_RUNNING
+
+**System capability**: SystemCapability.Ability.Form
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ----------- | --------------- | ---- | -------------------------------- |
+| formProviderFilter | [formInfo.FormProviderFilter](js-apis-app-form-formInfo.md#formProviderFilter) | Yes | Information about the widget provider.|
+| callback | AsyncCallback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the result. If the widget host information is obtained, **error** is **undefined** and **data** is the information obtained; otherwise, **error** is an error object.|
+
+**Error codes**
+
+For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
+
+| ID| Error Message|
+| -------- | -------- |
+| 201 | Permissions denied. |
+| 202 | The application is not a system application. |
+| 401 | If the input parameter is not valid parameter. |
+| 16500050 | An IPC connection error happened. |
+| 16500100 | Failed to obtain the configuration information. |
+| 16501000 | An internal functional error occurred. |
+
+
+```ts
+import formObserver from '@ohos.app.form.formObserver';
+
+let formInstanceFilter = {
+ bundleName: "com.example.formprovide",
+ abilityName: "EntryFormAbility",
+ formName: "widget",
+ moduleName: "entry"
+}
+try {
+ formObserver.getRunningFormInfosByFilter(formInstanceFilter,(error, data) => {
+ if (error) {
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
+ } else {
+ console.log('formObserver getRunningFormInfosByFilter, data: ${JSON.stringify(data)}');
+ }
+ });
+} catch(error) {
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
+}
+```
+
+## getRunningFormInfoById
+
+getRunningFormInfoById(formId: string): Promise<formInfo.RunningFormInfo>
+
+
+Obtains the information about widget hosts based on the widget ID. This API uses a promise to return the result.
+
+**Required permissions**: ohos.permission.OBSERVE_FORM_RUNNING
+
+**System capability**: SystemCapability.Ability.Form
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ----------- | --------------- | ---- | -------------------------------- |
+| formId | string | Yes | Widget ID.|
+
+**Return value**
+
+| Type | Description |
+| ------------------- | ------------------------- |
+| Promise<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)> | Promise used to return the widget host information obtained.|
+
+**Error codes**
+
+For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
+
+| ID| Error Message|
+| -------- | -------- |
+| 201 | Permissions denied. |
+| 202 | The application is not a system application. |
+| 401 | If the input parameter is not valid parameter. |
+| 16500050 | An IPC connection error happened. |
+| 16500100 | Failed to obtain the configuration information. |
+| 16501000 | An internal functional error occurred. |
+
+
+```ts
+import formObserver from '@ohos.app.form.formObserver';
+let formId = '12400633174999288';
+try {
+ formObserver.getRunningFormInfoById(formId).then(data1 => {
+ console.info('formObserver getRunningFormInfoById return err :');
+ }).catch((error) => {
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
+ });
+} catch(error) {
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
+}
+```
+
+## getRunningFormInfoById
+
+getRunningFormInfoById(formId: string, callback: AsyncCallback<formInfo.RunningFormInfo>): void
+
+Obtains the information about widget hosts based on the widget provider information. This API uses an asynchronous callback to return the result.
+
+**Required permissions**: ohos.permission.OBSERVE_FORM_RUNNING
+
+**System capability**: SystemCapability.Ability.Form
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ----------- | --------------- | ---- | -------------------------------- |
+| formId | string | Yes | Widget ID.|
+| callback | AsyncCallback<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)> | Yes| Callback used to return the result. If the widget host information is obtained, **error** is **undefined** and **data** is the information obtained; otherwise, **error** is an error object.|
+
+**Error codes**
+
+For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
+
+| ID| Error Message|
+| -------- | -------- |
+| 201 | Permissions denied. |
+| 202 | The application is not a system application. |
+| 401 | If the input parameter is not valid parameter. |
+| 16500050 | An IPC connection error happened. |
+| 16500100 | Failed to obtain the configuration information. |
+| 16501000 | An internal functional error occurred. |
+
+```ts
+import formObserver from '@ohos.app.form.formObserver';
+
+let formId = '12400633174999288';
+try {
+ formObserver.getRunningFormInfoById(formId,(error, data) => {
+ if (error) {
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
+ } else {
+ console.log('formObserver getRunningFormInfoById, data: ${JSON.stringify(data)}');
+ }
+ });
+} catch(error) {
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
+}
+```
diff --git a/en/application-dev/reference/apis/js-apis-appAccount-authorizationExtensionAbility.md b/en/application-dev/reference/apis/js-apis-appAccount-authorizationExtensionAbility.md
deleted file mode 100644
index dd40fcecca457706871fa85fd8ed4dded9734d67..0000000000000000000000000000000000000000
--- a/en/application-dev/reference/apis/js-apis-appAccount-authorizationExtensionAbility.md
+++ /dev/null
@@ -1,70 +0,0 @@
-# @ohos.account.appAccount.AuthorizationExtensionAbility (App AuthorizationExtensionAbility)
-
-The **AuthorizationExtensionAbility** module provides APIs for implementing authorization to app accounts based on the ExtensionAbility framework.
-
-> **NOTE**
->
-> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.
-
-## Modules to Import
-
-```ts
-import AuthorizationExtensionAbility, { AuthorizationRequest, AuthorizationCallback } from '@ohos.account.appAccount.AuthorizationExtensionAbility';
-```
-
-## AuthorizationRequest
-
-Defines the app account authorization request.
-
-**System API**: This is a system API.
-
-**System capability**: SystemCapability.Account.AppAccount
-
-| Name | Type | Readable| Writable| Description |
-| --------- | ------------------------------- | ---- | ---- | ------------------------------------ |
-| callerUid | number | Yes | No | UID of the caller.|
-| parameters | [appAccount.AccountCapabilityRequest](js-apis-appAccount.md#accountcapabilityrequest10) | Yes | No | Service parameters.|
-
-## AuthorizationCallback
-
-Provides callbacks to be invoked during the app account authorization.
-
-**System API**: This is a system API.
-
-**System capability**: SystemCapability.Account.AppAccount
-
-| Name | Type | Readable| Writable| Description |
-| --------- | ------------------------------- | ---- | ---- | ------------------------------------ |
-| onResult | AsyncCallback<[appAccount.AccountCapabilityResponse](js-apis-appAccount.md#accountcapabilityresponse10), { [key: string]: object }> | Yes | No | Callback invoked to return the authorization result.|
-
-## AuthorizationExtensionAbility.onStartAuthorization
-
-onStartAuthorization(request: AuthorizationRequest, callback: AuthorizationCallback): void
-
-Called when an authorization request is received.
-
-**System API**: This is a system API.
-
-**System capability**: SystemCapability.Account.AppAccount
-
-**Parameters**
-
-| Name | Type | Mandatory | Description |
-| -------- | ---------------------------------------- | ---- | ----------------------- |
-| request | [AuthorizationRequest](#authorizationrequest) | Yes | Authorization request information.|
-| callback | [AuthorizationCallback](#authorizationcallback) | Yes | Authorization callback object.|
-
-**Example**
-
-```ts
-class MyAuthorizationExtensionAbility extends AuthorizationExtensionAbility {
- onStartAuthorization(request: AuthorizationRequest, callback: AuthorizationCallback) {
- console.log('onStartAuthorization, callerUid: ' + request.callerUid + ', parameters: ' + request.parameters);
- let response = {
- name: 'xxxx',
- scopes: ['xxx', 'xxx']
- };
- callback.onResult(null, response);
- }
-};
-```
diff --git a/en/application-dev/reference/apis/js-apis-appAccount.md b/en/application-dev/reference/apis/js-apis-appAccount.md
index ddf515f985c2f34bad319ddceb564307f73f1b95..30fbc107e9a490bdb139da859a45cb343db63308 100644
--- a/en/application-dev/reference/apis/js-apis-appAccount.md
+++ b/en/application-dev/reference/apis/js-apis-appAccount.md
@@ -1470,7 +1470,7 @@ Obtains the authorization token of the specified authentication type for an app
| ID| Error Message|
| ------- | -------|
| 12300001 | System service exception. |
-| 12300002 | Invalid name, owner or authType. |
+| 12300002 | Invalid name, owner, or authType. |
| 12300003 | Account not found. |
| 12300107 | AuthType not found. |
@@ -1559,7 +1559,7 @@ Sets an authorization token of the specific authentication type for an app accou
| 12300001 | System service exception. |
| 12300002 | Invalid name, authType, or token. |
| 12300003 | Account not found. |
-| 12400004 | The number of token reaches the upper limit. |
+| 12400004 | The number of tokens reaches the upper limit. |
**Example**
@@ -1606,7 +1606,7 @@ Sets an authorization token of the specific authentication type for an app accou
| 12300001 | System service exception. |
| 12300002 | Invalid name, authType, or token. |
| 12300003 | Account not found. |
-| 12400004 | The number of token reaches the upper limit. |
+| 12400004 | The number of tokens reaches the upper limit. |
**Example**
@@ -1637,7 +1637,7 @@ Deletes the authorization token of the specified authentication type for an app
| name | string | Yes | Name of the target app account. |
| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. |
| authType | string | Yes | Authentication type. |
-| token | string | Yes | Token to delete.|
+| token | string | Yes | Authorization token to delete.|
| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object. |
**Error codes**
@@ -4982,298 +4982,3 @@ Obtains the remote object of an authenticator. This API cannot be overloaded.
}
}
```
-
-## AccountCapabilityType10+
-
-Enumerates the account capability types.
-
-**System capability**: SystemCapability.Account.AppAccount
-
-| Name | Value | Description |
-| ---------------- | ----- | ----------------------- |
-| AUTHORIZATION | 1 | Authorization capability. |
-
-## AccountCapabilityProvider10+
-
-Represents the **AccountCapabilityProvider** class.
-
-### Attributes
-
-**System capability**: SystemCapability.Account.AppAccount
-
-| Name| Type| Readable| Writable| Description|
-| -------- | -------- | -------- | -------- | -------- |
-| capabilityType | [AccountCapabilityType](#accountcapabilitytype10) | Yes| No| Capability type of the account.|
-
-### constructor10+
-
-constructor(capabilityType: AccountCapabilityType)
-
-A constructor used to create an **AccountCapabilityProvider** instance.
-
-**System capability**: SystemCapability.Account.AppAccount
-
-**Parameters**
-
-| Name| Type | Mandatory| Description |
-| ------ | ------ | ---- | ------------------------------------- |
-| capabilityType | [AccountCapabilityType](#accountcapabilitytype10) | Yes | Capability type of the account. |
-
-**Example**
-
-```ts
-class MyAuthorizationProvider extends account_appAccount.AccountCapabilityProvider {
- constructor() {
- super(account_appAccount.AccountCapabilityType.AUTHORIZATION);
- }
-}
-
-try {
- let provider = new MyAuthorizationProvider();
- if (provider instanceof account_appAccount.AccountCapabilityProvider) {
- console.log("the provider is an instance of AccountCapabilityProvider");
- }
-} catch (err) {
- console.error('catch error: ' + JSON.stringify(err));
-}
-```
-
-## AccountCapabilityRequest10+
-
-Represents the **AccountCapabilityRequest** class.
-
-### constructor10+
-
-constructor(provider: AccountCapabilityProvider)
-
-A constructor used to create an **AccountCapabilityRequest** instance.
-
-**System capability**: SystemCapability.Account.AppAccount
-
-**Parameters**
-
-| Name| Type | Mandatory| Description |
-| ------ | ------ | ---- | ------------------------------------- |
-| provider | [AccountCapabilityProvider](#accountcapabilityprovider10) | Yes | Provider of the account capability. |
-
-**Example**
-
-```ts
-class MyAuthorizationProvider extends account_appAccount.AccountCapabilityProvider {
- constructor() {
- super(account_appAccount.AccountCapabilityType.AUTHORIZATION);
- }
-}
-
-class MyAuthorizationRequest extends account_appAccount.AccountCapabilityRequest {
- constructor() {
- let provider = new MyAuthorizationProvider();
- super(provider);
- }
-}
-
-try {
- let request = new MyAuthorizationRequest();
- if (request instanceof account_appAccount.AccountCapabilityRequest) {
- console.log("the request is an instance of AccountCapabilityRequest");
- }
-} catch (err) {
- console.error('catch error: ' + JSON.stringify(err));
-}
-```
-
-## AccountCapabilityResponse10+
-
-Represents the **AccountCapabilityResponse** class.
-
-### Attributes
-
-**System capability**: SystemCapability.Account.AppAccount
-
-| Name| Type| Readable| Writable| Description|
-| -------- | -------- | -------- | -------- | -------- |
-| request | [AccountCapabilityRequest](#accountcapabilityrequest10) | Yes| No| Account capability request corresponding to the response.|
-
-### constructor10+
-
-constructor(request: AccountCapabilityRequest)
-
-A constructor used to create an **AccountCapabilityResponse** instance.
-
-**System capability**: SystemCapability.Account.AppAccount
-
-**Parameters**
-
-| Name| Type | Mandatory| Description |
-| ------ | ------ | ---- | ------------------------------------- |
-| request | [AccountCapabilityRequest](#accountcapabilityrequest10) | Yes | Account capability request corresponding to the response.|
-
-**Example**
-
-```ts
-class MyAuthorizationProvider extends account_appAccount.AccountCapabilityProvider {
- constructor() {
- super(account_appAccount.AccountCapabilityType.AUTHORIZATION);
- }
-}
-
-class MyAuthorizationRequest extends account_appAccount.AccountCapabilityRequest {
- constructor() {
- let provider = new MyAuthorizationProvider();
- super(provider);
- }
-}
-
-class MyAuthorizationResponse extends account_appAccount.AccountCapabilityResponse {
- constructor(request) {
- super(request)
- }
-}
-
-try {
- let request = new MyAuthorizationRequest();
- let response = new MyAuthorizationResponse(request);
- if (response instanceof account_appAccount.AccountCapabilityResponse) {
- console.log("the response is an instance of AccountCapabilityResponse");
- }
-} catch (err) {
- console.error('catch error: ' + JSON.stringify(err));
-}
-```
-
-## AuthorizationProviderInfo10+
-
-Defines information about the authorization provider.
-
-**System capability**: SystemCapability.Account.AppAccount
-
-| Name | Type | Readable| Writable| Description |
-| ------- | ------ | ---- | --- | ---------- |
-| bundleName | string | Yes| No| Bundle name of the authorization provider.|
-| abilityName | string | Yes| No| Ability name of the authorization provider.|
-
-## AuthorizationProvider10+
-
-Represents the **AuthorizationProvider** class.
-
-### constructor10+
-
-constructor(info: AuthorizationProviderInfo)
-
-A constructor used to create an **AuthorizationProvider** instance.
-
-**System capability**: SystemCapability.Account.AppAccount
-
-**Parameters**
-
-| Name| Type | Mandatory| Description |
-| ------ | ------ | ---- | ------------------------------------- |
-| info | [AuthorizationProviderInfo](#authorizationproviderinfo10) | Yes | Information about the authorization provider.|
-
-**Example**
-
-```ts
-class MyAuthorizationProvider extends account_appAccount.AuthorizationProvider {
- constructor() {
- super({bundleName: 'xxx', abilityName: 'xxx'});
- }
-}
-
-try {
- let provider = new MyAuthorizationProvider();
- if (provider instanceof account_appAccount.AuthorizationProvider) {
- console.log("the provider is an instance of AuthorizationProvider");
- }
-} catch (err) {
- console.error("catch error: " + JSON.stringify(err));
-}
-```
-
-## AccountCapabilityScheduler10+
-
-Represents the **AccountCapabilityScheduler** class.
-
-### executeRequest10+
-
-executeRequest(request: AccountCapabilityRequest, callback: AsyncCallback<AccountCapabilityResponse, { [key: string]: object }>): void
-
-Executes an account capability request. This API uses an asynchronous callback to return the result.
-
-**System capability**: SystemCapability.Account.AppAccount
-
-**Parameters**
-
-| Name | Type | Mandatory | Description |
-| ---------- | ------------------------- | ---- | ------------------------- |
-| request | [AccountCapabilityRequest](#accountcapabilityrequest10) | Yes | Account capability request to execute. |
-| callback | AsyncCallback<[AccountCapabilityResponse](#accountcapabilityresponse10), { [key: string]: object }> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object. |
-
-**Error codes**
-
-| ID| Error Message|
-| ------- | ------- |
-| 12300001 | System service exception. |
-| 12300002 | Invalid request. |
-
-**Example**
-
-```ts
-let scheduler = new account_appAccount.AccountCapabilityScheduler();
-let provider = new account_appAccount.AuthorizationProvider({ bundleName: 'xxx', abilityName: 'xxx' });
-let request = new account_appAccount.AccountCapabilityRequest(provider);
-try {
- scheduler.executeRequest(request, (err, response) => {
- if (err != null) {
- console.log('executeRequest failed, error: ' + JSON.stringify(err));
- } else {
- console.log('executeRequest response: ' + JSON.stringify(response));
- }
- });
-} catch (err) {
- console.log('executeRequest exception: ' + JSON.stringify(err));
-}
-```
-
-### executeRequest10+
-
-executeRequest(request: AccountCapabilityRequest): Promise<AccountCapabilityResponse>
-
-Executes an account capability request. This API uses a promise to return the result.
-
-**System capability**: SystemCapability.Account.AppAccount
-
-**Parameters**
-
-| Name | Type | Mandatory | Description |
-| ---------- | ------- | ---- | ------------ |
-| request | [AccountCapabilityRequest](#accountcapabilityrequest10) | Yes | Account capability request to execute.|
-
-**Return value**
-
-| Type | Description |
-| ------------------- | --------------------- |
-| Promise<[AccountCapabilityResponse](#accountcapabilityresponse10)> | Promise used to return the result. |
-
-**Error codes**
-
-| ID| Error Message|
-| ------- | ------- |
-| 12300001 | System service exception. |
-| 12300002 | Invalid request. |
-
-**Example**
-
-```ts
-let scheduler = new account_appAccount.AccountCapabilityScheduler();
-let provider = new account_appAccount.AuthorizationProvider({ bundleName: 'xxx', abilityName: 'xxx' });
-let request = new account_appAccount.AccountCapabilityRequest(provider);
-try {
- scheduler.executeRequest(request).then((response) => {
- console.log('executeRequest response: ' + JSON.stringify(response));
- }).catch((err) => {
- console.log('executeRequest failed, error: ' + JSON.stringify(err));
- });
-} catch (err) {
- console.log('executeRequest exception: ' + JSON.stringify(err));
-}
-```
diff --git a/en/application-dev/reference/apis/js-apis-arkui-UIContext.md b/en/application-dev/reference/apis/js-apis-arkui-UIContext.md
index 59d38206114407df5e3e220060274da684707cee..946463e335769b047494f0ed5b85ddbb911b3490 100644
--- a/en/application-dev/reference/apis/js-apis-arkui-UIContext.md
+++ b/en/application-dev/reference/apis/js-apis-arkui-UIContext.md
@@ -608,9 +608,9 @@ Obtains the size, position, translation, scaling, rotation, and affine matrix in
**Return value**
-| Type | Description |
-| ------------- | ------------------------------------------------------------ |
-| ComponentInfo | Size, position, translation, scaling, rotation, and affine matrix information of the component. |
+| Type | Description |
+| -------------------------------------------------------- | ------------------------------------------------ |
+| [ComponentInfo](js-apis-arkui-componentUtils.md#componentinfo) | Size, position, translation, scaling, rotation, and affine matrix information of the component.|
**Example**
diff --git a/en/application-dev/reference/apis/js-apis-arkui-componentUtils.md b/en/application-dev/reference/apis/js-apis-arkui-componentUtils.md
new file mode 100644
index 0000000000000000000000000000000000000000..7dd3cbb5a41f2bb4b6cbb401cd6f90c0d77d39e9
--- /dev/null
+++ b/en/application-dev/reference/apis/js-apis-arkui-componentUtils.md
@@ -0,0 +1,230 @@
+# @ohos.arkui.componentUtils (componentUtils)
+
+The **componentUtils** module provides API for obtaining the coordinates and size of the drawing area of a component.
+
+> **NOTE**
+>
+> The APIs of this module are supported since API version 10. Updates will be marked with a superscript to indicate their earliest API version.
+>
+> The functionality of this module depends on UI context. This means that the APIs of this module cannot be used where the UI context is unclear. For details, see [UIContext](./js-apis-arkui-UIContext.md#uicontext).
+>
+> Since API version 10, you can use the [getComponentUtils](./js-apis-arkui-UIContext.md#getcomponentutils) API in **UIContext** to obtain the **ComponentUtils** object associated with the current UI context. For this API to work correctly, call it after the notification indicating completion of component layout is received through [@ohos.arkui.inspector (layout callback)](js-apis-arkui-inspector.md).
+
+## Modules to Import
+
+```js
+import componentUtils from '@ohos.arkui.componentUtils'
+```
+## componentUtils.getRectangleById
+
+getRectangleById(id: string): ComponentInfo
+
+Obtains a **ComponentInfo** object based on the component ID.
+
+**System capability**: SystemCapability.ArkUI.ArkUI.Full
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | ------ | ---- | ---------- |
+| id | string | Yes | Component ID.|
+
+**Return value**
+
+| Type | Description |
+| ------ | ---------- |
+| [ComponentInfo](#componentinfo) | **ComponentInfo** object, which provides the size, position, translation, scaling, rotation, and affine matrix information of the component.|
+
+**Example**
+
+```js
+let modePosition = componentUtils.getRectangleById("onClick");
+```
+
+## ComponentInfo
+
+**System capability**: SystemCapability.ArkUI.ArkUI.Full
+
+| Name | Type | Mandatory | Description |
+| ---------------|------------ | -----------------------------| -----------------------------|
+| size | [Size](#size) | Yes| Component size. |
+| localOffset | [Offset](#offset) | Yes| Offset of the component relative to the parent component. |
+| windowOffset | [Offset](#offset) | Yes| Offset of the component relative to the window. |
+| screenOffset | [Offset](#offset) | Yes| Offset of the component relative to the screen. |
+| translate | [TranslateResult](#translateresult) | Yes| Translation of the component. |
+| scale | [ScaleResult](#scaleresult) | Yes| Scaling of the component. |
+| rotate | [RotateResult](#rotateresult) | Yes| Rotation of the component. |
+| transform | [Matrix4Result](#matrix4result) | Yes| Affine matrix of the component, which is a 4x4 matrix object created based on the input parameter. |
+
+### Size
+
+**System capability**: SystemCapability.ArkUI.ArkUI.Full
+
+| Name | Type| Mandatory| Description |
+| -------- | ---- | ----------------------------------| ----------------------------------|
+| width | number | Yes| Component width. |
+| height | number | Yes| Component height. |
+
+### Offset
+
+**System capability**: SystemCapability.ArkUI.ArkUI.Full
+
+| Name | Type| Mandatory| Description |
+| --------| ---- | -----------------------------------| -----------------------------------|
+| x | number | Yes| X coordinate. |
+| y | number | Yes| Y coordinate. |
+
+### TranslateResult
+
+**System capability**: SystemCapability.ArkUI.ArkUI.Full
+
+| Name | Type| Mandatory| Description |
+| --------| ---- | -----------------------------------| -----------------------------------|
+| x | number | Yes| Translation distance along the x-axis. |
+| y | number | Yes| Translation distance along the y-axis. |
+| z | number | Yes| Translation distance along the z-axis. |
+
+### ScaleResult
+
+**System capability**: SystemCapability.ArkUI.ArkUI.Full
+
+| Name | Type| Mandatory| Description |
+| --------| ---- | -----------------------------------| -----------------------------------|
+| x | number | Yes| Scale factor along the x-axis. |
+| y | number | Yes| Scale factor along the y-axis. |
+| z | number | Yes| Scale factor along the z-axis. |
+| centerX | number | Yes| X coordinate of the center point. |
+| centerY | number | Yes| Y coordinate of the center point. |
+
+### RotateResult
+
+**System capability**: SystemCapability.ArkUI.ArkUI.Full
+
+| Name | Type| Mandatory| Description |
+| --------| ---- | -----------------------------------| -----------------------------------|
+| x | number | Yes| X coordinate of the rotation vector. |
+| y | number | Yes| Y coordinate of the rotation vector. |
+| z | number | Yes| Z coordinate of the rotation vector. |
+| angle | number | Yes| Rotation angle. |
+| centerX | number | Yes| X coordinate of the center point. |
+| centerY | number | Yes| Y coordinate of the center point. |
+
+### Matrix4Result
+
+**System capability**: SystemCapability.ArkUI.ArkUI.Full
+
+| Value Range | Description |
+| --------| -----------------------------------|
+| [number,number,number,number, number,number,number,number, number,number,number,number, number,number,number,number] | A number array whose length is 16 (4 x 4). For details, see **4 x 4 matrix description**.|
+
+**4 x 4 matrix description**
+
+| Name| Type | Mandatory| Description |
+| ------ | ------ | ---- | ------------------------------------ |
+| m00 | number | Yes | Scale factor along the x-axis. Defaults to **1** for the identity matrix. |
+| m01 | number | Yes | The second value, which is affected by the rotation of the x, y, and z axes. |
+| m02 | number | Yes | The third value, which is affected by the rotation of the x, y, and z axes. |
+| m03 | number | Yes | Meaningless value. |
+| m10 | number | Yes | The fifth value, which is affected by the rotation of the x, y, and z axes. |
+| m11 | number | Yes | Scale factor along the y-axis. Defaults to **1** for the identity matrix. |
+| m12 | number | Yes | The seventh value, which is affected by the rotation of the x, y, and z axes. |
+| m13 | number | Yes | Meaningless value. |
+| m20 | number | Yes | The ninth value, which is affected by the rotation of the x, y, and z axes. |
+| m21 | number | Yes | The tenth value, which is affected by the rotation of the x, y, and z axes. |
+| m22 | number | Yes | Scale factor along the z-axis. Defaults to **1** for the identity matrix. |
+| m23 | number | Yes | Meaningless value. |
+| m30 | number | Yes | Translation value of the x-axis, in px. Defaults to **0** for the unit matrix.|
+| m31 | number | Yes | Translation value of the y-axis, in px. The default value is **0** for the identity matrix.|
+| m32 | number | Yes | Translation value of the z-axis, in px. The default value is **0** for the identity matrix.|
+| m33 | number | Yes | Valid in homogeneous coordinates, presenting the perspective projection effect. |
+
+**Example**
+
+ ```js
+import matrix4 from '@ohos.matrix4';
+import componentUtils from '@ohos.arkui.componentUtils';
+
+@Entry
+@Component
+struct Utils{
+ private getComponentRect(key) {
+ console.info("Mode Key: " + key);
+ let modePosition = componentUtils.getRectangleById(key);
+
+ let localOffsetWidth = modePosition.size.width;
+ let localOffsetHeight = modePosition.size.height;
+ let localOffsetX = modePosition.localOffset.x;
+ let localOffsetY = modePosition.localOffset.y;
+
+ let windowOffsetX = modePosition.windowOffset.x;
+ let windowOffsetY = modePosition.windowOffset.y;
+
+ let screenOffsetX = modePosition.screenOffset.x;
+ let screenOffsetY = modePosition.screenOffset.y;
+
+ let translateX = modePosition.translate.x;
+ let translateY = modePosition.translate.y;
+ let translateZ = modePosition.translate.z;
+
+ let scaleX = modePosition.scale.x;
+ let scaleY = modePosition.scale.y;
+ let scaleZ = modePosition.scale.z;
+ let scaleCenterX = modePosition.scale.centerX;
+ let scaleCenterY = modePosition.scale.centerY;
+
+ let rotateX = modePosition.rotate.x;
+ let rotateY = modePosition.rotate.y;
+ let rotateZ = modePosition.rotate.z;
+ let rotateCenterX = modePosition.rotate.centerX;
+ let rotateCenterY = modePosition.rotate.centerY;
+ let rotateAngle = modePosition.rotate.angle;
+
+ let Matrix4_1 = modePosition.transform[0];
+ let Matrix4_2 = modePosition.transform[1];
+ let Matrix4_3 = modePosition.transform[2];
+ let Matrix4_4 = modePosition.transform[3];
+ let Matrix4_5 = modePosition.transform[4];
+ let Matrix4_6 = modePosition.transform[5];
+ let Matrix4_7 = modePosition.transform[6];
+ let Matrix4_8 = modePosition.transform[7];
+ let Matrix4_9 = modePosition.transform[8];
+ let Matrix4_10 = modePosition.transform[9];
+ let Matrix4_11 = modePosition.transform[10];
+ let Matrix4_12 = modePosition.transform[11];
+ let Matrix4_13 = modePosition.transform[12];
+ let Matrix4_14 = modePosition.transform[13];
+ let Matrix4_15 = modePosition.transform[14];
+ let Matrix4_16 = modePosition.transform[15];
+ console.info("[getRectangleById] current component obj is: " + modePosition );
+ }
+ @State x: number = 120;
+ @State y: number = 10;
+ @State z: number = 100;
+ private matrix1 = matrix4.identity().translate({ x: this.x, y: this.y, z: this.z });
+ build() {
+ Column() {
+ Image($r("app.media.icon"))
+ .transform(this.matrix1)
+ .translate({ x: 100, y: 10, z: 50})
+ .scale({ x: 2, y: 0.5, z: 1 })
+ .rotate({
+ x: 1,
+ y: 1,
+ z: 1,
+ centerX: '50%',
+ centerY: '50%',
+ angle: 300
+ })
+ .width("40%")
+ .height(100)
+ .key("image_01")
+ Button() {
+ Text('getRectangleById').fontSize(40).fontWeight(FontWeight.Bold);
+ }.margin({ top: 20 })
+ .onClick(() => {
+ this.getComponentRect("image_01");
+ }).id('onClick');
+ }
+ }
+}
+ ```
diff --git a/en/application-dev/reference/apis/js-apis-audio.md b/en/application-dev/reference/apis/js-apis-audio.md
index 1a104a95a4885b36806cd99c0ed30cb2d7fb47b7..5da2213e83ae6d18cfe66227e12a143d8fe7a815 100644
--- a/en/application-dev/reference/apis/js-apis-audio.md
+++ b/en/application-dev/reference/apis/js-apis-audio.md
@@ -74,7 +74,6 @@ Creates an **AudioRenderer** instance. This API uses an asynchronous callback to
**Example**
```js
-import featureAbility from '@ohos.ability.featureAbility';
import fs from '@ohos.file.fs';
import audio from '@ohos.multimedia.audio';
@@ -129,7 +128,6 @@ Creates an **AudioRenderer** instance. This API uses a promise to return the res
**Example**
```js
-import featureAbility from '@ohos.ability.featureAbility';
import fs from '@ohos.file.fs';
import audio from '@ohos.multimedia.audio';
@@ -545,7 +543,7 @@ Enumerates the audio stream usage.
| STREAM_USAGE_UNKNOWN | 0 | Unknown usage.|
| STREAM_USAGE_MEDIA | 1 | Media. |
| STREAM_USAGE_MUSIC10+ | 1 | Music. |
-| STREAM_USAGE_VOICE_COMMUNICATION | 2 | Voice communication.|
+| STREAM_USAGE_VOICE_COMMUNICATION | 2 | Voice communication.|
| STREAM_USAGE_VOICE_ASSISTANT9+ | 3 | Voice assistant.|
| STREAM_USAGE_ALARM10+ | 4 | Alarming. |
| STREAM_USAGE_VOICE_MESSAGE10+ | 5 | Voice message.|
@@ -813,7 +811,7 @@ Describes audio capturer configurations.
| ----------------------------------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ |
| streamInfo | [AudioStreamInfo](#audiostreaminfo8) | Yes | Audio stream information. **System capability**: SystemCapability.Multimedia.Audio.Capturer |
| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo) | Yes | Audio capturer information. **System capability**: SystemCapability.Multimedia.Audio.Capturer |
-| playbackCaptureConfig10+ | [AudioPlaybackCaptureConfig](#audioplaybackcaptureconfig) | No | Configuration of internal audio recording. **System capability**: SystemCapability.Multimedia.Audio.PlaybackCapture |
+| playbackCaptureConfig10+ | [AudioPlaybackCaptureConfig](#audioplaybackcaptureconfig) | No | Configuration of internal audio recording. **System capability**: SystemCapability.Multimedia.Audio.PlaybackCapture|
## AudioCapturerInfo8+
@@ -835,7 +833,8 @@ Enumerates the audio source types.
| SOURCE_TYPE_INVALID | -1 | Invalid audio source. **System capability**: SystemCapability.Multimedia.Audio.Core |
| SOURCE_TYPE_MIC | 0 | Mic source. **System capability**: SystemCapability.Multimedia.Audio.Core|
| SOURCE_TYPE_VOICE_RECOGNITION9+ | 1 | Voice recognition source. **System capability**: SystemCapability.Multimedia.Audio.Core |
-| SOURCE_TYPE_PLAYBACK_CAPTURE10+ | 2 | Internal audio recording source. **System capability**: SystemCapability.Multimedia.Audio.PlaybackCapture |
+| SOURCE_TYPE_PLAYBACK_CAPTURE10+ | 2 | Internal audio recording source. **System capability**: SystemCapability.Multimedia.Audio.PlaybackCapture|
+| SOURCE_TYPE_WAKEUP 10+ | 3 | Audio recording source in voice wakeup scenarios. **System capability**: SystemCapability.Multimedia.Audio.Core **Required permissions**: ohos.permission.MANAGE_INTELLIGENT_VOICE This is a system API.|
| SOURCE_TYPE_VOICE_COMMUNICATION | 7 | Voice communication source. **System capability**: SystemCapability.Multimedia.Audio.Core|
## AudioPlaybackCaptureConfig10+
@@ -3076,7 +3075,7 @@ Checks whether the fixed volume mode is enabled. When the fixed volume mode is e
**Example**
```js
-bool volumeAdjustSwitch = audioVolumeGroupManager.isVolumeUnadjustable();
+let volumeAdjustSwitch = audioVolumeGroupManager.isVolumeUnadjustable();
console.info(`Whether it is volume unadjustable: ${volumeAdjustSwitch}.`);
```
@@ -5226,36 +5225,32 @@ let bufferSize;
audioRenderer.getBufferSize().then((data)=> {
console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`);
bufferSize = data;
- }).catch((err) => {
- console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`);
- });
-console.info(`Buffer size: ${bufferSize}`);
-let context = featureAbility.getContext();
-let path;
-async function getCacheDir(){
- path = await context.getCacheDir();
-}
-let filePath = path + '/StarWars10s-2C-48000-4SW.wav';
-let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY);
-fs.stat(path).then((stat) => {
- let buf = new ArrayBuffer(bufferSize);
- let len = stat.size % bufferSize == 0 ? Math.floor(stat.size / bufferSize) : Math.floor(stat.size / bufferSize + 1);
- for (let i = 0;i < len; i++) {
- let options = {
- offset: i * bufferSize,
- length: bufferSize
- }
- let readsize = await fs.read(file.fd, buf, options)
- let writeSize = await new Promise((resolve,reject)=>{
- audioRenderer.write(buf,(err,writeSize)=>{
- if(err){
- reject(err)
- }else{
- resolve(writeSize)
- }
+ console.info(`Buffer size: ${bufferSize}`);
+ let path = getContext().cacheDir;
+ let filePath = path + '/StarWars10s-2C-48000-4SW.wav';
+ let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY);
+ fs.stat(filePath).then(async (stat) => {
+ let buf = new ArrayBuffer(bufferSize);
+ let len = stat.size % bufferSize == 0 ? Math.floor(stat.size / bufferSize) : Math.floor(stat.size / bufferSize + 1);
+ for (let i = 0;i < len; i++) {
+ let options = {
+ offset: i * bufferSize,
+ length: bufferSize
+ }
+ let readsize = await fs.read(file.fd, buf, options)
+ let writeSize = await new Promise((resolve,reject)=>{
+ audioRenderer.write(buf,(err,writeSize)=>{
+ if(err){
+ reject(err)
+ }else{
+ resolve(writeSize)
+ }
+ })
})
- })
- }
+ }
+ });
+}).catch((err) => {
+ console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`);
});
@@ -5282,32 +5277,28 @@ let bufferSize;
audioRenderer.getBufferSize().then((data) => {
console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`);
bufferSize = data;
- }).catch((err) => {
- console.info(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`);
+ console.info(`BufferSize: ${bufferSize}`);
+ let path = getContext().cacheDir;
+ let filePath = path + '/StarWars10s-2C-48000-4SW.wav';
+ let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY);
+ fs.stat(filePath).then(async (stat) => {
+ let buf = new ArrayBuffer(bufferSize);
+ let len = stat.size % bufferSize == 0 ? Math.floor(stat.size / bufferSize) : Math.floor(stat.size / bufferSize + 1);
+ for (let i = 0;i < len; i++) {
+ let options = {
+ offset: i * bufferSize,
+ length: bufferSize
+ }
+ let readsize = await fs.read(file.fd, buf, options)
+ try{
+ let writeSize = await audioRenderer.write(buf);
+ } catch(err) {
+ console.error(`audioRenderer.write err: ${err}`);
+ }
+ }
});
-console.info(`BufferSize: ${bufferSize}`);
-let context = featureAbility.getContext();
-let path;
-async function getCacheDir(){
- path = await context.getCacheDir();
-}
-let filePath = path + '/StarWars10s-2C-48000-4SW.wav';
-let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY);
-fs.stat(path).then((stat) => {
- let buf = new ArrayBuffer(bufferSize);
- let len = stat.size % bufferSize == 0 ? Math.floor(stat.size / bufferSize) : Math.floor(stat.size / bufferSize + 1);
- for (let i = 0;i < len; i++) {
- let options = {
- offset: i * bufferSize,
- length: bufferSize
- }
- let readsize = await fs.read(file.fd, buf, options)
- try{
- let writeSize = await audioRenderer.write(buf);
- } catch(err) {
- console.error(`audioRenderer.write err: ${err}`);
- }
- }
+}).catch((err) => {
+ console.info(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`);
});
```
@@ -5790,13 +5781,13 @@ audioRenderer.getCurrentOutputDevices((err, deviceInfo) => {
console.error(`getCurrentOutputDevices Fail: ${err}`);
} else {
console.info(`DeviceInfo id: ${deviceInfo.id}`);
- console.info(`DeviceInfo type: ${descriptor.deviceType}`);
- console.info(`DeviceInfo role: ${descriptor.deviceRole}`);
- console.info(`DeviceInfo name: ${descriptor.name}`);
- console.info(`DeviceInfo address: ${descriptor.address}`);
- console.info(`DeviceInfo samplerates: ${descriptor.sampleRates[0]}`);
- console.info(`DeviceInfo channelcounts: ${descriptor.channelCounts[0]}`);
- console.info(`DeviceInfo channelmask: ${descriptor.channelMasks}`);
+ console.info(`DeviceInfo type: ${deviceInfo.deviceType}`);
+ console.info(`DeviceInfo role: ${deviceInfo.deviceRole}`);
+ console.info(`DeviceInfo name: ${deviceInfo.name}`);
+ console.info(`DeviceInfo address: ${deviceInfo.address}`);
+ console.info(`DeviceInfo samplerates: ${deviceInfo.sampleRates[0]}`);
+ console.info(`DeviceInfo channelcounts: ${deviceInfo.channelCounts[0]}`);
+ console.info(`DeviceInfo channelmask: ${deviceInfo.channelMasks}`);
}
});
```
@@ -5819,13 +5810,13 @@ Obtains the output device descriptors of the audio streams. This API uses a prom
```js
audioRenderer.getCurrentOutputDevices().then((deviceInfo) => {
console.info(`DeviceInfo id: ${deviceInfo.id}`);
- console.info(`DeviceInfo type: ${descriptor.deviceType}`);
- console.info(`DeviceInfo role: ${descriptor.deviceRole}`);
- console.info(`DeviceInfo name: ${descriptor.name}`);
- console.info(`DeviceInfo address: ${descriptor.address}`);
- console.info(`DeviceInfo samplerates: ${descriptor.sampleRates[0]}`);
- console.info(`DeviceInfo channelcounts: ${descriptor.channelCounts[0]}`);
- console.info(`DeviceInfo channelmask: ${descriptor.channelMasks}`);
+ console.info(`DeviceInfo type: ${deviceInfo.deviceType}`);
+ console.info(`DeviceInfo role: ${deviceInfo.deviceRole}`);
+ console.info(`DeviceInfo name: ${deviceInfo.name}`);
+ console.info(`DeviceInfo address: ${deviceInfo.address}`);
+ console.info(`DeviceInfo samplerates: ${deviceInfo.sampleRates[0]}`);
+ console.info(`DeviceInfo channelcounts: ${deviceInfo.channelCounts[0]}`);
+ console.info(`DeviceInfo channelmask: ${deviceInfo.channelMasks}`);
}).catch((err) => {
console.error(`Get current output devices Fail: ${err}`);
});
@@ -6073,7 +6064,7 @@ Subscribes to audio output device change events.
**Example**
```js
-audioRenderer.on('outputDeviceChange', (deviceChangeInfo) => {
+audioRenderer.on('outputDeviceChange', (err, deviceChangeInfo) => {
if (err) {
console.error(`Subscribes output device change event callback Fail: ${err}`);
} else {
@@ -6105,7 +6096,7 @@ Unsubscribes from audio output device event changes.
**Example**
```js
-audioRenderer.off('outputDeviceChange', (deviceChangeInfo) => {
+audioRenderer.off('outputDeviceChange', (err,deviceChangeInfo) => {
if (err) {
console.error(`Unsubscribes output device change event callback Fail: ${err}`);
} else {
diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-abilityInfo.md b/en/application-dev/reference/apis/js-apis-bundleManager-abilityInfo.md
index b15708816fdcaf8293209bcb008e2119979817f3..32dbd9820d824bd08a791c062b9d0df4e1169def 100644
--- a/en/application-dev/reference/apis/js-apis-bundleManager-abilityInfo.md
+++ b/en/application-dev/reference/apis/js-apis-bundleManager-abilityInfo.md
@@ -15,11 +15,11 @@ The **AbilityInfo** module defines the ability information. A system application
| bundleName | string | Yes | No | Bundle name. |
| moduleName | string | Yes | No | Name of the HAP file to which the ability belongs. |
| name | string | Yes | No | Ability name. |
-| label | string | Yes | No | Ability name visible to users. |
+| label | string | Yes | No | Resource descriptor of the ability name visible to users. Example: **"label": "$string: mainability_description"**. |
| labelId | number | Yes | No | ID of the ability label. |
| description | string | Yes | No | Ability description. |
| descriptionId | number | Yes | No | ID of the ability description. |
-| icon | string | Yes | No | Index of the ability icon resource file. |
+| icon | string | Yes | No | Resource descriptor of the ability icon. Example: **"icon": "$media:icon"**. |
| iconId | number | Yes | No | ID of the ability icon. |
| process | string | Yes | No | Process in which the ability runs. If this parameter is not set, the bundle name is used.|
| exported | boolean | Yes | No | Whether the ability can be called by other bundles. |
diff --git a/en/application-dev/reference/apis/js-apis-bundleManager.md b/en/application-dev/reference/apis/js-apis-bundleManager.md
index 99e99255972ca0ae8a91b4fb55f4ae2387816b8d..61802e558ab82748cc27b12151669309599bd384 100644
--- a/en/application-dev/reference/apis/js-apis-bundleManager.md
+++ b/en/application-dev/reference/apis/js-apis-bundleManager.md
@@ -100,7 +100,7 @@ Enumerates the types of Extension abilities.
| Name| Value| Description|
|:----------------:|:---:|-----|
| FORM | 0 | [FormExtensionAbility](../../application-models/service-widget-overview.md): provides APIs for widget development.|
-| WORK_SCHEDULER | 1 | [WorkSchedulerExtensionAbility](../../task-management/work-scheduler.md): enables applications to execute non-real-time tasks when the system is idle. |
+| WORK_SCHEDULER | 1 | [WorkSchedulerExtensionAbility](../../task-management/work-scheduler.md): enables applications to execute non-real-time tasks when the system is idle.|
| INPUT_METHOD | 2 | [InputMethodExtensionAbility](js-apis-inputmethod-extension-ability.md): provides APIs for developing input method applications.|
| SERVICE | 3 | [ServiceExtensionAbility](../../application-models/serviceextensionability.md): enables applications to run in the background and provide services.|
| ACCESSIBILITY | 4 | [AccessibilityExtensionAbility](js-apis-application-accessibilityExtensionAbility.md): provides accessibility for access to and operations on the UI.|
@@ -116,7 +116,6 @@ Enumerates the types of Extension abilities.
| PRINT10+ | 15 | PrintExtensionAbility: provides APIs for printing images. Printing documents is not supported yet.|
| PUSH10+ | 17 | PushExtensionAbility: provides APIs for pushing scenario-specific messages. This ability is reserved.|
| DRIVER10+ | 18 | DriverExtensionAbility: provides APIs for the peripheral driver. This type of ability is not supported yet.|
-| APP_ACCOUNT_AUTHORIZATION10+ | 19 | [AuthorizationExtensionAbility](js-apis-appAccount-authorizationExtensionAbility.md): provides APIs to process authorization requests for application accounts and allow account authorization from a third-party (relative to the operating system vendor) ecosystem platform.|
| UNSPECIFIED | 255 | No type is specified. It is used together with **queryExtensionAbilityInfo** to query all types of Extension abilities.|
diff --git a/en/application-dev/reference/apis/js-apis-camera.md b/en/application-dev/reference/apis/js-apis-camera.md
index d9ec7a942cc86ce8d331eb8920b81111e1c8c8c4..8877fff44a94b34057a4daebb158fa8fd80dbe80 100644
--- a/en/application-dev/reference/apis/js-apis-camera.md
+++ b/en/application-dev/reference/apis/js-apis-camera.md
@@ -32,7 +32,7 @@ Obtains a **CameraManager** instance. This API returns the result synchronously.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -267,7 +267,7 @@ Creates a **CameraInput** instance with the specified **CameraDevice** object. T
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -311,7 +311,7 @@ Creates a **CameraInput** instance with the specified camera position and type.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -355,7 +355,7 @@ Creates a **PreviewOutput** instance. This API returns the result synchronously.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -397,7 +397,7 @@ Creates a **PhotoOutput** instance. This API returns the result synchronously.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -439,7 +439,7 @@ Creates a **VideoOutput** instance. This API returns the result synchronously.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -480,7 +480,7 @@ Creates a **MetadataOutput** instance. This API returns the result synchronously
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -515,7 +515,7 @@ Creates a **CaptureSession** instance. This API returns the result synchronously
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -606,7 +606,7 @@ Checks whether a camera supports prelaunch. This API is called in prior to **set
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -640,7 +640,7 @@ setPrelaunchConfig(prelaunchConfig: PrelaunchConfig): void
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -665,7 +665,7 @@ if(this.cameraManager.isPrelaunchSupported(cameras[0])) {
prelaunch(): void
-Prelaunches the camera. This API is called when the camera application is started after a user clicks the system camera icon.
+Prelaunches the camera. This API is called when a user clicks the system camera icon to start the camera application.
**System API**: This is a system API.
@@ -706,7 +706,7 @@ Creates a deferred **PreviewOutput** instance and adds it to the data stream ins
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -868,7 +868,7 @@ Opens this camera. This API uses an asynchronous callback to return the result.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -904,7 +904,7 @@ Opens this camera. This API uses a promise to return the result.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -938,7 +938,7 @@ Closes this camera. This API uses an asynchronous callback to return the result.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -972,7 +972,7 @@ Closes this camera. This API uses a promise to return the result.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -1096,7 +1096,7 @@ Starts configuration for the session.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -1129,7 +1129,7 @@ Commits the configuration for this **CaptureSession** instance. This API uses an
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -1164,7 +1164,7 @@ Commits the configuration for this **CaptureSession** instance. This API uses a
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -1204,7 +1204,7 @@ Adds a [CameraInput](#camerainput) instance to the session.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -1244,7 +1244,7 @@ Removes a [CameraInput](#camerainput) instance from the session.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -1284,7 +1284,7 @@ Adds a [CameraOutput](#cameraoutput) instance to the session.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -1324,7 +1324,7 @@ Removes a [CameraOutput](#cameraoutput) instance from the session.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -1358,7 +1358,7 @@ Starts this **CaptureSession**. This API uses an asynchronous callback to return
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -1393,7 +1393,7 @@ Starts this **CaptureSession**. This API uses a promise to return the result.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -1426,7 +1426,7 @@ Stops this **CaptureSession**. This API uses an asynchronous callback to return
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -1460,7 +1460,7 @@ Stops this **CaptureSession**. This API uses a promise to return the result.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -1492,7 +1492,7 @@ Releases this **CaptureSession**. This API uses an asynchronous callback to retu
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -1526,7 +1526,7 @@ Releases this **CaptureSession**. This API uses a promise to return the result.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -1558,7 +1558,7 @@ Checks whether the device has flash. This API uses an asynchronous callback to r
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -1597,7 +1597,7 @@ Checks whether a flash mode is supported.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -1641,7 +1641,7 @@ Before the setting, do the following checks:
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -1674,7 +1674,7 @@ Obtains the flash mode in use.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -1713,7 +1713,7 @@ Checks whether an exposure mode is supported.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -1746,7 +1746,7 @@ Obtains the exposure mode in use.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -1785,7 +1785,7 @@ Sets an exposure mode for the device.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -1818,7 +1818,7 @@ Obtains the metering point of the device.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -1859,7 +1859,7 @@ The coordinate system is based on the horizontal device direction with the devic
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -1893,7 +1893,7 @@ Obtains the exposure compensation values of the device.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -1928,7 +1928,7 @@ Before the setting, you are advised to use **[getExposureBiasRange](#getexposure
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -1962,7 +1962,7 @@ Obtains the exposure value in use.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -2001,7 +2001,7 @@ Checks whether a focus mode is supported.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -2042,7 +2042,7 @@ Before the setting, use **[isFocusModeSupported](#isfocusmodesupported)** to che
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -2075,7 +2075,7 @@ Obtains the focus mode in use.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -2116,7 +2116,7 @@ The coordinate system is based on the horizontal device direction with the devic
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -2150,7 +2150,7 @@ Obtains the focal point of the device.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -2183,7 +2183,7 @@ Obtains the focal length of the device.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -2216,7 +2216,7 @@ Obtains the supported zoom ratio range.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -2255,7 +2255,7 @@ Sets a zoom ratio, with a maximum precision of two decimal places.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -2289,7 +2289,7 @@ Obtains the zoom ratio in use.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -2328,7 +2328,7 @@ Checks whether the specified video stabilization mode is supported.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -2361,7 +2361,7 @@ Obtains the video stabilization mode in use.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -2400,7 +2400,7 @@ Sets a video stabilization mode for the device.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -2487,7 +2487,7 @@ Starts to output preview streams. This API uses an asynchronous callback to retu
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -2521,7 +2521,7 @@ Starts to output preview streams. This API uses a promise to return the result.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -2603,7 +2603,7 @@ Releases output resources. This API uses an asynchronous callback to return the
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -2637,7 +2637,7 @@ Releases output resources. This API uses a promise to return the result.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -2726,7 +2726,7 @@ previewOutput.on('error', (previewOutputError) => {
addDeferredSurface(surfaceId: string): void
-Adds a surface for delayed preview. This API can run after **session.commitConfig()** is used to commit the configuration for a stream and **session.start()** is used to start the stream.
+Adds a surface for delayed preview. This API can run after **session.commitConfig()** or **session.start()** is called.
**System API**: This is a system API.
@@ -2740,7 +2740,7 @@ Adds a surface for delayed preview. This API can run after **session.commitConfi
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -2836,7 +2836,7 @@ Captures a photo with the default shooting parameters. This API uses an asynchro
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -2871,7 +2871,7 @@ Captures a photo with the default shooting parameters. This API uses a promise t
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -2905,7 +2905,7 @@ Captures a photo with the specified shooting parameters. This API uses an asynch
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -2958,7 +2958,7 @@ Captures a photo with the specified shooting parameters. This API uses a promise
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -3023,7 +3023,7 @@ Releases output resources. This API uses an asynchronous callback to return the
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -3057,7 +3057,7 @@ Releases output resources. This API uses a promise to return the result.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -3187,7 +3187,7 @@ This API takes effect after **CaptureSession.addOutput** and **CaptureSession.ad
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -3233,7 +3233,7 @@ This API takes effect after **CaptureSession.addOutput** and **CaptureSession.ad
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -3356,7 +3356,7 @@ Starts video recording. This API uses an asynchronous callback to return the res
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -3391,7 +3391,7 @@ Starts video recording. This API uses a promise to return the result.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -3474,7 +3474,7 @@ Releases output resources. This API uses an asynchronous callback to return the
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -3508,7 +3508,7 @@ Releases output resources. This API uses a promise to return the result.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -3613,7 +3613,7 @@ Starts to output metadata. This API uses an asynchronous callback to return the
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
@@ -3648,7 +3648,7 @@ Starts to output metadata. This API uses a promise to return the result.
**Error codes**
-For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
+For details about the error codes, see [Camera Error Codes](../errorcodes/errorcode-camera.md).
| ID | Error Message |
| --------------- | --------------- |
diff --git a/en/application-dev/reference/apis/js-apis-cert.md b/en/application-dev/reference/apis/js-apis-cert.md
index bd2479de2399427cab87c95afe13d1d71e4d5956..a8676acc561469bdb3c7ea89d7e28c195db290c2 100644
--- a/en/application-dev/reference/apis/js-apis-cert.md
+++ b/en/application-dev/reference/apis/js-apis-cert.md
@@ -553,12 +553,16 @@ cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
});
```
-### getSerialNumber
+### getSerialNumber(deprecated)
getSerialNumber() : number
Obtains the X.509 certificate serial number.
+> **NOTE**
+>
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [getCertSerialNumber](#getcertserialnumber10).
+
**System capability**: SystemCapability.Security.Cert
**Return value**
@@ -589,6 +593,48 @@ cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
});
```
+### getCertSerialNumber10+
+
+getCertSerialNumber() : bigint
+
+Obtains the X.509 certificate serial number.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| ------ | ------------------ |
+| bigint | X.509 certificate serial number obtained.|
+
+**Error codes**
+
+| ID| Error Message |
+| -------- | ------------------------------------------------- |
+| 19020002 | runtime error. |
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Certificate binary data, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
+ if (error != null) {
+ console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Cert success");
+ let serialNumber = x509Cert.getCertSerialNumber();
+ }
+});
+```
+
### getIssuerName
getIssuerName() : DataBlob
diff --git a/en/application-dev/reference/apis/js-apis-componentUtils.md b/en/application-dev/reference/apis/js-apis-componentUtils.md
deleted file mode 100644
index ed08051817ea9e1bf74c3f2377c507f597aacb9e..0000000000000000000000000000000000000000
--- a/en/application-dev/reference/apis/js-apis-componentUtils.md
+++ /dev/null
@@ -1,210 +0,0 @@
-# @ohos.componentUtils (componentUtils)
-
-The **componentUtils** module provides API for obtaining the coordinates and size of the drawing area of a component.
-
-> **NOTE**
->
-> The APIs of this module are supported since API version 10. Updates will be marked with a superscript to indicate their earliest API version.
->
-> The functionality of this module depends on UI context. This means that the APIs of this module cannot be used where the UI context is unclear. For details, see [UIContext](./js-apis-arkui-UIContext.md#uicontext).
->
-> Since API version 10, you can use the [getComponentUtils](./js-apis-arkui-UIContext.md#getcomponentutils) API in **UIContext** to obtain the **ComponentUtils** object associated with the current UI context. For this API to work correctly, call it after the notification indicating completion of component layout is received through [@ohos.arkui.inspector (layout callback)](js-apis-arkui-inspector.md).
-
-## Modules to Import
-
-```js
-import componentUtils from '@ohos.componentUtils'
-```
-## componentUtils.getRectangleById
-
-getRectangleById(id: string): ComponentInfo
-
-Obtains a **ComponentInfo** object based on the component ID.
-
-**System capability**: SystemCapability.ArkUI.ArkUI.Full
-
-**Parameters**
-
-| Name| Type | Mandatory| Description |
-| ------ | ------ | ---- | ---------- |
-| id | string | Yes | Component ID.|
-
-**Return value**
-
-| Type | Description |
-| ------ | ---------- |
-| [ComponentInfo](#componentinfo) | **ComponentInfo** object, which provides the size, position, translation, scaling, rotation, and affine matrix information of the component.|
-
-**Example**
-
-```js
-let modePosition = componentUtils.getRectangleById("onClick");
-```
-
-## ComponentInfo
-
-| Name | Type | Description |
-| ---------------|------------ | -----------------------------|
-| size | [Size](#size) | Component size. |
-| localOffset | [Offset](#offset) | Offset of the component relative to the parent component. |
-| windowOffset | [Offset](#offset) | Offset of the component relative to the window. |
-| screenOffset | [Offset](#offset) | Offset of the component relative to the screen. |
-| translate | [TranslateResult](#translateresult) | Translation of the component. |
-| scale | [ScaleResult](#scaleresult) | Scaling of the component. |
-| rotate | [RotateResult](#rotateresult) | Rotation of the component. |
-| transform | [Matrix4Result](#matrix4result) | Affine matrix of the component, which is a 4x4 matrix object created based on the input parameter. |
-
-### Size
-
-| Name | Type| Description |
-| -------- | ---- | ----------------------------------|
-| width | number | Component width. |
-| height | number | Component height. |
-
-### Offset
-
-| Name | Type| Description |
-| --------| ---- | -----------------------------------|
-| x | number | X coordinate. |
-| y | number | Y coordinate. |
-
-### TranslateResult
-
-| Name | Type| Description |
-| --------| ---- | -----------------------------------|
-| x | number | Translation distance along the x-axis. |
-| y | number | Translation distance along the y-axis. |
-| z | number | Translation distance along the z-axis. |
-
-### ScaleResult
-
-| Name | Type| Description |
-| --------| ---- | -----------------------------------|
-| x | number | Scale factor along the x-axis. |
-| y | number | Scale factor along the y-axis. |
-| z | number | Scale factor along the z-axis. |
-| centerX | number | X coordinate of the center point. |
-| centerY | number | Y coordinate of the center point. |
-
-### RotateResult
-
-| Name | Type| Description |
-| --------| ---- | -----------------------------------|
-| x | number | X coordinate of the rotation vector. |
-| y | number | Y coordinate of the rotation vector. |
-| z | number | Z coordinate of the rotation vector. |
-| angle | number | Rotation angle. |
-| centerX | number | X coordinate of the center point. |
-| centerY | number | Y coordinate of the center point. |
-
-### Matrix4Result
-
-| Name | Type| Description |
-| --------| ---- | -----------------------------------|
-| number | number | Scale factor along the x-axis. Defaults to **1** for the identity matrix. |
-| number | number | The second value, which is affected by the rotation of the x, y, and z axes.|
-| number | number | The third value, which is affected by the rotation of the x, y, and z axes.|
-| number | number | Meaningless value. |
-| number | number | The fifth value, which is affected by the rotation of the x, y, and z axes.|
-| number | number | Scale factor along the y-axis. Defaults to **1** for the identity matrix. |
-| number | number | The seventh value, which is affected by the rotation of the x, y, and z axes.|
-| number | number | Meaningless value. |
-| number | number | The ninth value, which is affected by the rotation of the x, y, and z axes.|
-| number | number | The tenth value, which is affected by the rotation of the x, y, and z axes.|
-| number | number | Scale factor along the z-axis. Defaults to **1** for the identity matrix. |
-| number | number | Meaningless value. |
-| number | number | Translation distance along the x-axis. Defaults to **0** for the identity matrix. |
-| number | number | Translation distance along the y-axis. Defaults to **0** for the identity matrix.|
-| number | number | Translation distance along the z-axis. Defaults to **0** for the identity matrix.|
-| number | number | Valid in homogeneous coordinates, presenting the perspective projection effect. |
-
-**Example**
-
- ```js
-import matrix4 from '@ohos.matrix4';
-import componentUtils from '@ohos.componentUtils';
-
-@Entry
-@Component
-struct Utils{
- private getComponentRect(key) {
- console.info("Mode Key: " + key);
- let modePosition = componentUtils.getRectangleById(key);
-
- let localOffsetWidth = modePosition.size.width;
- let localOffsetHeight = modePosition.size.height;
- let localOffsetX = modePosition.localOffset.x;
- let localOffsetY = modePosition.localOffset.y;
-
- let windowOffsetX = modePosition.windowOffset.x;
- let windowOffsetY = modePosition.windowOffset.y;
-
- let screenOffsetX = modePosition.screenOffset.x;
- let screenOffsetY = modePosition.screenOffset.y;
-
- let translateX = modePosition.translate.x;
- let translateY = modePosition.translate.y;
- let translateZ = modePosition.translate.z;
-
- let scaleX = modePosition.scale.x;
- let scaleY = modePosition.scale.y;
- let scaleZ = modePosition.scale.z;
- let scaleCenterX = modePosition.scale.centerX;
- let scaleCenterY = modePosition.scale.centerY;
-
- let rotateX = modePosition.rotate.x;
- let rotateY = modePosition.rotate.y;
- let rotateZ = modePosition.rotate.z;
- let rotateCenterX = modePosition.rotate.centerX;
- let rotateCenterY = modePosition.rotate.centerY;
- let rotateAngle = modePosition.rotate.angle;
-
- let Matrix4_1 = modePosition.transform[0];
- let Matrix4_2 = modePosition.transform[1];
- let Matrix4_3 = modePosition.transform[2];
- let Matrix4_4 = modePosition.transform[3];
- let Matrix4_5 = modePosition.transform[4];
- let Matrix4_6 = modePosition.transform[5];
- let Matrix4_7 = modePosition.transform[6];
- let Matrix4_8 = modePosition.transform[7];
- let Matrix4_9 = modePosition.transform[8];
- let Matrix4_10 = modePosition.transform[9];
- let Matrix4_11 = modePosition.transform[10];
- let Matrix4_12 = modePosition.transform[11];
- let Matrix4_13 = modePosition.transform[12];
- let Matrix4_14 = modePosition.transform[13];
- let Matrix4_15 = modePosition.transform[14];
- let Matrix4_16 = modePosition.transform[15];
- console.info("[getRectangleById] current component obj is: " + modePosition );
- }
- @State x: number = 120;
- @State y: number = 10;
- @State z: number = 100;
- private matrix1 = matrix4.identity().translate({ x: this.x, y: this.y, z: this.z });
- build() {
- Column() {
- Image($r("app.media.icon"))
- .transform(this.matrix1)
- .translate({ x: 100, y: 10, z: 50})
- .scale({ x: 2, y: 0.5, z: 1 })
- .rotate({
- x: 1,
- y: 1,
- z: 1,
- centerX: '50%',
- centerY: '50%',
- angle: 300
- })
- .width("40%")
- .height(100)
- .key("image_01")
- Button() {
- Text('getRectangleById').fontSize(40).fontWeight(FontWeight.Bold);
- }.margin({ top: 20 })
- .onClick(() => {
- this.getComponentRect("image_01");
- }).id('onClick');
- }
- }
-}
- ```
diff --git a/en/application-dev/reference/apis/js-apis-curve.md b/en/application-dev/reference/apis/js-apis-curve.md
index 235f7014246488fcc9a4b6d936a4e5bf16faf52e..ffc902f8eda9f2a5d5d0c55a4f6b6ceeabc1c031 100644
--- a/en/application-dev/reference/apis/js-apis-curve.md
+++ b/en/application-dev/reference/apis/js-apis-curve.md
@@ -78,7 +78,7 @@ Creates a step curve.
| Name| Type | Mandatory| Description |
| ------ | ------- | ----| ------------------------------------------------------------ |
-| count | number | Yes | Number of steps. The value must be a positive integer. Value range: [0, +∞) **NOTE** A value less than 0 evaluates to the value **0**.|
+| count | number | Yes | Number of steps. The value must be a positive integer. Value range: [1, +∞) **NOTE** A value less than 1 evaluates to the value **1**.|
| end | boolean | Yes | Whether jumping occurs when the interpolation ends. - **true**: Jumping occurs when the interpolation ends. - **false**: Jumping occurs when the interpolation starts.|
**Return value**
@@ -174,7 +174,7 @@ Creates a spring animation curve. If multiple spring animations are applied to t
| Name | Type | Mandatory | Description |
| --------- | ------ | ---- | ----- |
| response | number | No | Duration of one complete oscillation. Default value: **0.55** Unit: second Value range: [0, +∞) **NOTE** A value less than 0 evaluates to the default value **0.55**.|
-| dampingFraction | number | No | Damping coefficient. **0**: undamped. In this case, the spring oscillates forever. > 0 and < 1: underdamped. In this case, the spring overshoots the equilibrium position. **1**: critically damped. > 1: overdamped. In this case, the spring approaches equilibrium gradually. Default value: **0.825** Unit: second Value range: [0, +∞) **NOTE** A value less than 0 evaluates to the default value **0.55**.|
+| dampingFraction | number | No | Damping coefficient. **0**: undamped. In this case, the spring oscillates forever. > 0 and < 1: underdamped. In this case, the spring overshoots the equilibrium position. **1**: critically damped. > 1: overdamped. In this case, the spring approaches equilibrium gradually. Default value: **0.825** Unit: second Value range: [0, +∞) **NOTE** A value less than 0 evaluates to the default value **0.825**.|
| overlapDuration | number | No | Duration for animations to overlap, in seconds. When animations overlap, the **response** values of these animations will transit smoothly over this duration if they are different. Default value: **0** Unit: second Value range: [0, +∞) **NOTE** A value less than 0 evaluates to the default value **0**. The spring animation curve is physics-based. Its duration depends on the **springMotion** parameters and the previous velocity, rather than the **duration** parameter in [animation](../arkui-ts/ts-animatorproperty.md) or [animateTo](../arkui-ts/ts-explicit-animation.md). The time cannot be normalized. Therefore, the interpolation cannot be obtained using the **interpolate** function of the curve.|
@@ -209,7 +209,7 @@ Creates a responsive spring animation curve. It is a special case of [springMoti
| --------- | ------ | ---- | ----- |
| response | number | No | See **response** in **springMotion**. Default value: **0.15** Unit: second Value range: [0, +∞) **NOTE** A value less than 0 evaluates to the default value **0.15**.|
| dampingFraction | number | No | See **dampingFraction** in **springMotion**. Default value: **0.86** Unit: second Value range: [0, +∞) **NOTE** A value less than 0 evaluates to the default value **0.86**.|
-| overlapDuration | number | No | See **overlapDuration** in **springMotion**. Default value: **0.25** Unit: second Value range: [0, +∞) **NOTE** A value less than 0 evaluates to the default value **0.25**. To apply custom settings for a spring animation, you are advised to use **springMotion**. When using **responsiveSpringMotion**, you are advised to retain the default settings. The duration of the responsive spring animation depends on the **responsiveSpringMotion** parameters and the previous velocity, rather than the **duration** parameter in [animation](../arkui-ts/ts-animatorproperty.md) or [animateTo](../arkui-ts/ts-explicit-animation.md). In addition, the interpolation cannot be obtained using the **interpolate** function of the curve. |
+| overlapDuration | number | No | See **overlapDuration** in **springMotion**. Default value: **0.25** Unit: second Value range: [0, +∞) **NOTE** A value less than 0 evaluates to the default value **0.25**. To apply custom settings for a spring animation, you are advised to use **springMotion**. When using **responsiveSpringMotion**, you are advised to retain the default settings. The duration of the responsive spring animation depends on the **responsiveSpringMotion** parameters and the previous velocity, rather than the **duration** parameter in [animation](../arkui-ts/ts-animatorproperty.md) or [animateTo](../arkui-ts/ts-explicit-animation.md). In addition, the interpolation cannot be obtained using the **interpolate** function of the curve.|
**Return value**
@@ -237,16 +237,16 @@ Creates an interpolating spring curve animated from 0 to 1. The actual animation
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------ | ---- | ----- |
-| velocity | number | Yes | Initial velocity. It is applied by external factors to the spring animation, designed to help ensure the smooth transition from the previous motion state. The velocity is the normalized velocity, and its value is equal to the actual velocity at the beginning of the animation divided by the animation attribute change value.|
-| mass | number | Yes | Mass, which influences the inertia in the spring system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position.|
-| stiffness | number | Yes | Stiffness. It is the degree to which an object deforms by resisting the force applied. In an elastic system, the greater the stiffness, the stronger the ability to resist deformation, and the faster the speed of restoring to the equilibrium position.|
-| damping | number | Yes | Damping. It is a pure number and has no real physical meaning. It is used to describe the oscillation and attenuation of the system after being disturbed. The larger the damping, the smaller the number of oscillations of elastic motion, and the smaller the oscillation amplitude.|
+| velocity | number | Yes | Initial velocity. It is applied by external factors to the spring animation, designed to help ensure the smooth transition from the previous motion state. The velocity is the normalized velocity, and its value is equal to the actual velocity at the beginning of the animation divided by the animation attribute change value. Value range: (-∞, +∞)|
+| mass | number | Yes | Mass, which influences the inertia in the spring system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position. Value range: [0, +∞) **NOTE** A value less than 0 evaluates to the value **1**.|
+| stiffness | number | Yes | Stiffness. It is the degree to which an object deforms by resisting the force applied. In an elastic system, the greater the stiffness, the stronger the ability to resist deformation, and the faster the speed of restoring to the equilibrium position. Value range: [0, +∞) **NOTE** A value less than 0 evaluates to the value **1**.|
+| damping | number | Yes | Damping. It is a pure number and has no real physical meaning. It is used to describe the oscillation and attenuation of the system after being disturbed. The larger the damping, the smaller the number of oscillations of elastic motion, and the smaller the oscillation amplitude. Value range: [0, +∞) **NOTE** A value less than 0 evaluates to the value **1**.|
**Return value**
| Type | Description |
| ---------------------------------- | ---------------- |
-| [ICurve](#icurve)| Interpolation curve.|
+| [ICurve](#icurve)| Curve. **NOTE** The spring animation curve is physics-based. Its duration depends on the** interpolatingSpring** parameters, rather than the **duration** parameter in [animation](../arkui-ts/ts-animatorproperty.md) or [animateTo](../arkui-ts/ts-explicit-animation.md). The time cannot be normalized. Therefore, the interpolation cannot be obtained using the [interpolate](#interpolate9) function of the curve.|
**Example**
diff --git a/en/application-dev/reference/apis/js-apis-data-cloudData.md b/en/application-dev/reference/apis/js-apis-data-cloudData.md
index 9be6e9f345455b73e01104101981d40e50c4b846..ea2aeae63b5e11dbfebc19b969724c493a93310f 100644
--- a/en/application-dev/reference/apis/js-apis-data-cloudData.md
+++ b/en/application-dev/reference/apis/js-apis-data-cloudData.md
@@ -16,7 +16,7 @@ This module provides the following common functions:
import cloudData from '@ohos.data.cloudData';
```
-## Action
+## ClearAction
Enumerates the actions to take to clear the downloaded cloud data locally.
@@ -347,9 +347,9 @@ try {
}
```
-### clean
+### clear
-static clean(accountId: string, appActions: {[bundleName: string]: Action}, callback: AsyncCallback<void>):void
+static clear(accountId: string, appActions: {[bundleName: string]: ClearAction}, callback: AsyncCallback<void>):void
Clears the cloud data locally. This API uses an asynchronous callback to return the result.
@@ -361,26 +361,26 @@ Clears the cloud data locally. This API uses an asynchronous callback to return
**Parameters**
-| Name | Type | Mandatory| Description |
-| ---------- | ----------------------------------------- | ---- | -------------------------------- |
-| accountId | string | Yes | ID of the cloud account. |
-| appActions | {[bundleName: string]: [Action](#action)} | Yes | Information about the application whose data is to be cleared and the action to take.|
-| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. |
+| Name | Type | Mandatory| Description |
+| ---------- | --------------------------------------------------- | ---- | -------------------------------- |
+| accountId | string | Yes | ID of the cloud account. |
+| appActions | {[bundleName: string]: [ClearAction](#clearaction)} | Yes | Information about the application whose data is to be cleared and the action to take.|
+| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. |
**Example**
```js
-let action = cloudData.Action;
+let action = cloudData.ClearAction;
let account = "test_id";
let bundleName1 = "test_bundleName1";
let bundleName2 = "test_bundleName2";
let appActions = { [bundleName1]: action.CLEAR_CLOUD_INFO, [bundleName2]: action.CLEAR_CLOUD_DATA_AND_INFO };
try {
- cloudData.Config.clean(account, appActions, function (err) {
+ cloudData.Config.clear(account, appActions, function (err) {
if (err === undefined) {
- console.info('Succeeding in cleaning cloud data');
+ console.info('Succeeding in clearing cloud data');
} else {
- console.error(`Failed to clean cloud data. Code: ${err.code}, message: ${err.message}`);
+ console.error(`Failed to clear cloud data. Code: ${err.code}, message: ${err.message}`);
}
});
} catch (error) {
@@ -388,9 +388,9 @@ try {
}
```
-### clean
+### clear
-static clean(accountId: string, appActions: {[bundleName: string]: Action}): Promise<void>
+static clear(accountId: string, appActions: {[bundleName: string]: ClearAction}): Promise<void>
Clears the cloud data locally. This API uses a promise to return the result.
@@ -402,10 +402,10 @@ Clears the cloud data locally. This API uses a promise to return the result.
**Parameters**
-| Name | Type | Mandatory| Description |
-| ---------- | ----------------------------------------- | ---- | -------------------------------- |
-| accountId | string | Yes | ID of the cloud account. |
-| appActions | {[bundleName: string]: [Action](#action)} | Yes | Information about the application whose data is to be cleared and the action to take.|
+| Name | Type | Mandatory| Description |
+| ---------- | --------------------------------------------------- | ---- | -------------------------------- |
+| accountId | string | Yes | ID of the cloud account. |
+| appActions | {[bundleName: string]: [ClearAction](#clearaction)} | Yes | Information about the application whose data is to be cleared and the action to take.|
**Return value**
@@ -416,16 +416,16 @@ Clears the cloud data locally. This API uses a promise to return the result.
**Example**
```js
-let action = cloudData.Action;
+let action = cloudData.ClearAction;
let account = "test_id";
let bundleName1 = "test_bundleName1";
let bundleName2 = "test_bundleName2";
let appActions = { [bundleName1]: action.CLEAR_CLOUD_INFO, [bundleName2]: action.CLEAR_CLOUD_DATA_AND_INFO };
try {
- cloudData.Config.clean(account, appActions).then(() => {
- console.info('Succeeding in cleaning cloud data');
+ cloudData.Config.clear(account, appActions).then(() => {
+ console.info('Succeeding in clearing cloud data');
}).catch((err) => {
- console.error(`Failed to clean cloud data. Code: ${err.code}, message: ${err.message}`);
+ console.error(`Failed to clear cloud 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-preferences.md b/en/application-dev/reference/apis/js-apis-data-preferences.md
index fb937559c7217c6d0429fb85ea0129d31c733492..a8188ec8afa535a6d0ba5bc3e2bbd0fb32b8458c 100644
--- a/en/application-dev/reference/apis/js-apis-data-preferences.md
+++ b/en/application-dev/reference/apis/js-apis-data-preferences.md
@@ -55,14 +55,14 @@ let preferences = null;
try {
data_preferences.getPreferences(context, 'mystore', function (err, val) {
if (err) {
- console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
- return;
- }
- preferences = val;
- console.info("Obtained the preferences successfully.");
- })
+ console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
+ return;
+ }
+ preferences = val;
+ console.info("Succeeded in getting preferences.");
+ })
} catch (err) {
- console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
}
```
@@ -78,14 +78,14 @@ class EntryAbility extends UIAbility {
try {
data_preferences.getPreferences(this.context, 'mystore', function (err, val) {
if (err) {
- console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
return;
}
preferences = val;
- console.info("Obtained the preferences successfully.");
+ console.info("Succeeded in getting preferences.");
})
} catch (err) {
- console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
}
}
}
@@ -126,12 +126,12 @@ try {
let promise = data_preferences.getPreferences(context, 'mystore');
promise.then((object) => {
preferences = object;
- console.info("Obtained the preferences successfully.");
+ console.info("Succeeded in getting preferences.");
}).catch((err) => {
- console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
- console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
}
```
@@ -148,12 +148,12 @@ class EntryAbility extends UIAbility {
let promise = data_preferences.getPreferences(this.context, 'mystore');
promise.then((object) => {
preferences = object;
- console.info("Obtained the preferences successfully.");
+ console.info("Succeeded in getting preferences.");
}).catch((err) => {
- console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
- console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
}
}
}
@@ -195,16 +195,16 @@ let context = featureAbility.getContext();
let preferences = null;
try {
- data_preferences.getPreferences(context, {name: 'mystore'}, function (err, val) {
+ data_preferences.getPreferences(context, { name: 'mystore' }, function (err, val) {
if (err) {
- console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
- return;
- }
- preferences = val;
- console.info("Obtained the preferences successfully.");
- })
+ console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
+ return;
+ }
+ preferences = val;
+ console.info("Succeeded in getting preferences.");
+ })
} catch (err) {
- console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
}
```
@@ -219,16 +219,16 @@ let preferences = null;
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
try {
- data_preferences.getPreferences(this.context, {name: 'mystore', dataGroupId:'myId'}, function (err, val) {
+ data_preferences.getPreferences(this.context, { name: 'mystore', dataGroupId:'myId' }, function (err, val) {
if (err) {
- console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
return;
}
preferences = val;
- console.info("Obtained the preferences successfully.");
+ console.info("Succeeded in getting preferences.");
})
} catch (err) {
- console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
}
}
}
@@ -275,15 +275,15 @@ let context = featureAbility.getContext();
let preferences = null;
try {
- let promise = data_preferences.getPreferences(context, {name: 'mystore'});
+ let promise = data_preferences.getPreferences(context, { name: 'mystore' });
promise.then((object) => {
preferences = object;
- console.info("Obtained the preferences successfully.");
+ console.info("Succeeded in getting preferences.");
}).catch((err) => {
- console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
- console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
}
```
@@ -297,20 +297,83 @@ let preferences = null;
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
try {
- let promise = data_preferences.getPreferences(this.context, {name: 'mystore', dataGroupId:'myId'});
+ let promise = data_preferences.getPreferences(this.context, { name: 'mystore', dataGroupId:'myId' });
promise.then((object) => {
preferences = object;
- console.info("Obtained the preferences successfully.");
+ console.info("Succeeded in getting preferences.");
}).catch((err) => {
- console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
- console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
}
}
}
```
+## data_preferences.getPreferencesSync10+
+
+getPreferencesSync(context: Context, options: Options): Preferences
+
+Obtains the **Preferences** instance. This API is a synchronous interface.
+
+**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
+
+**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).|
+| options | [Options](#options10) | Yes | Configuration options of the **Preferences** instance. |
+
+**Return value**
+
+| Type | Description |
+| --------------------------- | --------------------- |
+| [Preferences](#preferences) | **Preferences** instance obtained.|
+
+**Error codes**
+
+For details about the error codes, see [User Preference Error Codes](../errorcodes/errorcode-preferences.md).
+
+| ID| Error Message |
+| -------- | ------------------------------- |
+| 15501001 | Only supported in stage mode. |
+| 15501002 | The data group id is not valid. |
+
+**Example**
+
+FA model:
+
+```js
+// Obtain the context.
+import featureAbility from '@ohos.ability.featureAbility';
+let context = featureAbility.getContext();
+let preferences = null;
+
+try {
+ preferences = data_preferences.getPreferencesSync(context, { name: 'mystore' });
+} catch(err) {
+ console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
+}
+```
+
+Stage model:
+
+```ts
+import UIAbility from '@ohos.app.ability.UIAbility';
+let preferences = null;
+
+class EntryAbility extends UIAbility {
+ onWindowStageCreate(windowStage) {
+ try {
+ preferences = data_preferences.getPreferencesSync(this.context, { name: 'mystore', dataGroupId:'myId' });
+ } catch(err) {
+ console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
+ }
+ }
+}
+```
## data_preferences.deletePreferences
@@ -350,13 +413,13 @@ let context = featureAbility.getContext();
try {
data_preferences.deletePreferences(context, 'mystore', function (err) {
if (err) {
- console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
return;
}
- console.info("Deleted the preferences successfully." );
+ console.info("Succeeded in deleting preferences." );
})
} catch (err) {
- console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
}
```
@@ -370,13 +433,13 @@ class EntryAbility extends UIAbility {
try {
data_preferences.deletePreferences(this.context, 'mystore', function (err) {
if (err) {
- console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
return;
}
- console.info("Deleted the preferences successfully." );
+ console.info("Succeeded in deleting preferences." );
})
} catch (err) {
- console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
}
}
}
@@ -425,12 +488,12 @@ let context = featureAbility.getContext();
try {
let promise = data_preferences.deletePreferences(context, 'mystore');
promise.then(() => {
- console.info("Deleted the preferences successfully.");
+ console.info("Succeeded in deleting preferences.");
}).catch((err) => {
- console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
- console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
}
```
@@ -444,12 +507,12 @@ class EntryAbility extends UIAbility {
try{
let promise = data_preferences.deletePreferences(this.context, 'mystore');
promise.then(() => {
- console.info("Deleted the preferences successfully.");
+ console.info("Succeeded in deleting preferences.");
}).catch((err) => {
- console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
- console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
}
}
}
@@ -493,15 +556,15 @@ import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
try {
- data_preferences.deletePreferences(context, {name: 'mystore'}, function (err) {
+ data_preferences.deletePreferences(context, { name: 'mystore' }, function (err) {
if (err) {
- console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
return;
}
- console.info("Deleted the preferences successfully." );
+ console.info("Succeeded in deleting preferences." );
})
} catch (err) {
- console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
}
```
@@ -513,15 +576,15 @@ import UIAbility from '@ohos.app.ability.UIAbility';
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
try {
- data_preferences.deletePreferences(this.context, {name: 'mystore', dataGroupId:'myId'}, function (err) {
+ data_preferences.deletePreferences(this.context, { name: 'mystore', dataGroupId:'myId' }, function (err) {
if (err) {
- console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
return;
}
- console.info("Deleted the preferences successfully." );
+ console.info("Succeeded in deleting preferences." );
})
} catch (err) {
- console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
}
}
}
@@ -571,14 +634,14 @@ import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
try {
- let promise = data_preferences.deletePreferences(context, {name: 'mystore'});
+ let promise = data_preferences.deletePreferences(context, { name: 'mystore' });
promise.then(() => {
- console.info("Deleted the preferences successfully.");
+ console.info("Succeeded in deleting preferences.");
}).catch((err) => {
- console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
- console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
}
```
@@ -590,14 +653,14 @@ import UIAbility from '@ohos.app.ability.UIAbility';
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
try{
- let promise = data_preferences.deletePreferences(this.context, {name: 'mystore', dataGroupId:'myId'});
+ let promise = data_preferences.deletePreferences(this.context, { name: 'mystore', dataGroupId:'myId' });
promise.then(() => {
- console.info("Deleted the preferences successfully.");
+ console.info("Succeeded in deleting preferences.");
}).catch((err) => {
- console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
- console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
}
}
}
@@ -635,13 +698,13 @@ let context = featureAbility.getContext();
try {
data_preferences.removePreferencesFromCache(context, 'mystore', function (err) {
if (err) {
- console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
return;
}
- console.info("Removed the preferences successfully.");
+ console.info("Succeeded in removing preferences.");
})
} catch (err) {
- console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
}
```
@@ -655,13 +718,13 @@ class EntryAbility extends UIAbility {
try {
data_preferences.removePreferencesFromCache(this.context, 'mystore', function (err) {
if (err) {
- console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
return;
}
- console.info("Removed the preferences successfully.");
+ console.info("Succeeded in removing preferences.");
})
} catch (err) {
- console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
}
}
}
@@ -702,13 +765,13 @@ import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
try {
let promise = data_preferences.removePreferencesFromCache(context, 'mystore');
- promise.then(() => {
- console.info("Removed the preferences successfully.");
+ promise.then(() => {
+ console.info("Succeeded in removing preferences.");
}).catch((err) => {
- console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
- console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
}
```
@@ -722,12 +785,12 @@ class EntryAbility extends UIAbility {
try {
let promise = data_preferences.removePreferencesFromCache(this.context, 'mystore');
promise.then(() => {
- console.info("Removed the preferences successfully.");
+ console.info("Succeeded in removing preferences.");
}).catch((err) => {
- console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
- console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
}
}
}
@@ -737,7 +800,7 @@ class EntryAbility extends UIAbility {
removePreferencesFromCacheSync(context: Context, name: string): void
-Synchronously removes a **Preferences** instance from the cache.
+Removes a **Preferences** instance from the cache. This API returns the result synchronously.
After an application calls [getPreferences](#data_preferencesgetpreferences) for the first time to obtain a **Preferences** instance, the obtained **Preferences** instance is cached. When the application calls [getPreferences](#data_preferencesgetpreferences) again, the **Preferences** instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling **getPreferences** again will read data from the persistent file and create a new **Preferences** instance.
@@ -763,7 +826,7 @@ let context = featureAbility.getContext();
try {
data_preferences.removePreferencesFromCacheSync(context, 'mystore');
} catch(err) {
- console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
}
```
@@ -777,7 +840,7 @@ class EntryAbility extends UIAbility {
try {
data_preferences.removePreferencesFromCacheSync(this.context, 'mystore');
} catch(err) {
- console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
}
}
}
@@ -821,15 +884,15 @@ FA model:
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
try {
- data_preferences.removePreferencesFromCache(context, {name: 'mystore'}, function (err) {
+ data_preferences.removePreferencesFromCache(context, { name: 'mystore' }, function (err) {
if (err) {
- console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
return;
}
- console.info("Removed the preferences successfully.");
+ console.info("Succeeded in removing preferences.");
})
} catch (err) {
- console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
}
```
@@ -841,15 +904,15 @@ import UIAbility from '@ohos.app.ability.UIAbility';
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
try {
- data_preferences.removePreferencesFromCache(this.context, {name: 'mystore', dataGroupId:'myId'}, function (err) {
+ data_preferences.removePreferencesFromCache(this.context, { name: 'mystore', dataGroupId:'myId' }, function (err) {
if (err) {
- console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
return;
}
- console.info("Removed the preferences successfully.");
+ console.info("Succeeded in removing preferences.");
})
} catch (err) {
- console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
}
}
}
@@ -898,14 +961,14 @@ FA model:
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
try {
- let promise = data_preferences.removePreferencesFromCache(context, {name: 'mystore'});
- promise.then(() => {
- console.info("Removed the preferences successfully.");
+ let promise = data_preferences.removePreferencesFromCache(context, { name: 'mystore' });
+ promise.then(() => {
+ console.info("Succeeded in removing preferences.");
}).catch((err) => {
- console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
- console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
}
```
@@ -917,14 +980,73 @@ import UIAbility from '@ohos.app.ability.UIAbility';
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
try {
- let promise = data_preferences.removePreferencesFromCache(this.context, {name: 'mystore', dataGroupId:'myId'});
+ let promise = data_preferences.removePreferencesFromCache(this.context, { name: 'mystore', dataGroupId:'myId' });
promise.then(() => {
- console.info("Removed the preferences successfully.");
+ console.info("Succeeded in removing preferences.");
}).catch((err) => {
- console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
- console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
+ }
+ }
+}
+```
+
+## data_preferences.removePreferencesFromCacheSync10+
+
+removePreferencesFromCacheSync(context: Context, options: Options):void
+
+Removes a **Preferences** instance from the cache. This API returns the result synchronously.
+
+After an application calls [getPreferences](#data_preferencesgetpreferences) for the first time to obtain a **Preferences** instance, the obtained **Preferences** instance is cached. When the application calls [getPreferences](#data_preferencesgetpreferences) again, the **Preferences** instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling **getPreferences** again will read data from the persistent file and create a new **Preferences** instance.
+
+After the **Preferences** instance is removed, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the removed **Preferences** instance to null. The system will reclaim the removed **Preferences** instances in a unified manner.
+
+**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
+
+**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).|
+| options | [Options](#options10) | Yes | Configuration options of the **Preferences** instance. |
+
+**Error codes**
+
+For details about the error codes, see [User Preference Error Codes](../errorcodes/errorcode-preferences.md).
+
+| ID| Error Message |
+| -------- | ------------------------------- |
+| 15501001 | Only supported in stage mode. |
+| 15501002 | The data group id is not valid. |
+
+**Example**
+
+FA model:
+
+```js
+// Obtain the context.
+import featureAbility from '@ohos.ability.featureAbility';
+let context = featureAbility.getContext();
+try {
+ data_preferences.removePreferencesFromCacheSync(context, { name: 'mystore' });
+} catch(err) {
+ console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
+}
+```
+
+Stage model:
+
+```ts
+import UIAbility from '@ohos.app.ability.UIAbility';
+
+class EntryAbility extends UIAbility {
+ onWindowStageCreate(windowStage) {
+ try {
+ data_preferences.removePreferencesFromCacheSync(this.context, { name: 'mystore', dataGroupId:'myId' });
+ } catch(err) {
+ console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
}
}
}
@@ -970,13 +1092,13 @@ Obtains the value corresponding to the specified key from the cached **Preferenc
try {
preferences.get('startup', 'default', function (err, val) {
if (err) {
- console.info("Failed to obtain value of 'startup'. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message);
return;
}
console.info("Obtained the value of 'startup' successfully. val: " + val);
})
} catch (err) {
- console.info("Failed to obtain value of 'startup'. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message);
}
```
@@ -1010,10 +1132,10 @@ try {
promise.then((data) => {
console.info("Got the value of 'startup'. Data: " + data);
}).catch((err) => {
- console.info("Failed to obtain value of 'startup'. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
- console.info("Failed to obtain value of 'startup'. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message);
}
```
@@ -1021,7 +1143,7 @@ try {
getSync(key: string, defValue: ValueType): ValueType
-Synchronously obtains the value corresponding to the specified key from the cached **Preferences** instance. If the value is null or is not of the default value type, **defValue** is returned.
+Obtains the value corresponding to the specified key from the cached **Preferences** instance. This API returns the result synchronously. If the value is null or is not of the default value type, **defValue** is returned.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
@@ -1043,9 +1165,9 @@ Synchronously obtains the value corresponding to the specified key from the cach
```js
try {
let value = preferences.getSync('startup', 'default');
- console.info("Obtained the value of 'startup'. Data: " + value);
+ console.info("Succeeded in getting value of 'startup'. Data: " + value);
} catch(err) {
- console.info("Failed to obtain value of 'startup'. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message);
}
```
@@ -1069,7 +1191,7 @@ Obtains all KV pairs from the cached **Preferences** instance. This API uses an
try {
preferences.getAll(function (err, value) {
if (err) {
- console.info("Failed to obtain all KV pairs. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message);
return;
}
let allKeys = Object.keys(value);
@@ -1077,7 +1199,7 @@ try {
console.info("getAll object = " + JSON.stringify(value));
})
} catch (err) {
- console.info("Failed to obtain all KV pairs. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message);
}
```
@@ -1106,10 +1228,10 @@ try {
console.info('getAll keys = ' + allKeys);
console.info("getAll object = " + JSON.stringify(value));
}).catch((err) => {
- console.info("Failed to obtain all KV pairs. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message);
})
} catch (err) {
- console.info("Failed to obtain all KV pairs. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message);
}
```
@@ -1117,7 +1239,7 @@ try {
getAllSync(): Object
-Obtains all KV pairs from the cached **Preferences** instance synchronously.
+Obtains all KV pairs from the cached **Preferences** instance. This API returns the result synchronously.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
@@ -1136,7 +1258,7 @@ try {
console.info('getAll keys = ' + allKeys);
console.info("getAll object = " + JSON.stringify(value));
} catch (err) {
- console.info("Failed to obtain all KV pairs. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message);
}
```
@@ -1162,13 +1284,13 @@ Writes data to the cached **Preferences** instance. This API uses an asynchronou
try {
preferences.put('startup', 'auto', function (err) {
if (err) {
- console.info("Failed to put the value of 'startup'. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to put value of 'startup'. code =" + err.code + ", message =" + err.message);
return;
}
console.info("Successfully put the value of 'startup'.");
})
} catch (err) {
- console.info("Failed to put the value of 'startup'. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to put value of 'startup'. code =" + err.code + ", message =" + err.message);
}
```
@@ -1202,10 +1324,10 @@ try {
promise.then(() => {
console.info("Successfully put the value of 'startup'.");
}).catch((err) => {
- console.info("Failed to put the value of 'startup'. code =" + err.code +", message =" + err.message);
+ console.error("Failed to put value of 'startup'. code =" + err.code +", message =" + err.message);
})
} catch(err) {
- console.info("Failed to put the value of 'startup'. code =" + err.code +", message =" + err.message);
+ console.error("Failed to put value of 'startup'. code =" + err.code +", message =" + err.message);
}
```
@@ -1214,7 +1336,7 @@ try {
putSync(key: string, value: ValueType): void
-Synchronously writes data to the cached **Preferences** instance. You can use [flush](#flush) to persist the **Preferences** instance.
+Writes data to the cached **Preferences** instance. This API returns the result synchronously. You can use [flush](#flush) to persist the **Preferences** instance.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
@@ -1231,7 +1353,7 @@ Synchronously writes data to the cached **Preferences** instance. You can use [f
try {
preferences.putSync('startup', 'auto');
} catch(err) {
- console.info("Failed to put the value of 'startup'. code =" + err.code +", message =" + err.message);
+ console.error("Failed to put value of 'startup'. code =" + err.code +", message =" + err.message);
}
```
@@ -1257,7 +1379,7 @@ Checks whether the cached **Preferences** instance contains the KV pair of the g
try {
preferences.has('startup', function (err, val) {
if (err) {
- console.info("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
return;
}
if (val) {
@@ -1267,7 +1389,7 @@ try {
}
})
} catch (err) {
- console.info("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
}
```
@@ -1304,10 +1426,10 @@ try {
console.info("The key 'startup' is not contained.");
}
}).catch((err) => {
- console.info("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
- console.info("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
}
```
@@ -1316,7 +1438,7 @@ try {
hasSync(key: string): boolean
-Synchronously checks whether the cached **Preferences** instance contains the KV pair of the given key.
+Checks whether the cached **Preferences** instance contains the KV pair of the given key. This API returns the result synchronously.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
@@ -1343,7 +1465,7 @@ try {
console.info("The key 'startup' is not contained.");
}
} catch(err) {
- console.info("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
}
```
@@ -1369,13 +1491,13 @@ Deletes a KV pair from the cached **Preferences** instance based on the specifie
try {
preferences.delete('startup', function (err) {
if (err) {
- console.info("Failed to delete the key 'startup'. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to delete the key 'startup'. code =" + err.code + ", message =" + err.message);
return;
}
console.info("Deleted the key 'startup'.");
})
} catch (err) {
- console.info("Failed to delete the key 'startup'. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to delete the key 'startup'. code =" + err.code + ", message =" + err.message);
}
```
@@ -1405,13 +1527,13 @@ Deletes a KV pair from the cached **Preferences** instance based on the specifie
```js
try {
let promise = preferences.delete('startup');
- promise.then(() => {
+ promise.then(() => {
console.info("Deleted the key 'startup'.");
}).catch((err) => {
- console.info("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message);
+ console.error("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message);
})
} catch(err) {
- console.info("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message);
+ console.error("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message);
}
```
@@ -1420,7 +1542,7 @@ try {
deleteSync(key: string): void
-Synchronously deletes a KV pair from the cached **Preferences** instance based on the specified key. You can use [flush](#flush) to persist the **Preferences** instance.
+Deletes a KV pair from the cached **Preferences** instance based on the specified key. This API returns the result synchronously. You can use [flush](#flush) to persist the **Preferences** instance.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
@@ -1436,7 +1558,7 @@ Synchronously deletes a KV pair from the cached **Preferences** instance based o
try {
preferences.deleteSync('startup');
} catch(err) {
- console.info("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message);
+ console.error("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message);
}
```
@@ -1461,13 +1583,13 @@ Flushes the data in the cached **Preferences** instance to the persistent file.
try {
preferences.flush(function (err) {
if (err) {
- console.info("Failed to flush data. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to flush. code =" + err.code + ", message =" + err.message);
return;
}
console.info("Successfully flushed data.");
})
} catch (err) {
- console.info("Failed to flush data. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to flush. code =" + err.code + ", message =" + err.message);
}
```
@@ -1494,10 +1616,10 @@ try {
promise.then(() => {
console.info("Successfully flushed data.");
}).catch((err) => {
- console.info("Failed to flush data. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to flush. code =" + err.code + ", message =" + err.message);
})
} catch (err) {
- console.info("Failed to flush data. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to flush. code =" + err.code + ", message =" + err.message);
}
```
@@ -1520,15 +1642,15 @@ Clears all data in the cached **Preferences** instance. This API uses an asynchr
```js
try {
- preferences.clear(function (err) {
+ preferences.clear(function (err) {
if (err) {
- console.info("Failed to clear data. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to clear. code =" + err.code + ", message =" + err.message);
return;
}
console.info("Successfully cleared data.");
})
} catch (err) {
- console.info("Failed to clear data. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to clear. code =" + err.code + ", message =" + err.message);
}
```
@@ -1552,13 +1674,13 @@ Clears all data in the cached **Preferences** instance. This API uses a promise
```js
try {
let promise = preferences.clear();
- promise.then(() => {
- console.info("Successfully cleared data.");
+ promise.then(() => {
+ console.info("Successfully cleared data.");
}).catch((err) => {
- console.info("Failed to clear data. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to clear. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
- console.info("Failed to clear data. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to clear. code =" + err.code + ", message =" + err.message);
}
```
@@ -1567,7 +1689,7 @@ try {
clearSync(): void
-Synchronously clears all data in the cached **Preferences** instance. You can use [flush](#flush) to persist the **Preferences** instance.
+Clears all data in the cached **Preferences** instance. This API returns the result synchronously. You can use [flush](#flush) to persist the **Preferences** instance.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
@@ -1577,7 +1699,7 @@ Synchronously clears all data in the cached **Preferences** instance. You can us
try {
preferences.clearSync();
} catch(err) {
- console.info("Failed to clear data. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to clear. code =" + err.code + ", message =" + err.message);
}
```
@@ -1601,33 +1723,33 @@ Subscribes to data changes. A callback will be triggered to return the new value
```js
try {
- data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) {
- if (err) {
- console.info("Failed to obtain the preferences.");
- return;
- }
- let observer = function (key) {
- console.info("The key " + key + " changed.");
- }
- preferences.on('change', observer);
- preferences.put('startup', 'manual', function (err) {
- if (err) {
- console.info("Failed to put the value of 'startup'. Cause: " + err);
- return;
- }
- console.info("Successfully put the value of 'startup'.");
-
- preferences.flush(function (err) {
- if (err) {
- console.info("Failed to flush data. Cause: " + err);
- return;
- }
- console.info("Successfully flushed data.");
- })
- })
- })
+ data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) {
+ if (err) {
+ console.error("Failed to get preferences.");
+ return;
+ }
+ let observer = function (key) {
+ console.info("The key " + key + " changed.");
+ }
+ preferences.on('change', observer);
+ preferences.put('startup', 'manual', function (err) {
+ if (err) {
+ console.error("Failed to put the value of 'startup'. Cause: " + err);
+ return;
+ }
+ console.info("Successfully put the value of 'startup'.");
+
+ preferences.flush(function (err) {
+ if (err) {
+ console.error("Failed to flush. Cause: " + err);
+ return;
+ }
+ console.info("Successfully flushed data.");
+ })
+ })
+ })
} catch (err) {
- console.info("Failed to flush data. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to flush. code =" + err.code + ", message =" + err.message);
}
```
@@ -1660,86 +1782,85 @@ For details about the error codes, see [User Preference Error Codes](../errorcod
```js
try {
- data_preferences.getPreferences(this.context, {name: 'mystore', dataGroupId:'myId'}, function (err, preferences) {
- if (err) {
- console.info("Failed to obtain the preferences.");
- return;
- }
- let observer = function (key) {
- console.info("The key " + key + " changed.");
- }
- preferences.on('multiProcessChange', observer);
- preferences.put('startup', 'manual', function (err) {
- if (err) {
- console.info("Failed to put the value of 'startup'. Cause: " + err);
- return;
- }
- console.info("Successfully put the value of 'startup'.");
-
- preferences.flush(function (err) {
- if (err) {
- console.info("Failed to flush data. Cause: " + err);
- return;
- }
- console.info("Successfully flushed data.");
- })
- })
- })
+ data_preferences.getPreferences(this.context, { name: 'mystore', dataGroupId:'myId' }, function (err, preferences) {
+ if (err) {
+ console.error("Failed to get preferences.");
+ return;
+ }
+ let observer = function (key) {
+ console.info("The key " + key + " changed.");
+ }
+ preferences.on('multiProcessChange', observer);
+ preferences.put('startup', 'manual', function (err) {
+ if (err) {
+ console.error("Failed to put the value of 'startup'. Cause: " + err);
+ return;
+ }
+ console.info("Successfully put the value of 'startup'.");
+
+ preferences.flush(function (err) {
+ if (err) {
+ console.error("Failed to flush. Cause: " + err);
+ return;
+ }
+ console.info("Successfully flushed data.");
+ })
+ })
+ })
} catch (err) {
- console.info("Failed to flush data. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to flush. code =" + err.code + ", message =" + err.message);
}
```
**Example 2**
```js
-let preferences = null;
try {
data_preferences.getPreferences(this.context, { name: 'mystore' }, function (err, val) {
if (err) {
- console.info("Failed to obtain the preferences.");
+ console.error("Failed to get preferences.");
return;
}
preferences = val;
let observer = function (key) {
console.info("The key " + key + " changed.");
try {
- data_preferences.removePreferencesFromCache(context, { name: 'mystore' }, function (err) {
+ data_preferences.removePreferencesFromCache(this.context, { name: 'mystore' }, function (err) {
if (err) {
- console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
return;
}
preferences = null;
- console.info("Removed the preferences successfully.");
+ console.info("Succeeded in removing preferences.");
})
} catch (err) {
- console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
}
try {
- data_preferences.getPreferences(context, { name: 'mystore' }, function (err, val) {
+ data_preferences.getPreferences(this.context, { name: 'mystore' }, function (err, val) {
if (err) {
- console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
return;
}
preferences = val;
- console.info("Obtained the preferences successfully.");
+ console.info("Succeeded in getting preferences.");
})
} catch (err) {
- console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
}
}
preferences.on('multiProcessChange', observer);
preferences.put('startup', 'manual', function (err) {
if (err) {
- console.info("Failed to put the value of 'startup'. Cause: " + err);
+ console.error("Failed to put the value of 'startup'. Cause: " + err);
return;
}
console.info("Successfully put the value of 'startup'.");
preferences.flush(function (err) {
if (err) {
- console.info("Failed to flush data. Cause: " + err);
+ console.error("Failed to flush. Cause: " + err);
return;
}
console.info("Successfully flushed data.");
@@ -1747,7 +1868,7 @@ try {
})
})
} catch (err) {
- console.info("Failed to flush data. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to flush. code =" + err.code + ", message =" + err.message);
}
```
@@ -1772,7 +1893,7 @@ Unsubscribes from data changes.
try {
data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) {
if (err) {
- console.info("Failed to obtain the preferences.");
+ console.error("Failed to get preferences.");
return;
}
let observer = function (key) {
@@ -1781,14 +1902,14 @@ try {
preferences.on('change', observer);
preferences.put('startup', 'auto', function (err) {
if (err) {
- console.info("Failed to put the value of 'startup'. Cause: " + err);
+ console.error("Failed to put the value of 'startup'. Cause: " + err);
return;
}
console.info("Successfully put the value of 'startup'.");
preferences.flush(function (err) {
if (err) {
- console.info("Failed to flush data. Cause: " + err);
+ console.error("Failed to flush. Cause: " + err);
return;
}
console.info("Successfully flushed data.");
@@ -1797,7 +1918,7 @@ try {
})
})
} catch (err) {
- console.info("Failed to flush data. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to flush. code =" + err.code + ", message =" + err.message);
}
```
@@ -1820,9 +1941,9 @@ Unsubscribes from inter-process data changes.
```js
try {
- data_preferences.getPreferences(this.context, {name: 'mystore', dataGroupId:'myId'}, function (err, preferences) {
+ data_preferences.getPreferences(this.context, { name: 'mystore', dataGroupId:'myId' }, function (err, preferences) {
if (err) {
- console.info("Failed to obtain the preferences.");
+ console.error("Failed to get preferences.");
return;
}
let observer = function (key) {
@@ -1831,14 +1952,14 @@ try {
preferences.on('multiProcessChange', observer);
preferences.put('startup', 'auto', function (err) {
if (err) {
- console.info("Failed to put the value of 'startup'. Cause: " + err);
+ console.error("Failed to put the value of 'startup'. Cause: " + err);
return;
}
console.info("Successfully put the value of 'startup'.");
preferences.flush(function (err) {
if (err) {
- console.info("Failed to flush data. Cause: " + err);
+ console.error("Failed to flush. Cause: " + err);
return;
}
console.info("Successfully flushed data.");
@@ -1847,7 +1968,7 @@ try {
})
})
} catch (err) {
- console.info("Failed to flush data. code =" + err.code + ", message =" + err.message);
+ console.error("Failed to flush. code =" + err.code + ", message =" + err.message);
}
```
## ValueType
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 21af7666f861e43b0bc81871308d25f39a07dfae..8d30126fec7cf31a42a9ae3bacf5d66db8b83238 100644
--- a/en/application-dev/reference/apis/js-apis-data-relationalStore.md
+++ b/en/application-dev/reference/apis/js-apis-data-relationalStore.md
@@ -216,6 +216,8 @@ FA model:
```js
import featureAbility from '@ohos.ability.featureAbility'
+var store;
+
// Obtain the context.
let context = featureAbility.getContext()
@@ -234,6 +236,8 @@ Stage model:
```ts
import UIAbility from '@ohos.app.ability.UIAbility'
+var store;
+
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
relationalStore.deleteRdbStore(this.context, "RdbTest.db", function (err) {
@@ -287,6 +291,8 @@ FA model:
```js
import featureAbility from '@ohos.ability.featureAbility'
+var store;
+
// Obtain the context.
let context = featureAbility.getContext();
@@ -304,6 +310,8 @@ Stage model:
```ts
import UIAbility from '@ohos.app.ability.UIAbility'
+var store;
+
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
let promise = relationalStore.deleteRdbStore(this.context, "RdbTest.db");
@@ -353,6 +361,8 @@ FA model:
```js
import featureAbility from '@ohos.ability.featureAbility'
+var store;
+
// Obtain the context.
let context = featureAbility.getContext()
const STORE_CONFIG = {
@@ -375,6 +385,8 @@ Stage model:
```ts
import UIAbility from '@ohos.app.ability.UIAbility'
+var store;
+
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
const STORE_CONFIG = {
@@ -434,6 +446,8 @@ FA model:
```js
import featureAbility from '@ohos.ability.featureAbility'
+var store;
+
// Obtain the context.
let context = featureAbility.getContext();
const STORE_CONFIG = {
@@ -455,6 +469,8 @@ Stage model:
```ts
import UIAbility from '@ohos.app.ability.UIAbility'
+var store;
+
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
const STORE_CONFIG = {
@@ -482,7 +498,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** (default) 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.|
| dataGroupId10+ | string | No| Application group ID, which needs to be obtained from the AppGallery. **Model restriction**: This attribute can be used only in the stage model. This parameter is supported since API version 10. It specifies the **relationalStore** instance created in the sandbox directory corresponding to the **dataGroupId**. If this parameter is not specified, the **relationalStore** instance is created in the sandbox directory of the application.|
## SecurityLevel
@@ -658,8 +674,8 @@ Enumerates the distributed table types. Use the enum names instead of the enum v
| Name | Value | Description |
| ------------------ | --- | -------------------------------------------------------------------------------------------------- |
-| DISTRIBUTED_DEVICE | - | Distributed database table between devices. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core |
-| DISTRIBUTED_CLOUD | - | Distributed database table between the device and the cloud. **System capability**: SystemCapability.DistributedDataManager.CloudSync.Client|
+| DISTRIBUTED_DEVICE | - | Distributed database table synchronized between devices. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core |
+| DISTRIBUTED_CLOUD | - | Distributed database table synchronized between the device and the cloud. **System capability**: SystemCapability.DistributedDataManager.CloudSync.Client |
## DistributedConfig10+
@@ -669,7 +685,7 @@ Defines the configuration of the distributed mode of tables.
| Name | Type | Mandatory| Description |
| -------- | ------- | ---- | ------------------------------------------------------------ |
-| autoSync | boolean | Yes | The value **true** means both automatic synchronization and manual synchronization are supported for the table. The value **false** means only manual synchronization is supported for the table.|
+| autoSync | boolean | Yes | The value **true** means both automatic synchronization and manual synchronization are supported for the table. The value **false** means only manual synchronization is supported for the table. |
## ConflictResolution10+
@@ -704,12 +720,12 @@ Represents the device-cloud synchronization statistics information.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
-| Name | Type | Mandatory| Description |
-| -------- | ------ | ---- | ---------------------------------------- |
-| total | number | Yes | Total number of rows to be synchronized between the device and cloud in the database table. |
-| success | number | Yes | Number of rows that are successfully synchronized between the device and cloud in the database table. |
-| failed | number | Yes | Number of rows that failed to be synchronized between the device and cloud in the database table. |
-| remained | number | Yes | Number of rows that are not executed for device-cloud synchronization in the database table.|
+| Name | Type | Mandatory| Description |
+| ---------- | ------ | ---- | ---------------------------------------- |
+| total | number | Yes | Total number of rows to be synchronized between the device and cloud in the database table. |
+| successful | number | Yes | Number of rows that are successfully synchronized between the device and cloud in the database table. |
+| failed | number | Yes | Number of rows that failed to be synchronized between the device and cloud in the database table. |
+| remained | number | Yes | Number of rows that are not executed for device-cloud synchronization in the database table.|
## TableDetails10+
@@ -2432,7 +2448,7 @@ store.query(predicates, function (err, resultSet) {
}
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
- while(resultSet.goToNextRow()) {
+ while (resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
@@ -2480,7 +2496,7 @@ store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err,
}
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
- while(resultSet.goToNextRow()) {
+ while (resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
@@ -2530,7 +2546,7 @@ let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
promise.then((resultSet) => {
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
- while(resultSet.goToNextRow()) {
+ while (resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
@@ -2585,7 +2601,7 @@ store.query("EMPLOYEE", predicates, function (err, resultSet) {
}
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
- while(resultSet.goToNextRow()) {
+ while (resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
@@ -2639,7 +2655,7 @@ store.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], fu
}
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
- while(resultSet.goToNextRow()) {
+ while (resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
@@ -2695,7 +2711,7 @@ let promise = store.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY"
promise.then((resultSet) => {
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
- while(resultSet.goToNextRow()) {
+ while (resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
@@ -2766,7 +2782,7 @@ store.remoteQuery(deviceId, "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALAR
}
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
- while(resultSet.goToNextRow()) {
+ while (resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
@@ -2837,7 +2853,7 @@ let promise = store.remoteQuery(deviceId, "EMPLOYEE", predicates, ["ID", "NAME",
promise.then((resultSet) => {
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
- while(resultSet.goToNextRow()) {
+ while (resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
@@ -2884,7 +2900,7 @@ store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = 'sanguo
}
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
- while(resultSet.goToNextRow()) {
+ while (resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
@@ -2930,7 +2946,7 @@ store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['s
}
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
- while(resultSet.goToNextRow()) {
+ while (resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
@@ -2978,7 +2994,7 @@ let promise = store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.
promise.then((resultSet) => {
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
- while(resultSet.goToNextRow()) {
+ while (resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
@@ -3533,7 +3549,46 @@ promise.then(() => {
### setDistributedTables10+
-setDistributedTables(tables: Array<string>, type: number, config: DistributedConfig, callback: AsyncCallback<void>): void
+setDistributedTables(tables: Array<string>, type: DistributedType, callback: AsyncCallback<void>): void
+
+Sets distributed tables. This API uses an asynchronous callback to return the result.
+
+**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
+
+**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ------------------------------------- | ---- | ---------------------------- |
+| tables | Array<string> | Yes | Names of the distributed tables to set.|
+| type | [DistributedType](#distributedtype10) | Yes | Distributed type of the tables. |
+| 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. |
+| 14800051 |The type of the distributed table does not match.|
+
+**Example**
+
+```js
+store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIBUTED_CLOUD, function (err) {
+ if (err) {
+ console.error(`SetDistributedTables failed, code is ${err.code},message is ${err.message}`);
+ return;
+ }
+ console.info(`SetDistributedTables successfully.`);
+})
+```
+
+### setDistributedTables10+
+
+setDistributedTables(tables: Array<string>, type: DistributedType, config: DistributedConfig, callback: AsyncCallback<void>): void
Sets distributed tables. This API uses an asynchronous callback to return the result.
@@ -3546,16 +3601,25 @@ Sets distributed tables. This API uses an asynchronous callback to return the re
| Name | Type | Mandatory | Description |
| -------- | ----------------------------------- | --- | --------------- |
| tables | Array<string> | Yes | Names of the distributed tables to set. |
-| type | number | Yes | Distributed type of the tables. Currently, only **relationalStore.DistributedType.DISTRIBUTED_DEVICE** and **relationalStore.DistributedType.DISTRIBUTED_CLOUD** are supported. The value **relationalStore.DistributedType.DISTRIBUTED_DEVICE** indicates distributed tables across different devices. The value **relationalStore.DistributedType.DISTRIBUTED_CLOUD** indicates distributed tables between the device and cloud.|
+| type | [DistributedType](#distributedtype10) | Yes | Distributed type of the tables.|
| config | [DistributedConfig](#distributedconfig10) | Yes| Configuration of the distributed mode.|
| 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. |
+| 14800051 | The type of the distributed table does not match. |
+
**Example**
```js
-let config = new relationalStore.DistributedConfig();
-config.autoSync = true;
-store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIBUTED_CLOUD, config, function (err) {
+store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIBUTED_CLOUD, {
+ autoSync: true
+}, function (err) {
if (err) {
console.error(`SetDistributedTables failed, code is ${err.code},message is ${err.message}`);
return;
@@ -3566,7 +3630,7 @@ store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIB
### setDistributedTables10+
- setDistributedTables(tables: Array<string>, type?: number, config?: DistributedConfig): Promise<void>
+ setDistributedTables(tables: Array<string>, type?: DistributedType, config?: DistributedConfig): Promise<void>
Sets distributed tables. This API uses a promise to return the result.
@@ -3578,8 +3642,8 @@ Sets distributed tables. This API uses a promise to return the result.
| Name| Type | Mandatory| Description |
| ------ | ----------------------------------------- | ---- | ------------------------------------------------------------ |
-| tables | Array<string> | Yes | Names of the distributed tables to set. |
-| type | number | No | Distributed type of the tables. The default value is **relationalStore.DistributedType.DISTRIBUTED_DEVICE**. Currently, only **relationalStore.DistributedType.DISTRIBUTED_DEVICE** and **relationalStore.DistributedType.DISTRIBUTED_CLOUD** are supported. The value **relationalStore.DistributedType.DISTRIBUTED_DEVICE** indicates distributed tables across different devices. The value **relationalStore.DistributedType.DISTRIBUTED_CLOUD** indicates distributed tables between the device and cloud.|
+| tables | Array<string> | Yes | Names of the distributed tables to set. |
+| type | [DistributedType](#distributedtype10) | No | Distributed type of the tables. The default value is **relationalStore.DistributedType.DISTRIBUTED_DEVICE**.|
| config | [DistributedConfig](#distributedconfig10) | No | Configuration of the distributed mode. If this parameter is not specified, the value of **autoSync** is **false** by default, which means only manual synchronization is supported.|
**Return value**
@@ -3588,12 +3652,21 @@ 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. |
+| 14800051 | The type of the distributed table does not match. |
+
**Example**
```js
-let config = new relationalStore.DistributedConfig();
-config.autoSync = true;
-let promise = store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIBUTED_CLOUD, config);
+let promise = store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIBUTED_CLOUD, {
+ autoSync: true
+});
promise.then(() => {
console.info(`SetDistributedTables successfully.`);
}).catch((err) => {
@@ -3860,7 +3933,7 @@ Manually starts device-cloud synchronization for all distributed tables. This AP
**Example**
```js
-relationalStore.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, function (progressDetails) {
+store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, function (progressDetails) {
console.info(`Progess: ${progressDetails}`);
}, function (err) {
if (err) {
@@ -3901,7 +3974,7 @@ function progress(progressDetail) {
console.info(`progress: ${progressDetail}`);
}
-relationalStore.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, progress).then(() => {
+store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, progress).then(() => {
console.info('Cloud sync succeeded');
}).catch((err) => {
console.error(`cloudSync failed, code is ${err.code},message is ${err.message}`);
@@ -3931,7 +4004,7 @@ Manually starts device-cloud synchronization of the specified table. This API us
```js
const tables = ["table1", "table2"];
-relationalStore.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, tables, function (progressDetails) {
+store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, tables, function (progressDetails) {
console.info(`Progess: ${progressDetails}`);
}, function (err) {
if (err) {
@@ -3974,7 +4047,7 @@ function progress(progressDetail) {
console.info(`progress: ${progressDetail}`);
}
-relationalStore.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, tables, progress).then(() => {
+store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, tables, progress).then(() => {
console.info('Cloud sync succeeded');
}).catch((err) => {
console.error(`cloudSync failed, code is ${err.code},message is ${err.message}`);
diff --git a/en/application-dev/reference/apis/js-apis-devicestatus-draginteraction.md b/en/application-dev/reference/apis/js-apis-devicestatus-draginteraction.md
new file mode 100644
index 0000000000000000000000000000000000000000..01b50c8fc58606caf233a011df6e5bdc86eb2b80
--- /dev/null
+++ b/en/application-dev/reference/apis/js-apis-devicestatus-draginteraction.md
@@ -0,0 +1,98 @@
+# @ohos. deviceStatus.dragInteraction (Drag)
+
+ The **dragInteraction** module provides the APIs to enable and disable listening for dragging status 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.
+>
+> - The APIs provided by this module are system APIs.
+
+## Modules to Import
+
+```js
+import dragInteraction from '@ohos.deviceStatus.dragInteraction'
+```
+
+## dragInteraction.on
+
+on(type: 'drag', callback: Callback<DragState>): void;
+
+Enables listening for dragging status changes.
+
+**System capability**: SystemCapability.Msdp.DeviceStatus.Drag
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ---------------------------- | ---- | ---------------------------- |
+| type | string | Yes | Event type. This field has a fixed value of **drag**.|
+| callback | Callback<[DragState](#dragstate)> | Yes | Callback used to return the dragging status.|
+
+**Example**
+
+```js
+try {
+ dragInteraction.on('drag', (data) => {
+ console.log(`Drag interaction event: ${JSON.stringify(data)}`);
+ });
+} catch (error) {
+ console.log(`Register failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
+}
+```
+
+## dragInteraction.off
+
+off(type: 'drag', callback?: Callback<DragState>): void;
+
+Disables listening for dragging status changes.
+
+**System capability**: SystemCapability.Msdp.DeviceStatus.Drag
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------------- | ---- | ---------------------------- |
+| type | string | Yes | Event type. This field has a fixed value of **drag**.|
+| callback | Callback<[DragState](#dragstate)> | No | Callback to be unregistered. If this parameter is not specified, all callbacks registered by the current application will be unregistered.|
+
+**Example**
+
+```js
+// Unregister a single callback.
+function callback(event) {
+ console.log(`Drag interaction event: ${JSON.stringify(event)}`);
+ return false;
+}
+try {
+ dragInteraction.on('drag', callback);
+ dragInteraction.off("drag", callback);
+} catch (error) {
+ console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
+}
+```
+```js
+// Unregister all callbacks.
+function callback(event) {
+ console.log(`Drag interaction event: ${JSON.stringify(event)}`);
+ return false;
+}
+try {
+ dragInteraction.on('drag', callback);
+ dragInteraction.off("drag");
+} catch (error) {
+ console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
+}
+```
+
+## DragState
+
+Enumerates dragging states.
+
+**System capability**: SystemCapability.Msdp.DeviceStatus.Drag
+
+| Name | Value | Description |
+| -------- | ----------------- | ----------------- |
+| MSG_DRAG_STATE_START | 1 | Dragging starts.|
+| MSG_DRAG_STATE_STOP | 2 | Dragging is ended. |
+| MSG_DRAG_STATE_CANCEL | 3 | Dragging is canceled. |
diff --git a/en/application-dev/reference/apis/js-apis-distributedDeviceManager.md b/en/application-dev/reference/apis/js-apis-distributedDeviceManager.md
index 7e3d76ec2e872342400131c9d9ca87b916d5fcb1..e1b55f7e188ddb088fc8381101e8d63b95853664 100644
--- a/en/application-dev/reference/apis/js-apis-distributedDeviceManager.md
+++ b/en/application-dev/reference/apis/js-apis-distributedDeviceManager.md
@@ -13,7 +13,7 @@ Applications can call the APIs to:
> **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 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
@@ -39,9 +39,9 @@ Creates a **DeviceManager** instance. The **DeviceManager** instance is the entr
**Return value**
- | Name | Description |
- | ------------------------------------------- | --------- |
- | [DeviceManager](#devicemanager) | **DeviceManager** instance created.|
+| Name | Description |
+| ------------------------------------------- | --------- |
+| [DeviceManager](#devicemanager) | **DeviceManager** instance created.|
**Example**
@@ -97,7 +97,7 @@ Represents the basic information about a distributed device.
| ---------------------- | ------------------------- | ---- | -------- |
| deviceId | string | Yes | Unique ID of the device. The value is the udid-hash (hash value of the UDID) and appid encrypted using SHA-256.|
| deviceName | string | Yes | Device name. |
-| deviceType | number | Yes | Device type. |
+| deviceType | string | Yes | Device type. |
| networkId | string | No | Network ID of the device. |
## DeviceStateChange
@@ -129,9 +129,9 @@ Obtains all trusted devices synchronously.
**Return value**
- | Name | Description |
- | ------------------------------------------- | --------- |
- | Array<[DeviceBasicInfo](#devicebasicinfo)> | List of trusted devices obtained.|
+| Name | Description |
+| ------------------------------------------- | --------- |
+| Array<[DeviceBasicInfo](#devicebasicinfo)> | List of trusted devices obtained.|
**Error codes**
@@ -163,9 +163,9 @@ Obtains all trusted devices. This API uses an asynchronous callback to return th
**Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | ---------------------------------------- | ---- | --------------------- |
- | callback | AsyncCallback<Array<[DeviceBasicInfo](#devicebasicinfo)>> | Yes | Callback invoked to return the list of trusted devices.|
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------------------------- | ---- | --------------------- |
+| callback | AsyncCallback<Array<[DeviceBasicInfo](#devicebasicinfo)>> | Yes | Callback invoked to return the list of trusted devices.|
**Error codes**
@@ -203,9 +203,9 @@ Obtains all trusted devices. This API uses a promise to return the result.
**Return value**
- | Type | Description |
- | ---------------------------------------------------------- | ---------------------------------- |
- | Promise<Array<[DeviceBasicInfo](#devicebasicinfo)>> | Promise used to return the result.|
+| Type | Description |
+| ---------------------------------------------------------- | ---------------------------------- |
+| Promise<Array<[DeviceBasicInfo](#devicebasicinfo)>> | Promise used to return the result.|
**Error codes**
@@ -237,9 +237,9 @@ Obtains the network ID of the local device.
**Return value**
- | Name | Description |
- | ------------------------- | ---------------- |
- | string | Network ID of the local device obtained.|
+| Name | Description |
+| ------------------------- | ---------------- |
+| string | Network ID of the local device obtained.|
**Error codes**
@@ -272,9 +272,9 @@ Obtains the local device name.
**Return value**
- | Name | Description |
- | ------------------------- | ---------------- |
- | string | Name of the local device obtained.|
+| Name | Description |
+| ------------------------- | ---------------- |
+| string | Name of the local device obtained.|
**Error codes**
@@ -307,9 +307,9 @@ Obtains the local device type.
**Return value**
- | Name | Description |
- | ------------------------- | ---------------- |
- | number | Local device type obtained.|
+| Name | Description |
+| ------------------------- | ---------------- |
+| number | Local device type obtained.|
**Error codes**
@@ -342,9 +342,9 @@ Obtains the local device ID.
**Return value**
- | Name | Description |
- | ------------------------- | ---------------- |
- | string | Local device ID obtained.|
+| Name | Description |
+| ------------------------- | ---------------- |
+| string | Local device ID obtained.|
**Error codes**
@@ -377,15 +377,15 @@ Obtains the device name based on the network ID of the specified device.
**Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | ---------------------------------------- | ---- | --------- |
- | networkId| string | Yes | Network ID of the device.|
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------------------------- | ---- | --------- |
+| networkId| string | Yes | Network ID of the device.|
**Return value**
- | Name | Description |
- | ------------------------- | ---------------- |
- | string | Device name obtained.|
+| Name | Description |
+| ------------------------- | ---------------- |
+| string | Device name obtained.|
**Error codes**
@@ -420,15 +420,15 @@ Obtains the device type based on the network ID of the specified device.
**Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | ---------------------------------------- | ---- | --------- |
- | networkId| string | Yes | Network ID of the device.|
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------------------------- | ---- | --------- |
+| networkId| string | Yes | Network ID of the device.|
**Return value**
- | Name | Description |
- | ------------------------- | ---------------- |
- | number | Device type obtained.|
+| Name | Description |
+| ------------------------- | ---------------- |
+| number | Device type obtained.|
**Error codes**
@@ -463,10 +463,10 @@ Starts to discover devices nearby. The discovery process automatically stops whe
**Parameters**
- | Name | Type | Mandatory | Description |
- | ------------- | ------------------------------- | ---- | ----- |
- | discoverParam | {[key: string]: Object} | Yes | Identifier of the device to discover. It specifies the type of the target to discover. **discoverTargetType**: The default discovery target is device. The value is **1**.|
- | filterOptions | {[key: string]: Object} | No | Options for filtering discovered devices. The default value is **undefined**, which means to discover offline devices. The following **key** values are carried: **availableStatus(0-1)**: Discover trusted devices only. The value **0** indicates that the device is untrusted. - **0**: The device is offline. The client needs to call **bindTarget** to bind the device. - **1**: The device is online and can be connected. **discoverDistance(0-100)**: Discover devices within a certain distance (in cm) from the local device. **authenticationStatus(0-1)**: Discover devices based on the authentication status. - **0**: The device is not authenticated. - **1**: The device has been authenticated. **authorizationType(0-2)**: Discover devices based on the authorization type. - **0**: device authenticated by a temporarily agreed session key. - **1**: device authenticated by a key of the same account. - **2**: devices authenticated by a credential key of different accounts.|
+| Name | Type | Mandatory | Description |
+| ------------- | ------------------------------- | ---- | ----- |
+| discoverParam | {[key: string]: Object} | Yes | Identifier of the device to discover. It specifies the type of the target to discover. **discoverTargetType**: The default discovery target is device. The value is **1**.|
+| filterOptions | {[key: string]: Object} | No | Options for filtering discovered devices. The default value is **undefined**, which means to discover offline devices. The following **key** values are carried: **availableStatus(0-1)**: Discover trusted devices only. The value **0** indicates that the device is untrusted. - **0**: The device is offline. The client needs to call **bindTarget** to bind the device. - **1**: The device is online and can be connected. **discoverDistance(0-100)**: Discover devices within a certain distance (in cm) from the local device. **authenticationStatus(0-1)**: Discover devices based on the authentication status. - **0**: The device is not authenticated. - **1**: The device has been authenticated. **authorizationType(0-2)**: Discover devices based on the authorization type. - **0**: device authenticated by a temporarily agreed session key. - **1**: device authenticated by a key of the same account. - **2**: devices authenticated by a credential key of different accounts.|
**Error codes**
@@ -537,11 +537,11 @@ Binds a device.
**Parameters**
- | Name | Type | Mandatory | Description |
- | ---------- | --------------------------------------------------- | ----- | ------------ |
- | deviceId | string | Yes | Device ID. |
- | bindParam | {[key: string]: Object} | Yes | Authentication parameters. You can determine the key-value pair to be passed in. By default, the following **key** values are carried: **bindType**: binding type. - **1**: PIN. - **2**: QR code. - 3: NFC. - 4: No interaction. **targetPkgName**: bundle name of the target to bind. **appName**: application that attempts to bind the target. **appOperation**: reason for the application to bind the target. **customDescription**: detailed description of the operation. |
- | callback | AsyncCallback<{deviceId: string, }> | Yes | Callback invoked to return the authentication result.|
+| Name | Type | Mandatory | Description |
+| ---------- | --------------------------------------------------- | ----- | ------------ |
+| deviceId | string | Yes | Device ID. |
+| bindParam | {[key: string]: Object} | Yes | Authentication parameters. You can determine the key-value pair to be passed in. By default, the following **key** values are carried: **bindType**: binding type. - **1**: PIN. - **2**: QR code. - 3: NFC. - 4: No interaction. **targetPkgName**: bundle name of the target to bind. **appName**: application that attempts to bind the target. **appOperation**: reason for the application to bind the target. **customDescription**: detailed description of the operation. |
+| callback | AsyncCallback<{deviceId: string, }> | Yes | Callback invoked to return the authentication result.|
**Error codes**
@@ -589,9 +589,9 @@ Unbinds a device.
**Parameters**
- | Name | Type | Mandatory| Description |
- | -------- | ------------------------- | ---- | ---------- |
- | deviceId | string | Yes | Device ID.|
+| Name | Type | Mandatory| Description |
+| -------- | ------------------------- | ---- | ---------- |
+| deviceId | string | Yes | Device ID.|
**Error codes**
@@ -626,10 +626,10 @@ Replies to the user's UI operation. This API can be used only by the PIN HAP of
**Parameters**
- | Name | Type | Mandatory | Description |
- | ------------- | --------------- | ---- | ------------------- |
- | action | number | Yes | User operation. |
- | actionResult | string | Yes | Operation result.|
+| Name | Type | Mandatory | Description |
+| ------------- | --------------- | ---- | ------------------- |
+| action | number | Yes | User operation. |
+| actionResult | string | Yes | Operation result.|
**Example**
@@ -664,10 +664,10 @@ Subscribes to the UI operation reply result.
**Parameters**
- | Name | Type | Mandatory| Description |
- | -------- | ------------------------------------ | ---- | ------------------------------ |
- | type | string | Yes | Event type to subscribe to. The value **replyResult** indicates the reply result of the UI operation.|
- | callback | Callback<{ param: string}> | Yes | Callback invoked to return the UI status. |
+| Name | Type | Mandatory| Description |
+| -------- | ------------------------------------ | ---- | ------------------------------ |
+| type | string | Yes | Event type to subscribe to. The value **replyResult** indicates the reply result of the UI operation.|
+| callback | Callback<{ param: string}> | Yes | Callback invoked to return the UI status. |
**Example**
@@ -698,10 +698,10 @@ Unsubscribes from the UI operation reply result.
**Parameters**
- | Name | Type | Mandatory| Description |
- | -------- | ------------------------------------- | ---- | ------------------------------ |
- | type | string | Yes | Event type to unsubscribe from. The value **replyResult** indicates the reply result of the UI operation.|
- | callback | Callback<{ param: string}> | No | Callback for the UI status.|
+| Name | Type | Mandatory| Description |
+| -------- | ------------------------------------- | ---- | ------------------------------ |
+| type | string | Yes | Event type to unsubscribe from. The value **replyResult** indicates the reply result of the UI operation.|
+| callback | Callback<{ param: string}> | No | Callback for the UI status.|
**Example**
@@ -725,10 +725,10 @@ Subscribes to changes in the device state.
**Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | ---------------------------------------- | ---- | ------------------------------ |
- | type | string | Yes | Event type. The value **'deviceStateChange'** indicates a device state change event.|
- | callback | Callback<{ action: [DeviceStateChange](#devicestatechange), device: [DeviceBasicInfo](#devicebasicinfo) }> | Yes | Callback invoked to return the device information and state. |
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------------------------- | ---- | ------------------------------ |
+| type | string | Yes | Event type. The value **'deviceStateChange'** indicates a device state change event.|
+| callback | Callback<{ action: [DeviceStateChange](#devicestatechange), device: [DeviceBasicInfo](#devicebasicinfo) }> | Yes | Callback invoked to return the device information and state. |
**Example**
@@ -754,10 +754,10 @@ Unsubscribes from changes in the device state.
**Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | ---------------------------------------- | ---- | --------------------------- |
- | type | string | Yes | Event type. The value **'deviceStateChange'** indicates a device state change event. |
- | callback | Callback<{ action: [deviceStateChange](#devicestatechange), device: [DeviceBasicInfo](#devicebasicinfo) }> | No | Callback for the device information and state.|
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------------------------- | ---- | --------------------------- |
+| type | string | Yes | Event type. The value **'deviceStateChange'** indicates a device state change event. |
+| callback | Callback<{ action: [deviceStateChange](#devicestatechange), device: [DeviceBasicInfo](#devicebasicinfo) }> | No | Callback for the device information and state.|
**Example**
@@ -783,10 +783,10 @@ Subscribes to device discovery events.
**Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | ---------------------------------------- | ---- | -------------------------- |
- | type | string | Yes | Event type. The value **'discoverSuccess'** indicates an event of successful device discovery.|
- | callback | Callback<{ device: [DeviceBasicInfo](#devicebasicinfo) }> | Yes | Callback invoked to return a device discovery event. |
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------------------------- | ---- | -------------------------- |
+| type | string | Yes | Event type. The value **'discoverSuccess'** indicates an event of successful device discovery.|
+| callback | Callback<{ device: [DeviceBasicInfo](#devicebasicinfo) }> | Yes | Callback invoked to return a device discovery event. |
**Example**
@@ -812,10 +812,10 @@ Unsubscribes from device discovery events.
**Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | ---------------------------------------- | ---- | --------------------------- |
- | type | string | Yes | Event type. The value **'discoverSuccess'** indicates a device discovery event. |
- | callback | Callback<{ device: [DeviceBasicInfo](#devicebasicinfo) }> | No | Callback for the device discovery event.|
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------------------------- | ---- | --------------------------- |
+| type | string | Yes | Event type. The value **'discoverSuccess'** indicates a device discovery event. |
+| callback | Callback<{ device: [DeviceBasicInfo](#devicebasicinfo) }> | No | Callback for the device discovery event.|
**Example**
@@ -841,10 +841,10 @@ Subscribes to device name changes.
**Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | ---------------------------------------- | ---- | ------------------------------ |
- | type | string | Yes | Event type. The value **'deviceNameChange'** indicates a device name change event.|
- | callback | Callback<{ deviceName: string}> | Yes | Callback invoked to return the device name change. |
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------------------------- | ---- | ------------------------------ |
+| type | string | Yes | Event type. The value **'deviceNameChange'** indicates a device name change event.|
+| callback | Callback<{ deviceName: string}> | Yes | Callback invoked to return the device name change. |
**Example**
@@ -870,10 +870,10 @@ Unsubscribes from device name changes.
**Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | ---------------------------------------- | ---- | ------------------------------ |
- | type | string | Yes | Event type. The value **'deviceNameChange'** indicates a device name change event.|
- | callback | Callback<{ deviceName: string}> | No | Callback for the device name change. |
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------------------------- | ---- | ------------------------------ |
+| type | string | Yes | Event type. The value **'deviceNameChange'** indicates a device name change event.|
+| callback | Callback<{ deviceName: string}> | No | Callback for the device name change. |
**Example**
@@ -899,10 +899,10 @@ Subscribes to device discovery failures.
**Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | ---------------------------------------- | ---- | ------------------------------ |
- | type | string | Yes | Event type. The value **'discoverFailure'** indicates an event reported when device discovery fails.|
- | callback | Callback<{ reason: number }> | Yes | Callback invoked to return a device discovery failure. |
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------------------------- | ---- | ------------------------------ |
+| type | string | Yes | Event type. The value **'discoverFailure'** indicates an event reported when device discovery fails.|
+| callback | Callback<{ reason: number }> | Yes | Callback invoked to return a device discovery failure. |
**Example**
@@ -928,10 +928,10 @@ Unsubscribes from device discovery failures.
**Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | ---------------------------------------- | ---- | ----------------- |
- | type | string | Yes | Event type. The value **'discoverFailure'** indicates an event reported when device discovery fails. |
- | callback | Callback<{ reason: number }> | No | Callback for the device discovery failure.|
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------------------------- | ---- | ----------------- |
+| type | string | Yes | Event type. The value **'discoverFailure'** indicates an event reported when device discovery fails. |
+| callback | Callback<{ reason: number }> | No | Callback for the device discovery failure.|
**Example**
@@ -957,10 +957,10 @@ Subscribes to dead events of the **DeviceManager** service.
**Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | ----------------------- | ---- | ---------------------------------------- |
- | type | string | Yes | Event type. The value **'serviceDie'** indicates an event reported when the **DeviceManager** service is terminated unexpectedly.|
- | callback | Callback<{}> | No | Callback invoked when a dead event of the **DeviceManager** service occurs. |
+| Name | Type | Mandatory | Description |
+| -------- | ----------------------- | ---- | ---------------------------------------- |
+| type | string | Yes | Event type. The value **'serviceDie'** indicates an event reported when the **DeviceManager** service is terminated unexpectedly.|
+| callback | Callback<{}> | No | Callback invoked when a dead event of the **DeviceManager** service occurs. |
**Example**
@@ -986,10 +986,10 @@ Unsubscribes from dead events of the **DeviceManager** service.
**Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | ----------------------- | ---- | ---------------------------------------- |
- | type | string | Yes | Event type. The value **'serviceDie'** indicates an event reported when the **DeviceManager** service is terminated unexpectedly.|
- | callback | Callback<{}> | No | Callback for the dead event of the **DeviceManager** service. |
+| Name | Type | Mandatory | Description |
+| -------- | ----------------------- | ---- | ---------------------------------------- |
+| type | string | Yes | Event type. The value **'serviceDie'** indicates an event reported when the **DeviceManager** service is terminated unexpectedly.|
+| callback | Callback<{}> | No | Callback for the dead event of the **DeviceManager** service. |
**Example**
@@ -1002,4 +1002,4 @@ Unsubscribes from dead events of the **DeviceManager** service.
console.error("serviceDie errCode:" + err.code + ",errMessage:" + err.message);
}
```
-
+
diff --git a/en/application-dev/reference/apis/js-apis-driver-deviceManager.md b/en/application-dev/reference/apis/js-apis-driver-deviceManager.md
index d86dc94bd0a66d94c96c8bd29ba45398656bc261..47672b03da27350a4633ef7b042561ee2e308e73 100644
--- a/en/application-dev/reference/apis/js-apis-driver-deviceManager.md
+++ b/en/application-dev/reference/apis/js-apis-driver-deviceManager.md
@@ -82,7 +82,8 @@ You need to use [deviceManager.queryDevices](#devicemanagerquerydevices) to obta
```js
try {
- deviceManager.bindDevice(device.deviceId, (error, data) => {
+ // For example, deviceId is 12345678. You can use queryDevices() to obtain the deviceId.
+ deviceManager.bindDevice(12345678, (error, data) => {
console.error('Device is disconnected');
}, (error, data) => {
if (error) {
@@ -131,7 +132,8 @@ You need to use [deviceManager.queryDevices](#devicemanagerquerydevices) to obta
```js
try {
- deviceManager.bindDevice(matchDevice.deviceId, (error, data) => {
+ // For example, deviceId is 12345678. You can use queryDevices() to obtain the deviceId.
+ deviceManager.bindDevice(12345678, (error, data) => {
console.error('Device is disconnected');
}).then(data => {
console.info('bindDevice success');
@@ -169,7 +171,8 @@ Unbinds a peripheral device. This API uses an asynchronous callback to return th
```js
try {
- deviceManager.unbindDevice(matchDevice.deviceId, (error, data) => {
+ // For example, deviceId is 12345678. You can use queryDevices() to obtain the deviceId.
+ deviceManager.unbindDevice(12345678, (error, data) => {
if (error) {
console.error('unbindDevice async fail. Code is ${error.code}, message is ${error.message}');
return;
@@ -211,7 +214,8 @@ Unbinds a peripheral device. This API uses a promise to return the result.
```js
try {
- deviceManager.unbindDevice(matchDevice.deviceId).then(data => {
+ // For example, deviceId is 12345678. You can use queryDevices() to obtain the deviceId.
+ deviceManager.unbindDevice(12345678).then(data => {
console.info('unbindDevice success');
}, error => {
console.error('unbindDevice async fail. Code is ${error.code}, message is ${error.message}');
diff --git a/en/application-dev/reference/apis/js-apis-effectKit.md b/en/application-dev/reference/apis/js-apis-effectKit.md
index 7535b67ab2c14e9596ba59dbfcf6068def89faa0..19b4bf42ed9c1cfa37a5b7a36be7351f1f865846 100644
--- a/en/application-dev/reference/apis/js-apis-effectKit.md
+++ b/en/application-dev/reference/apis/js-apis-effectKit.md
@@ -21,7 +21,7 @@ import effectKit from '@ohos.effectKit';
## effectKit.createEffect
createEffect(source: image.PixelMap): Filter
-Creates a **Filter** instance based on the pixel map.
+Creates a **Filter** instance based on a pixel map.
**System capability**: SystemCapability.Multimedia.Image.Core
@@ -53,7 +53,7 @@ image.createPixelMap(color, opts).then((pixelMap) => {
createColorPicker(source: image.PixelMap): Promise\
-Creates a **ColorPicker** instance based on the pixel map. This API uses a promise to return the result.
+Creates a **ColorPicker** instance based on a pixel map. This API uses a promise to return the result.
**System capability**: SystemCapability.Multimedia.Image.Core
@@ -83,11 +83,46 @@ image.createPixelMap(color, opts).then((pixelMap) => {
})
```
+## effectKit.createColorPicker10+
+
+createColorPicker(source: image.PixelMap, region: Array\): Promise\
+
+Creates a **ColorPicker** instance for the selected region based on a pixel map. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ----------- | ---- | -------------------------- |
+| source | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes | **PixelMap** instance created by the image module. An instance can be obtained by decoding an image or directly created. For details, see [Image Overview](../../media/image-overview.md).|
+| region | Array\ | Yes | Region of the image from which the color is picked. The array consists of four elements, representing the left, top, right, and bottom positions of the image, respectively. The value of each element must be in the range [0, 1]. The leftmost and topmost positions of the image correspond to 0, and the rightmost and bottom positions correspond to 1. In the array, the third element must be greater than the first element, and the fourth element must be greater than the second element. If no value is passed, the default value [0, 0, 1, 1] is used, indicating that the color region is the entire image.|
+
+**Return value**
+
+| Type | Description |
+| ---------------------- | -------------- |
+| Promise\<[ColorPicker](#colorpicker)> | Promise used to return the **ColorPicker** instance created.|
+
+**Example**
+
+```js
+import image from "@ohos.multimedia.image";
+
+const color = new ArrayBuffer(96);
+let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
+image.createPixelMap(color, opts).then((pixelMap) => {
+ effectKit.createColorPicker(pixelMap, [0, 0, 0.5, 0.5]).then(colorPicker => {
+ console.info("color picker=" + colorPicker);
+ }).catch(ex => console.error(".error=" + ex.toString()))
+})
+```
+
## effectKit.createColorPicker
createColorPicker(source: image.PixelMap, callback: AsyncCallback\): void
-Creates a **ColorPicker** instance based on the pixel map. This API uses an asynchronous callback to return the result.
+Creates a **ColorPicker** instance based on a pixel map. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Multimedia.Image.Core
@@ -116,6 +151,40 @@ image.createPixelMap(color, opts).then((pixelMap) => {
})
```
+## effectKit.createColorPicker10+
+
+createColorPicker(source: image.PixelMap, region:Array\, callback: AsyncCallback\): void
+
+Creates a **ColorPicker** instance for the selected region based on a pixel map. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ------------------ | ---- | -------------------------- |
+| source | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes |**PixelMap** instance created by the image module. An instance can be obtained by decoding an image or directly created. For details, see [Image Overview](../../media/image-overview.md). |
+| region | Array\ | Yes | Region of the image from which the color is picked. The array consists of four elements, representing the left, top, right, and bottom positions of the image, respectively. The value of each element must be in the range [0, 1]. The leftmost and topmost positions of the image correspond to 0, and the rightmost and bottom positions correspond to 1. In the array, the third element must be greater than the first element, and the fourth element must be greater than the second element. If no value is passed, the default value [0, 0, 1, 1] is used, indicating that the color region is the entire image.|
+| callback | AsyncCallback\<[ColorPicker](#colorpicker)> | Yes | Callback used to return the **ColorPicker** instance created.|
+
+**Example**
+
+```js
+import image from "@ohos.multimedia.image";
+
+const color = new ArrayBuffer(96);
+let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
+image.createPixelMap(color, opts).then((pixelMap) => {
+ effectKit.createColorPicker(pixelMap, [0, 0, 0.5, 0.5], (error, colorPicker) => {
+ if (error) {
+ console.log('Failed to create color picker.');
+ } else {
+ console.log('Succeeded in creating color picker.');
+ }
+ })
+})
+```
+
## Color
A class that stores the color picked.
@@ -124,10 +193,10 @@ A class that stores the color picked.
| Name | Type | Readable| Writable| Description |
| ------ | ----- | ---- | ---- | ---------------- |
-| red | number | Yes | No | Value of the red component. |
-| green | number | Yes | No | Value of the green component. |
-| blue | number | Yes | No | Value of the blue component. |
-| alpha | number | Yes | No | Value of the alpha component. |
+| red | number | Yes | No | Value of the red component. The value range is [0x0, 0xFF]. |
+| green | number | Yes | No | Value of the green component. The value range is [0x0, 0xFF]. |
+| blue | number | Yes | No | Value of the blue component. The value range is [0x0, 0xFF]. |
+| alpha | number | Yes | No | Value of the alpha component. The value range is [0x0, 0xFF]. |
## ColorPicker
@@ -250,10 +319,16 @@ console.log('get average color =' + color);
isBlackOrWhiteOrGrayColor(color: number): boolean
-Checks whether this image is black, white, and gray.
+Checks whether a color is black, white, and gray.
**System capability**: SystemCapability.Multimedia.Image.Core
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ----------- | ---- | -------------------------- |
+| color| number | Yes | Color to check. The value range is [0x0, 0xFFFFFFFF].|
+
**Return value**
| Type | Description |
diff --git a/en/application-dev/reference/apis/js-apis-enterprise-adminManager.md b/en/application-dev/reference/apis/js-apis-enterprise-adminManager.md
index b3ae186cc47031f89fae5b14d4280c6d1d687d0f..5732b77f4e588562bab5c38abd408a3ebbe06592 100644
--- a/en/application-dev/reference/apis/js-apis-enterprise-adminManager.md
+++ b/en/application-dev/reference/apis/js-apis-enterprise-adminManager.md
@@ -4,9 +4,11 @@ The **adminManager** module provides enterprise device management capabilities s
> **NOTE**
>
-> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
+> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
-> - The APIs provided by this module can be called only by a [device administrator application](enterpriseDeviceManagement-overview.md#basic-concepts).
+> The APIs of this module can be used only in the stage model.
+>
+> The APIs provided by this module can be called only by a [device administrator application](enterpriseDeviceManagement-overview.md#basic-concepts).
## Modules to Import
@@ -18,7 +20,7 @@ import adminManager from '@ohos.enterprise.adminManager';
enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, callback: AsyncCallback\): void
-Enables a device administrator application of the current user. This API uses an asynchronous callback to return the result. The super administrator application can be enabled only by the administrator.
+Enables a device administrator application for the current user. The super device administrator application can be activated only by the administrator. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN
@@ -30,9 +32,9 @@ Enables a device administrator application of the current user. This API uses an
| Name | Type | Mandatory | Description |
| -------------- | ----------------------------------- | ---- | ------------------ |
-| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application. |
+| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application to enable. |
| enterpriseInfo | [EnterpriseInfo](#enterpriseinfo) | Yes | Enterprise information of the device administrator application. |
-| type | [AdminType](#admintype) | Yes | Type of the device administrator to enable. |
+| type | [AdminType](#admintype) | Yes | Type of the device administrator application to enable. |
| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.|
**Error codes**
@@ -70,7 +72,7 @@ adminManager.enableAdmin(wantTemp, enterpriseInfo, adminManager.AdminType.ADMIN_
enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, userId: number, callback: AsyncCallback\): void
-Enables a device administrator application of the user specified by **userId**. This API uses an asynchronous callback to return the result. The super administrator application can be enabled only by the administrator.
+Enables a device administrator application for the specified user. The super device administrator application can be activated only by the administrator. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN
@@ -82,10 +84,10 @@ Enables a device administrator application of the user specified by **userId**.
| Name | Type | Mandatory | Description |
| -------------- | ----------------------------------- | ---- | ---------------------------- |
-| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application. |
+| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application to enable. |
| enterpriseInfo | [EnterpriseInfo](#enterpriseinfo) | Yes | Enterprise information of the device administrator application. |
-| type | [AdminType](#admintype) | Yes | Type of the device administrator to enable. |
-| userId | number | Yes | User ID. The default value is the user ID of the caller. The user ID must be greater than or equal to **0**.|
+| type | [AdminType](#admintype) | Yes | Type of the device administrator application to enable. |
+| userId | number | Yes | User ID, which must be greater than or equal to 0. The default value is the user ID of the caller. |
| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object. |
**Error codes**
@@ -123,7 +125,7 @@ adminManager.enableAdmin(wantTemp, enterpriseInfo, adminManager.AdminType.ADMIN_
enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, userId?: number): Promise\
-Enables a device administrator application of the specified user (if **userId** is passed in) or the current user (if **userId** is not passed in). This API uses a promise to return the result. The super administrator application can be enabled only by the administrator.
+Enables a device administrator application for the current or specified user. The super device administrator application can be activated only by the administrator. This API uses a promise to return the result.
**Required permissions**: ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN
@@ -135,16 +137,16 @@ Enables a device administrator application of the specified user (if **userId**
| Name | Type | Mandatory | Description |
| -------------- | ----------------------------------- | ---- | ---------------------------- |
-| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application. |
+| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application to enable. |
| enterpriseInfo | [EnterpriseInfo](#enterpriseinfo) | Yes | Enterprise information of the device administrator application. |
-| type | [AdminType](#admintype) | Yes | Type of the device administrator to enable. |
-| userId | number | No | User ID. The default value is the user ID of the caller. The user ID must be greater than or equal to **0**.|
+| type | [AdminType](#admintype) | Yes | Type of the device administrator application to enable. |
+| userId | number | No | User ID, which must be greater than or equal to 0. - If **userId** is passed in, the application of the specified user is enabled. - If **userId** is not passed in, the application of the current user is enabled.|
**Return value**
| Type | Description |
| ----------------- | ----------------- |
-| Promise\ | Promise that returns no value. If the operation fails, an error object is thrown.|
+| Promise\ | Promise that returns no value. If the operation fails, an error object will be thrown.|
**Error codes**
@@ -177,7 +179,7 @@ adminManager.enableAdmin(wantTemp, enterpriseInfo, adminManager.AdminType.ADMIN_
disableAdmin(admin: Want, callback: AsyncCallback\): void
-Disables a device administrator application of the current user. This API uses an asynchronous callback to return the result.
+Disables a common administrator application for the current user. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN
@@ -189,7 +191,7 @@ Disables a device administrator application of the current user. This API uses a
| Name | Type | Mandatory | Description |
| -------- | ----------------------------------- | ---- | ------------------- |
-| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application. |
+| admin | [Want](js-apis-app-ability-want.md) | Yes | Common administrator application to disable. |
| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.|
**Error codes**
@@ -221,7 +223,7 @@ adminManager.disableAdmin(wantTemp, (err) => {
disableAdmin(admin: Want, userId: number, callback: AsyncCallback\): void
-Disables a device administrator application of the user specified by **userId**. This API uses an asynchronous callback to return the result.
+Disables a common administrator application for the specified user. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN
@@ -233,8 +235,8 @@ Disables a device administrator application of the user specified by **userId**.
| Name | Type | Mandatory | Description |
| -------- | ----------------------------------- | ---- | ---------------------------- |
-| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application. |
-| userId | number | Yes | User ID. The default value is the user ID of the caller. The user ID must be greater than or equal to **0**.|
+| admin | [Want](js-apis-app-ability-want.md) | Yes | Common administrator application to disable. |
+| userId | number | Yes | User ID, which must be greater than or equal to 0. The default value is the user ID of the caller. |
| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object. |
**Error codes**
@@ -266,7 +268,7 @@ adminManager.disableAdmin(wantTemp, 100, (err) => {
disableAdmin(admin: Want, userId?: number): Promise\
-Disables a device administrator application of the specified user (if **userId** is passed in) or the current user (if **userId** is not passed in). This API uses a promise to return the result.
+Disables a common administrator application for the current or specified user. This API uses a promise to return the result.
**Required permissions**: ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN
@@ -278,14 +280,14 @@ Disables a device administrator application of the specified user (if **userId**
| Name | Type | Mandatory | Description |
| ------ | ----------------------------------- | ---- | ---------------------------- |
-| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application. |
-| userId | number | No | User ID. The default value is the user ID of the caller. The user ID must be greater than or equal to **0**.|
+| admin | [Want](js-apis-app-ability-want.md) | Yes | Common administrator application to disable. |
+| userId | number | No | User ID, which must be greater than or equal to 0. - If **userId** is passed in, the application of the specified user is disabled. - If **userId** is not passed in, the application of the current user is disabled.|
**Return value**
| Type | Description |
| ----------------- | ----------------- |
-| Promise\ | Promise that returns no value. If the operation fails, an error object is thrown.|
+| Promise\ | Promise that returns no value. If the operation fails, an error object will be thrown.|
**Error codes**
@@ -312,7 +314,7 @@ adminManager.disableAdmin(wantTemp, 100).catch((err) => {
disableSuperAdmin(bundleName: String, callback: AsyncCallback\): void
-Disables a super device administrator application based on the specified bundle name. This API uses an asynchronous callback to return the result.
+Disables a super administrator application for the administrator based on **bundleName**. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN
@@ -324,14 +326,14 @@ Disables a super device administrator application based on the specified bundle
| Name | Type | Mandatory | Description |
| ---------- | ----------------------- | ---- | ------------------- |
-| bundleName | String | Yes | Bundle name of the super device administrator application. |
+| bundleName | String | Yes | Bundle name of the super administrator application to disable. |
| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.|
**Error codes**
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
-| ID| Error Message |
+| ID| Error Message |
| ------- | ----------------------------------------------------------------- |
| 9200005 | failed to disable the administrator application of the device. |
@@ -353,7 +355,7 @@ adminManager.disableSuperAdmin(bundleName, (err) => {
disableSuperAdmin(bundleName: String): Promise\
-Disables a super device administrator application based on the specified bundle name. This API uses a promise to return the result.
+Disables a super administrator application for the administrator based on **bundleName**. This API uses a promise to return the result.
**Required permissions**: ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN
@@ -365,13 +367,13 @@ Disables a super device administrator application based on the specified bundle
| Name | Type | Mandatory | Description |
| ---------- | ------ | ---- | ------------ |
-| bundleName | String | Yes | Bundle name of the super device administrator application.|
+| bundleName | String | Yes | Bundle name of the super administrator application to disable.|
**Return value**
| Type | Description |
| ----------------- | ----------------- |
-| Promise\ | Promise that returns no value. If the operation fails, an error object is thrown.|
+| Promise\ | Promise that returns no value. If the operation fails, an error object will be thrown.|
**Error codes**
@@ -405,7 +407,7 @@ Checks whether a device administrator application of the current user is enabled
| Name | Type | Mandatory | Description |
| -------- | ----------------------------------- | ---- | -------------------- |
-| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application. |
+| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application to check. |
| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is a Boolean value (**true** means that the device administrator application is enabled; and **false** means the opposite). If the operation fails, **err** is an error object.|
**Example**
@@ -429,7 +431,7 @@ adminManager.isAdminEnabled(wantTemp, (err, result) => {
isAdminEnabled(admin: Want, userId: number, callback: AsyncCallback\): void
-Checks whether a device administrator application of the user specified by **userId** is enabled. This API uses an asynchronous callback to return the result.
+Checks whether a device administrator application of the specified user is enabled. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Customization.EnterpriseDeviceManager
@@ -439,8 +441,8 @@ Checks whether a device administrator application of the user specified by **use
| Name | Type | Mandatory | Description |
| -------- | ----------------------------------- | ---- | ---------------------------- |
-| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application. |
-| userId | number | Yes | User ID. The default value is the user ID of the caller. The user ID must be greater than or equal to **0**.|
+| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application to check. |
+| userId | number | Yes | User ID, which must be greater than or equal to 0. The default value is the user ID of the caller. |
| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is a Boolean value (**true** means that the device administrator application is enabled; and **false** means the opposite). If the operation fails, **err** is an error object. |
**Example**
@@ -464,7 +466,7 @@ adminManager.isAdminEnabled(wantTemp, 100, (err, result) => {
isAdminEnabled(admin: Want, userId?: number): Promise\
-Checks whether a device administrator application of the specified user (if **userId** is passed in) or the current user (if **userId** is not passed in) is enabled. This API uses a promise to return the result.
+Checks whether a device administrator application of the current or specified user is enabled. This API uses a promise to return the result.
**System capability**: SystemCapability.Customization.EnterpriseDeviceManager
@@ -474,14 +476,14 @@ Checks whether a device administrator application of the specified user (if **us
| Name | Type | Mandatory | Description |
| ------ | ----------------------------------- | ---- | ---------------------------- |
-| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application. |
-| userId | number | No | User ID. The default value is the user ID of the caller. The user ID must be greater than or equal to **0**.|
+| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application to check. |
+| userId | number | No | User ID, which must be greater than or equal to 0. - If **userId** is passed in, the application of the specified user is checked. - If **userId** is not passed in, the application of the current user is checked.|
**Return value**
| Type | Description |
| ----------------- | ------------------- |
-| Promise\ | Promise used to return the result. If **true** is returned, the device administrator application is enabled. If **false** is returned, the device administrator application is not enabled.|
+| Promise\ | Promise used to return the result. The value **true** means the device administrator application is enabled; the value **false** means the opposite.|
**Example**
@@ -502,7 +504,7 @@ adminManager.isAdminEnabled(wantTemp, 100).then((result) => {
isSuperAdmin(bundleName: String, callback: AsyncCallback\): void
-Checks whether a super device administrator application is enabled based on the specified bundle name. This API uses an asynchronous callback to return the result.
+Checks whether a super administrator application of the administrator is enabled based on **bundleName**. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Customization.EnterpriseDeviceManager
@@ -512,8 +514,8 @@ Checks whether a super device administrator application is enabled based on the
| Name | Type | Mandatory | Description |
| ---------- | ----------------------- | ---- | -------------------- |
-| bundleName | String | Yes | Device administrator application. |
-| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is a Boolean value (**true** means that the super device administrator application is enabled; and **false** means the opposite). If the operation fails, **err** is an error object.|
+| bundleName | String | Yes | Super administrator application to check. |
+| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is a Boolean value (**true** means that the device administrator application is enabled; and **false** means the opposite). If the operation fails, **err** is an error object.|
**Example**
@@ -533,7 +535,7 @@ adminManager.isSuperAdmin(bundleName, (err, result) => {
isSuperAdmin(bundleName: String): Promise\
-Checks whether a super device administrator application is enabled based on the specified bundle name. This API uses a promise to return the result.
+Checks whether a super administrator application of the administrator is enabled based on **bundleName**. This API uses a promise to return the result.
**System capability**: SystemCapability.Customization.EnterpriseDeviceManager
@@ -543,13 +545,13 @@ Checks whether a super device administrator application is enabled based on the
| Name | Type | Mandatory | Description |
| ---------- | ------ | ---- | --------- |
-| bundleName | String | Yes | Super device administrator application.|
+| bundleName | String | Yes | Super administrator application to check.|
**Return value**
| ID | Error Message |
| ----------------- | ------------------- |
-| Promise\ | Promise used to return the result. If **true** is returned, the super device administrator application is enabled. If **false** is returned, the super device administrator application is not enabled.|
+| Promise\ | Promise used to return the result. The value **true** means the super administrator application is enabled; the value **false** means the opposite. |
**Example**
@@ -567,7 +569,7 @@ adminManager.isSuperAdmin(bundleName).then((result) => {
setEnterpriseInfo(admin: Want, enterpriseInfo: EnterpriseInfo, callback: AsyncCallback\;): void
-Sets the enterprise information of a device administrator application. This API uses an asynchronous callback to return the result.
+Sets enterprise information for a device administrator application. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.SET_ENTERPRISE_INFO
@@ -580,7 +582,7 @@ Sets the enterprise information of a device administrator application. This API
| Name | Type | Mandatory | Description |
| -------------- | ----------------------------------- | ---- | ---------------------- |
| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application. |
-| enterpriseInfo | [EnterpriseInfo](#enterpriseinfo) | Yes | Enterprise information of the device administrator application. |
+| enterpriseInfo | [EnterpriseInfo](#enterpriseinfo) | Yes | Enterprise information to set. |
| callback | AsyncCallback\; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.|
**Error codes**
@@ -616,7 +618,7 @@ adminManager.setEnterpriseInfo(wantTemp, enterpriseInfo, (err) => {
setEnterpriseInfo(admin: Want, enterpriseInfo: EnterpriseInfo): Promise\;
-Sets the enterprise information of a device administrator application. This API uses a promise to return the result.
+Sets enterprise information for a device administrator application. This API uses a promise to return the result.
**Required permissions**: ohos.permission.SET_ENTERPRISE_INFO
@@ -629,13 +631,13 @@ Sets the enterprise information of a device administrator application. This API
| Name | Type | Mandatory | Description |
| -------------- | ----------------------------------- | ---- | ------------ |
| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application. |
-| enterpriseInfo | [EnterpriseInfo](#enterpriseinfo) | Yes | Enterprise information of the device administrator application.|
+| enterpriseInfo | [EnterpriseInfo](#enterpriseinfo) | Yes | Enterprise information to set.|
**Return value**
| Type | Description |
| ----------------- | --------------------- |
-| Promise\ | Promise that returns no value. If the operation fails, an error object is thrown.|
+| Promise\ | Promise that returns no value. If the operation fails, an error object will be thrown.|
**Error codes**
@@ -724,7 +726,7 @@ Obtains the enterprise information of a device administrator application. This A
| Type | Description |
| ---------------------------------------- | ------------------------- |
-| Promise<[EnterpriseInfo](#enterpriseinfo)> | Promise used to return the enterprise information of the specified device administrator application obtained.|
+| Promise<[EnterpriseInfo](#enterpriseinfo)> | Promise used to return the enterprise information obtained.|
**Error codes**
@@ -753,7 +755,7 @@ adminManager.getEnterpriseInfo(wantTemp).then((result) => {
subscribeManagedEvent(admin: Want, managedEvents: Array\, callback: AsyncCallback\): void
-Subscribes to system management events through the specified device administrator application. This API uses an asynchronous callback to return the result.
+Subscribes to system management events of a device administrator application. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.ENTERPRISE_SUBSCRIBE_MANAGED_EVENT
@@ -800,7 +802,7 @@ adminManager.subscribeManagedEvent(wantTemp, events, (err) => {
subscribeManagedEvent(admin: Want, managedEvents: Array\): Promise\
-Subscribes to system management events through the specified device administrator application. This API uses a promise to return the result.
+Subscribes to system management events of a device administrator application. This API uses a promise to return the result.
**Required permissions**: ohos.permission.ENTERPRISE_SUBSCRIBE_MANAGED_EVENT
@@ -819,7 +821,7 @@ Subscribes to system management events through the specified device administrato
| Type | Description |
| ----- | ----------------------------------- |
-| Promise\ | Promise that returns no value. If the operation fails, an error object is thrown.|
+| Promise\ | Promise that returns no value. If the operation fails, an error object will be thrown.|
**Error codes**
@@ -849,7 +851,7 @@ adminManager.subscribeManagedEvent(wantTemp, events).then(() => {
unsubscribeManagedEvent(admin: Want, managedEvents: Array\, callback: AsyncCallback\): void
-Unsubscribes from system management events through the specified device administrator application. This API uses an asynchronous callback to return the result.
+Unsubscribes from system management events of a device administrator application. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.ENTERPRISE_SUBSCRIBE_MANAGED_EVENT
@@ -896,7 +898,7 @@ adminManager.unsubscribeManagedEvent(wantTemp, events, (err) => {
unsubscribeManagedEvent(admin: Want, managedEvents: Array\): Promise\
-Unsubscribes from system management events through the specified device administrator application. This API uses a promise to return the result.
+Unsubscribes from system management events of a device administrator application. This API uses a promise to return the result.
**Required permissions**: ohos.permission.ENTERPRISE_SUBSCRIBE_MANAGED_EVENT
@@ -915,7 +917,7 @@ Unsubscribes from system management events through the specified device administ
| Type | Description |
| ----- | ----------------------------------- |
-| Promise\ | Promise that returns no value. If the operation fails, an error object is thrown.|
+| Promise\ | Promise that returns no value. If the operation fails, an error object will be thrown.|
**Error codes**
@@ -943,7 +945,7 @@ adminManager.unsubscribeManagedEvent(wantTemp, events).then(() => {
## EnterpriseInfo
-Defines the enterprise information of a device administrator application.
+Represents the enterprise information of a device administrator application.
**System capability**: SystemCapability.Customization.EnterpriseDeviceManager
@@ -951,12 +953,12 @@ Defines the enterprise information of a device administrator application.
| Name | Type | Mandatory| Description |
| ----------- | --------| ---- | ------------------------------- |
-| name | string | Yes | Name of the enterprise to which the device administrator application belongs.|
-| description | string | Yes | Description of the enterprise to which the device administrator application belongs.|
+| name | string | Yes | Name of the enterprise.|
+| description | string | Yes | Description of the enterprise.|
## AdminType
-Enumerates the administrator types of the device administrator application.
+Enumerates the types of device administrator applications.
**System capability**: SystemCapability.Customization.EnterpriseDeviceManager
@@ -964,8 +966,8 @@ Enumerates the administrator types of the device administrator application.
| Name | Value | Description |
| ----------------- | ---- | ----- |
-| ADMIN_TYPE_NORMAL | 0x00 | Common administrator.|
-| ADMIN_TYPE_SUPER | 0x01 | Super administrator.|
+| ADMIN_TYPE_NORMAL | 0x00 | Common administrator application.|
+| ADMIN_TYPE_SUPER | 0x01 | Super administrator application.|
## ManagedEvent
diff --git a/en/application-dev/reference/apis/js-apis-file-fs.md b/en/application-dev/reference/apis/js-apis-file-fs.md
index 5effa68ff47127104f00d7d9113104470f027b91..3e783a185818183eb33d3419cf5bbb6f0d47cfa2 100644
--- a/en/application-dev/reference/apis/js-apis-file-fs.md
+++ b/en/application-dev/reference/apis/js-apis-file-fs.md
@@ -2687,7 +2687,7 @@ Represents detailed file information. Before calling any API of the **Stat()** c
| Name | Type | Readable | Writable | Description |
| ------ | ------ | ---- | ---- | ---------------------------------------- |
| ino | number | Yes | No | File ID. Different files on the same device have different **ino**s.| |
-| mode | number | Yes | No | File permissions. The meaning of each bit is as follows: - **0o400**: The owner has the read permission on a regular file or a directory entry. - **0o200**: The owner has the permission to write a regular file or create and delete a directory entry. - **0o100**: The owner has the permission to execute a regular file or search for the specified path in a directory. - **0o040**: The user group has the read permission on a regular file or a directory entry. - **0o020**: The user group has the permission to write a regular file or create and delete a directory entry. - **0o010**: The user group has the permission to execute a regular file or search for the specified path in a directory. - **0o004**: Other users have the permission to read a regular file or read a directory entry. - **0o002**: Other users have the permission to write a regular file or create and delete a directory entry. - **0o001**: Other users have the permission to execute a regular file or search for the specified path in a directory.|
+| mode | number | Yes | No | File permissions. The meaning of each bit is as follows: **NOTE** The following values are in octal format. The returned values are in decimal format. You need to convert the values. - **0o400**: The owner has the permission to read a regular file or a directory entry. - **0o200**: The owner has the permission to write a regular file or create and delete a directory entry. - **0o100**: The owner has the permission to execute a regular file or search for the specified path in a directory. - **0o040**: The user group has the permission to read a regular file or a directory entry. - **0o020**: The user group has the permission to write a regular file or create and delete a directory entry. - **0o010**: The user group has the permission to execute a regular file or search for the specified path in a directory. - **0o004**: Other users have the permission to read a regular file or a directory entry. - **0o002**: Other users have the permission to write a regular file or create and delete a directory entry. - **0o001**: Other users have the permission to execute a regular file or search for the specified path in a directory.|
| uid | number | Yes | No | ID of the file owner.|
| gid | number | Yes | No | ID of the user group of the file.|
| size | number | Yes | No | File size, in bytes. This parameter is valid only for regular files. |
diff --git a/en/application-dev/reference/apis/js-apis-fileAccess.md b/en/application-dev/reference/apis/js-apis-fileAccess.md
index 09dfaa48285b7229fcae30e22469f3332c25bacf..c54f46c1dbb6f11291fe2944eb8b45a465ecb4b6 100644
--- a/en/application-dev/reference/apis/js-apis-fileAccess.md
+++ b/en/application-dev/reference/apis/js-apis-fileAccess.md
@@ -1,6 +1,6 @@
# @ohos.file.fileAccess (User File Access and Management)
-The **fileAccess** module provides a framework for accessing and operating user files based on the ExtensionAbility mechanism. This module interacts with file management services, such as the media library and external storage management service, and provides a set of unified interfaces for system applications to access and manage files. The media library service allows access to user files on local and distributed devices. The external storage management service allows access to the user files stored on devices, such as shared disks, USB flash drives, and SD cards.
+The **fileAccess** module provides a framework for accessing and operating user files based on the ExtensionAbility mechanism. This module interacts with a variety of file management services, such as the storage management service, and provides a set of unified file access and management interfaces for system applications. The storage management service manages both the directories of the built-in storage and resources on external devices, such as shared disks, USB flash drives, and SD cards.
>**NOTE**
>
@@ -124,10 +124,9 @@ For details about error codes, see [File Management Error Codes](../errorcodes/e
createFileAccessHelper() {
let fileAccessHelper = null;
// Obtain wantInfos by using getFileAccessAbilityInfo().
- // Create a helper object to interact with the media library service only.
let wantInfos = [
{
- "bundleName": "com.ohos.medialibrary.medialibrarydata",
+ "bundleName": "com.ohos.UserFile.ExternalFileManager",
"abilityName": "FileExtensionAbility",
},
]
@@ -248,7 +247,7 @@ For details about error codes, see [File Management Error Codes](../errorcodes/e
try {
let fileIterator = fileInfoDir.listFile();
// listFile() with the filter implementation.
- // let fileIterator = rootInfo.listFile(filter);
+ // let fileIterator = fileInfoDir.listFile(filter);
if (!fileIterator) {
console.error("listFile interface returns an undefined object");
return;
@@ -304,7 +303,7 @@ For details about error codes, see [File Management Error Codes](../errorcodes/e
try {
let fileIterator = fileInfoDir.scanFile();
// scanFile() with the filter implementation.
- // let fileIterator = rootInfo.scanFile(filter);
+ // let fileIterator = fileInfoDir.scanFile(filter);
if (!fileIterator) {
console.error("scanFile interface returns an undefined object");
return;
@@ -651,10 +650,10 @@ For details about error codes, see [File Management Error Codes](../errorcodes/e
**Example**
```js
- // The media library URI is used as an example.
+ // A built-in storage directory is used as an example.
// In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo.
// You can use the URI obtained.
- let sourceUri = "file://media/file/6";
+ let sourceUri = "file://docs/storage/Users/currentUser/Download";
let displayName = "file1"
let fileUri = null;
try {
@@ -695,10 +694,10 @@ For details about error codes, see [File Management Error Codes](../errorcodes/e
**Example**
```js
- // The media library URI is used as an example.
+ // A built-in storage directory is used as an example.
// In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo.
// You can use the URI obtained.
- let sourceUri = "file://media/file/6";
+ let sourceUri = "file://docs/storage/Users/currentUser/Download";
let displayName = "file1"
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
@@ -744,10 +743,10 @@ For details about error codes, see [File Management Error Codes](../errorcodes/e
**Example**
```js
- // The media library URI is used as an example.
+ // A built-in storage directory is used as an example.
// In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo.
// You can use the URI obtained.
- let sourceUri = "file://media/file/6";
+ let sourceUri = "file://docs/storage/Users/currentUser/Download";
let dirName = "dirTest"
let dirUri = null;
try {
@@ -788,10 +787,10 @@ For details about error codes, see [File Management Error Codes](../errorcodes/e
**Example**
```js
- // The media library URI is used as an example.
+ // A built-in storage directory is used as an example.
// In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo.
// You can use the URI obtained.
- let sourceUri = "file://media/file/6";
+ let sourceUri = "file://docs/storage/Users/currentUser/Download";
let dirName = "dirTest"
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
@@ -837,10 +836,10 @@ For details about error codes, see [File Management Error Codes](../errorcodes/e
**Example**
```js
- // The media library URI is used as an example.
+ // A built-in storage directory is used as an example.
// In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
// You can use the URI obtained.
- let targetUri = "file://media/file/100";
+ let targetUri = "file://docs/storage/Users/currentUser/Download/1.txt";
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
let fd = await fileAccessHelper.openFile(targetUri, fileAccess.OPENFLAGS.READ);
@@ -874,10 +873,10 @@ For details about error codes, see [File Management Error Codes](../errorcodes/e
**Example**
```js
- // The media library URI is used as an example.
+ // A built-in storage directory is used as an example.
// In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
// You can use the URI obtained.
- let targetUri = "file://media/file/100";
+ let targetUri = "file://docs/storage/Users/currentUser/Download/1.txt";
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
fileAccessHelper.openFile(targetUri, fileAccess.OPENFLAGS.READ, function (err, fd) {
@@ -921,10 +920,10 @@ For details about error codes, see [File Management Error Codes](../errorcodes/e
**Example**
```js
- // The media library URI is used as an example.
+ // A built-in storage directory is used as an example.
// In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
// You can use the URI obtained.
- let targetUri = "file://media/file/100";
+ let targetUri = "file://docs/storage/Users/currentUser/Download/1.txt";
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
let code = await fileAccessHelper.delete(targetUri);
@@ -959,10 +958,10 @@ For details about error codes, see [File Management Error Codes](../errorcodes/e
**Example**
```js
- // The media library URI is used as an example.
+ // A built-in storage directory is used as an example.
// In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
// You can use the URI obtained.
- let targetUri = "file://media/file/100";
+ let targetUri = "file://docs/storage/Users/currentUser/Download/1.txt";
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
fileAccessHelper.delete(targetUri, function (err, code) {
@@ -1007,11 +1006,11 @@ For details about error codes, see [File Management Error Codes](../errorcodes/e
**Example**
```js
- // The media library URI is used as an example.
- // In the sample code, sourceFile destFile indicates the file or directory in the Download directory. The URI is the URI in fileInfo.
+ // A built-in storage directory is used as an example.
+ // In the sample code, sourceFile and destFile indicate the files or directories in the Download directory. The URI is the URI in fileInfo.
// You can use the URI obtained.
- let sourceFile = "file://media/file/102";
- let destFile = "file://media/file/101";
+ let sourceFile = "file://docs/storage/Users/currentUser/Download/1.txt";
+ let destFile = "file://docs/storage/Users/currentUser/Download/test";
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
let fileUri = await fileAccessHelper.move(sourceFile, destFile);
@@ -1046,11 +1045,11 @@ For details about error codes, see [File Management Error Codes](../errorcodes/e
**Example**
```js
- // The media library URI is used as an example.
- // In the sample code, sourceFile destFile indicates the file or directory in the Download directory. The URI is the URI in fileInfo.
+ // A built-in storage directory is used as an example.
+ // In the sample code, sourceFile and destFile indicate the files or directories in the Download directory. The URI is the URI in fileInfo.
// You can use the URI obtained.
- let sourceFile = "file://media/file/102";
- let destFile = "file://media/file/101";
+ let sourceFile = "file://docs/storage/Users/currentUser/Download/1.txt";
+ let destFile = "file://docs/storage/Users/currentUser/Download/test";
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
fileAccessHelper.move(sourceFile, destFile, function (err, fileUri) {
@@ -1095,10 +1094,10 @@ For details about error codes, see [File Management Error Codes](../errorcodes/e
**Example**
```js
- // The media library URI is used as an example.
+ // A built-in storage directory is used as an example.
// In the sample code, sourceDir indicates a file in the Download directory. The URI is the URI in fileInfo.
// You can use the URI obtained.
- let sourceDir = "file://media/file/100";
+ let sourceDir = "file://docs/storage/Users/currentUser/Download/1.txt";
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
let DestDir = await fileAccessHelper.rename(sourceDir, "testDir");
@@ -1133,10 +1132,10 @@ For details about error codes, see [File Management Error Codes](../errorcodes/e
**Example**
```js
- // The media library URI is used as an example.
+ // A built-in storage directory is used as an example.
// In the sample code, sourceDir indicates a file in the Download directory. The URI is the URI in fileInfo.
// You can use the URI obtained.
- let sourceDir = "file://media/file/100";
+ let sourceDir = "file://docs/storage/Users/currentUser/Download/1.txt";
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
fileAccessHelper.rename(sourceDir, "testDir", function (err, DestDir) {
@@ -1180,10 +1179,10 @@ For details about error codes, see [File Management Error Codes](../errorcodes/e
**Example**
```js
- // The media library URI is used as an example.
+ // A built-in storage directory is used as an example.
// In the sample code, sourceDir indicates a file in the Download directory. The URI is the URI in fileInfo.
// You can use the URI obtained.
- let sourceDir = "file://media/file/100";
+ let sourceDir = "file://docs/storage/Users/currentUser/Download/1.txt";
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
let existJudgment = await fileAccessHelper.access(sourceDir);
@@ -1220,10 +1219,10 @@ For details about error codes, see [File Management Error Codes](../errorcodes/e
**Example**
```js
- // The media library URI is used as an example.
- // In the sample code, sourceDir indicates a file in the Download directory. The URI is the URI in fileInfo.
+ // A built-in storage directory is used as an example.
+ // In the sample code, sourceDir indicates a folder in the Download directory. The URI is the URI in fileInfo.
// You can use the URI obtained.
- let sourceDir = "file://media/file/100";
+ let sourceDir = "file://docs/storage/Users/currentUser/Download/test";
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
fileAccessHelper.access(sourceDir, function (err, existJudgment) {
@@ -1266,10 +1265,10 @@ Obtains a **FileInfo** object based on the specified URI. This API uses a promis
**Example**
```js
- // The media library URI is used as an example.
+ // A built-in storage directory is used as an example.
// In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo.
// You can use the URI obtained.
- let sourceUri = "file://media/file/6";
+ let sourceUri = "file://docs/storage/Users/currentUser/Download";
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
let fileInfo = await fileAccessHelper.getFileInfoFromUri(sourceUri);
@@ -1298,10 +1297,10 @@ Obtains a **FileInfo** object based on the specified URI. This API uses an async
**Example**
```js
- // The media library URI is used as an example.
+ // A built-in storage directory is used as an example.
// In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo.
// You can use the URI obtained.
- let sourceUri = "file://media/file/6";
+ let sourceUri = "file://docs/storage/Users/currentUser/Download";
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
fileAccessHelper.getFileInfoFromUri(sourceUri, function (err, fileInfo) {
@@ -1342,7 +1341,6 @@ Obtains a **FileInfo** object based on the **relativePath**. This API uses a pro
**Example**
```js
- // The relative path of the Media Library is used as an example.
// In the sample code, relativePath indicates the Download directory, which is the relativePath in fileInfo.
// You can use the relativePath obtained.
let relativePath = "Download/";
@@ -1374,7 +1372,6 @@ Obtains a **FileInfo** object based on the **relativePath**. This API uses an as
**Example**
```js
- // The relative path of the Media Library is used as an example.
// In the sample code, relativePath indicates the Download directory, which is the relativePath in fileInfo.
// You can use the relativePath obtained.
let relativePath = "Download/";
@@ -1392,90 +1389,6 @@ Obtains a **FileInfo** object based on the **relativePath**. This API uses an as
};
```
-### getThumbnail10+
-
-getThumbnail(uri: string, size: image.Size) : Promise<image.PixelMap>
-
-Obtains the **Pixelmap** object of a media file based on the specified URI and size. This API uses a promise to return the result.
-
-**System capability**: SystemCapability.FileManagement.UserFileService
-
-**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
-
-**Parameters**
-
-| Name| Type | Mandatory| Description |
-| ------ | ----------------------------------- | ---- | ----------- |
-| uri | string | Yes | URI of the media file.|
-| size | [image.Size](js-apis-image.md#size) | Yes | Size of the thumbnail. |
-
-**Return value**
-
-| Type | Description |
-| :---------------------------- | :----------------- |
-| Promise<[image.PixelMap](js-apis-image.md#pixelmap7)> | Promise used to return the **Pixelmap** object obtained.|
-
-**Example**
-
-```js
-// The media library URI is used as an example.
-// In the sample code, targetUri indicates a media file (image, audio, or video) in the Download directory. The URI is the URI in fileInfo.
-// You can use the URI obtained.
-let targetUri = "file://media/image/100";
-let size = { width: 128, height: 128 };
-try {
- // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
- let pixelMap = await fileAccessHelper.getThumbnail(targetUri, size);
- let imageInfo = await pixelMap.getImageInfo();
- console.log("getThumbnail sucess, pixelMap.width: " + imageInfo.size.width);
- console.log("getThumbnail sucess, pixelMap.height: " + imageInfo.size.height);
-} catch (error) {
- console.error("getThumbnail failed, errCode:" + error.code + ", errMessage:" + error.message);
-};
-```
-
-### getThumbnail10+
-
- getThumbnail(uri: string, size: image.Size, callback: AsyncCallback<image.PixelMap>) : void
-
-Obtains the **Pixelmap** object of a media file based on the specified URI and size. This API uses an asynchronous callback to return the result.
-
-**System capability**: SystemCapability.FileManagement.UserFileService
-
-**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------- | ----------------------------------- | ---- | ------------------ |
-| uri | string | Yes | URI of the media file. |
-| size | [image.Size](js-apis-image.md#size) | Yes | Size of the thumbnail. |
-| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | Yes | Callback invoked to return the **Pixelmap** object obtained.|
-
-**Example**
-
-```js
-// The media library URI is used as an example.
-// In the sample code, targetUri indicates a media file (image, audio, or video) in the Download directory. The URI is the URI in fileInfo.
-// You can use the URI obtained.
-let targetUri = "file://media/image/100";
-let size = { width: 128, height: 128 };
-try {
- // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
- fileAccessHelper.getThumbnail(targetUri, size, async(err, pixelMap) => {
- if (err) {
- console.error("Failed to getThumbnail in async, errCode:" + err.code + ", errMessage:" + err.message);
- return;
- }
- let imageInfo = await pixelMap.getImageInfo();
- console.log("getThumbnail sucess, pixelMap.width: " + imageInfo.size.width);
- console.log("getThumbnail sucess, pixelMap.height: " + imageInfo.size.height);
- });
-} catch (error) {
- console.error("getThumbnail failed, errCode:" + error.code + ", errMessage:" + error.message);
-};
-```
-
### query10+
query(uri:string, metaJson: string) : Promise<string>
@@ -1502,7 +1415,7 @@ Queries the attribute information about a file or directory based on the URI. Th
**Example**
```js
-var imageFileRelativePath = "Download/queryTest/image/01.jpg";
+var imageFileRelativePath = "/storage/Users/currentUser/Download/queryTest/image/01.jpg";
var jsonStrSingleRelativepath = JSON.stringify({ [fileAccess.FileKey.RELATIVE_PATH]: "" });
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
@@ -1535,7 +1448,7 @@ Queries the attribute information about a file or directory based on the URI. Th
**Example**
```js
-var imageFileRelativePath = "Download/queryTest/image/01.jpg";
+var imageFileRelativePath = "/storage/Users/currentUser/Download/queryTest/image/01.jpg";
var jsonStrSingleRelativepath = JSON.stringify({ [fileAccess.FileKey.RELATIVE_PATH]: "" });
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
@@ -1566,8 +1479,8 @@ Copies a file or directory. This API uses a promise to return the result.
| Name | Type | Mandatory| Description |
| --------- | ------- | ---- | ------------------------------------------------------------ |
-| sourceUri | string | Yes | URI of the file or directory to copy, for example, **file://media/file/102**. |
-| destUri | string | Yes | URI of the destination directory, for example, **file://media/file/101**. |
+| sourceUri | string | Yes | URI of the file or folder to copy, for example, **file://docs/storage/Users/currentUser/Download/1.txt**. |
+| destUri | string | Yes | URI of the file or folder created, for example, **file://docs/storage/Users/currentUser/Download/test**. |
| force | boolean | No | Whether to forcibly overwrite the file with the same name. If **force** is **true**, the file with the same name will be overwritten. If **force** is **false** or not specified, the file with the same name will not be overwritten.|
**Return value**
@@ -1579,11 +1492,11 @@ Copies a file or directory. This API uses a promise to return the result.
Example 1: Copy a file with **force** unspecified.
```js
-// The media library URI is used as an example.
+// A built-in storage directory is used as an example.
// In the sample code, sourceFile indicates the file (directory) in the Download directory to copy, destFile indicates the destination directory in the Download directory, and uri is to URI in fileInfo.
// You can use the URI obtained.
-let sourceFile = "file://media/file/102";
-let destFile = "file://media/file/101";
+let sourceFile = "file://docs/storage/Users/currentUser/Download/1.txt";
+let destFile = "file://docs/storage/Users/currentUser/Download/test";
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
let copyResult = await fileAccessHelper.copy(sourceFile, destFile);
@@ -1605,11 +1518,11 @@ try {
Example 2: Copy a file or directory when **force** set to **true**.
```js
-// The media library URI is used as an example.
+// A built-in storage directory is used as an example.
// In the sample code, sourceFile indicates the file (directory) in the Download directory to copy, destFile indicates the destination directory in the Download directory, and uri is to URI in fileInfo.
// You can use the URI obtained.
-let sourceFile = "file://media/file/102";
-let destFile = "file://media/file/101";
+let sourceFile = "file://docs/storage/Users/currentUser/Download/1.txt";
+let destFile = "file://docs/storage/Users/currentUser/Download/test";
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
let copyResult = await fileAccessHelper.copy(sourceFile, destFile, true);
@@ -1642,18 +1555,18 @@ Copies a file or directory. This API uses an asynchronous callback to return the
| Name | Type | Mandatory| Description |
| --------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ |
-| sourceUri | string | Yes | URI of the file or directory to copy, for example, **file://media/file/102**. |
-| destUri | string | Yes | URI of the destination directory, for example, **file://media/file/101**. |
+| sourceUri | string | Yes | URI of the file or folder to copy, for example, **file://docs/storage/Users/currentUser/Download/1.txt**. |
+| destUri | string | Yes | URI of the file or folder created, for example, **file://docs/storage/Users/currentUser/Download/test**. |
| callback | AsyncCallback<Array<[CopyResult](#copyresult10)>> | Yes | Callback invoked to return the result. If the file or directory is copied successfully, no information is returned. If the file copy fails, **copyResult** is returned.|
**Example**
```js
-// The media library URI is used as an example.
+// A built-in storage directory is used as an example.
// In the sample code, sourceFile indicates the file (directory) in the Download directory to copy, destFile indicates the destination directory in the Download directory, and uri is to URI in fileInfo.
// You can use the URI obtained.
-let sourceFile = "file://media/file/102";
-let destFile = "file://media/file/101";
+let sourceFile = "file://docs/storage/Users/currentUser/Download/1.txt";
+let destFile = "file://docs/storage/Users/currentUser/Download/test";
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
fileAccessHelper.copy(sourceFile, destFile, async (err, copyResult) => {
@@ -1691,19 +1604,19 @@ Copies a file or directory. This API uses an asynchronous callback to return the
| Name | Type | Mandatory| Description |
| --------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ |
-| sourceUri | string | Yes | URI of the file or directory to copy, for example, **file://media/file/102**. |
-| destUri | string | Yes | URI of the destination directory, for example, **file://media/file/101**. |
+| sourceUri | string | Yes | URI of the file or folder to copy, for example, **file://docs/storage/Users/currentUser/Download/1.txt**. |
+| destUri | string | Yes | URI of the file or folder created, for example, **file://docs/storage/Users/currentUser/Download/test**. |
| force | boolean | Yes | Whether to forcibly overwrite the file with the same name. If **force** is **true**, the file with the same name will be overwritten. If **force** is **false** or not specified, the file with the same name will not be overwritten.|
| callback | AsyncCallback<Array<[CopyResult](#copyresult10)>> | Yes | Callback invoked to return the result. If the file or directory is copied successfully, no information is returned. If the file copy fails, **copyResult** is returned.|
**Example**
```js
-// The media library URI is used as an example.
+// A built-in storage directory is used as an example.
// In the sample code, sourceFile indicates the file (directory) in the Download directory to copy, destFile indicates the destination directory in the Download directory, and uri is to URI in fileInfo.
// You can use the URI obtained.
-let sourceFile = "file://media/file/102";
-let destFile = "file://media/file/101";
+let sourceFile = "file://docs/storage/Users/currentUser/Download/1.txt";
+let destFile = "file://docs/storage/Users/currentUser/Download/test";
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
fileAccessHelper.copy(sourceFile, destFile, true, async (err, copyResult) => {
@@ -1771,6 +1684,3 @@ Enumerates the keys of the file attributes to query.
| DATE_MODIFIED | 'date_modified' | Date when a file was modified, for example, **1665310670**. |
| RELATIVE_PATH | 'relative_path' | Relative path of the file, for example, **Pictures/Screenshots/**.|
| FILE_SIZE | 'size' | Size of a file, in bytes. |
-| WIDTH | 'width' | Width of the image file, in pixels. |
-| HEIGHT | 'height' | Height of the image file, in pixels. |
-| DURATION | 'duration' | Duration of the audio or video file, in milliseconds. |
diff --git a/en/application-dev/reference/apis/js-apis-font.md b/en/application-dev/reference/apis/js-apis-font.md
index f63ae0b839e472b9b6c11db6b6da4684507b11c6..6ed6b13fbe3c9e05d9fb0afb1c802770fe7044d1 100644
--- a/en/application-dev/reference/apis/js-apis-font.md
+++ b/en/application-dev/reference/apis/js-apis-font.md
@@ -54,7 +54,7 @@ struct FontExample {
// Both familyName and familySrc support the string type.
font.registerFont({
familyName: 'medium',
- familySrc: '/font/medium.ttf'
+ familySrc: '/font/medium.ttf' // The font file is at the same level as the pages directory.
})
// Both familyName and familySrc support the Resource type.
@@ -138,7 +138,7 @@ Obtains information about a system font based on the font name.
| ---------------- | ---------------------------- |
| FontInfo | Information about the system font. |
-## FontInfo
+## FontInfo10+
**System capability**: SystemCapability.ArkUI.ArkUI.Full
@@ -170,7 +170,7 @@ struct FontExample {
Column() {
Button("getFontByName")
.onClick(() => {
- this.fontInfo = font.getFontByName('HarmonyOS Sans Italic')
+ this.fontInfo = font.getFontByName('Sans Italic')
console.log("getFontByName(): path = " + this.fontInfo.path)
console.log("getFontByName(): postScriptName = " + this.fontInfo.postScriptName)
console.log("getFontByName(): fullName = " + this.fontInfo.fullName)
diff --git a/en/application-dev/reference/apis/js-apis-geoLocationManager.md b/en/application-dev/reference/apis/js-apis-geoLocationManager.md
index 263a1a525e0fa1dffcbd9e79703d2d359ac49dcc..647a3cb04a224a8ac0f0ca828ab79297f8d8ead8 100644
--- a/en/application-dev/reference/apis/js-apis-geoLocationManager.md
+++ b/en/application-dev/reference/apis/js-apis-geoLocationManager.md
@@ -53,7 +53,7 @@ Defines a reverse geocoding request.
| locale | string | Yes| Yes| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.|
| latitude | number | Yes| Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude. The value ranges from **-90** to **90**.|
| longitude | number | Yes| Yes| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude . The value ranges from **-180** to **180**.|
-| maxItems | number | Yes| Yes| Maximum number of location records to be returned. The value must be greater than or equal to **0**. A value smaller than **10** is recommended.|
+| maxItems | number | Yes| Yes| Maximum number of location records to be returned. The specified value must be greater than or equal to **0**. A value smaller than **10** is recommended.|
## GeoCodeRequest
@@ -66,7 +66,7 @@ Defines a geocoding request.
| -------- | -------- | -------- | -------- | -------- |
| locale | string | Yes| Yes| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.|
| description | string | Yes| Yes| Location description, for example, **No. xx, xx Road, Pudong New District, Shanghai**.|
-| maxItems | number | Yes| Yes| Maximum number of location records to be returned. The value must be greater than or equal to **0**. A value smaller than **10** is recommended.|
+| maxItems | number | Yes| Yes| Maximum number of location records to be returned. The specified value must be greater than or equal to **0**. A value smaller than **10** is recommended.|
| minLatitude | number | Yes| Yes| Minimum latitude. This parameter is used with **minLongitude**, **maxLatitude**, and **maxLongitude** to specify the latitude and longitude ranges. The value ranges from **-90** to **90**.|
| minLongitude | number | Yes| Yes| Minimum longitude. The value ranges from **-180** to **180**.|
| maxLatitude | number | Yes| Yes| Maximum latitude. The value ranges from **-90** to **90**.|
@@ -98,7 +98,7 @@ Defines a geographic location.
| phoneNumber | string | Yes| No| Phone number.|
| addressUrl | string | Yes| No| Website URL.|
| descriptions | Array<string> | Yes| No| Additional descriptions.|
-| descriptionsSize | number | Yes| No| Total number of additional descriptions. The value must be greater than or equal to **0**. A value smaller than **10** is recommended.|
+| descriptionsSize | number | Yes| No| Total number of additional descriptions. The specified value must be greater than or equal to **0**. A value smaller than **10** is recommended.|
| isFromMock | Boolean | Yes| No| Whether the geographical name is from the mock reverse geocoding function. **System API**: This is a system API.|
@@ -110,11 +110,11 @@ Defines a location request.
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
-| priority | [LocationRequestPriority](#locationrequestpriority) | Yes| Yes| Priority of the location request. For details about the value range, see [LocationRequestPriority](#locationrequestpriority).|
-| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes| Scenario of the location request. For details about the value range, see [LocationRequestScenario](#locationrequestscenario).|
-| timeInterval | number | Yes| Yes| Time interval at which location information is reported, in seconds. The value must be greater than **0**.|
-| distanceInterval | number | Yes| Yes| Distance interval at which location information is reported. The value must be greater than **0**, in meters.|
-| maxAccuracy | number | Yes| Yes| Location accuracy. This parameter is valid only when the precise location function is enabled, and is invalid when the approximate location function is enabled. The value must be greater than **0**.|
+| priority | [LocationRequestPriority](#locationrequestpriority) | Yes| Yes| Priority of the location request. This parameter is effective only when **scenario** is set to **UNSET**. If this parameter and **scenario** are set to **UNSET**, the attempt to initiate a location request will fail. For details about the value range, see [LocationRequestPriority](#locationrequestpriority).|
+| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes| Scenario of the location request. The **priority** parameter is effective only when this parameter is set to **UNSET**. If this parameter and **priority** are set to **UNSET**, the attempt to initiate a location request will fail. For details about the value range, see [LocationRequestScenario](#locationrequestscenario).|
+| timeInterval | number | Yes| Yes| Time interval at which location information is reported, in seconds. The specified value must be greater than or equal to **0**. The default value is **1**.|
+| distanceInterval | number | Yes| Yes| Distance interval at which location information is reported, in meters. The specified value must be greater than or equal to **0**. The default value is **0**.|
+| maxAccuracy | number | Yes| Yes| Location accuracy, in meters. This parameter is valid only when the precise location function is enabled, and is invalid when the approximate location function is enabled. The specified value must be greater than or equal to **0**. The default value is **0**.|
## CurrentLocationRequest
@@ -125,10 +125,10 @@ Defines the current location request.
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
-| priority | [LocationRequestPriority](#locationrequestpriority) | Yes| Yes| Priority of the location request. For details about the value range, see [LocationRequestPriority](#locationrequestpriority).|
-| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes| Scenario of the location request. For details about the value range, see [LocationRequestScenario](#locationrequestscenario).|
-| maxAccuracy | number | Yes| Yes| Location accuracy, in meters. This parameter is valid only when the precise location function is enabled, and is invalid when the approximate location function is enabled. The value must be greater than **0**.|
-| timeoutMs | number | Yes| Yes| Timeout duration, in milliseconds. The minimum value is **1000**. The value must be greater than or equal to **1000**.|
+| priority | [LocationRequestPriority](#locationrequestpriority) | Yes| Yes| Priority of the location request. This parameter is effective only when **scenario** is set to **UNSET**. If this parameter and **scenario** are set to **UNSET**, the attempt to initiate a location request will fail. For details about the value range, see [LocationRequestPriority](#locationrequestpriority).|
+| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes| Scenario of the location request. The **priority** parameter is effective only when this parameter is set to **UNSET**. If this parameter and **priority** are set to **UNSET**, the attempt to initiate a location request will fail. For details about the value range, see [LocationRequestScenario](#locationrequestscenario).|
+| maxAccuracy | number | Yes| Yes| Location accuracy, in meters. This parameter is valid only when the precise location function is enabled, and is invalid when the approximate location function is enabled. The specified value must be greater than or equal to **0**. The default value is **0**.|
+| timeoutMs | number | Yes| Yes| Timeout duration, in milliseconds. The minimum value is **1000**. The specified value must be greater than or equal to **1000**.|
## SatelliteStatusInfo
@@ -139,23 +139,23 @@ Defines the satellite status information.
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
-| satellitesNumber | number | Yes| No| Number of satellites. The value must be greater than or equal to **0**.|
-| satelliteIds | Array<number> | Yes| No| Array of satellite IDs. The value must be greater than or equal to **0**.|
-| carrierToNoiseDensitys | Array<number> | Yes| No| Carrier-to-noise density ratio, that is, **cn0**. The value must be greater than **0**.|
+| satellitesNumber | number | Yes| No| Number of satellites. The specified value must be greater than or equal to **0**.|
+| satelliteIds | Array<number> | Yes| No| Array of satellite IDs. The specified value must be greater than or equal to **0**.|
+| carrierToNoiseDensitys | Array<number> | Yes| No| Carrier-to-noise density ratio, that is, **cn0**. The specified value must be greater than **0**.|
| altitudes | Array<number> | Yes| No| Satellite altitude angle information. The value ranges from **-90** to **90**, in degrees.|
| azimuths | Array<number> | Yes| No| Azimuth information. The value ranges from **0** to **360**, in degrees.|
-| carrierFrequencies | Array<number> | Yes| No| Carrier frequency. The value must be greater than or equal to **0**, in Hz.|
+| carrierFrequencies | Array<number> | Yes| No| Carrier frequency, in Hz. The specified value must be greater than or equal to **0**.|
## CachedGnssLocationsRequest
-Represents a request for reporting cached GNSS locations.
+Defines a request for reporting cached GNSS locations.
**System capability**: SystemCapability.Location.Location.Gnss
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
-| reportingPeriodSec | number | Yes| Yes| Interval for reporting the cached GNSS locations, in milliseconds. The value must be greater than **0**.|
+| reportingPeriodSec | number | Yes| Yes| Interval for reporting the cached GNSS locations, in milliseconds. The specified value must be greater than **0**.|
| wakeUpCacheQueueFull | boolean | Yes| Yes | **true**: reports the cached GNSS locations to the application when the cache queue is full. **false**: discards the cached GNSS locations when the cache queue is full.|
@@ -169,13 +169,13 @@ Defines a GNSS geofence. Currently, only circular geofences are supported.
| -------- | -------- | -------- | -------- | -------- |
| latitude | number | Yes| Yes|Latitude information. The value ranges from **-90** to **90**.|
| longitude | number | Yes|Yes| Longitude information. The value ranges from **-180** to **180**.|
-| radius | number | Yes|Yes| Radius of a circular geofence. The value must be greater than **0**, in meters.|
-| expiration | number | Yes|Yes| Expiration period of a geofence, in milliseconds. The value must be greater than **0**.|
+| radius | number | Yes|Yes| Radius of a circular geofence, in meters. The specified value must be greater than **0**.|
+| expiration | number | Yes|Yes| Expiration period of a geofence, in milliseconds. The specified value must be greater than **0**.|
## GeofenceRequest
-Represents a GNSS geofencing request.
+Defines a GNSS geofencing request.
**System capability**: SystemCapability.Location.Location.Geofence
@@ -214,17 +214,17 @@ Defines a location.
| direction | number | Yes| No| Direction information. The value ranges from **0** to **360**, in degrees.|
| timeSinceBoot | number | Yes| No| Location timestamp since boot.|
| additions | Array<string> | Yes| No| Additional description.|
-| additionSize | number | Yes| No| Number of additional descriptions. The value must be greater than or equal to **0**. |
+| additionSize | number | Yes| No| Number of additional descriptions. The specified value must be greater than or equal to **0**. |
| isFromMock | Boolean | Yes| No| Whether the location information is from the mock location function. **System API**: This is a system API.|
## ReverseGeocodingMockInfo
-Represents information of the mock reverse geocoding function.
+Defines the configuration of the mock reverse geocoding function.
**System capability**: SystemCapability.Location.Location.Core
-**System API**: This is a system API and cannot be called by third-party applications.
+**System API**: This is a system API.
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
@@ -234,21 +234,21 @@ Represents information of the mock reverse geocoding function.
## LocationMockConfig
-Represents the information of the mock location function.
+Defines the configuration of the mock location function.
**System capability**: SystemCapability.Location.Location.Core
-**System API**: This is a system API and cannot be called by third-party applications.
+**System API**: This is a system API.
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
-| timeInterval | number | Yes| Yes| Interval at which mock locations are reported, in seconds.|
+| timeInterval | number | Yes| Yes| Time interval at which mock locations are reported, in seconds.|
| locations | Array<[Location](#location)> | Yes| Yes| Array of mocked locations.|
## CountryCode
-Represents country code information.
+Defines the country code information.
**System capability**: SystemCapability.Location.Location.Core
@@ -258,6 +258,69 @@ Represents country code information.
| type | [CountryCodeType](#countrycodetype) | Yes| No| Country code source.|
+## LocatingRequiredDataConfig10+
+
+Defines the configuration for obtaining the required data of the location service.
+
+**System capability**: SystemCapability.Location.Location.Core
+
+**System API**: This is a system API.
+
+| Name| Type| Readable|Writable| Description|
+| -------- | -------- | -------- | -------- | -------- |
+| type | [LocatingRequiredDataType](#locatingrequireddatatype10) | Yes| Yes| Type of the required data.|
+| needStartScan | boolean | Yes| Yes| Whether to initiate scanning.|
+| scanInterval | number | Yes| Yes| Scanning interval, in milliseconds. The specified value must be greater than **0**. The default value is **10000**.|
+| scanTimeout | number | Yes| Yes| Scanning timeout interval, in milliseconds. The value ranges from **0** to **600000**. The default value is **10000**.|
+
+
+## LocatingRequiredData10+
+
+Defines the required data of the location service, including the Wi-Fi or Bluetooth scanning result. After obtaining the data, an application can use the data for services such as network positioning.
+
+**System capability**: SystemCapability.Location.Location.Core
+
+**System API**: This is a system API.
+
+| Name| Type| Readable|Writable| Description|
+| -------- | -------- | -------- | -------- | -------- |
+| wifiData | [WifiScanInfo](#wifiscaninfo10) | Yes| No| Wi-Fi scanning result.|
+| bluetoothData | [BluetoothScanInfo](#bluetoothscaninfo10) | Yes| No| Bluetooth scanning result.|
+
+
+## WifiScanInfo10+
+
+Defines the Wi-Fi scanning information, including the SSID, BSSID, and RSSI of the scanned Wi-Fi hotspot.
+
+**System capability**: SystemCapability.Location.Location.Core
+
+**System API**: This is a system API.
+
+| Name| Type| Readable|Writable| Description|
+| -------- | -------- | -------- | -------- | -------- |
+| ssid | string | Yes| No| Service set identifier (SSID) of a Wi-Fi hotspot, in UTF-8 format.|
+| bssid | string | Yes| No| Base station subsystem identifier (BSSID) of a Wi-Fi hotspot.|
+| rssi | number | Yes| No| Received signal strength indicator (RSSI) of a Wi-Fi hotspot, in dBm.|
+| frequency | number | Yes| No| Frequency of a Wi-Fi hotspot.|
+| timestamp | number | Yes| No| Scanning timestamp.|
+
+
+## BluetoothScanInfo10+
+
+Defines the Bluetooth scanning information.
+
+**System capability**: SystemCapability.Location.Location.Core
+
+**System API**: This is a system API.
+
+| Name| Type| Readable|Writable| Description|
+| -------- | -------- | -------- | -------- | -------- |
+| deviceName | string | Yes| No| Name of a Bluetooth device.|
+| macAddress | string | Yes| No| MAC address of a Bluetooth device.|
+| rssi | number | Yes| No| Signal strength of a Bluetooth device, in dBm.|
+| timestamp | number | Yes| No| Scanning timestamp.|
+
+
## LocationRequestPriority
Sets the priority of the location request.
@@ -294,7 +357,7 @@ Defines the privacy statement type.
**System capability**: SystemCapability.Location.Location.Core
-**System API**: This is a system API and cannot be called by third-party applications.
+**System API**: This is a system API.
| Name| Value| Description|
| -------- | -------- | -------- |
@@ -305,7 +368,7 @@ Defines the privacy statement type.
## CountryCodeType
-Represents the country code source type.
+Defines the country code source type.
**System capability**: SystemCapability.Location.Location.Core
@@ -317,11 +380,25 @@ Represents the country code source type.
| COUNTRY_CODE_FROM_NETWORK | 4 | Country code obtained from the cellular network registration information.|
+## LocatingRequiredDataType10+
+
+Defines the type of the required data of the location service.
+
+**System capability**: SystemCapability.Location.Location.Core
+
+**System API**: This is a system API.
+
+| Name| Value| Description|
+| -------- | -------- | -------- |
+| WIFI | 1 | Wi-Fi scanning information.|
+| BLUETOOTH | 2 | Bluetooth scanning information.|
+
+
## geoLocationManager.on('locationChange')
on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>): void
-Registers a listener for location changes with a location request initiated.
+Subscribes to location change events with a location request initiated.
**Permission required**: ohos.permission.APPROXIMATELY_LOCATION
@@ -331,13 +408,13 @@ Registers a listener for location changes with a location request initiated.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
- | type | string | Yes| Event type. The value **locationChange** indicates a location change event.|
+ | type | string | Yes| Event type. The value **locationChange** indicates a location change.|
| request | [LocationRequest](#locationrequest) | Yes| Location request.|
- | callback | Callback<[Location](#location)> | Yes| Callback used to return the location change event.|
+ | callback | Callback<[Location](#location)> | Yes| Callback used to receive location change events.|
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -349,7 +426,7 @@ For details about the following error codes, see [Location Error Codes](../error
```ts
import geoLocationManager from '@ohos.geoLocationManager';
- let requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
+ let requestInfo = {'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX, 'scenario': geoLocationManager.LocationRequestScenario.UNSET, 'timeInterval': 1, 'distanceInterval': 0, 'maxAccuracy': 0};
let locationChange = (location) => {
console.log('locationChanger: data: ' + JSON.stringify(location));
};
@@ -366,7 +443,7 @@ For details about the following error codes, see [Location Error Codes](../error
off(type: 'locationChange', callback?: Callback<Location>): void
-Unregisters the listener for location changes with the corresponding location request deleted.
+Unsubscribes from location change events with the corresponding location request deleted.
**Permission required**: ohos.permission.APPROXIMATELY_LOCATION
@@ -376,12 +453,12 @@ Unregisters the listener for location changes with the corresponding location re
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
- | type | string | Yes| Event type. The value **locationChange** indicates a location change event.|
+ | type | string | Yes| Event type. The value **locationChange** indicates a location change.|
| callback | Callback<[Location](#location)> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.|
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -393,7 +470,7 @@ For details about the following error codes, see [Location Error Codes](../error
```ts
import geoLocationManager from '@ohos.geoLocationManager';
- let requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
+ let requestInfo = {'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX, 'scenario': geoLocationManager.LocationRequestScenario.UNSET, 'timeInterval': 1, 'distanceInterval': 0, 'maxAccuracy': 0};
let locationChange = (location) => {
console.log('locationChanger: data: ' + JSON.stringify(location));
};
@@ -410,7 +487,7 @@ For details about the following error codes, see [Location Error Codes](../error
on(type: 'locationEnabledChange', callback: Callback<boolean>): void
-Registers a listener for location service status change events.
+Subscribes to location service status change events.
**System capability**: SystemCapability.Location.Location.Core
@@ -418,12 +495,12 @@ Registers a listener for location service status change events.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
- | type | string | Yes| Event type. The value **locationEnabledChange** indicates a location service status change event.|
- | callback | Callback<boolean> | Yes| Callback used to return the location service status change event.|
+ | type | string | Yes| Event type. The value **locationEnabledChange** indicates a location service status change.|
+ | callback | Callback<boolean> | Yes| Callback used to receive location service status change events.|
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -448,7 +525,7 @@ For details about the following error codes, see [Location Error Codes](../error
off(type: 'locationEnabledChange', callback?: Callback<boolean>): void;
-Unregisters the listener for location service status change events.
+Unsubscribes from location service status change events.
**System capability**: SystemCapability.Location.Location.Core
@@ -456,12 +533,12 @@ Unregisters the listener for location service status change events.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
- | type | string | Yes| Event type. The value **locationEnabledChange** indicates a location service status change event.|
+ | type | string | Yes| Event type. The value **locationEnabledChange** indicates a location service status change.|
| callback | Callback<boolean> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.|
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -487,7 +564,7 @@ For details about the following error codes, see [Location Error Codes](../error
on(type: 'cachedGnssLocationsChange', request: CachedGnssLocationsRequest, callback: Callback<Array<Location>>): void;
-Registers a listener for cached GNSS location reports.
+Subscribes to cached GNSS location reports.
**Permission required**: ohos.permission.APPROXIMATELY_LOCATION
@@ -499,11 +576,11 @@ Registers a listener for cached GNSS location reports.
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value **cachedGnssLocationsChange** indicates reporting of cached GNSS locations.|
| request | [CachedGnssLocationsRequest](#cachedgnsslocationsrequest) | Yes| Request for reporting cached GNSS location.|
- | callback | Callback<boolean> | Yes| Callback used to return cached GNSS locations.|
+ | callback | Callback<boolean> | Yes| Callback used to receive cached GNSS locations.|
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -531,7 +608,7 @@ For details about the following error codes, see [Location Error Codes](../error
off(type: 'cachedGnssLocationsChange', callback?: Callback<Array<Location>>): void;
-Unregisters the listener for cached GNSS location reports.
+Unsubscribes from cached GNSS location reports.
**Permission required**: ohos.permission.APPROXIMATELY_LOCATION
@@ -546,7 +623,7 @@ Unregisters the listener for cached GNSS location reports.
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -575,7 +652,7 @@ For details about the following error codes, see [Location Error Codes](../error
on(type: 'satelliteStatusChange', callback: Callback<SatelliteStatusInfo>): void;
-Registers a listener for GNSS satellite status change events.
+Subscribes to GNSS satellite status change events.
**Permission required**: ohos.permission.APPROXIMATELY_LOCATION
@@ -585,12 +662,12 @@ Registers a listener for GNSS satellite status change events.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
- | type | string | Yes| Event type. The value **satelliteStatusChange** indicates a GNSS satellite status change event.|
- | callback | Callback<[SatelliteStatusInfo](#satellitestatusinfo)> | Yes| Callback used to return GNSS satellite status changes.|
+ | type | string | Yes| Event type. The value **satelliteStatusChange** indicates a GNSS satellite status change.|
+ | callback | Callback<[SatelliteStatusInfo](#satellitestatusinfo)> | Yes| Callback used to receive GNSS satellite status change events.|
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -617,7 +694,7 @@ For details about the following error codes, see [Location Error Codes](../error
off(type: 'satelliteStatusChange', callback?: Callback<SatelliteStatusInfo>): void;
-Unregisters the listener for GNSS satellite status change events.
+Unsubscribes from GNSS satellite status change events.
**Permission required**: ohos.permission.APPROXIMATELY_LOCATION
@@ -627,12 +704,12 @@ Unregisters the listener for GNSS satellite status change events.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
- | type | string | Yes| Event type. The value **satelliteStatusChange** indicates a GNSS satellite status change event.|
+ | type | string | Yes| Event type. The value **satelliteStatusChange** indicates a GNSS satellite status change.|
| callback | Callback<[SatelliteStatusInfo](#satellitestatusinfo)> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.|
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -660,7 +737,7 @@ For details about the following error codes, see [Location Error Codes](../error
on(type: 'nmeaMessage', callback: Callback<string>): void;
-Registers a listener for GNSS NMEA message change events.
+Subscribes to GNSS NMEA message change events.
**Required permissions**: ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION
@@ -670,12 +747,12 @@ Registers a listener for GNSS NMEA message change events.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
- | type | string | Yes| Event type. The value **nmeaMessage** indicates a GNSS NMEA message change event.|
- | callback | Callback<string> | Yes| Callback used to return GNSS NMEA message changes.|
+ | type | string | Yes| Event type. The value **nmeaMessage** indicates a GNSS NMEA message change.|
+ | callback | Callback<string> | Yes| Callback used to receive GNSS NMEA message change events.|
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -703,7 +780,7 @@ For details about the following error codes, see [Location Error Codes](../error
off(type: 'nmeaMessage', callback?: Callback<string>): void;
-Unregisters the listener for GNSS NMEA message change events.
+Unsubscribes from GNSS NMEA message change events.
**Required permissions**: ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION
@@ -713,12 +790,12 @@ Unregisters the listener for GNSS NMEA message change events.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
- | type | string | Yes| Event type. The value **nmeaMessage** indicates a GNSS NMEA message change event.|
+ | type | string | Yes| Event type. The value **nmeaMessage** indicates a GNSS NMEA message change.|
| callback | Callback<string> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.|
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -747,7 +824,7 @@ For details about the following error codes, see [Location Error Codes](../error
on(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): void;
-Registers a listener for status change events of the specified geofence.
+Subscribes to status change events of the specified geofence.
**Permission required**: ohos.permission.APPROXIMATELY_LOCATION
@@ -757,13 +834,13 @@ Registers a listener for status change events of the specified geofence.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
- | type | string | Yes| Event type. The value **gnssFenceStatusChange** indicates a geofence status change event.|
+ | type | string | Yes| Event type. The value **gnssFenceStatusChange** indicates a geofence status change.|
| request | [GeofenceRequest](#geofencerequest) | Yes| Geofencing request.|
- | want | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes| **WantAgent** used to return geofence (entrance or exit) events.|
+ | want | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes| **WantAgent** used to receive geofence (entrance or exit) events.|
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -805,7 +882,7 @@ For details about the following error codes, see [Location Error Codes](../error
off(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): void;
-Unregisters the listener for status change events of the specified geofence.
+Unsubscribes from status change events of the specified geofence.
**Permission required**: ohos.permission.APPROXIMATELY_LOCATION
@@ -815,13 +892,13 @@ Unregisters the listener for status change events of the specified geofence.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
- | type | string | Yes| Event type. The value **gnssFenceStatusChange** indicates a geofence status change event.|
+ | type | string | Yes| Event type. The value **gnssFenceStatusChange** indicates a geofence status change.|
| request | [GeofenceRequest](#geofencerequest) | Yes| Geofencing request.|
- | want | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes| **WantAgent** used to return geofence (entrance or exit) events.|
+ | want | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes| **WantAgent** used to receive geofence (entrance or exit) events.|
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -864,7 +941,7 @@ For details about the following error codes, see [Location Error Codes](../error
on(type: 'countryCodeChange', callback: Callback<CountryCode>): void;
-Registers a listener for country code change events.
+Subscribes to country code change events.
**System capability**: SystemCapability.Location.Location.Core
@@ -872,12 +949,12 @@ Registers a listener for country code change events.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
- | type | string | Yes| Event type. The value **countryCodeChange** indicates a country code change event.|
- | callback | Callback<[CountryCode](#countrycode)> | Yes| Callback used to return the country code change event.|
+ | type | string | Yes| Event type. The value **countryCodeChange** indicates a country code change.|
+ | callback | Callback<[CountryCode](#countrycode)> | Yes| Callback used to receive country code change events.|
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -905,7 +982,7 @@ For details about the following error codes, see [Location Error Codes](../error
off(type: 'countryCodeChange', callback?: Callback<CountryCode>): void;
-Unregisters the listener for country code change events.
+Unsubscribes from country code change events.
**System capability**: SystemCapability.Location.Location.Core
@@ -913,12 +990,12 @@ Unregisters the listener for country code change events.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
- | type | string | Yes| Event type. The value **countryCodeChange** indicates a country code change event.|
+ | type | string | Yes| Event type. The value **countryCodeChange** indicates a country code change.|
| callback | Callback<[CountryCode](#countrycode)> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.|
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -942,6 +1019,89 @@ For details about the following error codes, see [Location Error Codes](../error
```
+## geoLocationManager.on('locatingRequiredDataChange')10+
+
+on(type: 'locatingRequiredDataChange', config: LocatingRequiredDataConfig, callback: Callback<Array<LocatingRequiredData>>): void;
+
+Subscribes to changes in the required data of the location service, including Wi-Fi and Bluetooth scanning information. An application can then determine whether to enable Wi-Fi and Bluetooth scanning based on the return result.
+
+**Required permissions**: ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION
+
+**System capability**: SystemCapability.Location.Location.Core
+
+**System API**: This is a system API.
+
+**Parameters**
+
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | type | string | Yes| Event type. The value **locatingRequiredDataChange** indicates a change in the required data of the location service.|
+ | config | [LocatingRequiredDataConfig](#locatingrequireddataconfig10) | Yes| Configuration for obtaining the required data of the location service.|
+ | callback | Callback<Array<[LocatingRequiredData](#locatingrequireddata10)>> | Yes| Callback used to receive the required data of the location service.|
+
+**Error codes**
+
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+
+| ID| Error Message|
+| -------- | ---------------------------------------- |
+|3301800 | Failed to start WiFi or Bluetooth scanning. |
+
+**Example**
+
+ ```ts
+ import geoLocationManager from '@ohos.geoLocationManager';
+ let callback = (code) => {
+ console.log('locatingRequiredDataChange: ' + JSON.stringify(code));
+ }
+ let config = {'type': 1, 'needStartScan': true, 'scanInterval': 10000};
+ try {
+ geoLocationManager.on('locatingRequiredDataChange', config, callback);
+ } catch (err) {
+ console.error("errCode:" + err.code + ",errMessage:" + err.message);
+ }
+ ```
+
+
+## geoLocationManager.off('locatingRequiredDataChange')10+
+
+off(type: 'locatingRequiredDataChange', callback?: Callback<Array<LocatingRequiredData>>): void;
+
+Unsubscribes from changes in the required data of the location service and stops Wi-Fi and Bluetooth scanning.
+
+**Required permissions**: ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION
+
+**System capability**: SystemCapability.Location.Location.Core
+
+**System API**: This is a system API.
+
+**Parameters**
+
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | type | string | Yes| Event type. The value **locatingRequiredDataChange** indicates a change in the required data of the location service.|
+ | callback | Callback<Array<[LocatingRequiredData](#locatingrequireddata10)>> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.|
+
+**Error codes**
+
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+
+**Example**
+
+ ```ts
+ import geoLocationManager from '@ohos.geoLocationManager';
+ let callback = (code) => {
+ console.log('locatingRequiredDataChange: ' + JSON.stringify(code));
+ }
+ let config = {'type': 1, 'needStartScan': true, 'scanInterval': 10000};
+ try {
+ geoLocationManager.on('locatingRequiredDataChange', config, callback);
+ geoLocationManager.off('locatingRequiredDataChange', callback);
+ } catch (err) {
+ console.error("errCode:" + err.code + ",errMessage:" + err.message);
+ }
+ ```
+
## geoLocationManager.getCurrentLocation
@@ -958,11 +1118,11 @@ Obtains the current location. This API uses an asynchronous callback to return t
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| request | [CurrentLocationRequest](#currentlocationrequest) | Yes| Location request.|
- | callback | AsyncCallback<[Location](#location)> | Yes| Callback used to return the current location.|
+ | callback | AsyncCallback<[Location](#location)> | Yes| Callback used to receive the current location.|
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -974,7 +1134,7 @@ For details about the following error codes, see [Location Error Codes](../error
```ts
import geoLocationManager from '@ohos.geoLocationManager';
- let requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0};
+ let requestInfo = {'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX, 'scenario': geoLocationManager.LocationRequestScenario.UNSET,'maxAccuracy': 0};
let locationChange = (err, location) => {
if (err) {
console.log('locationChanger: err=' + JSON.stringify(err));
@@ -1005,11 +1165,11 @@ Obtains the current location. This API uses an asynchronous callback to return t
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
- | callback | AsyncCallback<[Location](#location)> | Yes| Callback used to return the current location.|
+ | callback | AsyncCallback<[Location](#location)> | Yes| Callback used to receive the current location.|
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -1061,7 +1221,7 @@ Obtains the current location. This API uses a promise to return the result.
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -1073,7 +1233,7 @@ For details about the following error codes, see [Location Error Codes](../error
```ts
import geoLocationManager from '@ohos.geoLocationManager';
- let requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0};
+ let requestInfo = {'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX, 'scenario': geoLocationManager.LocationRequestScenario.UNSET,'maxAccuracy': 0};
try {
geoLocationManager.getCurrentLocation(requestInfo).then((result) => {
console.log('current location: ' + JSON.stringify(result));
@@ -1105,7 +1265,7 @@ Obtains the last location.
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -1141,7 +1301,7 @@ Checks whether the location service is enabled.
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -1165,7 +1325,7 @@ enableLocation(callback: AsyncCallback<void>): void;
Enables the location service. This API uses an asynchronous callback to return the result.
-**System API**: This is a system API and cannot be called by third-party applications.
+**System API**: This is a system API.
**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS
@@ -1175,11 +1335,11 @@ Enables the location service. This API uses an asynchronous callback to return t
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
- | callback | AsyncCallback<void> | Yes| Callback used to return the error message.|
+ | callback | AsyncCallback<void> | Yes| Callback used to receive the error message.|
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -1207,7 +1367,7 @@ enableLocation(): Promise<void>
Enables the location service. This API uses a promise to return the result.
-**System API**: This is a system API and cannot be called by third-party applications.
+**System API**: This is a system API.
**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS
@@ -1221,7 +1381,7 @@ Enables the location service. This API uses a promise to return the result.
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -1249,7 +1409,7 @@ disableLocation(): void;
Disables the location service.
-**System API**: This is a system API and cannot be called by third-party applications.
+**System API**: This is a system API.
**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS
@@ -1257,7 +1417,7 @@ Disables the location service.
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -1275,7 +1435,6 @@ For details about the following error codes, see [Location Error Codes](../error
```
-
## geoLocationManager.getAddressesFromLocation
getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void
@@ -1289,11 +1448,11 @@ Converts coordinates into geographic description through reverse geocoding. This
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| request | [ReverseGeoCodeRequest](#reversegeocoderequest) | Yes| Reverse geocoding request.|
- | callback | AsyncCallback<Array<[GeoAddress](#geoaddress)>> | Yes| Callback used to return the reverse geocoding result.|
+ | callback | AsyncCallback<Array<[GeoAddress](#geoaddress)>> | Yes| Callback used to receive the reverse geocoding result.|
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -1342,7 +1501,7 @@ Converts coordinates into geographic description through reverse geocoding. This
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -1380,11 +1539,11 @@ Converts geographic description into coordinates through geocoding. This API use
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| request | [GeoCodeRequest](#geocoderequest) | Yes| Geocoding request.|
- | callback | AsyncCallback<Array<[GeoAddress](#geoaddress)>> | Yes| Callback used to return the geocoding result.|
+ | callback | AsyncCallback<Array<[GeoAddress](#geoaddress)>> | Yes| Callback used to receive the geocoding result.|
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -1433,7 +1592,7 @@ Converts geographic description into coordinates through geocoding. This API use
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -1473,7 +1632,7 @@ Obtains the (reverse) geocoding service status.
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -1505,11 +1664,11 @@ Obtains the number of cached GNSS locations.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
- | callback | AsyncCallback<number> | Yes| Callback used to return the number of cached GNSS locations. |
+ | callback | AsyncCallback<number> | Yes| Callback used to receive the number of cached GNSS locations. |
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -1553,7 +1712,7 @@ Obtains the number of cached GNSS locations.
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -1591,11 +1750,11 @@ Obtains all cached GNSS locations and clears the GNSS cache queue.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
- | callback | AsyncCallback<void> | Yes| Callback used to return the error message.|
+ | callback | AsyncCallback<void> | Yes| Callback used to receive the error message.|
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -1633,11 +1792,11 @@ Obtains all cached GNSS locations and clears the GNSS cache queue.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
- | Promise<void> | void | NA | Promise used to return the error code.|
+ | Promise<void> | void | NA | Promise used to receive the error code.|
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -1675,11 +1834,11 @@ Sends an extended command to the location subsystem.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| command | [LocationCommand](#locationcommand) | Yes| Extended command (string) to be sent.|
- | callback | AsyncCallback<void> | Yes| Callback used to return the error code.|
+ | callback | AsyncCallback<void> | Yes| Callback used to receive the error code.|
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -1720,11 +1879,11 @@ Sends an extended command to the location subsystem.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
- | Promise<void> | void | NA | Promise used to return the error code.|
+ | Promise<void> | void | NA | Promise used to receive the error code.|
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -1760,11 +1919,11 @@ Obtains the current country code.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
- | callback | AsyncCallback<[CountryCode](#countrycode)> | Yes| Callback used to return the country code.|
+ | callback | AsyncCallback<[CountryCode](#countrycode)> | Yes| Callback used to receive the country code.|
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -1802,11 +1961,11 @@ Obtains the current country code.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
- | Promise<[CountryCode](#countrycode)> | [CountryCode](#countrycode) | NA | Promise used to return the country code.|
+ | Promise<[CountryCode](#countrycode)> | [CountryCode](#countrycode) | NA | Promise used to receive the country code.|
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -1839,11 +1998,11 @@ Enables the mock location function.
**System capability**: SystemCapability.Location.Location.Core
-**System API**: This is a system API and cannot be called by third-party applications.
+**System API**: This is a system API.
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -1870,11 +2029,11 @@ Disables the mock location function.
**System capability**: SystemCapability.Location.Location.Core
-**System API**: This is a system API and cannot be called by third-party applications.
+**System API**: This is a system API.
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -1903,7 +2062,7 @@ This API can be invoked only after [geoLocationManager.enableLocationMock](#geol
**System capability**: SystemCapability.Location.Location.Core
-**System API**: This is a system API and cannot be called by third-party applications.
+**System API**: This is a system API.
**Parameters**
@@ -1913,7 +2072,7 @@ This API can be invoked only after [geoLocationManager.enableLocationMock](#geol
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -1949,11 +2108,11 @@ Enables the mock reverse geocoding function.
**System capability**: SystemCapability.Location.Location.Core
-**System API**: This is a system API and cannot be called by third-party applications.
+**System API**: This is a system API.
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -1979,11 +2138,11 @@ Disables the mock geocoding function.
**System capability**: SystemCapability.Location.Location.Core
-**System API**: This is a system API and cannot be called by third-party applications.
+**System API**: This is a system API.
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -2011,7 +2170,7 @@ This API can be invoked only after [geoLocationManager.enableReverseGeocodingMoc
**System capability**: SystemCapability.Location.Location.Core
-**System API**: This is a system API and cannot be called by third-party applications.
+**System API**: This is a system API.
**Parameters**
@@ -2021,7 +2180,7 @@ This API can be invoked only after [geoLocationManager.enableReverseGeocodingMoc
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -2053,7 +2212,7 @@ isLocationPrivacyConfirmed(type: LocationPrivacyType): boolean;
Checks whether a user agrees with the privacy statement of the location service. This API can only be called by system applications.
-**System API**: This is a system API and cannot be called by third-party applications.
+**System API**: This is a system API.
**System capability**: SystemCapability.Location.Location.Core
@@ -2067,11 +2226,11 @@ Checks whether a user agrees with the privacy statement of the location service.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
- | boolean | boolean | NA | Callback used to return the result, which indicates whether the user agrees with the privacy statement.|
+ | boolean | boolean | NA | Whether the user agrees with the privacy statement.|
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -2095,7 +2254,7 @@ setLocationPrivacyConfirmStatus(type: LocationPrivacyType, isConfirmed: boolean)
Sets the user confirmation status for the privacy statement of the location service. This API can only be called by system applications.
-**System API**: This is a system API and cannot be called by third-party applications.
+**System API**: This is a system API.
**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS
@@ -2106,11 +2265,11 @@ Sets the user confirmation status for the privacy statement of the location serv
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | [LocationPrivacyType](#locationprivacytype) | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when the location service is enabled.|
- | isConfirmed | boolean | Yes| Callback used to return the result, which indicates whether the user agrees with the privacy statement.|
+ | isConfirmed | boolean | Yes| Whether the user agrees with the privacy statement.|
**Error codes**
-For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
@@ -2126,3 +2285,53 @@ For details about the following error codes, see [Location Error Codes](../error
console.error("errCode:" + err.code + ",errMessage:" + err.message);
}
```
+
+
+## geoLocationManager.getLocatingRequiredData10+
+
+getLocatingRequiredData(config: LocatingRequiredDataConfig): Promise<Array<LocatingRequiredData>>;
+
+Obtains the required data of the location service. This API uses a promise to return the result.
+
+**Required permissions**: ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION
+
+**System capability**: SystemCapability.Location.Location.Core
+
+**System API**: This is a system API.
+
+**Parameters**
+
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | config | [LocatingRequiredDataConfig](#locatingrequireddataconfig10) | Yes| Configuration for obtaining the required data of the location service.|
+
+**Return value**
+
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | Promise<Array<[LocatingRequiredData](#locatingrequireddata10)>> | [LocatingRequiredData](#locatingrequireddata10) | NA | Promise used to receive the required data of the location service, such as the Wi-Fi and Bluetooth scanning information.|
+
+**Error codes**
+
+For details about the error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
+
+| ID| Error Message|
+| -------- | ---------------------------------------- |
+|3301800 | Failed to start WiFi or Bluetooth scanning. |
+
+**Example**
+
+ ```ts
+ import geoLocationManager from '@ohos.geoLocationManager';
+ let config = {'type': 1, 'needStartScan': true, 'scanInterval': 10000};
+ try {
+ geoLocationManager.getLocatingRequiredData(config).then((result) => {
+ console.log('getLocatingRequiredData return: ' + JSON.stringify(result));
+ })
+ .catch((error) => {
+ console.log('promise, getLocatingRequiredData: error=' + JSON.stringify(error));
+ });
+ } catch (err) {
+ console.error("errCode:" + err.code + ",errMessage:" + err.message);
+ }
+ ```
diff --git a/en/application-dev/reference/apis/js-apis-hidebug.md b/en/application-dev/reference/apis/js-apis-hidebug.md
index 896cee276b582a87806745accf135f74a38c057a..7eee03067795a058c83cfaac77e97cb26fbb4dfe 100644
--- a/en/application-dev/reference/apis/js-apis-hidebug.md
+++ b/en/application-dev/reference/apis/js-apis-hidebug.md
@@ -175,23 +175,30 @@ Obtains system service information.
```js
import fs from '@ohos.file.fs'
import hidebug from '@ohos.hidebug'
-import featureAbility from '@ohos.ability.featureAbility'
-
-let context = featureAbility.getContext();
-context.getFilesDir().then((data) => {
- var path = data + "/serviceInfo.txt";
- console.info("output path: " + path);
- let file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
- var serviceId = 10;
- var args = new Array("allInfo");
- try {
- hidebug.getServiceDump(serviceId, file.fd, args);
- } catch (error) {
- console.info(error.code);
- console.info(error.message);
- }
- fs.closeSync(file);
-})
+import common from '@ohos.app.ability.common'
+
+let applicationContext: common.Context;
+try {
+ applicationContext = this.context.getApplicationContext();
+} catch (error) {
+ console.info(error.code);
+ console.info(error.message);
+}
+
+var filesDir = applicationContext.filesDir;
+var path = filesDir + "/serviceInfo.txt";
+console.info("output path: " + path);
+let file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
+var serviceId = 10;
+var args = new Array("allInfo");
+
+try {
+ hidebug.getServiceDump(serviceId, file.fd, args);
+} catch (error) {
+ console.info(error.code);
+ console.info(error.message);
+}
+fs.closeSync(file);
```
## hidebug.startJsCpuProfiling9+
diff --git a/en/application-dev/reference/apis/js-apis-image.md b/en/application-dev/reference/apis/js-apis-image.md
index e09c5fd1a1b2fc826611889232ccaf2ad8717d43..12dc0c1abb87c54a08d020de84f4003103a30f5a 100644
--- a/en/application-dev/reference/apis/js-apis-image.md
+++ b/en/application-dev/reference/apis/js-apis-image.md
@@ -1732,7 +1732,7 @@ Creates an array of **PixelMap** objects based on the default parameters. This A
**Example**
```js
-imageSourceApi.createPixelMap( pixelmaplist => {
+imageSourceApi.createPixelMapList( pixelmaplist => {
console.info('Succeeded in creating pixelmaplist object.');
})
```
@@ -1763,14 +1763,14 @@ let decodeOpts = {
desiredPixelFormat: 3,
index: 0,
};
-imageSourceApi.createPixelMap(decodeOpts, pixelmaplist => {
+imageSourceApi.createPixelMapList(decodeOpts, pixelmaplist => {
console.log('Succeeded in creating pixelmaplist object.');
})
```
-### getDelayTime10+
+### getDelayTimeList10+
-getDelayTime(callback: AsyncCallback>): void;
+getDelayTimeList(callback: AsyncCallback>): void;
Obtains an array of delay times. This API uses an asynchronous callback to return the result.
@@ -1785,14 +1785,14 @@ Obtains an array of delay times. This API uses an asynchronous callback to retur
**Example**
```js
-imageSourceApi.getDelayTime( delayTimes => {
+imageSourceApi.getDelayTimeList( delayTimes => {
console.log('Succeeded in getting delay time.');
});
```
-### getDelayTime10+
+### getDelayTimeList10+
-getDelayTime(): Promise>;
+getDelayTimeList(): Promise>;
Obtains an array of delay times. This API uses a promise to return the result.
@@ -1807,7 +1807,7 @@ Obtains an array of delay times. This API uses a promise to return the result.
**Example**
```js
-let delayTimes = imageSourceApi.getDelayTime();
+let delayTimes = imageSourceApi.getDelayTimeList();
```
### getFrameCount10+
@@ -2839,9 +2839,9 @@ Defines image decoding options.
| Name | Type | Readable| Writable| Description |
| ------------------ | ---------------------------------- | ---- | ---- | ---------------- |
-| sampleSize | number | Yes | Yes | Thumbnail sampling size.|
+| sampleSize | number | Yes | Yes | Thumbnail sampling size. Currently, this option can only be set to **1**.|
| rotate | number | Yes | Yes | Rotation angle. |
-| editable | boolean | Yes | Yes | Whether the image is editable. |
+| editable | boolean | Yes | Yes | Whether the image is editable. If this option is set to **false**, the image cannot be edited again, and operations such as cropping will fail. |
| desiredSize | [Size](#size) | Yes | Yes | Expected output size. |
| desiredRegion | [Region](#region7) | Yes | Yes | Region to decode. |
| desiredPixelFormat | [PixelMapFormat](#pixelmapformat7) | Yes | Yes | Pixel map format for decoding.|
@@ -2899,34 +2899,34 @@ Describes the exchangeable image file format (EXIF) data of an image.
| GPS_LONGITUDE | "GPSLongitude" | Image longitude. |
| GPS_LATITUDE_REF | "GPSLatitudeRef" | Latitude reference, for example, N or S. |
| GPS_LONGITUDE_REF | "GPSLongitudeRef" | Longitude reference, for example, W or E. |
-| DATE_TIME_ORIGINAL9+ | "DateTimeOriginal" | Shooting time, for example, 2022:09:06 15:48:00. |
-| EXPOSURE_TIME9+ | "ExposureTime" | Exposure time, for example, 1/33 sec.|
-| SCENE_TYPE9+ | "SceneType" | Shooting scene type, for example, portrait, scenery, motion, and night. |
-| ISO_SPEED_RATINGS9+ | "ISOSpeedRatings" | ISO sensitivity or ISO speed, for example, 400. |
-| F_NUMBER9+ | "FNumber" | Aperture, for example, f/1.8. |
-| DATE_TIME10+ | "DateTime" | Date and time. |
-| GPS_TIME_STAMP10+ | "GPSTimeStamp" | GPS timestamp. |
-| GPS_DATE_STAMP10+ | "GPSDateStamp" | GPS date stamp. |
-| IMAGE_DESCRIPTION10+ | "ImageDescription" | Image description. |
-| MAKE10+ | "Make" | Vendor. |
-| PHOTO_MODE10+ | "PhotoMode " | Photo mode. |
-| SENSITIVITY_TYPE10+ | "SensitivityType" | Sensitivity type. |
-| STANDARD_OUTPUT_SENSITIVITY10+ | "StandardOutputSensitivity" | Standard output sensitivity. |
-| RECOMMENDED_EXPOSURE_INDEX10+ | "RecommendedExposureIndex" | Recommended exposure index. |
-| ISO_SPEED10+ | "ISOSpeedRatings" | ISO speed. |
-| APERTURE_VALUE10+ | "ApertureValue" | Aperture value. |
-| EXPOSURE_BIAS_VALUE10+ | "ExposureBiasValue" | Exposure bias value. |
-| METERING_MODE10+ | "MeteringMode" | Metering mode. |
-| LIGHT_SOURCE10+ | "LightSource" | Light source. |
-| FLASH 10+ | "Flash" | Flash status. |
-| FOCAL_LENGTH 10+ | "FocalLength" | Focal length. |
-| USER_COMMENT 10+ | "UserComment" | User comment. |
-| PIXEL_X_DIMENSION 10+ | "PixelXDimension" | Pixel X dimension. |
-| PIXEL_Y_DIMENSION10+ | "PixelYDimension" | Pixel Y dimension. |
-| WHITE_BALANCE 10+ | "WhiteBalance" | White balance. |
-| FOCAL_LENGTH_IN_35_MM_FILM 10+ | "FocalLengthIn35mmFilm" | Focal length in 35mm film. |
-| CAPTURE_MODE 10+ | "HwMnoteCaptureMode" | Capture mode. |
-| PHYSICAL_APERTURE 10+ | "HwMnotePhysicalAperture" | Physical aperture. |
+| DATE_TIME_ORIGINAL9+ | "DateTimeOriginal" | Shooting time, for example, 2022:09:06 15:48:00. This attribute is read-only. |
+| EXPOSURE_TIME9+ | "ExposureTime" | Exposure time, for example, 1/33 sec. Currently, this attribute is read-only.|
+| SCENE_TYPE9+ | "SceneType" | Shooting scene type, for example, portrait, scenery, motion, and night. Currently, this attribute is read-only. |
+| ISO_SPEED_RATINGS9+ | "ISOSpeedRatings" | ISO sensitivity or ISO speed, for example, 400. Currently, this attribute is read-only. |
+| F_NUMBER9+ | "FNumber" | Aperture, for example, f/1.8. Currently, this attribute is read-only. |
+| DATE_TIME10+ | "DateTime" | Date and time. Currently, this attribute is read-only. |
+| GPS_TIME_STAMP10+ | "GPSTimeStamp" | GPS timestamp. Currently, this parameter is read-only. |
+| GPS_DATE_STAMP10+ | "GPSDateStamp" | GPS date stamp. Currently, this attribute is read-only. |
+| IMAGE_DESCRIPTION10+ | "ImageDescription" | Image description. Currently, this attribute is read-only. |
+| MAKE10+ | "Make" | Vendor. Currently, this attribute is read-only. |
+| PHOTO_MODE10+ | "PhotoMode " | Photo mode. Currently, this attribute is read-only. |
+| SENSITIVITY_TYPE10+ | "SensitivityType" | Sensitivity type. Currently, this attribute is read-only. |
+| STANDARD_OUTPUT_SENSITIVITY10+ | "StandardOutputSensitivity" | Standard output sensitivity. Currently, this attribute is read-only. |
+| RECOMMENDED_EXPOSURE_INDEX10+ | "RecommendedExposureIndex" | Recommended exposure index. Currently, this attribute is read-only. |
+| ISO_SPEED10+ | "ISOSpeedRatings" | ISO speed. Currently, this attribute is read-only. |
+| APERTURE_VALUE10+ | "ApertureValue" | Aperture value. Currently, this attribute is read-only. |
+| EXPOSURE_BIAS_VALUE10+ | "ExposureBiasValue" | Exposure bias value. Currently, this attribute is read-only. |
+| METERING_MODE10+ | "MeteringMode" | Metering mode. Currently, this attribute is read-only. |
+| LIGHT_SOURCE10+ | "LightSource" | Light source. Currently, this attribute is read-only. |
+| FLASH 10+ | "Flash" | Flash status. Currently, this attribute is read-only. |
+| FOCAL_LENGTH 10+ | "FocalLength" | Focal length. Currently, this attribute is read-only. |
+| USER_COMMENT 10+ | "UserComment" | User comment. Currently, this attribute is read-only. |
+| PIXEL_X_DIMENSION 10+ | "PixelXDimension" | Pixel X dimension. Currently, this attribute is read-only. |
+| PIXEL_Y_DIMENSION10+ | "PixelYDimension" | Pixel Y dimension. Currently, this attribute is read-only. |
+| WHITE_BALANCE 10+ | "WhiteBalance" | White balance. Currently, this attribute is read-only. |
+| FOCAL_LENGTH_IN_35_MM_FILM 10+ | "FocalLengthIn35mmFilm" | Focal length in 35mm film. Currently, this attribute is read-only. |
+| CAPTURE_MODE 10+ | "HwMnoteCaptureMode" | Capture mode. Currently, this parameter is read-only. |
+| PHYSICAL_APERTURE 10+ | "HwMnotePhysicalAperture" | Physical aperture. Currently, this parameter is read-only. |
## ImageFormat9+
diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md b/en/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md
index 7ce1bcb0c99124d4f731aef43c33fe3eb89f402d..211f4b32bf94bc12e0671f644d3a12d78a6bcba5 100644
--- a/en/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md
+++ b/en/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md
@@ -1,6 +1,10 @@
# AbilityResult
-The **AbilityResult** module defines the result code and data returned when an ability is terminated after being started. You can use [startAbilityForResult](js-apis-ability-featureAbility.md#featureabilitystartabilityforresult7) to obtain the **AbilityResult** object returned after the started ability is terminated. The started ability returns the **AbilityResult** object by calling [terminateSelfWithResult](js-apis-ability-featureAbility.md#featureabilityterminateselfwithresult7).
+The **AbilityResult** module defines the result code and data returned when an ability is terminated after being started.
+
+In the stage model, you can use [startAbilityForResult](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartabilityforresult) to obtain the **AbilityResult** object returned after the started ability is terminated by calling [terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult).
+
+In the FA model, you can use [startAbilityForResult](js-apis-ability-featureAbility.md#featureabilitystartabilityforresult7) to obtain the **AbilityResult** object returned after the started ability is terminated by calling [terminateSelfWithResult](js-apis-ability-featureAbility.md#featureabilityterminateselfwithresult7).
> **NOTE**
>
@@ -8,6 +12,12 @@ The **AbilityResult** module defines the result code and data returned when an a
## Modules to Import
+Stage model:
+```ts
+import common from '@ohos.app.ability.common';
+```
+
+FA model:
```ts
import ability from '@ohos.ability.ability';
```
diff --git a/en/application-dev/reference/apis/js-apis-inner-app-context.md b/en/application-dev/reference/apis/js-apis-inner-app-context.md
index 939c4247fb1595465bab6b812a56c4d06113164e..17a71edfcd77b3bf9baaa74b58acd53cd843e4e7 100644
--- a/en/application-dev/reference/apis/js-apis-inner-app-context.md
+++ b/en/application-dev/reference/apis/js-apis-inner-app-context.md
@@ -495,7 +495,7 @@ Sets the display orientation for this ability. This API uses an asynchronous cal
```ts
import featureAbility from '@ohos.ability.featureAbility';
-import bundle from '@ohos.bundle';
+import bundle from '@ohos.bundle.bundleManager';
let context: featureAbility.Context = featureAbility.getContext();
let orientation = bundle.DisplayOrientation.UNSPECIFIED;
context.setDisplayOrientation(orientation, (error) => {
@@ -522,7 +522,7 @@ Sets the display orientation for this ability. This API uses a promise to return
```ts
import featureAbility from '@ohos.ability.featureAbility';
-import bundle from '@ohos.bundle';
+import bundle from '@ohos.bundle.bundleManager';
let context: featureAbility.Context = featureAbility.getContext();
let orientation = bundle.DisplayOrientation.UNSPECIFIED;
context.setDisplayOrientation(orientation).then((data) => {
@@ -709,7 +709,7 @@ context.getProcessInfo().then((data) => {
getElementName(callback: AsyncCallback\): void
-Obtains the **ohos.bundle.ElementName** object of this ability. This API uses an asynchronous callback to return the result.
+Obtains the **ohos.bundleManager.ElementName** object of this ability. This API uses an asynchronous callback to return the result.
This API is available only to Page abilities.
@@ -719,7 +719,7 @@ This API is available only to Page abilities.
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | -------------------------------------- |
-| callback | AsyncCallback\<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | Callback used to return the **ohos.bundle.ElementName** object.|
+| callback | AsyncCallback\<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | Callback used to return the **ohos.bundleManager.ElementName** object.|
**Example**
@@ -741,7 +741,7 @@ context.getElementName((error, data) => {
getElementName(): Promise\
-Obtains the **ohos.bundle.ElementName** object of this ability. This API uses a promise to return the result.
+Obtains the **ohos.bundleManager.ElementName** object of this ability. This API uses a promise to return the result.
This API is available only to Page abilities.
@@ -751,7 +751,7 @@ This API is available only to Page abilities.
| Type | Description |
| --------------------- | ------------------------------------ |
-| Promise\<[ElementName](js-apis-bundleManager-elementName.md)> | Promise used to return the **ohos.bundle.ElementName** object.|
+| Promise\<[ElementName](js-apis-bundleManager-elementName.md)> | Promise used to return the **ohos.bundleManager.ElementName** object.|
**Example**
diff --git a/en/application-dev/reference/apis/js-apis-inner-application-MediaControlExtensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-MediaControlExtensionContext.md
new file mode 100644
index 0000000000000000000000000000000000000000..8bddcb5adb58f3968494957ae8fd494fbe5c7467
--- /dev/null
+++ b/en/application-dev/reference/apis/js-apis-inner-application-MediaControlExtensionContext.md
@@ -0,0 +1,11 @@
+# MediaControlExtensionContext (ExtensionAbility Context for Media Playback Control)
+
+**MediaControlExtensionContext**, inherited from [UIExtensionContext](js-apis-inner-application-uiExtensionContext.md), provides the context environment for [MediaControlExtensionAbility](js-apis-app-ability-MediaControlExtensionAbility.md). It provides MediaControlExtensionAbility-related configuration and APIs for operating the MediaControlExtensionAbility. For example, you can use the APIs to start a MediaControlExtensionAbility.
+
+**System capability**: SystemCapability.Multimedia.AVSession.Core
+
+> **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 of this module can be used only in the stage model.
+> - The APIs provided by this module are system APIs.
diff --git a/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md
index 5d20e8796f0cf1e4b865bffe7a36087875c2390d..7fca822e57ec3930ddca727f5569ae4bd51ff82b 100644
--- a/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md
+++ b/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md
@@ -734,6 +734,234 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
}
```
+## ServiceExtensionContext.startAbilityAsCaller10+
+
+starAbilityAsCaller(want: Want, callback: AsyncCallback): void;
+
+Starts an ability with the caller information specified. The caller information is carried in **want** and identified at the system service layer. The ability can obtain the caller information from the **want** parameter in the **onCreate** lifecycle callback. When this API is used to start an ability, the caller information carried in **want** is not overwritten by the current application information. The system service layer can obtain the initial caller information. This API uses an asynchronous callback to return the result.
+
+Observe the following when using this API:
+ - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission.
+ - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission.
+ - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
+
+**System capability**: SystemCapability.Ability.AbilityRuntime.Core
+
+**System API**: This is a system API and cannot be called by third-party applications.
+
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.|
+| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the ability is started, **err** is **undefined**. Otherwise, **err** is an error object.|
+
+**Error codes**
+
+| ID| Error Message|
+| ------- | -------------------------------- |
+| 16000001 | The specified ability does not exist. |
+| 16000002 | Incorrect ability type. |
+| 16000004 | Can not start invisible component. |
+| 16000005 | The specified process does not have the permission. |
+| 16000006 | Cross-user operations are not allowed. |
+| 16000008 | The crowdtesting application expires. |
+| 16000009 | An ability cannot be started or stopped in Wukong mode. |
+| 16000010 | The call with the continuation flag is forbidden. |
+| 16000011 | The context does not exist. |
+| 16000012 | The application is controlled. |
+| 16000013 | The application is controlled by EDM. |
+| 16000050 | Internal error. |
+| 16000053 | The ability is not on the top of the UI. |
+| 16000055 | Installation-free timed out. |
+| 16200001 | The caller has been released. |
+
+For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
+
+**Example**
+
+```ts
+import extension from '@ohos.app.ability.ServiceExtensionAbility';
+import Want from '@ohos.app.ability.Want';
+
+export default class EntryAbility extends extension {
+ onCreate(want, launchParam) {
+ // want contains the information about the caller who starts the application.
+ let localWant: Want = want;
+ localWant.bundleName = 'com.example.demo';
+ localWant.moduleName = 'entry';
+ localWant.abilityName = 'TestAbility';
+
+ // Start a new ability using the caller information.
+ this.context.startAbilityAsCaller(localWant, (err) => {
+ if (err && err.code != 0) {
+ console.error('startAbilityAsCaller failed, err:' + JSON.stringify(err));
+ } else {
+ console.log('startAbilityAsCaller success.');
+ }
+ })
+ }
+}
+
+```
+
+## UIAbiliServiceExtensionContexttyContext.startAbilityAsCaller10+
+
+startAbilityAsCaller(want: Want, options: StartOptions, callback: AsyncCallback): void;
+
+Starts an ability with the caller information and start options specified. The caller information is carried in **want** and identified at the system service layer. The ability can obtain the caller information from the **want** parameter in the **onCreate** lifecycle callback. When this API is used to start an ability, the caller information carried in **want** is not overwritten by the current application information. The system service layer can obtain the initial caller information. This API uses an asynchronous callback to return the result.
+
+Observe the following when using this API:
+ - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission.
+ - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission.
+ - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
+
+**System capability**: SystemCapability.Ability.AbilityRuntime.Core
+
+**System API**: This is a system API and cannot be called by third-party applications.
+
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.|
+| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.|
+| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the ability is started, **err** is **undefined**. Otherwise, **err** is an error object.|
+
+**Error codes**
+
+| ID| Error Message|
+| ------- | -------------------------------- |
+| 16000001 | The specified ability does not exist. |
+| 16000002 | Incorrect ability type. |
+| 16000004 | Can not start invisible component. |
+| 16000005 | The specified process does not have the permission. |
+| 16000006 | Cross-user operations are not allowed. |
+| 16000008 | The crowdtesting application expires. |
+| 16000009 | An ability cannot be started or stopped in Wukong mode. |
+| 16000010 | The call with the continuation flag is forbidden. |
+| 16000011 | The context does not exist. |
+| 16000012 | The application is controlled. |
+| 16000013 | The application is controlled by EDM. |
+| 16000050 | Internal error. |
+| 16000053 | The ability is not on the top of the UI. |
+| 16000055 | Installation-free timed out. |
+| 16200001 | The caller has been released. |
+
+For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
+
+**Example**
+
+```ts
+import extension from '@ohos.app.ability.ServiceExtensionAbility';
+import Want from '@ohos.app.ability.Want';
+
+export default class EntryAbility extends extension {
+ onCreate(want, launchParam) {
+ // want contains the information about the caller who starts the application.
+ let localWant: Want = want;
+ localWant.bundleName = 'com.example.demo';
+ localWant.moduleName = 'entry';
+ localWant.abilityName = 'TestAbility';
+
+ let option: StartOptions = {
+ displayId: 0
+ }
+
+ // Start a new ability using the caller information.
+ this.context.startAbilityAsCaller(localWant, option, (err) => {
+ if (err && err.code != 0) {
+ console.error('startAbilityAsCaller failed, err:' + JSON.stringify(err));
+ } else {
+ console.log('startAbilityAsCaller success.');
+ }
+ })
+ }
+}
+
+```
+
+## ServiceExtensionContext.startAbilityAsCaller10+
+
+startAbilityAsCaller(want: Want, options?: StartOptions): Promise;
+
+Starts an ability with the caller information specified. The caller information is carried in **want** and identified at the system service layer. The ability can obtain the caller information from the **want** parameter in the **onCreate** lifecycle callback. When this API is used to start an ability, the caller information carried in **want** is not overwritten by the current application information. The system service layer can obtain the initial caller information. This API uses a promise to return the result.
+
+Observe the following when using this API:
+ - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission.
+ - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission.
+ - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
+
+**System capability**: SystemCapability.Ability.AbilityRuntime.Core
+
+**System API**: This is a system API and cannot be called by third-party applications.
+
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.|
+| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.|
+
+**Return value**
+
+| Type| Description|
+| -------- | -------- |
+| Promise<void> | Promise that returns no value.|
+
+**Error codes**
+
+| ID| Error Message|
+| ------- | -------------------------------- |
+| 16000001 | The specified ability does not exist. |
+| 16000002 | Incorrect ability type. |
+| 16000004 | Can not start invisible component. |
+| 16000005 | The specified process does not have the permission. |
+| 16000006 | Cross-user operations are not allowed. |
+| 16000008 | The crowdtesting application expires. |
+| 16000009 | An ability cannot be started or stopped in Wukong mode. |
+| 16000010 | The call with the continuation flag is forbidden. |
+| 16000011 | The context does not exist. |
+| 16000012 | The application is controlled. |
+| 16000013 | The application is controlled by EDM. |
+| 16000050 | Internal error. |
+| 16000053 | The ability is not on the top of the UI. |
+| 16000055 | Installation-free timed out. |
+| 16200001 | The caller has been released. |
+
+For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
+
+**Example**
+
+```ts
+import extension from '@ohos.app.ability.ServiceExtensionAbility';
+import Want from '@ohos.app.ability.Want';
+
+export default class EntryAbility extends extension {
+ onCreate(want, launchParam) {
+ // want contains the information about the caller who starts the application.
+ let localWant: Want = want;
+ localWant.bundleName = 'com.example.demo';
+ localWant.moduleName = 'entry';
+ localWant.abilityName = 'TestAbility';
+
+ let option: StartOptions = {
+ displayId: 0
+ }
+
+ // Start a new ability using the caller information.
+ this.context.startAbilityAsCaller(localWant, option)
+ .then(() => {
+ console.log('startAbilityAsCaller success.');
+ })
+ .catch((err) => {
+ console.error('startAbilityAsCaller failed, err:' + JSON.stringify(err));
+ })
+ }
+}
+
+```
+
## ServiceExtensionContext.stopServiceExtensionAbility
stopServiceExtensionAbility(want: Want, callback: AsyncCallback\): void;
@@ -1324,7 +1552,7 @@ Observe the following when using this API:
- If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission.
- The rules for using this API in the same-device and cross-device scenarios are different. For details, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
-**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER
+**Required permissions**: ohos.permission.ABILITY_BACKGROUND_COMMUNICATION
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
@@ -1638,7 +1866,7 @@ Observe the following when using this API:
- If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission.
- The rules for using this API in the same-device and cross-device scenarios are different. For details, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
-**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER and ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
+**Required permissions**: ohos.permission.ABILITY_BACKGROUND_COMMUNICATION and ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
diff --git a/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md b/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md
index d4631ab32d661917983f344e6e80afd3059d90ae..19b715770bba3a2349d6e7726fe03aa78b004233 100644
--- a/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md
+++ b/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md
@@ -37,6 +37,7 @@ Observe the following when using this API:
- If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission.
- If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission.
- For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
+ - If the ability to start is in another mission stack and the result needs to be returned to the caller, set the **want** parameter by following the description provided in [Want](js-apis-app-ability-want.md).
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
@@ -44,7 +45,7 @@ Observe the following when using this API:
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.|
+| want | [Want](js-apis-app-ability-want.md) | Yes| Want information about the target ability.|
| callback | AsyncCallback<void> | Yes| Callback used to return the result.|
**Error codes**
@@ -388,7 +389,7 @@ try {
startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityResult>;
-Starts an ability. This API uses a promise to return the result when the ability is terminated. The following situations may be possible to an ability after it is started:
+Starts an ability. This API uses a promise to return the result when the ability is terminated. The following situations may be possible for a started ability:
- Normally, you can call [terminateSelfWithResult](#uiabilitycontextterminateselfwithresult) to terminate the ability. The result is returned to the caller.
- If an exception occurs, for example, the ability is killed, an error message, in which **resultCode** is **-1**, is returned to the caller.
- If different applications call this API to start an ability that uses the singleton mode and then call [terminateSelfWithResult](#uiabilitycontextterminateselfwithresult) to terminate the ability, the normal result is returned to the last caller, and an error message, in which **resultCode** is **-1**, is returned to others.
@@ -1700,7 +1701,7 @@ Observe the following when using this API:
- If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission.
- The rules for using this API in the same-device and cross-device scenarios are different. For details, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
-**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER
+**Required permissions**: ohos.permission.ABILITY_BACKGROUND_COMMUNICATION
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
@@ -2719,7 +2720,7 @@ Observe the following when using this API:
- If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission.
- The rules for using this API in the same-device and cross-device scenarios are different. For details, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
-**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER and ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
+**Required permissions**: ohos.permission.ABILITY_BACKGROUND_COMMUNICATION and ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
@@ -2792,6 +2793,228 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
}
```
+## UIAbilityContext.startAbilityAsCaller10+
+
+starAbilityAsCaller(want: Want, callback: AsyncCallback): void;
+
+Starts an ability with the caller information specified. The caller information is carried in **want** and identified at the system service layer. The ability can obtain the caller information from the **want** parameter in the **onCreate** lifecycle callback. When this API is used to start an ability, the caller information carried in **want** is not overwritten by the current application information. The system service layer can obtain the initial caller information. This API uses an asynchronous callback to return the result.
+
+Observe the following when using this API:
+ - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission.
+ - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission.
+ - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
+
+**System capability**: SystemCapability.Ability.AbilityRuntime.Core
+
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.|
+| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the ability is started, **err** is **undefined**. Otherwise, **err** is an error object.|
+
+**Error codes**
+
+| ID| Error Message|
+| ------- | -------------------------------- |
+| 16000001 | The specified ability does not exist. |
+| 16000002 | Incorrect ability type. |
+| 16000004 | Can not start invisible component. |
+| 16000005 | The specified process does not have the permission. |
+| 16000006 | Cross-user operations are not allowed. |
+| 16000008 | The crowdtesting application expires. |
+| 16000009 | An ability cannot be started or stopped in Wukong mode. |
+| 16000010 | The call with the continuation flag is forbidden. |
+| 16000011 | The context does not exist. |
+| 16000012 | The application is controlled. |
+| 16000013 | The application is controlled by EDM. |
+| 16000050 | Internal error. |
+| 16000053 | The ability is not on the top of the UI. |
+| 16000055 | Installation-free timed out. |
+| 16200001 | The caller has been released. |
+
+For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
+
+**Example**
+
+```ts
+import UIAbility from '@ohos.app.ability.UIAbility';
+import Want from '@ohos.app.ability.Want';
+
+export default class EntryAbility extends UIAbility {
+ onCreate(want, launchParam) {
+ // want contains the information about the caller who starts the application.
+ let localWant: Want = want;
+ localWant.bundleName = 'com.example.demo';
+ localWant.moduleName = 'entry';
+ localWant.abilityName = 'TestAbility';
+
+ // Start a new ability using the caller information.
+ this.context.startAbilityAsCaller(localWant, (err) => {
+ if (err && err.code != 0) {
+ console.error('startAbilityAsCaller failed, err:' + JSON.stringify(err));
+ } else {
+ console.log('startAbilityAsCaller success.');
+ }
+ })
+ }
+}
+
+```
+
+## UIAbilityContext.startAbilityAsCaller10+
+
+startAbilityAsCaller(want: Want, options: StartOptions, callback: AsyncCallback): void;
+
+Starts an ability with the caller information and start options specified. The caller information is carried in **want** and identified at the system service layer. The ability can obtain the caller information from the **want** parameter in the **onCreate** lifecycle callback. When this API is used to start an ability, the caller information carried in **want** is not overwritten by the current application information. The system service layer can obtain the initial caller information. This API uses an asynchronous callback to return the result.
+
+Observe the following when using this API:
+ - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission.
+ - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission.
+ - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
+
+**System capability**: SystemCapability.Ability.AbilityRuntime.Core
+
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.|
+| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.|
+| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the ability is started, **err** is **undefined**. Otherwise, **err** is an error object.|
+
+**Error codes**
+
+| ID| Error Message|
+| ------- | -------------------------------- |
+| 16000001 | The specified ability does not exist. |
+| 16000002 | Incorrect ability type. |
+| 16000004 | Can not start invisible component. |
+| 16000005 | The specified process does not have the permission. |
+| 16000006 | Cross-user operations are not allowed. |
+| 16000008 | The crowdtesting application expires. |
+| 16000009 | An ability cannot be started or stopped in Wukong mode. |
+| 16000010 | The call with the continuation flag is forbidden. |
+| 16000011 | The context does not exist. |
+| 16000012 | The application is controlled. |
+| 16000013 | The application is controlled by EDM. |
+| 16000050 | Internal error. |
+| 16000053 | The ability is not on the top of the UI. |
+| 16000055 | Installation-free timed out. |
+| 16200001 | The caller has been released. |
+
+For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
+
+**Example**
+
+```ts
+import UIAbility from '@ohos.app.ability.UIAbility';
+import Want from '@ohos.app.ability.Want';
+
+export default class EntryAbility extends UIAbility {
+ onCreate(want, launchParam) {
+ // want contains the information about the caller who starts the application.
+ let localWant: Want = want;
+ localWant.bundleName = 'com.example.demo';
+ localWant.moduleName = 'entry';
+ localWant.abilityName = 'TestAbility';
+
+ let option: StartOptions = {
+ displayId: 0
+ }
+
+ // Start a new ability using the caller information.
+ this.context.startAbilityAsCaller(localWant, option, (err) => {
+ if (err && err.code != 0) {
+ console.error('startAbilityAsCaller failed, err:' + JSON.stringify(err));
+ } else {
+ console.log('startAbilityAsCaller success.');
+ }
+ })
+ }
+}
+
+```
+
+## UIAbilityContext.startAbilityAsCaller10+
+
+startAbilityAsCaller(want: Want, options?: StartOptions): Promise;
+
+Starts an ability with the caller information specified. The caller information is carried in **want** and identified at the system service layer. The ability can obtain the caller information from the **want** parameter in the **onCreate** lifecycle callback. When this API is used to start an ability, the caller information carried in **want** is not overwritten by the current application information. The system service layer can obtain the initial caller information. This API uses a promise to return the result.
+
+Observe the following when using this API:
+ - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission.
+ - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission.
+ - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
+
+**System capability**: SystemCapability.Ability.AbilityRuntime.Core
+
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.|
+| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.|
+
+**Return value**
+
+| Type| Description|
+| -------- | -------- |
+| Promise<void> | Promise that returns no value.|
+
+**Error codes**
+
+| ID| Error Message|
+| ------- | -------------------------------- |
+| 16000001 | The specified ability does not exist. |
+| 16000002 | Incorrect ability type. |
+| 16000004 | Can not start invisible component. |
+| 16000005 | The specified process does not have the permission. |
+| 16000006 | Cross-user operations are not allowed. |
+| 16000008 | The crowdtesting application expires. |
+| 16000009 | An ability cannot be started or stopped in Wukong mode. |
+| 16000010 | The call with the continuation flag is forbidden. |
+| 16000011 | The context does not exist. |
+| 16000012 | The application is controlled. |
+| 16000013 | The application is controlled by EDM. |
+| 16000050 | Internal error. |
+| 16000053 | The ability is not on the top of the UI. |
+| 16000055 | Installation-free timed out. |
+| 16200001 | The caller has been released. |
+
+For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
+
+**Example**
+
+```ts
+import UIAbility from '@ohos.app.ability.UIAbility';
+import Want from '@ohos.app.ability.Want';
+
+export default class EntryAbility extends UIAbility {
+ onCreate(want, launchParam) {
+ // want contains the information about the caller who starts the application.
+ let localWant: Want = want;
+ localWant.bundleName = 'com.example.demo';
+ localWant.moduleName = 'entry';
+ localWant.abilityName = 'TestAbility';
+
+ let option: StartOptions = {
+ displayId: 0
+ }
+
+ // Start a new ability using the caller information.
+ this.context.startAbilityAsCaller(localWant, option)
+ .then(() => {
+ console.log('startAbilityAsCaller success.');
+ })
+ .catch((err) => {
+ console.error('startAbilityAsCaller failed, err:' + JSON.stringify(err));
+ })
+ }
+}
+
+```
+
## UIAbilityContext.reportDrawnCompleted10+
reportDrawnCompleted(callback: AsyncCallback\): void;
diff --git a/en/application-dev/reference/apis/js-apis-inner-application-uiExtensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-uiExtensionContext.md
new file mode 100644
index 0000000000000000000000000000000000000000..701a564bbc88a541ce6bd5244579c15c8bc0fa7a
--- /dev/null
+++ b/en/application-dev/reference/apis/js-apis-inner-application-uiExtensionContext.md
@@ -0,0 +1,290 @@
+# UIExtensionContext
+
+**UIExtensionContext**, inherited from [ExtensionContext](js-apis-inner-application-extensionContext.md), provides the context environment for [UIExtensionAbility](js-apis-app-ability-uiExtensionAbility.md). It provides UIExtensionAbility-related configuration and APIs for operating the UIExtensionAbility. For example, you can use the APIs to start a UIExtensionAbility.
+
+> **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 of this module can be used only in the stage model.
+
+## Modules to Import
+
+```ts
+import common from '@ohos.app.ability.common';
+```
+
+## UIExtensionContext.startAbility
+
+startAbility(want: Want, callback: AsyncCallback<void>): void;
+
+Starts an ability. This API uses an asynchronous callback to return the result.
+
+Observe the following when using this API:
+ - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission.
+ - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission.
+ - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
+
+**System capability**: SystemCapability.Ability.AbilityRuntime.Core
+
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.|
+| callback | AsyncCallback<void> | Yes| Callback used to return the result.|
+
+**Error codes**
+
+| ID| Error Message|
+| ------- | -------------------------------- |
+| 16000001 | The specified ability does not exist. |
+| 16000002 | Incorrect ability type. |
+| 16000004 | Can not start invisible component. |
+| 16000005 | The specified process does not have the permission. |
+| 16000006 | Cross-user operations are not allowed. |
+| 16000008 | The crowdtesting application expires. |
+| 16000009 | An ability cannot be started or stopped in Wukong mode. |
+| 16000010 | The call with the continuation flag is forbidden. |
+| 16000011 | The context does not exist. |
+| 16000012 | The application is controlled. |
+| 16000013 | The application is controlled by EDM. |
+| 16000050 | Internal error. |
+| 16000053 | The ability is not on the top of the UI. |
+| 16000055 | Installation-free timed out. |
+| 16200001 | The caller has been released. |
+
+For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
+
+## UIExtensionContext.startAbility
+
+startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void;
+
+Starts an ability with the start options specified. This API uses an asynchronous callback to return the result.
+
+Observe the following when using this API:
+ - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission.
+ - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission.
+ - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
+
+**System capability**: SystemCapability.Ability.AbilityRuntime.Core
+
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.|
+| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.|
+| callback | AsyncCallback<void> | Yes| Callback used to return the result.|
+
+**Error codes**
+
+| ID| Error Message|
+| ------- | -------------------------------- |
+| 16000001 | The specified ability does not exist. |
+| 16000002 | Incorrect ability type. |
+| 16000004 | Can not start invisible component. |
+| 16000005 | The specified process does not have the permission. |
+| 16000006 | Cross-user operations are not allowed. |
+| 16000008 | The crowdtesting application expires. |
+| 16000009 | An ability cannot be started or stopped in Wukong mode. |
+| 16000010 | The call with the continuation flag is forbidden. |
+| 16000011 | The context does not exist. |
+| 16000012 | The application is controlled. |
+| 16000013 | The application is controlled by EDM. |
+| 16000050 | Internal error. |
+| 16000053 | The ability is not on the top of the UI. |
+| 16000055 | Installation-free timed out. |
+| 16200001 | The caller has been released. |
+
+For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
+
+## UIExtensionContext.startAbility
+
+startAbility(want: Want, options?: StartOptions): Promise<void>;
+
+Starts an ability. This API uses a promise to return the result.
+
+Observe the following when using this API:
+ - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission.
+ - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission.
+ - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
+
+**System capability**: SystemCapability.Ability.AbilityRuntime.Core
+
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.|
+| options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Parameters used for starting the ability.|
+
+**Return value**
+
+| Type| Description|
+| -------- | -------- |
+| Promise<void> | Promise used to return the result.|
+
+**Error codes**
+
+| ID| Error Message|
+| ------- | -------------------------------- |
+| 16000001 | The specified ability does not exist. |
+| 16000002 | Incorrect ability type. |
+| 16000004 | Can not start invisible component. |
+| 16000005 | The specified process does not have the permission. |
+| 16000006 | Cross-user operations are not allowed. |
+| 16000008 | The crowdtesting application expires. |
+| 16000009 | An ability cannot be started or stopped in Wukong mode. |
+| 16000010 | The call with the continuation flag is forbidden. |
+| 16000011 | The context does not exist. |
+| 16000012 | The application is controlled. |
+| 16000013 | The application is controlled by EDM. |
+| 16000050 | Internal error. |
+| 16000053 | The ability is not on the top of the UI. |
+| 16000055 | Installation-free timed out. |
+| 16200001 | The caller has been released. |
+
+For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
+
+## UIExtensionContext.startAbilityForResult
+
+startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): void;
+
+Starts an ability. This API uses an asynchronous callback to return the result when the ability is terminated. The following situations may be possible for a started ability:
+ - Normally, you can call [terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to terminate the ability. The result is returned to the caller.
+ - If an exception occurs, for example, the ability is killed, an error message, in which **resultCode** is **-1**, is returned to the caller.
+ - If different applications call this API to start an ability that uses the singleton mode and then call [terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to terminate the ability, the normal result is returned to the last caller, and an exception message, in which **resultCode** is **-1**, is returned to others.
+
+Observe the following when using this API:
+ - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission.
+ - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission.
+ - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
+
+**System capability**: SystemCapability.Ability.AbilityRuntime.Core
+
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| want |[Want](js-apis-application-want.md) | Yes| Want information about the target ability.|
+| callback | AsyncCallback<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Yes| Callback used to return the result.|
+
+**Error codes**
+
+| ID| Error Message|
+| ------- | -------------------------------- |
+| 16000001 | The specified ability does not exist. |
+| 16000002 | Incorrect ability type. |
+| 16000004 | Can not start invisible component. |
+| 16000005 | The specified process does not have the permission. |
+| 16000006 | Cross-user operations are not allowed. |
+| 16000008 | The crowdtesting application expires. |
+| 16000009 | An ability cannot be started or stopped in Wukong mode. |
+| 16000010 | The call with the continuation flag is forbidden. |
+| 16000011 | The context does not exist. |
+| 16000012 | The application is controlled. |
+| 16000013 | The application is controlled by EDM. |
+| 16000050 | Internal error. |
+| 16000053 | The ability is not on the top of the UI. |
+| 16000055 | Installation-free timed out. |
+| 16200001 | The caller has been released. |
+
+For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
+
+## UIExtensionContext.startAbilityForResult
+
+startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback<AbilityResult>): void;
+
+Starts an ability with the start options specified. This API uses an asynchronous callback to return the result when the ability is terminated. The following situations may be possible for a started ability:
+ - Normally, you can call [terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to terminate the ability. The result is returned to the caller.
+ - If an exception occurs, for example, the ability is killed, an error message, in which **resultCode** is **-1**, is returned to the caller.
+ - If different applications call this API to start an ability that uses the singleton mode and then call [terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to terminate the ability, the normal result is returned to the last caller, and an exception message, in which **resultCode** is **-1**, is returned to others.
+
+Observe the following when using this API:
+ - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission.
+ - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission.
+ - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
+
+**System capability**: SystemCapability.Ability.AbilityRuntime.Core
+
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| want |[Want](js-apis-application-want.md) | Yes| Want information about the target ability.|
+| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.|
+| callback | AsyncCallback<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Yes| Callback used to return the result.|
+
+**Error codes**
+
+| ID| Error Message|
+| ------- | -------------------------------- |
+| 16000001 | The specified ability does not exist. |
+| 16000002 | Incorrect ability type. |
+| 16000004 | Can not start invisible component. |
+| 16000005 | The specified process does not have the permission. |
+| 16000006 | Cross-user operations are not allowed. |
+| 16000008 | The crowdtesting application expires. |
+| 16000009 | An ability cannot be started or stopped in Wukong mode. |
+| 16000010 | The call with the continuation flag is forbidden. |
+| 16000011 | The context does not exist. |
+| 16000012 | The application is controlled. |
+| 16000013 | The application is controlled by EDM. |
+| 16000050 | Internal error. |
+| 16000053 | The ability is not on the top of the UI. |
+| 16000055 | Installation-free timed out. |
+| 16200001 | The caller has been released. |
+
+For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
+
+## UIExtensionContext.startAbilityForResult
+
+startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityResult>;
+
+Starts an ability. This API uses a promise to return the result when the ability is terminated. The following situations may be possible for a started ability:
+ - Normally, you can call [terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to terminate the ability. The result is returned to the caller.
+ - If an exception occurs, for example, the ability is killed, an error message, in which **resultCode** is **-1**, is returned to the caller.
+ - If different applications call this API to start an ability that uses the singleton mode and then call [terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to terminate the ability, the normal result is returned to the last caller, and an exception message, in which **resultCode** is **-1**, is returned to others.
+
+Observe the following when using this API:
+ - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission.
+ - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission.
+ - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
+
+**System capability**: SystemCapability.Ability.AbilityRuntime.Core
+
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.|
+| options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Parameters used for starting the ability.|
+
+
+**Return value**
+
+| Type| Description|
+| -------- | -------- |
+| Promise<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Promise used to return the result.|
+
+**Error codes**
+
+| ID| Error Message|
+| ------- | -------------------------------- |
+| 16000001 | The specified ability does not exist. |
+| 16000002 | Incorrect ability type. |
+| 16000004 | Can not start invisible component. |
+| 16000005 | The specified process does not have the permission. |
+| 16000006 | Cross-user operations are not allowed. |
+| 16000008 | The crowdtesting application expires. |
+| 16000009 | An ability cannot be started or stopped in Wukong mode. |
+| 16000010 | The call with the continuation flag is forbidden. |
+| 16000011 | The context does not exist. |
+| 16000012 | The application is controlled. |
+| 16000013 | The application is controlled by EDM. |
+| 16000050 | Internal error. |
+| 16000053 | The ability is not on the top of the UI. |
+| 16000055 | Installation-free timed out. |
+| 16200001 | The caller has been released. |
+
+For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
diff --git a/en/application-dev/reference/apis/js-apis-installer.md b/en/application-dev/reference/apis/js-apis-installer.md
index 3e31435e0f3030b1e659c038a9e11062c4316836..73a21ac50aba267e90a9a039e7a150dd01bb536d 100644
--- a/en/application-dev/reference/apis/js-apis-installer.md
+++ b/en/application-dev/reference/apis/js-apis-installer.md
@@ -20,6 +20,9 @@ import installer from '@ohos.bundle.installer';
| ohos.permission.INSTALL_ENTERPRISE_BUNDLE | system_core | Permission to install enterprise InHouse applications.|
| ohos.permission.INSTALL_ENTERPRISE_MDM_BUNDLE | system_core | Permission to install enterprise MDM applications.|
| ohos.permission.INSTALL_ENTERPRISE_NORMAL_BUNDLE | system_core | Permission to install enterprise Normal applications.|
+| ohos.permission.UNINSTALL_BUNDLE | system_core | Allows an application to uninstall applications.|
+| ohos.permission.RECOVER_BUNDLE | system_core | Allows an application to restore pre-installed applications.|
+| ohos.permission.INSTALL_SELF_BUNDLE | system_core | Allows automatic updates of the enterprise MDM applications on enterprise devices.|
For details, see [Permission Levels](../../security/accesstoken-overview.md#permission-levels).
@@ -96,13 +99,18 @@ Installs a bundle. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
-**Required permissions**: ohos.permission.INSTALL_BUNDLE or ohos.permission.INSTALL_ENTERPRISE_BUNDLE10+
+**Required permissions**: ohos.permission.INSTALL_BUNDLE, ohos.permission.INSTALL_ENTERPRISE_BUNDLE10+ , ohos.permission.INSTALL_ENTERPRISE_NORMAL_BUNDLE10+ , or ohos.permission.INSTALL_ENTERPRISE_MDM_BUNDLE10+
+
> **NOTE**
>
-> Since API version 10, this API can be called with the **ohos.permission.INSTALL_ENTERPRISE_BUNDLE** permission.
+> Since API version 10, this API can be called with the permission **ohos.permission.INSTALL_ENTERPRISE_BUNDLE**, **ohos.permission.INSTALL_ENTERPRISE_NORMAL_BUNDLE**, or **ohos.permission.INSTALL_ENTERPRISE_MDM_BUNDLE**.
>
> To install an enterprise application, you must have the **ohos.permission.INSTALL_ENTERPRISE_BUNDLE** permission.
>
+> To install an enterprise Normal application, you must have the **ohos.permission.INSTALL_ENTERPRISE_NORMAL_BUNDLE** or **ohos.permission.INSTALL_ENTERPRISE_MDM_BUNDLE** permission.
+>
+> To install an enterprise MDM application, you must have the **ohos.permission.INSTALL_ENTERPRISE_MDM_BUNDLE** permission.
+>
> To install a common application, you must have the **ohos.permission.INSTALL_BUNDLE** permission.
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
@@ -138,6 +146,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
| 17700044 | Failed to install the HAP because the isolationMode configured is not supported. |
| 17700047 | Failed to install the HAP because the VersionCode to be updated is not greater than the current VersionCode. |
| 17700048 | Failed to install the HAP because the code signature verification is failed. |
+| 17700050 | Failed to install the HAP because enterprise normal/MDM bundle cannot be installed on non-enterprise device. |
**Example**
@@ -173,13 +182,17 @@ Installs a bundle. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
-**Required permissions**: ohos.permission.INSTALL_BUNDLE or ohos.permission.INSTALL_ENTERPRISE_BUNDLE10+
-> **NOTE**
+**Required permissions**: ohos.permission.INSTALL_BUNDLE, ohos.permission.INSTALL_ENTERPRISE_BUNDLE10+ , ohos.permission.INSTALL_ENTERPRISE_NORMAL_BUNDLE10+ , or ohos.permission.INSTALL_ENTERPRISE_MDM_BUNDLE10+
+> **NOTE**
>
-> Since API version 10, this API can be called with the **ohos.permission.INSTALL_ENTERPRISE_BUNDLE** permission.
+> Since API version 10, this API can be called with the permission **ohos.permission.INSTALL_ENTERPRISE_BUNDLE**, **ohos.permission.INSTALL_ENTERPRISE_NORMAL_BUNDLE**, or **ohos.permission.INSTALL_ENTERPRISE_MDM_BUNDLE**.
>
> To install an enterprise application, you must have the **ohos.permission.INSTALL_ENTERPRISE_BUNDLE** permission.
>
+> To install an enterprise Normal application, you must have the **ohos.permission.INSTALL_ENTERPRISE_NORMAL_BUNDLE** or **ohos.permission.INSTALL_ENTERPRISE_MDM_BUNDLE** permission.
+>
+> To install an enterprise MDM application, you must have the **ohos.permission.INSTALL_ENTERPRISE_MDM_BUNDLE** permission.
+>
> To install a common application, you must have the **ohos.permission.INSTALL_BUNDLE** permission.
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
@@ -213,6 +226,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
| 17700044 | Failed to install the HAP because the isolationMode configured is not supported. |
| 17700047 | Failed to install the HAP because the VersionCode to be updated is not greater than the current VersionCode. |
| 17700048 | Failed to install the HAP because the code signature verification is failed. |
+| 17700050 | Failed to install the HAP because enterprise normal/MDM bundle cannot be installed on non-enterprise device. |
**Example**
@@ -245,13 +259,17 @@ Installs a bundle. This API uses a promise to return the result.
**System API**: This is a system API.
-**Required permissions**: ohos.permission.INSTALL_BUNDLE or ohos.permission.INSTALL_ENTERPRISE_BUNDLE10+
-> **NOTE**
+**Required permissions**: ohos.permission.INSTALL_BUNDLE, ohos.permission.INSTALL_ENTERPRISE_BUNDLE10+ , ohos.permission.INSTALL_ENTERPRISE_NORMAL_BUNDLE10+ , or ohos.permission.INSTALL_ENTERPRISE_MDM_BUNDLE10+
+> **NOTE**
>
-> Since API version 10, this API can be called with the **ohos.permission.INSTALL_ENTERPRISE_BUNDLE** permission.
+> Since API version 10, this API can be called with the permission **ohos.permission.INSTALL_ENTERPRISE_BUNDLE**, **ohos.permission.INSTALL_ENTERPRISE_NORMAL_BUNDLE**, or **ohos.permission.INSTALL_ENTERPRISE_MDM_BUNDLE**.
>
> To install an enterprise application, you must have the **ohos.permission.INSTALL_ENTERPRISE_BUNDLE** permission.
>
+> To install an enterprise Normal application, you must have the **ohos.permission.INSTALL_ENTERPRISE_NORMAL_BUNDLE** or **ohos.permission.INSTALL_ENTERPRISE_MDM_BUNDLE** permission.
+>
+> To install an enterprise MDM application, you must have the **ohos.permission.INSTALL_ENTERPRISE_MDM_BUNDLE** permission.
+>
> To install a common application, you must have the **ohos.permission.INSTALL_BUNDLE** permission.
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
@@ -292,6 +310,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
| 17700044 | Failed to install the HAP because the isolationMode configured is not supported. |
| 17700047 | Failed to install the HAP because the VersionCode to be updated is not greater than the current VersionCode. |
| 17700048 | Failed to install the HAP because the code signature verification is failed. |
+| 17700050 | Failed to install the HAP because enterprise normal/MDM bundle cannot be installed on non-enterprise device. |
**Example**
@@ -328,7 +347,7 @@ Uninstalls a bundle. This API uses an asynchronous callback to return the result
**System API**: This is a system API.
-**Required permissions**: ohos.permission.INSTALL_BUNDLE
+**Required permissions**: ohos.permission.INSTALL_BUNDLE or ohos.permission.UNINSTALL_BUNDLE10+
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
@@ -388,7 +407,7 @@ Uninstalls a bundle. This API uses an asynchronous callback to return the result
**System API**: This is a system API.
-**Required permissions**: ohos.permission.INSTALL_BUNDLE
+**Required permissions**: ohos.permission.INSTALL_BUNDLE or ohos.permission.UNINSTALL_BUNDLE10+
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
@@ -440,7 +459,7 @@ Uninstalls a bundle. This API uses a promise to return the result.
**System API**: This is a system API.
-**Required permissions**: ohos.permission.INSTALL_BUNDLE
+**Required permissions**: ohos.permission.INSTALL_BUNDLE or ohos.permission.UNINSTALL_BUNDLE10+
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
@@ -503,7 +522,7 @@ Rolls back a bundle to the initial installation state. This API uses an asynchro
**System API**: This is a system API.
-**Required permissions**: ohos.permission.INSTALL_BUNDLE
+**Required permissions**: ohos.permission.INSTALL_BUNDLE or ohos.permission.RECOVER_BUNDLE10+
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
@@ -561,7 +580,7 @@ Rolls back a bundle to the initial installation state. This API uses an asynchro
**System API**: This is a system API.
-**Required permissions**: ohos.permission.INSTALL_BUNDLE
+**Required permissions**: ohos.permission.INSTALL_BUNDLE or ohos.permission.RECOVER_BUNDLE10+
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
@@ -611,7 +630,7 @@ Rolls back a bundle to the initial installation state. This API uses a promise t
**System API**: This is a system API.
-**Required permissions**: ohos.permission.INSTALL_BUNDLE
+**Required permissions**: ohos.permission.INSTALL_BUNDLE or ohos.permission.RECOVER_BUNDLE10+
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
@@ -671,7 +690,7 @@ Uninstalls a shared bundle. This API uses an asynchronous callback to return the
**System API**: This is a system API.
-**Required permissions**: ohos.permission.INSTALL_BUNDLE
+**Required permissions**: ohos.permission.INSTALL_BUNDLE or ohos.permission.UNINSTALL_BUNDLE10+
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
@@ -725,7 +744,7 @@ Uninstalls a shared bundle. This API uses a promise to return the result.
**System API**: This is a system API.
-**Required permissions**: ohos.permission.INSTALL_BUNDLE
+**Required permissions**: ohos.permission.INSTALL_BUNDLE or ohos.permission.UNINSTALL_BUNDLE10+
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
@@ -776,6 +795,220 @@ try {
}
```
+## BundleInstaller.updateBundleForSelf10+
+
+updateBundleForSelf(hapFilePaths: Array\, installParam: InstallParam, callback: AsyncCallback\): void;
+
+Updates the current bundle. This API uses an asynchronous callback to return the result. It can be called only by enterprise MDM applications on enterprise devices, and the HAPs in **hapFilePaths** must belong to the current application.
+
+**System API**: This is a system API.
+
+**Required permissions**: ohos.permission.INSTALL_SELF_BUNDLE
+
+**System capability**: SystemCapability.BundleManager.BundleFramework.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| --------------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ |
+| hapFilePaths | Array<string> | Yes | Paths where the HAP files of the bundle are stored, which are the data directories. If only one directory is passed, the HAP files in the directory must belong to the same bundle and have the same signature.|
+| installParam | [InstallParam](#installparam) | Yes | Parameters required for the installation. |
+| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is undefined; otherwise, **err** is an error object.|
+
+**Error codes**
+
+For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md).
+
+| ID| Error Message |
+| -------- | ------------------------------------------------------------ |
+| 17700004 | The specified user ID is not found. |
+| 17700010 | Failed to install the HAP because the HAP fails to be parsed. |
+| 17700011 | Failed to install the HAP because the HAP signature fails to be verified. |
+| 17700012 | Failed to install the HAP because the HAP path is invalid or the HAP is too large. |
+| 17700015 | Failed to install the HAPs because they have different configuration information. |
+| 17700016 | Failed to install the HAP because of insufficient system disk space. |
+| 17700017 | Failed to install the HAP since the version of the HAP to install is too early. |
+| 17700018 | Failed to install because the dependent module does not exist. |
+| 17700031 | Failed to install the HAP because the overlay check of the HAP is failed. |
+| 17700039 | Failed to install because disallow install a shared bundle by hapFilePaths. |
+| 17700041 | Failed to install because enterprise device management disallow install. |
+| 17700042 | Failed to install the HAP because of incorrect URI in the data proxy. |
+| 17700043 | Failed to install the HAP because of low APL in the non-system data proxy (required APL: system_basic or system_core). |
+| 17700044 | Failed to install the HAP because the isolationMode configured is not supported. |
+| 17700047 | Failed to install the HAP because the VersionCode to be updated is not greater than the current VersionCode. |
+| 17700048 | Failed to install the HAP because the code signature verification is failed. |
+| 17700049 | Failed to install the HAP because the bundleName is different from the bundleName of the caller application. |
+| 17700050 | Failed to install the HAP because enterprise normal/MDM bundle cannot be installed on non-enterprise device. |
+| 17700051 | Failed to install the HAP because the distribution type of caller application is not enterprise_mdm. |
+
+**Example**
+
+```ts
+import installer from '@ohos.bundle.installer';
+let hapFilePaths = ['/data/storage/el2/base/haps/entry/files/'];
+let installParam = {
+ userId: 100,
+ isKeepData: false,
+ installFlag: 1,
+};
+
+try {
+ installer.getBundleInstaller().then(data => {
+ data.updateBundleForSelf(hapFilePaths, installParam, err => {
+ if (err) {
+ console.error('updateBundleForSelf failed:' + err.message);
+ } else {
+ console.info('updateBundleForSelf successfully.');
+ }
+ });
+ }).catch(error => {
+ console.error('getBundleInstaller failed. Cause: ' + error.message);
+ });
+} catch (error) {
+ console.error('getBundleInstaller failed. Cause: ' + error.message);
+}
+```
+
+## BundleInstaller.updateBundleForSelf10+
+
+updateBundleForSelf(hapFilePaths: Array\, callback: AsyncCallback\): void;
+
+Updates the current bundle. This API uses an asynchronous callback to return the result. It can be called only by enterprise MDM applications on enterprise devices, and the HAPs in **hapFilePaths** must belong to the current application.
+
+**System API**: This is a system API.
+
+**Required permissions**: ohos.permission.INSTALL_SELF_BUNDLE
+
+**System capability**: SystemCapability.BundleManager.BundleFramework.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| --------------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ |
+| hapFilePaths | Array<string> | Yes | Paths where the HAP files of the bundle are stored, which are the data directories. If only one directory is passed, the HAP files in the directory must belong to the same bundle and have the same signature.|
+| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is undefined; otherwise, **err** is an error object.|
+
+**Error codes**
+
+For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md).
+
+| ID| Error Message |
+| -------- | ------------------------------------------------------------ |
+| 17700004 | The specified user ID is not found. |
+| 17700010 | Failed to install the HAP because the HAP fails to be parsed. |
+| 17700011 | Failed to install the HAP because the HAP signature fails to be verified. |
+| 17700012 | Failed to install the HAP because the HAP path is invalid or the HAP is too large. |
+| 17700015 | Failed to install the HAPs because they have different configuration information. |
+| 17700016 | Failed to install the HAP because of insufficient system disk space. |
+| 17700017 | Failed to install the HAP since the version of the HAP to install is too early. |
+| 17700018 | Failed to install because the dependent module does not exist. |
+| 17700031 | Failed to install the HAP because the overlay check of the HAP is failed. |
+| 17700039 | Failed to install because disallow install a shared bundle by hapFilePaths. |
+| 17700041 | Failed to install because enterprise device management disallow install. |
+| 17700042 | Failed to install the HAP because of incorrect URI in the data proxy. |
+| 17700043 | Failed to install the HAP because of low APL in the non-system data proxy (required APL: system_basic or system_core). |
+| 17700044 | Failed to install the HAP because the isolationMode configured is not supported. |
+| 17700047 | Failed to install the HAP because the VersionCode to be updated is not greater than the current VersionCode. |
+| 17700048 | Failed to install the HAP because the code signature verification is failed. |
+| 17700049 | Failed to install the HAP because the bundleName is different from the bundleName of the caller application. |
+| 17700050 | Failed to install the HAP because enterprise normal/MDM bundle cannot be installed on non-enterprise device. |
+| 17700051 | Failed to install the HAP because the distribution type of caller application is not enterprise_mdm. |
+
+**Example**
+
+```ts
+import installer from '@ohos.bundle.installer';
+let hapFilePaths = ['/data/storage/el2/base/haps/entry/files/'];
+
+try {
+ installer.getBundleInstaller().then(data => {
+ data.updateBundleForSelf(hapFilePaths, err => {
+ if (err) {
+ console.error('updateBundleForSelf failed:' + err.message);
+ } else {
+ console.info('updateBundleForSelf successfully.');
+ }
+ });
+ }).catch(error => {
+ console.error('getBundleInstaller failed. Cause: ' + error.message);
+ });
+} catch (error) {
+ console.error('getBundleInstaller failed. Cause: ' + error.message);
+}
+```
+
+## BundleInstaller.updateBundleForSelf10+
+
+updateBundleForSelf(hapFilePaths: Array\, installParam?: InstallParam): Promise\;
+
+Updates the current bundle. This API uses a promise to return the result. It can be called only by enterprise MDM applications on enterprise devices, and the HAPs in **hapFilePaths** must belong to the current application.
+
+**System API**: This is a system API.
+
+**Required permissions**: ohos.permission.INSTALL_SELF_BUNDLE
+
+**System capability**: SystemCapability.BundleManager.BundleFramework.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| --------------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ |
+| hapFilePaths | Array<string> | Yes | Paths where the HAP files of the bundle are stored, which are the data directories. If only one directory is passed, the HAP files in the directory must belong to the same bundle and have the same signature.|
+| installParam | [InstallParam](#installparam) | No | Parameters required for the installation. For details about their default values, see [InstallParam](#installparam). |
+
+**Error codes**
+
+For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md).
+
+| ID| Error Message |
+| -------- | ------------------------------------------------------------ |
+| 17700004 | The specified user ID is not found. |
+| 17700010 | Failed to install the HAP because the HAP fails to be parsed. |
+| 17700011 | Failed to install the HAP because the HAP signature fails to be verified. |
+| 17700012 | Failed to install the HAP because the HAP path is invalid or the HAP is too large. |
+| 17700015 | Failed to install the HAPs because they have different configuration information. |
+| 17700016 | Failed to install the HAP because of insufficient system disk space. |
+| 17700017 | Failed to install the HAP since the version of the HAP to install is too early. |
+| 17700018 | Failed to install because the dependent module does not exist. |
+| 17700031 | Failed to install the HAP because the overlay check of the HAP is failed. |
+| 17700039 | Failed to install because disallow install a shared bundle by hapFilePaths. |
+| 17700041 | Failed to install because enterprise device management disallow install. |
+| 17700042 | Failed to install the HAP because of incorrect URI in the data proxy. |
+| 17700043 | Failed to install the HAP because of low APL in the non-system data proxy (required APL: system_basic or system_core). |
+| 17700044 | Failed to install the HAP because the isolationMode configured is not supported. |
+| 17700047 | Failed to install the HAP because the VersionCode to be updated is not greater than the current VersionCode. |
+| 17700048 | Failed to install the HAP because the code signature verification is failed. |
+| 17700049 | Failed to install the HAP because the bundleName is different from the bundleName of the caller application. |
+| 17700050 | Failed to install the HAP because enterprise normal/MDM bundle cannot be installed on non-enterprise device. |
+| 17700051 | Failed to install the HAP because the distribution type of caller application is not enterprise_mdm. |
+
+**Example**
+
+```ts
+import installer from '@ohos.bundle.installer';
+let hapFilePaths = ['/data/storage/el2/base/haps/entry/files/'];
+let installParam = {
+ userId: 100,
+ isKeepData: false,
+ installFlag: 1,
+};
+
+try {
+ installer.getBundleInstaller().then(data => {
+ data.updateBundleForSelf(hapFilePaths, installParam)
+ .then((data) => {
+ console.info('updateBundleForSelf successfully: ' + JSON.stringify(data));
+ }).catch((error) => {
+ console.error('updateBundleForSelf failed:' + error.message);
+ });
+ }).catch(error => {
+ console.error('getBundleInstaller failed. Cause: ' + error.message);
+ });
+} catch (error) {
+ console.error('getBundleInstaller failed. Cause: ' + error.message);
+}
+```
+
## HashParam
Defines the hash parameters for bundle installation and uninstall.
diff --git a/en/application-dev/reference/apis/js-apis-linkedlist.md b/en/application-dev/reference/apis/js-apis-linkedlist.md
index fa13281b52c968658e016fd7ee82be77e570fd60..f4c57358389eebbf15bb3abcdc8a5dbaca648ba8 100644
--- a/en/application-dev/reference/apis/js-apis-linkedlist.md
+++ b/en/application-dev/reference/apis/js-apis-linkedlist.md
@@ -145,8 +145,8 @@ Inserts an element at the specified position in this container.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| element | T | Yes| Target element.|
| index | number | Yes| Index of the position where the element is to be inserted.|
+| element | T | Yes| Target element.|
**Error codes**
diff --git a/en/application-dev/reference/apis/js-apis-matrix4.md b/en/application-dev/reference/apis/js-apis-matrix4.md
index 67864b311bd4fbf30b87e17abb84db12e24889be..7aea13609e2d96615d36668eddbd275960916133 100644
--- a/en/application-dev/reference/apis/js-apis-matrix4.md
+++ b/en/application-dev/reference/apis/js-apis-matrix4.md
@@ -27,7 +27,7 @@ Matrix constructor, which is used to create a 4 x 4 matrix by using the input pa
| Name| Type | Mandatory| Description |
| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
-| option | [number,number,number,number, number,number,number,number, number,number,number,number, number,number,number,number] | Yes | A number array whose length is 16 (4 x 4). For details, see **Description of a 4 x 4 matrix**. Default value: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] |
+| option | [number,number,number,number, number,number,number,number, number,number,number,number, number,number,number,number] | Yes | A number array whose length is 16 (4 x 4). For details, see **4 x 4 matrix description**. Default value: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] |
**Return value**
@@ -35,7 +35,7 @@ Matrix constructor, which is used to create a 4 x 4 matrix by using the input pa
| --------------------------------- | ---------------------------- |
| [Matrix4Transit](#matrix4transit) | 4 x 4 matrix object created based on the input parameter.|
-**Description of a 4 x 4 matrix**
+**4 x 4 matrix description**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | -------------------- |
@@ -150,6 +150,7 @@ import matrix4 from '@ohos.matrix4'
@Component
struct Test {
private matrix1 = matrix4.identity().translate({ x: 100 })
+ // Perform the scale operation on the copy matrix of matrix1, which does not affect matrix1.
private matrix2 = this.matrix1.copy().scale({ x: 2 })
build() {
@@ -305,7 +306,7 @@ This API is deprecated since API version 10.
combine(options: Matrix4Transit): Matrix4Transit
-Combines the effects of two matrices to generate a new matrix object.
+Combines the effects of two matrices to generate a new matrix object. The original matrix that calls this API will be changed.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
@@ -330,8 +331,8 @@ import matrix4 from '@ohos.matrix4'
@Entry
@Component
struct Test {
- private matrix1 = matrix4.identity().translate({ x: 200 }).copy()
- private matrix2 = matrix4.identity().scale({ x: 2 }).copy()
+ private matrix1 = matrix4.identity().translate({ x: 200 })
+ private matrix2 = matrix4.identity().scale({ x: 2 })
build() {
Column() {
@@ -342,7 +343,7 @@ struct Test {
.margin({ top: 50 })
// Translate the x-axis by 200px, and then scale it twice to obtain the resultant matrix.
Image($r("app.media.icon"))
- .transform(this.matrix1.combine(this.matrix2))
+ .transform(this.matrix1.copy().combine(this.matrix2))
.width("40%")
.height(100)
.margin({ top: 50 })
@@ -358,7 +359,7 @@ struct Test {
invert(): Matrix4Transit
-Inverts this matrix object.
+Inverts this matrix object. The original matrix that calls this API will be changed.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
@@ -374,7 +375,7 @@ Inverts this matrix object.
import matrix4 from '@ohos.matrix4'
// The effect of matrix 1 (width scaled up by 2x) is opposite to that of matrix 2 (width scaled down by 2x).
let matrix1 = matrix4.identity().scale({ x: 2 })
-let matrix2 = matrix1.invert()
+let matrix2 = matrix1.copy().invert()
@Entry
@Component
@@ -401,7 +402,7 @@ struct Tests {
translate(options: TranslateOption): Matrix4Transit
-Translates this matrix object along the x, y, and z axes.
+Translates this matrix object along the x, y, and z axes. The original matrix that calls this API will be changed.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
@@ -446,7 +447,7 @@ struct Test {
scale(options: ScaleOption): Matrix4Transit
-Scales this matrix object along the x, y, and z axes.
+Scales this matrix object along the x, y, and z axes. The original matrix that calls this API will be changed.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
@@ -490,7 +491,7 @@ struct Test {
rotate(options: RotateOption): Matrix4Transit
-Rotates this matrix object along the x, y, and z axes.
+Rotates this matrix object along the x, y, and z axes. The original matrix that calls this API will be changed.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
@@ -604,9 +605,9 @@ struct Test {
| Name | Type | Mandatory| Description |
| ------- | ------ | ---- | ------------------------------------------------------------ |
-| x | number | No | Scaling multiple along the x-axis. If the value is greater than 1, the image is scaled up along the x-axis. If the value is less than 1, the image is scaled down along the x-axis. Default value: **1** Value range: [0, +∞) **NOTE** A value less than 0 evaluates to the default value.|
-| y | number | No | Scaling multiple along the y-axis. If the value is greater than 1, the image is scaled up along the y-axis. If the value is less than 1, the image is scaled down along the y-axis. Default value: **1** Value range: [0, +∞) **NOTE** A value less than 0 evaluates to the default value.|
-| z | number | No | Scaling multiple along the z-axis. If the value is greater than 1, the image is scaled up along the z-axis. If the value is less than 1, the image is scaled down along the z-axis. Default value: **1** Value range: [0, +∞) **NOTE** A value less than 0 evaluates to the default value.|
+| x | number | No | Scaling multiple along the x-axis. x > 1: The image is scaled up along the x-axis. 0 < x < 1: The image is scaled down along the x-axis. x < 0: The image is scaled in the reverse direction of the x-axis. Default value: **1** Value range: (-∞, +∞)|
+| y | number | No | Scaling multiple along the y-axis. y > 1: The image is scaled up along the y-axis. 0 < y < 1: The image is scaled down along the y-axis. y < 0: The image is scaled in the reverse direction of the y-axis. Default value: **1** Value range: (-∞, +∞)|
+| z | number | No | Scaling multiple along the z-axis. z > 1: The image is scaled up along the z-axis. 0 < z < 1: The image is scaled down along the z-axis. z < 0: The image is scaled in the reverse direction of the z-axis. Default value: **1** Value range: (-∞, +∞)|
| centerX | number | No | X coordinate of the center point. Default value: **0** Value range: (-∞, +∞) |
| centerY | number | No | Y coordinate of the center point. Default value: **0** Value range: (-∞, +∞) |
@@ -616,9 +617,9 @@ struct Test {
| Name | Type | Mandatory| Description |
| ------- | ------ | ---- | ------------------------------------------------------- |
-| x | number | No | X coordinate of the rotation axis vector. Default value: **1** Value range: (-∞, +∞)|
-| y | number | No | Y coordinate of the rotation axis vector. Default value: **1** Value range: (-∞, +∞)|
-| z | number | No | Z coordinate of the rotation axis vector. Default value: **1** Value range: (-∞, +∞)|
+| x | number | No | X coordinate of the rotation axis vector. Default value: **0** Value range: (-∞, +∞)|
+| y | number | No | Y coordinate of the rotation axis vector. Default value: **0** Value range: (-∞, +∞)|
+| z | number | No | Z coordinate of the rotation axis vector. Default value: **0** Value range: (-∞, +∞) **NOTE** The rotation axis vector is valid only when at least one of **x**, **y**, and **z** is not 0.|
| angle | number | No | Rotation angle. Default value: **0** |
| centerX | number | No | X coordinate of the center point. Default value: **0** |
| centerY | number | No | Y coordinate of the center point. Default value: **0** |
diff --git a/en/application-dev/reference/apis/js-apis-measure.md b/en/application-dev/reference/apis/js-apis-measure.md
index 4b0eac439ab60844ca48f768ed768126b01d64da..3b379749cfe0fc234959acdd1da2da2632cd1ee8 100644
--- a/en/application-dev/reference/apis/js-apis-measure.md
+++ b/en/application-dev/reference/apis/js-apis-measure.md
@@ -116,7 +116,7 @@ Provides attributes of the measured text.
| constraintWidth10+ | number \| string \| [Resource](../arkui-ts/ts-types.md#resource) | No | Layout width of the measured text. The default unit is vp. |
| fontSize | number \| string \| [Resource](../arkui-ts/ts-types.md#resource) | No | Font size of the measured text. If the value is of the number type, the unit fp is used. Default value: **16fp** **NOTE** The value cannot be a percentage. |
| fontStyle | number \| [FontStyle](../arkui-ts/ts-appendix-enums.md#fontstyle) | No | Font style of the measured text. Default value: **FontStyle.Normal** |
-| fontWeight | number \| string \| [FontWeight](../arkui-ts/ts-appendix-enums.md#fontweight) | No | Font width of the measured text. For the number type, the value ranges from 100 to 900, at an interval of 100. The default value is **400**. A larger value indicates a heavier font weight. The string type supports only the string of the number type, for example, **400**, **"bold"**, **"bolder"**, **"lighter"**, **"regular"**, and **"medium"**, which correspond to the enumerated values in **FontWeight**. Default value: **FontWeight.Normal**|
+| fontWeight | number \| string \| [FontWeight](../arkui-ts/ts-appendix-enums.md#fontweight) | No | Font width of the measured text. For the number type, the value ranges from 100 to 900, at an interval of 100. A larger value indicates a heavier font weight. The default value is **400**. For the string type, only strings of the number type are supported, for example, **400**, **"bold"**, **"bolder"**, **"lighter"**, **"regular"**, and **"medium"**, which correspond to the enumerated values in **FontWeight**. Default value: **FontWeight.Normal**|
| fontFamily | string \| [Resource](../arkui-ts/ts-types.md#resource) | No | Font family of the measured text. Default value: **'HarmonyOS Sans'** Only the default font is supported.|
| letterSpacing | number \| string | No | Letter spacing of the measured text.|
| textAlign10+ | number \| [TextAlign](../arkui-ts/ts-appendix-enums.md#textalign) | No | Horizontal alignment mode of the measured text. Default value: **TextAlign.Start**|
diff --git a/en/application-dev/reference/apis/js-apis-media.md b/en/application-dev/reference/apis/js-apis-media.md
index 5654300a33ef42db7686a4c3de3ff541f4bdb8a0..19f986bfa6309762591b3878e0602476168d25b4 100644
--- a/en/application-dev/reference/apis/js-apis-media.md
+++ b/en/application-dev/reference/apis/js-apis-media.md
@@ -1781,7 +1781,7 @@ let AVRecorderConfig = {
audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC,
videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV,
profile : AVRecorderProfile,
- url : 'fd://', // Before passing in an FD to this parameter, the file must be created by the caller and granted with the read and write permissions. Example value: eg.fd://45.
+ url : 'fd://', // Before passing in an FD to this parameter, the file must be created by the caller and granted with the read and write permissions. Example value: fd://45.
rotation: 0, // The value can be 0, 90, 180, or 270. If any other value is used, prepare() reports an error.
location : { latitude : 30, longitude : 130 }
}
@@ -1852,7 +1852,7 @@ let AVRecorderConfig = {
audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC,
videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV,
profile : AVRecorderProfile,
- url : 'fd://', // Before passing in an FD to this parameter, the file must be created by the caller and granted with the read and write permissions. Example value: eg.fd://45.
+ url : 'fd://', // Before passing in an FD to this parameter, the file must be created by the caller and granted with the read and write permissions. Example value: fd://45.
rotation: 0, // The value can be 0, 90, 180, or 270. If any other value is used, prepare() reports an error.
location : { latitude : 30, longitude : 130 }
}
diff --git a/en/application-dev/reference/apis/js-apis-medialibrary.md b/en/application-dev/reference/apis/js-apis-medialibrary.md
index 6edbbc62092208dec500e6e9e540209e3cd8272a..247f7fe55d79701c01435ae36bf63c7a505338e9 100644
--- a/en/application-dev/reference/apis/js-apis-medialibrary.md
+++ b/en/application-dev/reference/apis/js-apis-medialibrary.md
@@ -20,7 +20,7 @@ Obtains a **MediaLibrary** instance, which is used to access and modify personal
This API can be used only in the stage model.
> **NOTE**
-> This API is deprecated since API Version 9. Use [getPhotoAccessHelper](js-apis-photoAccessHelper.md#photoaccesshelpergetphotoaccesshelper) instead.
+> This API is deprecated since API version 9. Use [getPhotoAccessHelper](js-apis-photoAccessHelper.md#photoaccesshelpergetphotoaccesshelper) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -62,7 +62,7 @@ Obtains a **MediaLibrary** instance, which is used to access and modify personal
This API can be used only in the FA model.
> **NOTE**
-> This API is deprecated since API Version 9. There is no substitute API.
+> This API is deprecated since API version 9. There is no substitute API.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -88,8 +88,8 @@ Obtains file assets (also called files). This API uses an asynchronous callback
> **NOTE**
>
-> - This API is deprecated since API Version 9. Use [getAssets](js-apis-photoAccessHelper.md#getassets) instead.
-> - From API version 10, the albums represented by physical directories are replaced by logical albums, which allows multiple files in an album and presence of a file in multiple albums. This design, however, makes **parent**, **albumId**, **albumUri**, and **albumName** incompatible. They cannot be used as parameters of **MediaFetchOptions** in **getFileAssets()**. For details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md).
+> - This API is deprecated since API version 9. Use [getAssets](js-apis-photoAccessHelper.md#getassets) instead.
+> - From API version 10, the albums represented by physical directories are replaced by logical albums, which allow multiple files in an album and presence of a file in multiple albums. This design, however, makes **parent**, **albumId**, **albumUri**, and **albumName** incompatible. They cannot be used as parameters of **MediaFetchOptions** in **getFileAssets()**. For details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md).
**Required permissions**: ohos.permission.READ_MEDIA
@@ -161,8 +161,8 @@ Obtains file assets. This API uses a promise to return the result.
> **NOTE**
>
-> - This API is deprecated since API Version 9. Use [getAssets](js-apis-photoAccessHelper.md#getassets-1) instead.
-> - From API version 10, the albums represented by physical directories are replaced by logical albums, which allows multiple files in an album and presence of a file in multiple albums. This design, however, makes **parent**, **albumId**, **albumUri**, and **albumName** incompatible. They cannot be used as parameters of **MediaFetchOptions** in **getFileAssets()**. For details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md).
+> - This API is deprecated since API version 9. Use [getAssets](js-apis-photoAccessHelper.md#getassets-1) instead.
+> - From API version 10, the albums represented by physical directories are replaced by logical albums, which allow multiple files in an album and presence of a file in multiple albums. This design, however, makes **parent**, **albumId**, **albumUri**, and **albumName** incompatible. They cannot be used as parameters of **MediaFetchOptions** in **getFileAssets()**. For details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md).
**Required permissions**: ohos.permission.READ_MEDIA
@@ -234,7 +234,8 @@ on(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange'
Subscribes to the media library changes. This API uses a callback to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. Use [registerChange](js-apis-photoAccessHelper.md#registerchange) instead.
+>
+> This API is deprecated since API version 9. Use [registerChange](js-apis-photoAccessHelper.md#registerchange) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -260,7 +261,8 @@ off(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange
Unsubscribes from the media library changes. This API uses a callback to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. Use [unRegisterChange](js-apis-photoAccessHelper.md#unregisterchange) instead.
+>
+> This API is deprecated since API version 9. Use [unRegisterChange](js-apis-photoAccessHelper.md#unregisterchange) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -287,7 +289,7 @@ Creates a media asset. This API uses an asynchronous callback to return the resu
> **NOTE**
>
-> - This API is deprecated since API Version 9. Use [createAsset](js-apis-photoAccessHelper.md#createasset) instead.
+> - This API is deprecated since API version 9. Use [createAsset](js-apis-photoAccessHelper.md#createasset) instead.
> - From the SDK of API version 10, **relativePath** is no longer associated with an album. After a file is created, the last-level directory of **relativePath** is not displayed. For details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md).
**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
@@ -329,7 +331,7 @@ Creates a media asset. This API uses a promise to return the result.
> **NOTE**
>
-> - This API is deprecated since API Version 9. Use [createAsset](js-apis-photoAccessHelper.md#createasset-1) instead.
+> - This API is deprecated since API version 9. Use [createAsset](js-apis-photoAccessHelper.md#createasset-1) instead.
> - From the SDK of API version 10, **relativePath** is no longer associated with an album. After a file is created, the last-level directory of **relativePath** is not displayed. For details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md).
**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
@@ -375,7 +377,8 @@ Deletes a file asset. This API uses a promise to return the result.
Before calling this API, call [FileAsset.trash](#trash8) to move the file to the trash. Otherwise, the file fails to be deleted.
> **NOTE**
-> This API is deprecated since API Version 9. Use [deleteAssets](js-apis-photoAccessHelper.md#deleteassets-3) instead.
+>
+> This API is deprecated since API version 9. Use [deleteAssets](js-apis-photoAccessHelper.md#deleteassets-3) instead.
**System API**: This is a system API.
@@ -429,7 +432,8 @@ Deletes a file asset. This API uses an asynchronous callback to return the resul
Before calling this API, call [FileAsset.trash](#trash8) to move the file to the trash. Otherwise, the file fails to be deleted.
> **NOTE**
-> This API is deprecated since API Version 9. Use [deleteAssets](js-apis-photoAccessHelper.md#deleteassets-2) instead.
+>
+> This API is deprecated since API version 9. Use [deleteAssets](js-apis-photoAccessHelper.md#deleteassets-2) instead.
**System API**: This is a system API.
@@ -478,7 +482,8 @@ getPublicDirectory(type: DirectoryType, callback: AsyncCallback<string>):
Obtains a user directory. This API uses an asynchronous callback to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. There is no substitute API.
+>
+> This API is deprecated since API version 9. There is no substitute API.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -509,7 +514,8 @@ getPublicDirectory(type: DirectoryType): Promise<string>
Obtains a user directory. This API uses a promise to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. There is no substitute API.
+>
+> This API is deprecated since API version 9. There is no substitute API.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -550,7 +556,7 @@ Obtains albums. This API uses an asynchronous callback to return the result.
> **NOTE**
>
-> - This API is deprecated since API Version 9. Use [getAlbums](js-apis-photoAccessHelper.md#getalbums) instead.
+> - This API is deprecated since API version 9. Use [getAlbums](js-apis-photoAccessHelper.md#getalbums) instead.
> - From the SDK of API version 10, **relativePath** is no longer associated with an album. Therefore, **relativePath** cannot be used as a search criterion in **getAlbums**. Currently, only **Camera** and **ScreenShots** albums are supported. For more details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md).
**Required permissions**: ohos.permission.READ_MEDIA
@@ -590,7 +596,7 @@ Obtains albums. This API uses a promise to return the result.
> **NOTE**
>
-> - This API is deprecated since API Version 9. Use [getAlbums](js-apis-photoAccessHelper.md#getalbums-2) instead.
+> - This API is deprecated since API version 9. Use [getAlbums](js-apis-photoAccessHelper.md#getalbums-2) instead.
> - From the SDK of API version 10, **relativePath** is no longer associated with an album. Therefore, **relativePath** cannot be used as a search criterion in **getAlbums**. Currently, only **Camera** and **ScreenShots** albums are supported. For more details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md).
**Required permissions**: ohos.permission.READ_MEDIA
@@ -633,7 +639,8 @@ Releases this **MediaLibrary** instance.
Call this API when you no longer need to use the APIs in the **MediaLibrary** instance.
> **NOTE**
-> This API is deprecated since API Version 9. Use [release](js-apis-photoAccessHelper.md#release) instead.
+>
+> This API is deprecated since API version 9. Use [release](js-apis-photoAccessHelper.md#release) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -659,7 +666,7 @@ Releases this **MediaLibrary** instance.
Call this API when you no longer need to use the APIs in the **MediaLibrary** instance.
> **NOTE**
-> This API is deprecated since API Version 9. Use [release](js-apis-photoAccessHelper.md#release-1) instead.
+> This API is deprecated since API version 9. Use [release](js-apis-photoAccessHelper.md#release-1) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -684,7 +691,7 @@ Stores a media asset. This API uses an asynchronous callback to return the URI o
> **NOTE**
>
> - This API is supported since API version 6 and can be used only in the FA model.
-> - This API is deprecated since API Version 9. Use [save](js-apis-file-picker.md#save-1) instead.
+> - This API is deprecated since API version 9. Use [save](js-apis-file-picker.md#save-1) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -722,7 +729,7 @@ Stores a media asset. This API uses a promise to return the URI of the media ass
> **NOTE**
>
> - This API is supported since API version 6 and can be used only in the FA model.
-> - This API is deprecated since API Version 9. Use [save](js-apis-file-picker.md#save) instead.
+> - This API is deprecated since API version 9. Use [save](js-apis-file-picker.md#save) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -758,12 +765,12 @@ mediaLibrary.getMediaLibrary().storeMediaAsset(option).then((value) => {
startImagePreview(images: Array<string>, index: number, callback: AsyncCallback<void>): void
-Starts image preview, with the first image to preview specified. This API can be used to preview local images whose URIs start with **datashare://** or online images whose URIs start with **https://**. It uses an asynchronous callback to return the result.
+Starts image preview, with the first image to preview specified. This API can be used to preview a local image with the specified index (**file://**) or all online images (**https://**). It uses an asynchronous callback to return the result.
> **NOTE**
>
> - This API is supported since API version 6 and can be used only in the FA model.
-> - This API is deprecated since API Version 9. You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead. The **\** component can be used to render and display local and online images.
+> - This API is deprecated since API version 9. You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead. The **\** component can be used to render and display local and online images.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -771,7 +778,7 @@ Starts image preview, with the first image to preview specified. This API can be
| Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | ---------------------------------------- |
-| images | Array<string> | Yes | URIs of the images to preview. The value can start with either **'https://'** or **'datashare://'**.|
+| images | Array<string> | Yes | Images to preview. You can preview a local image (**file://**) or all online images (**https://**).|
| index | number | Yes | Index of the first image to preview. |
| callback | AsyncCallback<void> | Yes | Callback that returns no value. |
@@ -802,12 +809,12 @@ mediaLibrary.getMediaLibrary().startImagePreview(images, index, (error) => {
startImagePreview(images: Array<string>, callback: AsyncCallback<void>): void
-Starts image preview. This API can be used to preview local images whose URIs start with **datashare://** or online images whose URIs start with **https://**. It uses an asynchronous callback to return the result.
+Starts image preview. This API can be used to preview the first local image (**file://**) or all online images (**https://**). It uses an asynchronous callback to return the result.
> **NOTE**
>
> - This API is supported since API version 6 and can be used only in the FA model.
-> - This API is deprecated since API Version 9. You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead. The **\** component can be used to render and display local and online images.
+> - This API is deprecated since API version 9. You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead. The **\** component can be used to render and display local and online images.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -815,7 +822,7 @@ Starts image preview. This API can be used to preview local images whose URIs st
| Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | ---------------------------------------- |
-| images | Array<string> | Yes | URIs of the images to preview. The value can start with either **'https://'** or **'datashare://'**.|
+| images | Array<string> | Yes | Images to preview. You can preview a local image (**file://**) or all online images (**https://**).|
| callback | AsyncCallback<void> | Yes | Callback that returns no value. |
**Example**
@@ -844,12 +851,12 @@ mediaLibrary.getMediaLibrary().startImagePreview(images, (error) => {
startImagePreview(images: Array<string>, index?: number): Promise<void>
-Starts image preview, with the first image to preview specified. This API can be used to preview local images whose URIs start with **datashare://** or online images whose URIs start with **https://**. It uses a promise to return the execution result.
+Starts image preview, with the first image to preview specified. This API can be used to preview a local image with the specified index (**file://**) or all online images (**https://**). It uses a promise to return the execution result.
> **NOTE**
>
> - This API is supported since API version 6 and can be used only in the FA model.
-> - This API is deprecated since API Version 9. You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead. The **\** component can be used to render and display local and online images.
+> - This API is deprecated since API version 9. You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead. The **\** component can be used to render and display local and online images.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -857,7 +864,7 @@ Starts image preview, with the first image to preview specified. This API can be
| Name | Type | Mandatory | Description |
| ------ | ------------------- | ---- | ---------------------------------------- |
-| images | Array<string> | Yes | URIs of the images to preview. The value can start with either **'https://'** or **'datashare://'**.|
+| images | Array<string> | Yes | Images to preview. You can preview a local image (**file://**) or all online images (**https://**).|
| index | number | No | Index of the first image to preview. If this parameter is not specified, the default value **0** is used. |
**Return value**
@@ -896,7 +903,7 @@ Starts media selection. This API uses an asynchronous callback to return the URI
> **NOTE**
>
> - This API is supported since API version 6 and can be used only in the FA model.
-> - This API is deprecated since API Version 9. Use [select](js-apis-file-picker.md#select-1) instead.
+> - This API is deprecated since API version 9. Use [select](js-apis-file-picker.md#select-1) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -933,7 +940,7 @@ Starts media selection. This API uses a promise to return the URIs of the select
> **NOTE**
>
> - This API is supported since API version 6 and can be used only in the FA model.
-> - This API is deprecated since API Version 9. Use [select](js-apis-file-picker.md#select) instead.
+> - This API is deprecated since API version 9. Use [select](js-apis-file-picker.md#select) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -971,7 +978,8 @@ getActivePeers(): Promise\>;
Obtains information about online peer devices. This API uses a promise to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. There is no substitute API.
+>
+> This API is deprecated since API version 9. There is no substitute API.
**System API**: This is a system API.
@@ -1008,7 +1016,8 @@ getActivePeers(callback: AsyncCallback\>): void;
Obtains information about online peer devices. This API uses an asynchronous callback to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. There is no substitute API.
+>
+> This API is deprecated since API version 9. There is no substitute API.
**System API**: This is a system API.
@@ -1043,7 +1052,8 @@ getAllPeers(): Promise\>;
Obtains information about all peer devices. This API uses a promise to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. There is no substitute API.
+>
+> This API is deprecated since API version 9. There is no substitute API.
**System API**: This is a system API.
@@ -1080,7 +1090,8 @@ getAllPeers(callback: AsyncCallback\>): void;
Obtains information about all peer devices. This API uses an asynchronous callback to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. There is no substitute API.
+>
+> This API is deprecated since API version 9. There is no substitute API.
**System API**: This is a system API.
@@ -1116,7 +1127,7 @@ Provides APIs for encapsulating file asset attributes.
>
> - The system attempts to parse the file content if the file is an audio or video file. The actual field values will be restored from the passed values during scanning on some devices.
> - Some devices may not support the modification of **orientation**. You are advised to use [ModifyImageProperty](js-apis-image.md#modifyimageproperty9) of the **image** module.
-> - This API is deprecated since API Version 9. Use [PhotoAsset](js-apis-photoAccessHelper.md#photoasset) instead.
+> - This API is deprecated since API version 9. Use [PhotoAsset](js-apis-photoAccessHelper.md#photoasset) instead.
### Attributes
@@ -1153,7 +1164,8 @@ isDirectory(callback: AsyncCallback<boolean>): void
Checks whether this file asset is a directory. This API uses an asynchronous callback to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. There is no substitute API.
+>
+> This API is deprecated since API version 9. There is no substitute API.
**Required permissions**: ohos.permission.READ_MEDIA
@@ -1196,7 +1208,8 @@ isDirectory():Promise<boolean>
Checks whether this file asset is a directory. This API uses a promise to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. There is no substitute API.
+>
+> This API is deprecated since API version 9. There is no substitute API.
**Required permissions**: ohos.permission.READ_MEDIA
@@ -1238,7 +1251,7 @@ Commits the modification on the file metadata to the database. This API uses an
> **NOTE**
>
-> - This API is deprecated since API Version 9. Use [commitModify](js-apis-photoAccessHelper.md#commitmodify) instead.
+> - This API is deprecated since API version 9. Use [commitModify](js-apis-photoAccessHelper.md#commitmodify) instead.
> - Since the SDK of API version 10, **audio** does not have the **orientation** attribute. Therefore, the **orientation** attribute of the audio resource cannot be modified by **commitModify()**. For details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md).
**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
@@ -1280,7 +1293,7 @@ Commits the modification on the file asset to the database. This API uses a prom
> **NOTE**
>
-> - This API is deprecated since API Version 9. Use [commitModify](js-apis-photoAccessHelper.md#commitmodify-1) instead.
+> - This API is deprecated since API version 9. Use [commitModify](js-apis-photoAccessHelper.md#commitmodify-1) instead.
> Since the SDK of API version 10, **audio** does not have the **orientation** attribute. Therefore, the **orientation** attribute of the audio resource cannot be modified by **commitModify()**. For details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md).
**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
@@ -1319,9 +1332,11 @@ open(mode: string, callback: AsyncCallback<number>): void
Opens this file asset. This API uses an asynchronous callback to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. Use [open](js-apis-photoAccessHelper.md#open) instead.
-
-**NOTE** If a file is opened in 'w' mode, the returned file descriptor (FD) cannot be used to read the file. However, due to the implementation differences of file systems, some user-mode files opened in 'w' mode can be read by using FD. To perform the read or write operation on a file by using FD, you are advised to open the file in 'rw' mode. The write operations are mutually exclusive. After a write operation is complete, you must call **close** to close the file.
+>
+> - This API is deprecated since API version 9. Use [open](js-apis-photoAccessHelper.md#open) instead.
+>
+> - If a file is opened in 'w' mode, the returned file descriptor (FD) cannot be used to read the file. However, due to the implementation differences of file systems, some user-mode files opened in 'w' mode can be read by using FD. To perform the read or write operation on a file by using FD, you are advised to open the file in 'rw' mode.
+> - The write operations are mutually exclusive. After a write operation is complete, you must call **close** to close the file.
**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA
@@ -1359,9 +1374,10 @@ open(mode: string): Promise<number>
Opens this file asset. This API uses a promise to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. Use [open](js-apis-photoAccessHelper.md#open-1) instead.
-
-**NOTE** If a file is opened in 'w' mode, the returned FD cannot be used to read the file. However, due to the implementation differences of file systems, some user-mode files opened in 'w' mode can be read by using FD. To perform the read or write operation on a file by using FD, you are advised to open the file in 'rw' mode. The write operations are mutually exclusive. After a write operation is complete, you must call **close** to close the file.
+>
+> - This API is deprecated since API version 9. Use [open](js-apis-photoAccessHelper.md#open-1) instead.
+> - If a file is opened in 'w' mode, the returned FD cannot be used to read the file. However, due to the implementation differences of file systems, some user-mode files opened in 'w' mode can be read by using FD. To perform the read or write operation on a file by using FD, you are advised to open the file in 'rw' mode.
+> - The write operations are mutually exclusive. After a write operation is complete, you must call **close** to close the file.
**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA
@@ -1402,7 +1418,8 @@ close(fd: number, callback: AsyncCallback<void>): void
Closes a file. This API uses an asynchronous callback to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. Use [close](js-apis-photoAccessHelper.md#close) instead.
+>
+> This API is deprecated since API version 9. Use [close](js-apis-photoAccessHelper.md#close) instead.
**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA
@@ -1451,7 +1468,8 @@ close(fd: number): Promise<void>
Closes a file. This API uses a promise to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. Use [close](js-apis-photoAccessHelper.md#close-1) instead.
+>
+> This API is deprecated since API version 9. Use [close](js-apis-photoAccessHelper.md#close-1) instead.
**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA
@@ -1503,7 +1521,8 @@ getThumbnail(callback: AsyncCallback<image.PixelMap>): void
Obtains the thumbnail of this file asset. This API uses an asynchronous callback to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. Use [close](js-apis-photoAccessHelper.md#getThumbnail) instead.
+>
+> This API is deprecated since API version 9. Use [close](js-apis-photoAccessHelper.md#getThumbnail) instead.
**Required permissions**: ohos.permission.READ_MEDIA
@@ -1546,7 +1565,8 @@ getThumbnail(size: Size, callback: AsyncCallback<image.PixelMap>): void
Obtains the file thumbnail of the given size. This API uses an asynchronous callback to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. Use [close](js-apis-photoAccessHelper.md#getThumbnail-1) instead.
+>
+> This API is deprecated since API version 9. Use [close](js-apis-photoAccessHelper.md#getThumbnail-1) instead.
**Required permissions**: ohos.permission.READ_MEDIA
@@ -1591,7 +1611,8 @@ getThumbnail(size?: Size): Promise<image.PixelMap>
Obtains the file thumbnail of the given size. This API uses a promise to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. Use [close](js-apis-photoAccessHelper.md#getThumbnail-2) instead.
+>
+> This API is deprecated since API version 9. Use [close](js-apis-photoAccessHelper.md#getThumbnail-2) instead.
**Required permissions**: ohos.permission.READ_MEDIA
@@ -1639,7 +1660,8 @@ favorite(isFavorite: boolean, callback: AsyncCallback<void>): void
Favorites or unfavorites this file asset. This API uses an asynchronous callback to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. Use [setFavorite](js-apis-photoAccessHelper.md#setfavorite) instead.
+>
+> This API is deprecated since API version 9. Use [setFavorite](js-apis-photoAccessHelper.md#setfavorite) instead.
**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
@@ -1683,7 +1705,8 @@ favorite(isFavorite: boolean): Promise<void>
Favorites or unfavorites this file asset. This API uses a promise to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. Use [setFavorite](js-apis-photoAccessHelper.md#setfavorite-1) instead.
+>
+> This API is deprecated since API version 9. Use [setFavorite](js-apis-photoAccessHelper.md#setfavorite-1) instead.
**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
@@ -1730,7 +1753,8 @@ isFavorite(callback: AsyncCallback<boolean>): void
Checks whether this file asset is favorited. This API uses an asynchronous callback to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. There is no substitute API.
+>
+> This API is deprecated since API version 9. There is no substitute API.
**Required permissions**: ohos.permission.READ_MEDIA
@@ -1773,7 +1797,8 @@ isFavorite():Promise<boolean>
Checks whether this file asset is favorited. This API uses a promise to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. There is no substitute API.
+>
+> This API is deprecated since API version 9. There is no substitute API.
**Required permissions**: ohos.permission.READ_MEDIA
@@ -1816,7 +1841,8 @@ Moves this file asset to the trash. This API uses an asynchronous callback to re
Files in the trash are not actually deleted. You can set **isTrash** to **false** to restore the files from the trash.
> **NOTE**
-> This API is deprecated since API Version 9. Use [deleteAssets](js-apis-photoAccessHelper.md#deleteAssets) instead.
+>
+> This API is deprecated since API version 9. Use [deleteAssets](js-apis-photoAccessHelper.md#deleteAssets) instead.
**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
@@ -1862,7 +1888,8 @@ Moves this file asset to the trash. This API uses a promise to return the result
Files in the trash are not actually deleted. You can set **isTrash** to **false** to restore the files from the trash.
> **NOTE**
-> This API is deprecated since API Version 9. Use [deleteAssets](js-apis-photoAccessHelper.md#deleteAssets-1) instead.
+>
+> This API is deprecated since API version 9. Use [deleteAssets](js-apis-photoAccessHelper.md#deleteAssets-1) instead.
**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
@@ -1909,7 +1936,8 @@ isTrash(callback: AsyncCallback<boolean>): void
Checks whether this file asset is in the trash. This API uses an asynchronous callback to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. There is no substitute API.
+>
+> This API is deprecated since API version 9. There is no substitute API.
**Required permissions**: ohos.permission.READ_MEDIA
@@ -1952,7 +1980,8 @@ isTrash():Promise<boolean>
Checks whether this file asset is in the trash. This API uses a promise to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. There is no substitute API.
+>
+> This API is deprecated since API version 9. There is no substitute API.
**Required permissions**: ohos.permission.READ_MEDIA
@@ -1991,7 +2020,8 @@ async function example() {
Provides APIs to manage the file retrieval result.
> **NOTE**
-> This API is deprecated since API Version 9. Use [FetchResult](js-apis-photoAccessHelper.md#fetchresult) instead.
+>
+> This API is deprecated since API version 9. Use [FetchResult](js-apis-photoAccessHelper.md#fetchresult) instead.
### getCount7+
@@ -2000,7 +2030,8 @@ getCount(): number
Obtains the total number of files in the result set.
> **NOTE**
-> This API is deprecated since API Version 9. Use [getCount](js-apis-photoAccessHelper.md#getcount) instead.
+>
+> This API is deprecated since API version 9. Use [getCount](js-apis-photoAccessHelper.md#getcount) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -2035,7 +2066,8 @@ isAfterLast(): boolean
Checks whether the cursor is in the last row of the result set.
> **NOTE**
-> This API is deprecated since API Version 9. Use [isAfterLast](js-apis-photoAccessHelper.md#isafterlast) instead.
+>
+> This API is deprecated since API version 9. Use [isAfterLast](js-apis-photoAccessHelper.md#isafterlast) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -2078,7 +2110,8 @@ close(): void
Releases and invalidates this **FetchFileResult** instance. After this instance is released, the APIs in this instance cannot be invoked.
> **NOTE**
-> This API is deprecated since API Version 9. Use [close](js-apis-photoAccessHelper.md#close) instead.
+>
+> This API is deprecated since API version 9. Use [close](js-apis-photoAccessHelper.md#close) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -2105,7 +2138,8 @@ getFirstObject(callback: AsyncCallback<FileAsset>): void
Obtains the first file asset in the result set. This API uses an asynchronous callback to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. Use [getFirstObject](js-apis-photoAccessHelper.md#getfirstobject) instead.
+>
+> This API is deprecated since API version 9. Use [getFirstObject](js-apis-photoAccessHelper.md#getfirstobject) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -2145,7 +2179,8 @@ getFirstObject(): Promise<FileAsset>
Obtains the first file asset in the result set. This API uses a promise to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. Use [getFirstObject](js-apis-photoAccessHelper.md#getfirstobject-1) instead.
+>
+> This API is deprecated since API version 9. Use [getFirstObject](js-apis-photoAccessHelper.md#getfirstobject-1) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -2185,7 +2220,7 @@ Obtains the next file asset in the result set. This API uses an asynchronous cal
> **NOTE**
>
> - Before using this API, you must use [getFirstObject](#getfirstobject7) to obtain the first file asset and then use [isAfterLast](#isafterlast7) to check that the cursor does not point to the last file asset in the result set.
-> - This API is deprecated since API Version 9. Use [getNextObject](js-apis-photoAccessHelper.md#getnextobject) instead.
+> - This API is deprecated since API version 9. Use [getNextObject](js-apis-photoAccessHelper.md#getnextobject) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -2232,7 +2267,7 @@ Obtains the next file asset in the result set. This API uses a promise to return
> **NOTE**
>
> - Before using this API, you must use [getFirstObject](#getfirstobject7) to obtain the first file asset and then use [isAfterLast](#isafterlast7) to check that the cursor does not point to the last file asset in the result set.
-> - This API is deprecated since API Version 9. Use [getNextObject](js-apis-photoAccessHelper.md#getnextobject-1) instead.
+> - This API is deprecated since API version 9. Use [getNextObject](js-apis-photoAccessHelper.md#getnextobject-1) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -2274,7 +2309,8 @@ getLastObject(callback: AsyncCallback<FileAsset>): void
Obtains the last file asset in the result set. This API uses an asynchronous callback to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. Use [getLastObject](js-apis-photoAccessHelper.md#getlastobject) instead.
+>
+> This API is deprecated since API version 9. Use [getLastObject](js-apis-photoAccessHelper.md#getlastobject) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -2314,7 +2350,8 @@ getLastObject(): Promise<FileAsset>
Obtains the last file asset in the result set. This API uses a promise to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. Use [getLastObject](js-apis-photoAccessHelper.md#getlastobject-1) instead.
+>
+> This API is deprecated since API version 9. Use [getLastObject](js-apis-photoAccessHelper.md#getlastobject-1) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -2352,7 +2389,8 @@ getPositionObject(index: number, callback: AsyncCallback<FileAsset>): void
Obtains a file asset with the specified index in the result set. This API uses an asynchronous callback to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. Use [getObjectByPosition](js-apis-photoAccessHelper.md#getobjectbyposition) instead.
+>
+> This API is deprecated since API version 9. Use [getObjectByPosition](js-apis-photoAccessHelper.md#getobjectbyposition) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -2393,7 +2431,8 @@ getPositionObject(index: number): Promise<FileAsset>
Obtains a file asset with the specified index in the result set. This API uses a promise to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. Use [getObjectByPosition](js-apis-photoAccessHelper.md#getobjectbyposition-1) instead.
+>
+> This API is deprecated since API version 9. Use [getObjectByPosition](js-apis-photoAccessHelper.md#getobjectbyposition-1) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -2437,7 +2476,8 @@ getAllObject(callback: AsyncCallback<Array<FileAsset>>): void
Obtains all the file assets in the result set. This API uses an asynchronous callback to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. Use [getAllObjects](js-apis-photoAccessHelper.md#getallobjects) instead.
+>
+> This API is deprecated since API version 9. Use [getAllObjects](js-apis-photoAccessHelper.md#getallobjects) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -2479,7 +2519,8 @@ getAllObject(): Promise<Array<FileAsset>>
Obtains all the file assets in the result set. This API uses a promise to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. Use [getAllObjects](js-apis-photoAccessHelper.md#getallobjects-1) instead.
+>
+> This API is deprecated since API version 9. Use [getAllObjects](js-apis-photoAccessHelper.md#getallobjects-1) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -2517,7 +2558,8 @@ async function example() {
Provides APIs to manage albums.
> **NOTE**
-> This API is deprecated since API Version 9. Use [Album](js-apis-photoAccessHelper.md#album) instead.
+>
+> This API is deprecated since API version 9. Use [Album](js-apis-photoAccessHelper.md#album) instead.
### Attributes
@@ -2540,7 +2582,8 @@ commitModify(callback: AsyncCallback<void>): void
Commits the modification on the album attributes to the database.
> **NOTE**
-> This API is deprecated since API Version 9. Use [commitModify](js-apis-photoAccessHelper.md#commitmodify-2) instead.
+>
+> This API is deprecated since API version 9. Use [commitModify](js-apis-photoAccessHelper.md#commitmodify-2) instead.
**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
@@ -2581,7 +2624,8 @@ commitModify(): Promise<void>
Commits the modification on the album attributes to the database.
> **NOTE**
-> This API is deprecated since API Version 9. Use [commitModify](js-apis-photoAccessHelper.md#commitmodify-3) instead.
+>
+> This API is deprecated since API version 9. Use [commitModify](js-apis-photoAccessHelper.md#commitmodify-3) instead.
**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
@@ -2620,7 +2664,8 @@ getFileAssets(callback: AsyncCallback<FetchFileResult>): void
Obtains the file assets in this album. This API uses an asynchronous callback to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. Use [getAssets](js-apis-photoAccessHelper.md#getassets) instead.
+>
+> This API is deprecated since API version 9. Use [getAssets](js-apis-photoAccessHelper.md#getassets) instead.
**Required permissions**: ohos.permission.READ_MEDIA
@@ -2664,7 +2709,8 @@ getFileAssets(options: MediaFetchOptions, callback: AsyncCallback<FetchFileRe
Obtains the file assets in this album based on specified conditions. This API uses an asynchronous callback to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. Use [getAssets](js-apis-photoAccessHelper.md#getassets) instead.
+>
+> This API is deprecated since API version 9. Use [getAssets](js-apis-photoAccessHelper.md#getassets) instead.
**Required permissions**: ohos.permission.READ_MEDIA
@@ -2713,7 +2759,8 @@ async function example() {
Obtains the file assets in this album based on specified conditions. This API uses a promise to return the result.
> **NOTE**
-> This API is deprecated since API Version 9. Use [getAssets](js-apis-photoAccessHelper.md#getassets-1) instead.
+>
+> This API is deprecated since API version 9. Use [getAssets](js-apis-photoAccessHelper.md#getassets-1) instead.
**Required permissions**: ohos.permission.READ_MEDIA
@@ -2763,7 +2810,8 @@ async function example() {
Defines information about a registered device.
> **NOTE**
-> This API is deprecated since API Version 9. There is no substitute API.
+>
+> This API is deprecated since API version 9. There is no substitute API.
**System API**: This is a system API.
@@ -2781,7 +2829,8 @@ Defines information about a registered device.
Enumerates media types.
> **NOTE**
-> This API is deprecated since API Version 9. Use [PhotoType](js-apis-photoAccessHelper.md#phototype) instead.
+>
+> This API is deprecated since API version 9. Use [PhotoType](js-apis-photoAccessHelper.md#phototype) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -2799,7 +2848,7 @@ Enumerates key file information.
> **NOTE**
>
> - The **bucket_id** field may change after file rename or movement. Therefore, you must obtain the field again before using it.
-> - This API is deprecated since API Version 9. Use [PhotoKeys](js-apis-photoAccessHelper.md#photokeys) instead.
+> - This API is deprecated since API version 9. Use [PhotoKeys](js-apis-photoAccessHelper.md#photokeys) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -2830,7 +2879,8 @@ Enumerates key file information.
Enumerates directory types.
> **NOTE**
-> This API is deprecated since API Version 9. There is no substitute API.
+>
+> This API is deprecated since API version 9. There is no substitute API.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -2848,7 +2898,8 @@ Enumerates directory types.
Enumerates the device types.
> **NOTE**
-> This API is deprecated since API Version 9. There is no substitute API.
+>
+> This API is deprecated since API version 9. There is no substitute API.
**System API**: This is a system API.
@@ -2869,15 +2920,16 @@ Enumerates the device types.
Defines the options for fetching media files.
> **NOTE**
-> This API is deprecated since API Version 9. Use [FetchOptions](js-apis-photoAccessHelper.md#fetchoptions) instead.
+>
+> This API is deprecated since API version 9. Use [FetchOptions](js-apis-photoAccessHelper.md#fetchoptions) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
| Name | Type | Readable| Writable| Description |
| ----------------------- | ------------------- | ---- | ---- | ------------------------------------------------------------ |
-| selections | string | Yes | Yes | Conditions for fetching files. The enumerated values in [FileKey](#filekey8) are used as the column names when files are fetched. Example: selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR ' + mediaLibrary.FileKey.MEDIA_TYPE + '= ?', |
+| selections | string | Yes | Yes | Conditions for fetching files. The enumerated values in [FileKey](#filekey8) are used as the column names when files are fetched. Example: selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR ' + mediaLibrary.FileKey.MEDIA_TYPE + '= ?', |
| selectionArgs | Array<string> | Yes | Yes | Values of the conditions specified in **selections**. Example: selectionArgs: [mediaLibrary.MediaType.IMAGE.toString(), mediaLibrary.MediaType.VIDEO.toString()], |
-| order | string | Yes | Yes | Sorting mode of the search results, which can be ascending or descending. The enumerated values in [FileKey](#filekey8) are used as the columns for sorting the search results. Example: Ascending: order: mediaLibrary.FileKey.DATE_ADDED + ' ASC' Descending: order: mediaLibrary.FileKey.DATE_ADDED + ' DESC'|
+| order | string | Yes | Yes | Sorting mode of the search results, which can be ascending or descending. The enumerated values in [FileKey](#filekey8) are used as the columns for sorting the search results. Example: Ascending: order: mediaLibrary.FileKey.DATE_ADDED + ' ASC' Descending: order: mediaLibrary.FileKey.DATE_ADDED + ' DESC' |
| uri8+ | string | Yes | Yes | URI of the file. |
| networkId8+ | string | Yes | Yes | Network ID of the registered device. |
| extendArgs8+ | string | Yes | Yes | Extended parameters for fetching the files. Currently, no extended parameters are available. |
@@ -2887,7 +2939,8 @@ Defines the options for fetching media files.
Defines the image size.
> **NOTE**
-> This API is deprecated since API Version 9. Use [image.Size](js-apis-image.md#size) instead.
+>
+> This API is deprecated since API version 9. Use [image.Size](js-apis-image.md#size) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -2901,26 +2954,28 @@ Defines the image size.
Defines the media asset option.
> **NOTE**
-> This API is deprecated since API Version 9. There is no substitute API.
+>
+> This API is deprecated since API version 9. There is no substitute API.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
| Name | Type | Readable| Writable| Description |
| ------------ | ------ | ---- | ---- | ------------------------------------------------------------ |
| src | string | Yes | Yes | Application sandbox oath of the local file. |
-| mimeType | string | Yes | Yes | Multipurpose Internet Mail Extensions (MIME) type of the media. The value can be 'image/\*', 'video/\*', 'audio/\*' or 'file\*'.|
-| relativePath | string | Yes | Yes | Custom path of media assets, for example, **Pictures/**. If this parameter is unspecified, media assets are stored in the default path. Default path of images: **'Pictures/'** Default path of videos: **'Videos/'** Default path of audios: **'Audios/'** Default path of documents: **'Documents/'**|
+| mimeType | string | Yes | Yes | Multipurpose Internet Mail Extensions (MIME) type of the media. The value can be 'image/\*', 'video/\*', 'audio/\*' or 'file/*'. |
+| relativePath | string | Yes | Yes | Customized path of media assets, for example, **Pictures/**. If this parameter is unspecified, the default paths of media assets are as follows: Default path of images: **'Pictures/'** Default path of videos: **'Videos/'** Default path of audio files: **'Audios/'** Default path of documents: **'Documents/'** |
## MediaSelectOption
Defines the media selection option.
> **NOTE**
-> This API is deprecated since API Version 9. There is no substitute API.
+>
+> This API is deprecated since API version 9. There is no substitute API.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
| Name | Type | Readable| Writable| Description |
| ----- | ------ | ---- | ---- | -------------------- |
| type | 'image' | 'video' | 'media' | Yes | Yes | Media type, which can be **image**, **media**, or **video**. Currently, only **media** is supported.|
-| count | number | Yes | Yes | Maximum number of media assets that can be selected. The value starts from 1, which indicates that one media asset can be selected. |
+| count | number | Yes | Yes | Maximum number of media assets that can be selected. The value **1** means to select only one media asset; the value greater than **1** means to select multiple media assets. |
diff --git a/en/application-dev/reference/apis/js-apis-net-policy.md b/en/application-dev/reference/apis/js-apis-net-policy.md
index 295332057ba4042e12ff1c0009efe8a54acec759..1c1bb3adecc5c67136b722cbc9de1eacdf87f462 100644
--- a/en/application-dev/reference/apis/js-apis-net-policy.md
+++ b/en/application-dev/reference/apis/js-apis-net-policy.md
@@ -89,9 +89,11 @@ Specifies whether background applications are allowed to access the network. Thi
**Example**
```js
-policy.setBackgroundAllowed(true).then(function (error) {
- console.log(JSON.stringify(error))
-})
+policy.setBackgroundAllowed(true).then(() => {
+ console.log("setBackgroundAllowed success");
+}).catch(error => {
+ console.log(JSON.stringify(error));
+});
```
## policy.isBackgroundAllowed10+
@@ -164,10 +166,11 @@ Checks whether the current application is allowed to access the network when run
**Example**
```js
-policy.isBackgroundAllowed().then(function (error, data) {
- console.log(JSON.stringify(error))
- console.log(JSON.stringify(data))
-})
+policy.isBackgroundAllowed().then((data) => {
+ console.log(JSON.stringify(data));
+}).catch(error => {
+ console.log(JSON.stringify(error));
+});
```
## policy.setPolicyByUid10+
@@ -248,9 +251,11 @@ Sets the metered network access policy for the application specified by a given
**Example**
```js
-policy.setPolicyByUid(11111, policy.NetUidPolicy.NET_POLICY_NONE).then(function (error) {
- console.log(JSON.stringify(error))
-})
+policy.setPolicyByUid(11111, policy.NetUidPolicy.NET_POLICY_NONE).then(() => {
+ console.log("setPolicyByUid success");
+}).catch(error => {
+ console.log(JSON.stringify(error));
+});
```
## policy.getPolicyByUid10+
@@ -329,10 +334,11 @@ Obtains the network access policy for the application specified by a given UID.
**Example**
```js
-policy.getPolicyByUid(11111).then(function (error, data) {
- console.log(JSON.stringify(error))
- console.log(JSON.stringify(data))
-})
+policy.getPolicyByUid(11111).then((data) => {
+ console.log(JSON.stringify(data));
+}).catch(error => {
+ console.log(JSON.stringify(error));
+});
```
## policy.getUidsByPolicy10+
@@ -412,10 +418,11 @@ Obtains all UIDs that match the specified network policy. This API uses a promis
**Example**
```js
-policy.getUidsByPolicy(11111).then(function (error, data) {
- console.log(JSON.stringify(error))
- console.log(JSON.stringify(data))
-})
+policy.getUidsByPolicy(11111).then((data) => {
+ console.log(JSON.stringify(data));
+}).catch(error => {
+ console.log(JSON.stringify(error));
+});
```
## policy.getNetQuotaPolicies10+
@@ -487,11 +494,11 @@ Obtains the network quota policies. This API uses a promise to return the result
**Example**
```js
-policy.getNetQuotaPolicies().then(function (error, data) {
- console.log(JSON.stringify(error))
- console.log(JSON.stringify(data))
-})
-
+policy.getNetQuotaPolicies().then((data) => {
+ console.log(JSON.stringify(data));
+}).catch(error => {
+ console.log(JSON.stringify(error));
+});
```
## policy.setNetQuotaPolicies10+
@@ -608,9 +615,11 @@ let netquotapolicy = {
netQuotaPolicyList.push(netquotapolicy);
-policy.setNetQuotaPolicies(netQuotaPolicyList).then(function (error) {
- console.log(JSON.stringify(error))
-})
+policy.setNetQuotaPolicies(netQuotaPolicyList).then(() => {
+ console.log("setNetQuotaPolicies success");
+}).catch(error => {
+ console.log(JSON.stringify(error));
+});
```
## policy.isUidNetAllowed10+
@@ -692,10 +701,11 @@ Checks whether the application specified by a given UID is allowed to access a m
**Example**
```js
-policy.isUidNetAllowed(11111, true).then(function (error, data) {
- console.log(JSON.stringify(error))
- console.log(JSON.stringify(data))
-})
+policy.isUidNetAllowed(11111, true).then((data) => {
+ console.log(JSON.stringify(data));
+}).catch(error => {
+ console.log(JSON.stringify(error));
+});
```
## policy.isUidNetAllowed10+
@@ -777,10 +787,11 @@ Checks whether the application specified by a given UID is allowed to access the
**Example**
```js
-policy.isUidNetAllowed(11111, 'wlan0').then(function (error, data) {
- console.log(JSON.stringify(error))
- console.log(JSON.stringify(data))
-})
+policy.isUidNetAllowed(11111, 'wlan0').then((data) => {
+ console.log(JSON.stringify(data));
+}).catch(error => {
+ console.log(JSON.stringify(error));
+});
```
## policy.setDeviceIdleTrustlist10+
@@ -861,9 +872,11 @@ Adds applications specified by given UIDs to the device idle allowlist. This API
**Example**
```js
-policy.setDeviceIdleTrustlist([11111,22222], true).then(function (error) {
- console.log(JSON.stringify(error))
-})
+policy.setDeviceIdleTrustlist([11111,22222], true).then(() => {
+ console.log("setDeviceIdleTrustlist success");
+}).catch(error => {
+ console.log(JSON.stringify(error));
+});
```
## policy.getDeviceIdleTrustlist10+
@@ -934,10 +947,11 @@ Obtains the UIDs of applications that are on the device idle allowlist. This API
**Example**
```js
-policy.getDeviceIdleTrustlist().then(function (error, data) {
- console.log(JSON.stringify(error))
- console.log(JSON.stringify(data))
-})
+policy.getDeviceIdleTrustlist().then((data) => {
+ console.log(JSON.stringify(data));
+}).catch(error => {
+ console.log(JSON.stringify(error));
+});
```
## policy.getBackgroundPolicyByUid10+
@@ -1017,10 +1031,11 @@ Obtains the background network policy for the application specified by a given U
**Example**
```js
-policy.getBackgroundPolicyByUid(11111).then(function (error, data) {
- console.log(JSON.stringify(error))
- console.log(JSON.stringify(data))
-})
+policy.getBackgroundPolicyByUid(11111).then((data) => {
+ console.log(JSON.stringify(data));
+}).catch(error => {
+ console.log(JSON.stringify(error));
+});
```
## policy.resetPolicies10+
@@ -1099,9 +1114,11 @@ Restores all the policies (cellular network, background network, firewall, and a
**Example**
```js
-policy.resetPolicies('1').then(function (error) {
- console.log(JSON.stringify(error))
-})
+policy.resetPolicies('1').then(() => {
+ console.log("resetPolicies success");
+}).catch(error => {
+ console.log(JSON.stringify(error));
+});
```
## policy.updateRemindPolicy10+
@@ -1186,9 +1203,11 @@ Updates a reminder policy. This API uses a promise to return the result.
```js
import connection from '@ohos.net.connection';
-policy.updateRemindPolicy(connection.NetBearType.BEARER_CELLULAR, '1', policy.RemindType.REMIND_TYPE_WARNING).then(function (error) {
- console.log(JSON.stringify(error))
-})
+policy.updateRemindPolicy(connection.NetBearType.BEARER_CELLULAR, '1', policy.RemindType.REMIND_TYPE_WARNING).then(() => {
+ console.log("updateRemindPolicy success");
+}).catch(error => {
+ console.log(JSON.stringify(error));
+});
```
## policy.setPowerSaveTrustlist10+
@@ -1269,9 +1288,11 @@ Sets whether to add the application specified by a given UID to the power-saving
**Example**
```js
-policy.setPowerSaveTrustlist([11111,22222], true).then(function (error) {
- console.log(JSON.stringify(error))
-})
+policy.setPowerSaveTrustlist([11111,22222], true).then(() => {
+ console.log("setPowerSaveTrustlist success");
+}).catch(error => {
+ console.log(JSON.stringify(error));
+});
```
## policy.getPowerSaveTrustlist10+
@@ -1343,10 +1364,11 @@ Obtains the UID array of applications that are on the device idle allowlist. Thi
**Example**
```js
-policy.getPowerSaveTrustlist().then(function (error, data) {
- console.log(JSON.stringify(error))
- console.log(JSON.stringify(data))
-})
+policy.getPowerSaveTrustlist().then((data) => {
+ console.log(JSON.stringify(data));
+}).catch(error => {
+ console.log(JSON.stringify(error));
+});
```
## policy.on
diff --git a/en/application-dev/reference/apis/js-apis-net-vpn.md b/en/application-dev/reference/apis/js-apis-net-vpn.md
new file mode 100644
index 0000000000000000000000000000000000000000..9fbca9235ee22b561d8ed5f414ac37be7454767f
--- /dev/null
+++ b/en/application-dev/reference/apis/js-apis-net-vpn.md
@@ -0,0 +1,406 @@
+# @ohos.net.vpn (VPN Management)
+
+The **vpn** module implements virtual private network (VPN) management, such as starting and stopping a VPN.
+
+> **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 vpn from '@ohos.net.vpn';
+```
+
+## vpn.createVpnConnection
+
+createVpnConnection(context: AbilityContext): VpnConnection
+
+Creates a VPN connection.
+
+**System capability**: SystemCapability.Communication.NetManager.Vpn
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
+| context | [AbilityContext](js-apis-inner-application-uiAbilityContext.md#uiabilitycontext) | Yes | Specified context. |
+
+**Return value**
+
+| Type | Description |
+| :--------------------------------- | :---------------------- |
+| [VpnConnection](#vpnconnection) | VPN connection object.|
+
+**Error codes**
+
+For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md).
+
+| ID| Error Message |
+| ------- | ----------------------------- |
+| 401 | Parameter error. |
+
+**Example**
+Stage model:
+
+```ts
+// Obtain the context.
+import UIAbility from '@ohos.app.ability.UIAbility';
+class EntryAbility extends UIAbility {
+ onWindowStageCreate(windowStage){
+ globalThis.context = this.context;
+ }
+}
+let context = globalThis.context;
+VpnConnection = vpn.createVpnConnection(context);
+console.info("vpn onInit: " + JSON.stringify(VpnConnection));
+```
+
+## VpnConnection
+
+Defines a VPN connection object. Before calling **VpnConnection** APIs, you need to create a VPN connection object by calling [vpn.createVpnConnection](#vpncreatevpnconnection).
+
+### setUp
+
+setUp(config: VpnConfig, callback: AsyncCallback\): void
+
+Creates a VPN based on the specified configuration. This API uses an asynchronous callback to return the result.
+
+**System API**: This is a system API.
+
+**Required permissions**: ohos.permission.MANAGE_VPN
+
+**System capability**: SystemCapability.Communication.NetManager.Vpn
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
+| config | [VpnConfig](#vpnconfig) | Yes | VPN configuration. |
+| callback | AsyncCallback\ | Yes | Callback used to return the result. If a VPN is created successfully, **error** is **undefined** and **data** is the file descriptor of the vNIC. Otherwise, **error** is an error object.|
+
+**Error codes**
+
+For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md).
+
+| ID| Error Message |
+| ------- | ----------------------------- |
+| 201 | Permission denied. |
+| 202 | Non-system applications use system APIs. |
+| 401 | Parameter error. |
+| 2200001 | Invalid parameter value. |
+| 2200002 | Operation failed. Cannot connect to service. |
+| 2200003 | System internal error. |
+| 2203001 | VPN creation denied, please check the user type. |
+| 2203002 | VPN exist already, please execute destroy first. |
+
+**Example**
+
+```js
+ let config = {
+ addresses: [{
+ address: {
+ address: "10.0.0.5",
+ family: 1
+ },
+ prefixLength: 24,
+ }],
+ routes: [],
+ mtu: 1400,
+ dnsAddresses:[
+ "114.114.114.114"
+ ],
+ trustedApplications:[],
+ blockedApplications:[]
+ }
+ VpnConnection.setUp(config, (error, data) => {
+ console.info(JSON.stringify(error));
+ console.info("tunfd: " + JSON.stringify(data));
+ })
+```
+
+### setUp
+
+setUp(config: VpnConfig): Promise\
+
+Creates a VPN based on the specified configuration. This API uses a promise to return the result.
+
+**System API**: This is a system API.
+
+**Required permissions**: ohos.permission.MANAGE_VPN
+
+**System capability**: SystemCapability.Communication.NetManager.Vpn
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
+| config | [VpnConfig](#vpnconfig) | Yes | VPN configuration. |
+
+**Return value**
+
+| Type | Description |
+| --------------------------------- | ------------------------------------- |
+| Promise\ | The obtaining result is returned in Promise format. The file descriptor fd of the specified virtual network adapter is returned.|
+
+**Error codes**
+
+For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md).
+
+| ID| Error Message |
+| ------- | ----------------------------- |
+| 201 | Permission denied. |
+| 202 | Non-system applications use system APIs. |
+| 401 | Parameter error. |
+| 2200001 | Invalid parameter value. |
+| 2200002 | Operation failed. Cannot connect to service. |
+| 2200003 | System internal error. |
+| 2203001 | VPN creation denied, please check the user type. |
+| 2203002 | VPN exist already, please execute destroy first. |
+
+**Example**
+
+```js
+ let config = {
+ addresses: [{
+ address: {
+ address: "10.0.0.5",
+ family: 1
+ },
+ prefixLength: 24,
+ }],
+ routes: [],
+ mtu: 1400,
+ dnsAddresses:[
+ "114.114.114.114"
+ ],
+ trustedApplications:[],
+ blockedApplications:[]
+ }
+ VpnConnection.setUp(config).then((data) => {
+ console.info(TAG + "setUp success, tunfd: " + JSON.stringify(data))
+ }).catch(err => {
+ console.info(TAG + "setUp fail" + JSON.stringify(err))
+ })
+```
+
+### protect
+
+protect(socketFd: number, callback: AsyncCallback\): void
+
+Protects sockets against a VPN connection. The data sent through sockets is directly transmitted over the physical network and therefore the traffic does not traverse through the VPN. This API uses an asynchronous callback to return the result.
+
+**System API**: This is a system API.
+
+**Required permissions**: ohos.permission.MANAGE_VPN
+
+**System capability**: SystemCapability.Communication.NetManager.Vpn
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
+| socketFd | number | Yes | Socket file descriptor. It can be obtained through [getSocketFd](js-apis-socket.md#getsocketfd10). |
+| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **error** is **undefined**. If the operation fails, an error message is returned.|
+
+**Error codes**
+
+For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md).
+
+| ID| Error Message |
+| ------- | ----------------------------- |
+| 201 | Permission denied. |
+| 202 | Non-system applications use system APIs. |
+| 401 | Parameter error. |
+| 2200001 | Invalid parameter value. |
+| 2200002 | Operation failed. Cannot connect to service. |
+| 2200003 | System internal error. |
+| 2203004 | Invalid socket file descriptor. |
+
+**Example**
+
+```js
+ import socket from "@ohos.net.socket";
+ var tcp = socket.constructTCPSocketInstance();
+ tcp.bind({
+ address: "0.0.0.0",
+ family: 1
+ })
+ let connectAddress = {
+ address: "192.168.1.11",
+ port: 8888,
+ family: 1
+ };
+ tcp.connect({
+ address: connectAddress, timeout: 6000
+ })
+ tcp.getSocketFd().then((tunnelfd) => {
+ console.info("tunenlfd: " + tunnelfd);
+ VpnConnection.protect(tunnelfd, (error) => {
+ console.info(JSON.stringify(error));
+ })
+ })
+```
+
+### protect
+
+protect(socketFd: number): Promise\
+
+Protects sockets against a VPN connection. The data sent through sockets is directly transmitted over the physical network and therefore traffic does not traverse through the VPN. This API uses a promise to return the result.
+
+**System API**: This is a system API.
+
+**Required permissions**: ohos.permission.MANAGE_VPN
+
+**System capability**: SystemCapability.Communication.NetManager.Vpn
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
+| socketFd | number | Yes | Socket file descriptor. It can be obtained through [getSocketFd](js-apis-socket.md#getsocketfd10-1). |
+
+**Return value**
+
+| Type | Description |
+| --------------------------------- | ------------------------------------- |
+| Promise\ | Promise used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.|
+
+**Error codes**
+
+For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md).
+
+| ID| Error Message |
+| ------- | ----------------------------- |
+| 201 | Permission denied. |
+| 202 | Non-system applications use system APIs. |
+| 401 | Parameter error. |
+| 2200001 | Invalid parameter value. |
+| 2200002 | Operation failed. Cannot connect to service. |
+| 2200003 | System internal error. |
+| 2203004 | Invalid socket file descriptor. |
+
+**Example**
+
+```js
+ import socket from "@ohos.net.socket";
+ var tcp = socket.constructTCPSocketInstance();
+ tcp.bind({
+ address: "0.0.0.0",
+ family: 1
+ })
+ let connectAddress = {
+ address: "192.168.1.11",
+ port: 8888,
+ family: 1
+ };
+ tcp.connect({
+ address: connectAddress, timeout: 6000
+ })
+ tcp.getSocketFd().then((tunnelfd) => {
+ console.info("tunenlfd: " + tunnelfd);
+ VpnConnection.protect(tunnelfd).then(() => {
+ console.info("protect success.")
+ }).catch(err => {
+ console.info("protect fail" + JSON.stringify(err))
+ })
+ })
+```
+
+### destroy
+
+destroy(callback: AsyncCallback\): void
+
+Destroys a VPN. This API uses an asynchronous callback to return the result.
+
+**System API**: This is a system API.
+
+**Required permissions**: ohos.permission.MANAGE_VPN
+
+**System capability**: SystemCapability.Communication.NetManager.Vpn
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
+| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **error** is **undefined**. If the operation fails, an error message is returned.|
+
+**Error codes**
+
+For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md).
+
+| ID| Error Message |
+| ------- | ----------------------------- |
+| 201 | Permission denied. |
+| 202 | Non-system applications use system APIs. |
+| 401 | Parameter error. |
+| 2200002 | Operation failed. Cannot connect to service. |
+| 2200003 | System internal error. |
+
+**Example**
+
+```js
+ VpnConnection.destroy((error) => {
+ console.info(JSON.stringify(error));
+ })
+```
+
+### destroy
+
+destroy(): Promise\
+
+Destroys a VPN. This API uses a promise to return the result.
+
+**System API**: This is a system API.
+
+**Required permissions**: ohos.permission.MANAGE_VPN
+
+**System capability**: SystemCapability.Communication.NetManager.Vpn
+
+**Return value**
+
+| Type | Description |
+| --------------------------------- | ------------------------------------- |
+| Promise\ | Promise used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.|
+
+**Error codes**
+
+For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md).
+
+| ID| Error Message |
+| ------- | ----------------------------- |
+| 201 | Permission denied. |
+| 202 | Non-system applications use system APIs. |
+| 2200002 | Operation failed. Cannot connect to service. |
+| 2200003 | System internal error. |
+
+**Example**
+
+```js
+ VpnConnection.destroy().then(() => {
+ console.info("destroy success.")
+ }).catch(err => {
+ console.info("destroy fail" + JSON.stringify(err))
+ });
+```
+
+## VpnConfig
+
+Defines the VPN configuration.
+
+**System API**: This is a system API.
+
+**System capability**: SystemCapability.Communication.NetManager.Vpn
+
+| Name| Type| Mandatory| Description|
+| ------- | ------ | -- |------------------------------ |
+| addresses | Array\<[LinkAddress](js-apis-net-connection.md#linkaddress8)\> | Yes| IP address of the vNIC.|
+| routes | Array\<[RouteInfo](js-apis-net-connection.md#routeinfo8)\> | No| Route information of the vNIC.|
+| dnsAddresses | Array\ | No| IP address of the DNS server.|
+| searchDomains | Array\ | No| List of DNS search domains.|
+| mtu | number | No| Maximum transmission unit (MTU), in bytes.|
+| isIPv4Accepted | boolean | No| Whether IPv4 is supported. The default value is **true**.|
+| isIPv6Accepted | boolean | No| Whether IPv6 is supported. The default value is **false**.|
+| isLegacy | boolean | No| Whether the built-in VPN is supported. The default value is **false**.|
+| isBlocking | boolean | No| Whether the blocking mode is used. The default value is **false**.|
+| trustedApplications | Array\ | No| List of trusted applications, which are represented by bundle names of the string type.|
+| blockedApplications | Array\ | No| List of blocked applications, which are represented by bundle names of the string type.|
diff --git a/en/application-dev/reference/apis/js-apis-nfcTag.md b/en/application-dev/reference/apis/js-apis-nfcTag.md
index 9aeadd303e320824c99d7eb58148274bbb537e9b..07e68bebed8fd58bbf29a1bb6d800b8a5710821c 100644
--- a/en/application-dev/reference/apis/js-apis-nfcTag.md
+++ b/en/application-dev/reference/apis/js-apis-nfcTag.md
@@ -23,20 +23,18 @@ Before developing applications related to tag read and write, you must declare N
// Add the nfc tag action.
"ohos.nfc.tag.action.TAG_FOUND"
+ ],
+ "uris": [
+ {
+ "type":"tag-tech/NfcA"
+ },
+ {
+ "type":"tag-tech/IsoDep"
+ }
+ // Add other technology if neccessary,
+ // such as NfcB, NfcF, NfcV, Ndef, MifareClassic, MifareUL, and NdefFormatable.
]
}
- ],
- "metadata": [
- {
- "name": "tag-tech",
- "value": "NfcA"
- },
- {
- "name": "tag-tech",
- "value": "IsoDep"
- }
- // Add other technologies,
- // such as NfcB, NfcF, NfcV, Ndef, MifareClassic, MifareUL, and NdefFormatable.
]
}
],
@@ -49,13 +47,11 @@ Before developing applications related to tag read and write, you must declare N
}
}
```
-> **CAUTION**
+> **CAUTION**
>
> - The **actions** field is mandatory. It must be **ohos.nfc.tag.action.TAG_FOUND** and cannot be changed.
-> - The **name** field under **metadata** is mandatory. It must be **tag-tech** and cannot be changed.
-> - The **value** field under **metadata** is mandatory. It can be **NfcA**, **NfcB**, **NfcF**, **NfcV**, **IsoDep**, **Ndef**, **MifareClassic**, **MifareUL**, **NdefFormatable** or any of their combinations. Incorrect settings of this field will cause a parsing failure.
+> - The **type** field under **uris** must start with **tag-tech/**, followed by NfcA, NfcB, NfcF, NfcV, IsoDep, Ndef, MifareClassic, MifareUL, or NdefFormatable. If there are multiple types, enter them in different lines. Incorrect settings of this field will cause a parsing failure.
> - The **name** field under **requestPermissions** is mandatory. It must be **ohos.permission.NFC_TAG** and cannot be changed.
-
## **Modules to Import**
```js
@@ -528,8 +524,16 @@ import tag from '@ohos.nfc.tag';
let elementName = null;
let discTech = [tag.NFC_A, tag.NFC_B]; // replace with the tech(s) that is needed by foreground ability
-function foregroundCb(tagInfo: any) {
- console.log("foreground callback: tag found tagInfo = ", JSON.stringify(tagInfo));
+
+function foregroundCb(err, taginfo) {
+ if (!err) {
+ console.log("foreground callback: tag found tagInfo = ", JSON.stringify(tagInfo));
+ } else {
+ console.log("foreground callback err: " + err.message);
+ return;
+ }
+ // other Operations of taginfo
+
}
export default class MainAbility extends UIAbility {
@@ -885,7 +889,7 @@ Enumerates the tag technology types.
| **Name** | **Value**| **Description** |
| ---------------------------- | ------ | --------------------------- |
| NFC_A | 1 | NFC-A (ISO 14443-3A). |
-| NFC_B | 2 | NFC-B (ISO 14443-3B).|
+| NFC_B | 2 | NFC-B (ISO 14443-3B). |
| ISO_DEP | 3 | ISO-DEP (ISO 14443-4).|
| NFC_F | 4 | NFC-F (JIS 6319-4). |
| NFC_V | 5 | NFC-V (ISO 15693). |
diff --git a/en/application-dev/reference/apis/js-apis-osAccount.md b/en/application-dev/reference/apis/js-apis-osAccount.md
index c5575525ae030c63abda09464bb309b70dab3f6f..a3aa13b74e274359295edb15006bd1bcd0541995 100644
--- a/en/application-dev/reference/apis/js-apis-osAccount.md
+++ b/en/application-dev/reference/apis/js-apis-osAccount.md
@@ -481,7 +481,7 @@ Checks whether this OS account has been verified. This API uses an asynchronous
| Name | Type | Mandatory| Description |
| -------- | ---------------------------- | ---- | ------------------------------------------------------------- |
-| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If true is returned, the current account has been verified. If false is returned, the current account has not been verified.|
+| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means the OS account has been verified; the value **false** means the opposite.|
**Error codes**
@@ -508,6 +508,41 @@ Checks whether this OS account has been verified. This API uses an asynchronous
### checkOsAccountVerified9+
+checkOsAccountVerified(): Promise<boolean>
+
+Checks whether this OS account has been verified. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Account.OsAccount
+
+**Return value**
+
+| Type | Description |
+| ---------------------- | ------------------------------------------------------------------------ |
+| Promise<boolean> | Promise used to return the result. The value **true** means the OS account has been verified; the value **false** means the opposite.|
+
+**Error codes**
+
+| ID| Error Message |
+| -------- | ------------------- |
+| 12300001 | System service exception. |
+
+**Example**
+
+ ```js
+ let accountManager = account_osAccount.getAccountManager();
+ try {
+ accountManager.checkOsAccountVerified().then((isVerified) => {
+ console.log('checkOsAccountVerified successfully, isVerified: ' + isVerified);
+ }).catch((err) => {
+ console.log('checkOsAccountVerified failed, error: ' + JSON.stringify(err));
+ });
+ } catch (err) {
+ console.log('checkOsAccountVerified exception: ' + JSON.stringify(err));
+ }
+ ```
+
+### checkOsAccountVerified9+
+
checkOsAccountVerified(localId: number, callback: AsyncCallback<boolean>): void
Checks whether an OS account has been verified. This API uses an asynchronous callback to return the result.
@@ -595,6 +630,41 @@ Checks whether an OS account has been verified. This API uses a promise to retur
}
```
+### checkOsAccountVerified9+
+
+checkOsAccountVerified(): Promise<boolean>
+
+Checks whether this OS account has been verified. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Account.OsAccount
+
+**Return value**
+
+| Type | Description |
+| ---------------------- | ----------------------------------------------------------------- |
+| Promise<boolean> | Promise used to return the result. The value **true** means the OS account has been verified; the value **false** means the opposite.|
+
+**Error codes**
+
+| ID| Error Message |
+| -------- | ------------------- |
+| 12300001 | System service exception. |
+
+**Example**
+
+ ```js
+ let accountManager = account_osAccount.getAccountManager();
+ try {
+ accountManager.checkOsAccountVerified().then((isVerified) => {
+ console.log('checkOsAccountVerified successfully, isVerified: ' + isVerified);
+ }).catch((err) => {
+ console.log('checkOsAccountVerified failed, error: ' + JSON.stringify(err));
+ });
+ } catch (err) {
+ console.log('checkOsAccountVerified exception: ' + JSON.stringify(err));
+ }
+ ```
+
### removeOsAccount
removeOsAccount(localId: number, callback: AsyncCallback<void>): void
@@ -1552,7 +1622,7 @@ Creates an OS account. This API uses an asynchronous callback to return the resu
| 12300002 | Invalid localName or type. |
| 12300005 | Multi-user not supported. |
| 12300006 | Unsupported account type. |
-| 12300007 | The number of account reaches the upper limit. |
+| 12300007 | The number of accounts reaches the upper limit. |
**Example**
@@ -1601,7 +1671,7 @@ Creates an OS account. This API uses a promise to return the result.
| 12300002 | Invalid localName or type. |
| 12300005 | Multi-user not supported. |
| 12300006 | Unsupported account type. |
-| 12300007 | The number of account reaches the upper limit. |
+| 12300007 | The number of accounts reaches the upper limit. |
**Example**
@@ -1646,7 +1716,7 @@ Creates an OS account and associates it with the specified domain account. This
| 12300002 | Invalid type or domainInfo. |
| 12300005 | Multi-user not supported. |
| 12300006 | Unsupported account type. |
-| 12300007 | The number of account reaches the upper limit. |
+| 12300007 | The number of accounts reaches the upper limit. |
**Example**
@@ -1696,7 +1766,7 @@ Creates an OS account and associates it with the specified domain account. This
| 12300002 | Invalid type or domainInfo. |
| 12300005 | Multi-user not supported. |
| 12300006 | Unsupported account type. |
-| 12300007 | The number of account reaches the upper limit. |
+| 12300007 | The number of accounts reaches the upper limit. |
**Example**
@@ -1720,7 +1790,7 @@ getCurrentOsAccount(callback: AsyncCallback<OsAccountInfo>): void
Obtains information about the OS account to which the current process belongs. This API uses an asynchronous callback to return the result.
-**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS
+**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.GET_LOCAL_ACCOUNTS10+
**System capability**: SystemCapability.Account.OsAccount
@@ -1756,7 +1826,7 @@ getCurrentOsAccount(): Promise<OsAccountInfo>
Obtains information about the OS account to which the current process belongs. This API uses a promise to return the result.
-**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS
+**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.GET_LOCAL_ACCOUNTS10+
**System capability**: SystemCapability.Account.OsAccount
@@ -4109,8 +4179,10 @@ Performs authentication of the current user. This API uses an asynchronous callb
| 12300001 | System service exception. |
| 12300002 | Invalid challenge, authType, or authTrustLevel. |
| 12300101 | Credential is incorrect. |
+| 12300102 | Credential not enrolled. |
| 12300105 | Unsupported authTrustLevel. |
| 12300106 | Unsupported authType. |
+| 12300109 | Authentication is canceled. |
| 12300110 | Authentication is locked. |
| 12300111 | Authentication timeout. |
| 12300112 | Authentication service is busy. |
@@ -4168,8 +4240,10 @@ Performs authentication of the specified user. This API uses an asynchronous cal
| 12300001 | System service exception. |
| 12300002 | Invalid userId, challenge, authType, or authTrustLevel. |
| 12300101 | Credential is incorrect. |
+| 12300102 | Credential not enrolled. |
| 12300105 | Unsupported authTrustLevel. |
| 12300106 | Unsupported authType. |
+| 12300109 | Authentication is canceled. |
| 12300110 | Authentication is locked. |
| 12300111 | Authentication timeout. |
| 12300112 | Authentication service is busy. |
@@ -5319,6 +5393,9 @@ Adds credential information, including the credential type, subtype, and token (
| 12300002 | Invalid credentialInfo, i.e. authType or authSubType. |
| 12300101 | Token is invalid. |
| 12300106 | Unsupported authType. |
+| 12300109 | Operation is canceled. |
+| 12300111 | Operation timeout. |
+| 12300115 | The number of credentials reaches the upper limit. |
**Example**
```js
@@ -5375,7 +5452,10 @@ Updates credential information. This API uses a callback to return the result.
| 12300001 | System service exception. |
| 12300002 | Invalid credentialInfo, i.e. authType or authSubType or token. |
| 12300101 | Token is invalid. |
+| 12300102 | Credential not enrolled.|
| 12300106 | Unsupported authType. |
+| 12300109 | Operation is canceled. |
+| 12300111 | Operation timeout. |
**Example**
```js
@@ -5538,7 +5618,7 @@ Deletes user credential information.
| 12300001 | System service exception. |
| 12300002 | Invalid credentialId. |
| 12300101 | Token is invalid. |
-| 12300102 | Credential not found. |
+| 12300102 | Credential not enrolled. |
**Example**
```js
@@ -5580,6 +5660,7 @@ Obtains authentication information. This API uses an asynchronous callback to re
| ID| Error Message |
| -------- | --------------------- |
| 12300001 | System service exception. |
+| 12300102 | Credential not enrolled. |
**Example**
```js
@@ -5619,6 +5700,7 @@ Obtains authentication information of the specified type. This API uses an async
| -------- | ------------------- |
| 12300001 | System service exception. |
| 12300002 | Invalid authType. |
+| 12300102 | Credential not enrolled. |
**Example**
```js
@@ -5663,6 +5745,7 @@ Obtains authentication information of the specified type. This API uses a promis
| -------- | ------------------- |
| 12300001 | System service exception. |
| 12300002 | Invalid authType. |
+| 12300102 | Credential not enrolled. |
**Example**
```js
diff --git a/en/application-dev/reference/apis/js-apis-photoAccessHelper.md b/en/application-dev/reference/apis/js-apis-photoAccessHelper.md
index 808334727bbbf917dad8a7f801bcc7896ad12ee3..aae05347c5a05bdcb5e6bcae488fe53fa89602f4 100644
--- a/en/application-dev/reference/apis/js-apis-photoAccessHelper.md
+++ b/en/application-dev/reference/apis/js-apis-photoAccessHelper.md
@@ -1275,6 +1275,151 @@ async function example() {
}
```
+### getPhotoIndex
+
+getPhotoIndex(photoUri: string, albumUri: string, options: FetchOptions, callback: AsyncCallback<number>): void
+
+Obtains the index of an image or video in an album. This API uses an asynchronous callback to return the result.
+
+**System API**: This is a system API.
+
+**Required permissions**: ohos.permission.READ_IMAGEVIDEO
+
+**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ------------------------- | ---- | ---------- |
+| photoUri | string | Yes | URI of the media asset whose index is to be obtained.|
+| albumUri | string | Yes | Album URI, which can be an empty string. If it is an empty string, all the media assets in the Gallery are obtained by default. |
+| options | [FetchOptions](#fetchoptions) | Yes | Fetch options. Only one search condition or sorting mode must be set in **predicates**. If no value is set or multiple search conditions or sorting modes are set, the API cannot be called successfully. |
+
+**Return value**
+
+| Type | Description |
+| --------------------------------------- | ----------------- |
+| AsyncCallback<number>| Promise used to return the index obtained.|
+
+**Error codes**
+
+For details about the error codes, see [Universal Error Codes](../errorcodes/errorcode-universal.md).
+
+| ID| Error Message|
+| -------- | ---------------------------------------- |
+| 401 | if parameter is invalid. |
+
+**Example**
+
+```ts
+import dataSharePredicates from '@ohos.data.dataSharePredicates';
+
+async function example() {
+ console.info('getPhotoIndexDemo');
+ let predicatesForGetAsset = new dataSharePredicates.DataSharePredicates();
+ let fetchOp = {
+ fetchColumns: [],
+ predicates: predicatesForGetAsset
+ };
+ //Obtain the uri of the album
+ let albumFetchResult = await helper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE, fetchOp);
+ let album = await albumFetchResult.getFirstObject();
+
+ let predicates = new dataSharePredicates.DataSharePredicates();
+ predicates.orderByAsc("add_modified");
+ let fetchOptions = {
+ fetchColumns: [],
+ predicates: predicates
+ };
+ let photoFetchResult = await album.getAssets(fetchOptions);
+ let expectIndex = 1;
+ //Obtain the uri of the second file
+ let photoAsset = await photoFetchResult.getObjectByPosition(expectIndex);
+
+ photoAccessHelper.getPhotoIndex(photoAsset.uri, album.albumUri, fetchOptions, (err, index) => {
+ try {
+ if (err == undefined) {
+ console.info(`getPhotoIndex successfully and index is : ${index}`);
+ } else {
+ console.info(`getPhotoIndex failed;`);
+ }
+ } catch (error) {
+ console.info(`getPhotoIndex failed; error: ${error}`);
+ }
+ }
+}
+```
+
+### getPhotoIndex
+
+getPhotoIndex(photoUri: string, albumUri: string, options: FetchOptions): Promise<number>
+
+Obtains the index of an image or video in an album. This API uses a promise to return the result.
+
+**System API**: This is a system API.
+
+**Required permissions**: ohos.permission.READ_IMAGEVIDEO
+
+**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ------------------------- | ---- | ---------- |
+| photoUri | string | Yes | URI of the media asset whose index is to be obtained.|
+| albumUri | string | Yes | Album URI, which can be an empty string. If it is an empty string, all the media assets in the Gallery are obtained by default. |
+| options | [FetchOptions](#fetchoptions) | Yes | Fetch options. Only one search condition or sorting mode must be set in **predicates**. If no value is set or multiple search conditions or sorting modes are set, the API cannot be called successfully. |
+
+**Return value**
+
+| Type | Description |
+| --------------------------------------- | ----------------- |
+| Promise<number>| Promise used to return the index obtained.|
+
+**Error codes**
+
+For details about the error codes, see [Universal Error Codes](../errorcodes/errorcode-universal.md).
+
+| ID| Error Message|
+| -------- | ---------------------------------------- |
+| 401 | if parameter is invalid. |
+
+**Example**
+
+```ts
+import dataSharePredicates from '@ohos.data.dataSharePredicates';
+
+async function example() {
+ console.info('getPhotoIndexDemo');
+ let predicatesForGetAsset = new dataSharePredicates.DataSharePredicates();
+ let fetchOp = {
+ fetchColumns: [],
+ predicates: predicatesForGetAsset
+ };
+ //Obtain the uri of the album
+ let albumFetchResult = await helper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE, fetchOp);
+ let album = await albumFetchResult.getFirstObject();
+
+ let predicates = new dataSharePredicates.DataSharePredicates();
+ predicates.orderByAsc("add_modified");
+ let fetchOptions = {
+ fetchColumns: [],
+ predicates: predicates
+ };
+ let photoFetchResult = await album.getAssets(fetchOptions);
+ let expectIndex = 1;
+ //Obtain the uri of the second file
+ let photoAsset = await photoFetchResult.getObjectByPosition(expectIndex);
+
+ photoAccessHelper.getPhotoIndex(photoAsset.uri, album.albumUri, fetchOptions)
+ .then((index) => {
+ console.info(`getPhotoIndex successfully and index is : ${index}`);
+ }).catch((err) => {
+ console.info(`getPhotoIndex failed; error: ${err}`);
+ })
+}
+```
+
### release
release(callback: AsyncCallback<void>): void
@@ -1360,7 +1505,7 @@ Provides APIs for encapsulating file asset attributes.
| Name | Type | Readable| Writable| Description |
| ------------------------- | ------------------------ | ---- | ---- | ------------------------------------------------------ |
-| uri | string | Yes | No | File asset URI, for example, **file://media/image/2**. |
+| uri | string | Yes | No | File asset URI, for example, **file://media/Photo/1/IMG_datetime_0001/displayName.jpg**. |
| photoType | [PhotoType](#phototype) | Yes | No | Type of the file. |
| displayName | string | Yes | No | File name, including the file name extension, to display. |
@@ -2243,6 +2388,282 @@ async function example() {
}
```
+### getExif10+
+
+getExif(): Promise<string>
+
+Obtains a JSON string consisting of the EXIF tags of this JPG image. This API uses a promise to return the result.
+
+**CAUTION** This API returns a JSON string consisting of EXIF tags. The complete EXIF information consists of **all_exif** and **js-apis-photoAccessHelper.md**. These two fields must be passed in via **fetchColumns**.
+
+**System API**: This is a system API.
+
+**Required permissions**: ohos.permission.READ_IMAGEVIDEO
+
+**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
+
+**Return value**
+
+| Type | Description |
+| --------------------------------------- | ----------------- |
+| Promise<string> | Callback invoked to return the JSON string obtained.|
+
+**Supported EXIF tags**
+
+For details about the EXIF tags, see [image.PropertyKey](js-apis-image.md#propertykey7).
+
+| Key Value | Description |
+| --------------------------------------- | ----------------- |
+| BitsPerSample | Number of bits per pixel.|
+| Orientation | Image orientation.|
+| ImageLength | Image length.|
+| ImageWidth | Image width.|
+| GPSLatitude | GPS latitude of the image.|
+| GPSLongitude | GPS longitude of the image.|
+| GPSLatitudeRef | Longitude reference, for example, W or E.|
+| GPSLongitudeRef | Latitude reference, for example, N or S.|
+| DateTimeOriginal | Shooting time.|
+| ExposureTime | Exposure time.|
+| SceneType | Shooting scene type.|
+| ISOSpeedRatings | ISO sensitivity or speed.|
+| FNumber | f-number.|
+| DateTime | Date and time when the image was last modified.|
+| GPSTimeStamp | GPS timestamp.|
+| GPSDateStamp | GPS date stamp.|
+| ImageDescription | Image description.|
+| Make | Camera vendor.|
+| Model | Model.|
+| PhotoMode | Photo mode.|
+| SensitivityType | Sensitivity type.|
+| StandardOutputSensitivity | Standard output sensitivity.|
+| RecommendedExposureIndex | Recommended exposure index.|
+| ApertureValue | Aperture value.|
+| MeteringMode | Metering mode.|
+| LightSource | Light source.|
+| Flash | Flash status.|
+| FocalLength | Focal length.|
+| UserComment | User comment.|
+| PixelXDimension | Pixel X dimension.|
+| PixelYDimension | Pixel Y dimension.|
+| WhiteBalance | White balance.|
+| FocalLengthIn35mmFilm | Focal length in 35 mm film.|
+| ExposureBiasValue | Exposure compensation.|
+
+**Example**
+
+```ts
+import dataSharePredicates from '@ohos.data.dataSharePredicates';
+
+async function example() {
+ try {
+ console.info('getExifDemo');
+ let predicates = new dataSharePredicates.DataSharePredicates();
+ let fetchOptions = {
+ fetchColumns: [ 'all_exif', photoKeys.USER_COMMENT],
+ predicates: predicates
+ };
+ let fetchResult = await phAccessHelper.getAssets(fetchOptions);
+ let fileAsset = await fetchResult.getFirstObject();
+ let exifMessage = await fileAsset.getExif();
+ let userCommentKey = 'UserComment';
+ let userComment = JSON.stringify(JSON.parse(exifMessage), [userCommentKey]);
+ fetchResult.close();
+ } catch (err) {
+ console.error('getExifDemoCallback failed with error: ' + err);
+ }
+}
+```
+
+### getExif10+
+
+getExif(callback: AsyncCallback<string>): void
+
+Obtains a JSON string consisting of the EXIF tags of this JPG image. This API uses an asynchronous callback to return the result.
+
+**CAUTION** This API returns a JSON string consisting of EXIF tags. The complete EXIF information consists of **all_exif** and **ImageVideoKey.USER_COMMENT**. These two fields must be passed in via **fetchColumns**.
+
+**System API**: This is a system API.
+
+**Required permissions**: ohos.permission.READ_IMAGEVIDEO
+
+**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ------------------------- | ---- | ---------- |
+| callback | AsyncCallback<string> | Yes | Callback invoked to return the JSON string obtained.|
+
+**Supported EXIF tags**
+
+For details about the EXIF tags, see [image.PropertyKey](js-apis-image.md#propertykey7).
+
+| Key Value | Description |
+| --------------------------------------- | ----------------- |
+| BitsPerSample | Number of bits per pixel.|
+| Orientation | Image orientation.|
+| ImageLength | Image length.|
+| ImageWidth | Image width.|
+| GPSLatitude | GPS latitude of the image.|
+| GPSLongitude | GPS longitude of the image.|
+| GPSLatitudeRef | Longitude reference, for example, W or E.|
+| GPSLongitudeRef | Latitude reference, for example, N or S.|
+| DateTimeOriginal | Shooting time.|
+| ExposureTime | Exposure time.|
+| SceneType | Shooting scene type.|
+| ISOSpeedRatings | ISO sensitivity or speed.|
+| FNumber | f-number.|
+| DateTime | Date and time when the image was last modified.|
+| GPSTimeStamp | GPS timestamp.|
+| GPSDateStamp | GPS date stamp.|
+| ImageDescription | Image description.|
+| Make | Camera vendor.|
+| Model | Model.|
+| PhotoMode | Photo mode.|
+| SensitivityType | Sensitivity type.|
+| StandardOutputSensitivity | Standard output sensitivity.|
+| RecommendedExposureIndex | Recommended exposure index.|
+| ApertureValue | Aperture value.|
+| MeteringMode | Metering mode.|
+| LightSource | Light source.|
+| Flash | Flash status.|
+| FocalLength | Focal length.|
+| UserComment | User comment.|
+| PixelXDimension | Pixel X dimension.|
+| PixelYDimension | Pixel Y dimension.|
+| WhiteBalance | White balance.|
+| FocalLengthIn35mmFilm | Focal length in 35 mm film.|
+| ExposureBiasValue | Exposure compensation.|
+
+**Example**
+
+```ts
+import dataSharePredicates from '@ohos.data.dataSharePredicates';
+
+async function example() {
+ try {
+ console.info('getExifDemo');
+ let predicates = new dataSharePredicates.DataSharePredicates();
+ let fetchOptions = {
+ fetchColumns: [ 'all_exif', photoKeys.USER_COMMENT],
+ predicates: predicates
+ };
+ let fetchResult = await phAccessHelper.getAssets(fetchOptions);
+ let fileAsset = await fetchResult.getFirstObject();
+ let userCommentKey = 'UserComment';
+ fileAsset.getExif((err, exifMessage) => {
+ if (exifMessage != undefined) {
+ let userComment = JSON.stringify(JSON.parse(exifMessage), [userCommentKey]);
+ } else {
+ console.error('getExif failed, message = ', err);
+ }
+ });
+ fetchResult.close();
+ } catch (err) {
+ console.error('getExifDemoCallback failed with error: ' + err);
+ }
+}
+```
+
+### setUserComment10+
+
+setUserComment(userComment: string): Promise<void>
+
+Sets user comment information of an image or video. This API uses a promise to return the result.
+
+**NOTE** This API can be used to modify the comment information of only images or videos.
+
+**System API**: This is a system API.
+
+**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO
+
+**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ------------------------- | ---- | ---------- |
+| userComment | string | Yes | User comment information to set, which cannot exceed 140 characters.|
+
+**Return value**
+
+| Type | Description |
+| --------------------------------------- | ----------------- |
+|Promise<void> | Promise that returns no value.|
+
+**Example**
+
+```ts
+import dataSharePredicates from '@ohos.data.dataSharePredicates';
+
+async function example() {
+ try {
+ console.info('setUserCommentDemo')
+ let predicates = new dataSharePredicates.DataSharePredicates();
+ let fetchOptions = {
+ fetchColumns: [],
+ predicates: predicates
+ };
+ let fetchResult = await phAccessHelper.getAssets(fetchOptions);
+ let fileAsset = await fetchResult.getFirstObject();
+ let userComment = 'test_set_user_comment';
+ await fileAsset.setUserComment(userComment);
+ } catch (err) {
+ console.error('setUserCommentDemoCallback failed with error: ' + err);
+ }
+}
+```
+
+### setUserComment10+
+
+setUserComment(userComment: string, callback: AsyncCallback<void>): void
+
+Sets user comment information of an image or video. This API uses an asynchronous callback to return the result.
+
+**NOTE** This API can be used to modify the comment information of only images or videos.
+
+**System API**: This is a system API.
+
+**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO
+
+**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ------------------------- | ---- | ---------- |
+| userComment | string | Yes | User comment information to set, which cannot exceed 140 characters.|
+| callback | AsyncCallback<void> | Yes | Callback that returns no value.|
+
+**Example**
+
+```ts
+import dataSharePredicates from '@ohos.data.dataSharePredicates';
+
+async function example() {
+ try {
+ console.info('setUserCommentDemo')
+ let predicates = new dataSharePredicates.DataSharePredicates();
+ let fetchOptions = {
+ fetchColumns: [],
+ predicates: predicates
+ };
+ let fetchResult = await phAccessHelper.getAssets(fetchOptions);
+ let fileAsset = await fetchResult.getFirstObject();
+ let userComment = 'test_set_user_comment';
+ fileAsset.setUserComment(userComment, (err) => {
+ if (err === undefined) {
+ console.info('setUserComment successfully');
+ } else {
+ console.error('setUserComment failed with error: ' + err);
+ }
+ });
+ } catch (err) {
+ console.error('setUserCommentDemoCallback failed with error: ' + err);
+ }
+}
+```
+
## FetchResult
Provides APIs to manage the file retrieval result.
@@ -3726,6 +4147,7 @@ Defines the key information about an image or video file.
| DATE_TRASHED | 'date_trashed' | Date when the file was deleted. The value is the number of seconds between the time when the file is deleted and January 1, 1970. **System API**: This is a system API. |
| HIDDEN | 'hidden' | Whether the file is hidden. **System API**: This is a system API. |
| CAMERA_SHOT_KEY | 'camera_shot_key' | Key for the Untra Snamshot feature, which allows the camera to take photos or record videos with the screen off. (This parameter is available only for the system camera, and the key value is defined by the system camera.) **System API**: This is a system API. |
+| USER_COMMENT10+ | 'user_comment' | User comment information. **System API**: This is a system API. |
## AlbumKeys
diff --git a/en/application-dev/reference/apis/js-apis-request.md b/en/application-dev/reference/apis/js-apis-request.md
index f2eb1a5fff829317cf67affa7980deaee7c67158..9acb13cab11b2ff8458554a3bf32f67fab291f75 100644
--- a/en/application-dev/reference/apis/js-apis-request.md
+++ b/en/application-dev/reference/apis/js-apis-request.md
@@ -286,6 +286,10 @@ on(type: 'progress', callback:(uploadedSize: number, totalSize: number) => vo
Subscribes to upload progress events. This API uses a callback to return the result synchronously.
+> **NOTE**
+>
+> To maintain a balance between power consumption and performance, this API cannot be called when the application is running in the background.
+
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Upload
@@ -851,6 +855,10 @@ on(type: 'progress', callback:(receivedSize: number, totalSize: number) => vo
Subscribes to download progress events. This API uses a callback to return the result synchronously.
+> **NOTE**
+>
+> To maintain a balance between power consumption and performance, this API cannot be called when the application is running in the background.
+
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Download
diff --git a/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md b/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md
index ab24d98a8529e112fba804daf3177416678f7208..d61b8272edee9b2b522139a9976df17027be98a5 100644
--- a/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md
+++ b/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md
@@ -630,7 +630,7 @@ Enumerates the efficiency resource types.
| CPU | 1 | CPU resources, which prevent the application from being suspended. |
| COMMON_EVENT | 2 | Common events are not proxied when the application is suspended.|
| TIMER | 4 | System timers are not proxied when the application is suspended.|
-| WORK_SCHEDULER | 8 | WorkScheduler uses a loose control policy by default. For details, see [Restrictions on Using Work Scheduler Tasks](../../task-management/background-task-overview.md#restrictions-on using-work-scheduler-tasks).|
+| WORK_SCHEDULER | 8 | Work Scheduler uses a loose control policy by default. For details about the constraints on the Work Scheduler usage, see [Constraints](../../task-management/work-scheduler.md#constraints).|
| BLUETOOTH | 16 | Bluetooth resources are not proxied when the application is suspended.|
| GPS | 32 | GPS resources are not proxied when the application is suspended.|
| AUDIO | 64 | Audio resources are not proxied when the application is suspended.|
diff --git a/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md b/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md
index 5bc61a1776965b66f60da9cd287080bcff5c28fc..85c085f6fb9ef65fb711aecbfe3610ab3d17f5d9 100644
--- a/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md
+++ b/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md
@@ -8,6 +8,7 @@ The system schedules and executes deferred tasks at an appropriate time, subject
>
> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The APIs of this module can be used only in the stage model.
+> - For details about the constraints on deferred task scheduling, see [Constraints](../../task-management/work-scheduler.md#constraints).
## Modules to Import
@@ -410,7 +411,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
```
## WorkInfo
-Provides detailed information about the task.
+Provides detailed information about the task. For details about the constraints on setting the **WorkInfo** parameter, see [Constraints](../../task-management/work-scheduler.md#constraints).
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
@@ -418,7 +419,7 @@ Provides detailed information about the task.
| --------------- | --------------------------------- | ---- | ---------------- |
| workId | number | Yes | Task ID. |
| bundleName | string | Yes | Bundle name of the application that requests the task. |
-| abilityName | string | Yes | Name of the component to be notified by a deferred task scheduling callback. |
+| abilityName | string | Yes | Name of the component to be notified by a deferred task scheduling callback.|
| networkType | [NetworkType](#networktype) | No | Network type. |
| isCharging | boolean | No | Whether the device is charging. |
| chargerType | [ChargingType](#chargingtype) | No | Charging type. |
diff --git a/en/application-dev/reference/apis/js-apis-rpc.md b/en/application-dev/reference/apis/js-apis-rpc.md
index 22df13e5169b5c8589753aeb553689576e6f7c65..b4742e449161ac43ab08daca6d8b529c56cc3d4a 100644
--- a/en/application-dev/reference/apis/js-apis-rpc.md
+++ b/en/application-dev/reference/apis/js-apis-rpc.md
@@ -293,14 +293,6 @@ Sets the size of the data contained in this **MessageSequence** object.
| ------ | ------ | ---- | ------ |
| size | number | Yes | Data size to set, in bytes.|
-**Error codes**
-
-For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
-
- | ID| Error Message|
- | -------- | -------- |
- | 1900009 | write data to message sequence failed |
-
**Example**
```ts
@@ -334,7 +326,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
| ID| Error Message|
| -------- | -------- |
- | 1900009 | write data to message sequence failed |
| 1900011 | parcel memory alloc failed |
**Example**
@@ -461,12 +452,6 @@ Moves the read pointer to the specified position.
| ------ | ------ | ---- | ------- |
| pos | number | Yes | Position from which data is to read.|
-**Error codes**
-
- | ID| Error Message|
- | -------- | -------- |
- | 1900010 | read data from message sequence failed |
-
**Example**
```ts
@@ -499,12 +484,6 @@ Moves the write pointer to the specified position.
| ------ | ------ | ---- | ----- |
| pos | number | Yes | Position from which data is to write.|
-**Error codes**
-
- | ID| Error Message|
- | -------- | -------- |
- | 1900009 | write data to message sequence failed |
-
**Example**
```ts
@@ -2945,8 +2924,8 @@ Writes an anonymous shared object to this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
- | -------- | -------- |
- | 1900009 | write data to message sequence failed |
+ | -------- | ------- |
+ | 1900003 | write to ashmem failed |
**Example**
@@ -2979,7 +2958,7 @@ Reads the anonymous shared object from this **MessageSequence** object.
| Type | Description |
| ------ | ------------------ |
- | Ashmem | Anonymous share object read.|
+ | Ashmem | Anonymous share object obtained.|
**Error codes**
@@ -2987,7 +2966,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
| ID| Error Message|
| -------- | -------- |
- | 1900010 | read data from message sequence failed |
+ | 1900004 | read from ashmem failed |
**Example**
@@ -3091,7 +3070,7 @@ Reads raw data from this **MessageSequence** object.
| Type | Description |
| -------- | ------------------------------ |
- | number[] | Raw data read, in bytes.|
+ | number[] | Raw data obtained, in bytes.|
**Error codes**
@@ -5960,7 +5939,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
| ID| Error Message|
| -------- | -------- |
- | 1900005 | only proxy object permitted |
+ | 1900008 | proxy or remote object is invalid |
### addDeathrecipient(deprecated)
@@ -6006,7 +5985,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
| ID| Error Message|
| -------- | -------- |
- | 1900005 | only proxy object permitted |
+ | 1900008 | proxy or remote object is invalid |
### removeDeathRecipient(deprecated)
diff --git a/en/application-dev/reference/apis/js-apis-secureElement.md b/en/application-dev/reference/apis/js-apis-secureElement.md
index 4314ea817608a8e26cdb5d0fa45aa01b64297227..daa96f217bdcc86ffcd76fde5b8a7d08b2a3a966 100644
--- a/en/application-dev/reference/apis/js-apis-secureElement.md
+++ b/en/application-dev/reference/apis/js-apis-secureElement.md
@@ -66,7 +66,7 @@ try {
if (state == secureElement.ServiceState.DISCONNECTED) {
console.log("Service state is Disconnected");
} else {
- console.log.("Service state is Connected");
+ console.log("Service state is Connected");
}
});
} catch (e) {
@@ -114,7 +114,6 @@ try {
try {
nfcOmaReaderList = nfcSEService.getReaders();
if (nfcOmaReaderList != null && nfcOmaReaderList.length > 0) {
- nfcOmaReader = this.nfcOmaReaderList[0];
console.log("get reader successfully");
} else {
console.log("get reader failed");
@@ -205,7 +204,6 @@ import secureElement from '@ohos.secureElement';
let nfcSEService = null;
-this.result = "version: "
try {
// refer to newSEService for this.nfcSEService
console.log("version: " + nfcSEService.getVersion());
@@ -349,7 +347,7 @@ For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.m
```js
import secureElement from '@ohos.secureElement';
-nfcOmaReader = null;
+let nfcOmaReader = null;
try {
// refer to SEService.getReaders for this.nfcOmaReader
@@ -584,10 +582,11 @@ import secureElement from '@ohos.secureElement';
let nfcOmaSession = null;
let nfcOmaChannel = null;
+let aidArray = [720, 1080];
try {
// See Reader.openSession for this.nfcOmaSession.
- let getPromise = nfcOmaSession.openBasicChannel(this.aidArray);
+ let getPromise = nfcOmaSession.openBasicChannel(aidArray);
getPromise.then((channel) => {
nfcOmaChannel = channel;
console.log("openBasicChannel1 get channel successfully");
@@ -737,7 +736,6 @@ For details about error codes, see [SE Error Codes](../errorcodes/errorcode-se.m
```js
import secureElement from '@ohos.secureElement';
-
let nfcOmaSession = null;
let nfcOmaChannel = null;
let aidArray = [720, 1080];
@@ -915,8 +913,9 @@ if (nfcOmaSession) {
}).catch ((err) => {
console.log("openLogicChannel3 exception");
})
-} catch (e) {
- console.log("openLogicChannel3 exception:" + e.message);
+ } catch (e) {
+ console.log("openLogicChannel3 exception:" + e.message);
+ }
}
```
diff --git a/en/application-dev/reference/apis/js-apis-sms.md b/en/application-dev/reference/apis/js-apis-sms.md
index 41a3fe10bbda7d00fc5aa588ed75072a702971bb..302ef980536e7e06d5ae6b8c8fee250085e13105 100644
--- a/en/application-dev/reference/apis/js-apis-sms.md
+++ b/en/application-dev/reference/apis/js-apis-sms.md
@@ -195,7 +195,7 @@ let destinationHost = '+861xxxxxxxxxx';
let serviceCenter = '+861xxxxxxxxxx';
let destinationPort = 1000;
let options = {slotId, content, destinationHost, serviceCenter, destinationPort, sendCallback, deliveryCallback};
-sms.sendMessage(options, (err) => {
+sms.sendShortMessage(options, (err) => {
console.log(`callback: err->${JSON.stringify(err)}`);
});
```
@@ -1341,7 +1341,7 @@ sms.isImsSmsSupported(slotId, (err, data) => {
isImsSmsSupported\(slotId: number\): Promise\
-This API uses an asynchronous callback to return the result. This API uses a promise to return the result.
+Checks whether SMS is supported on IMS. This API uses a promise to return the result.
**System API**: This is a system API.
diff --git a/en/application-dev/reference/apis/js-apis-system-app.md b/en/application-dev/reference/apis/js-apis-system-app.md
index e0acf1c2ba47df2555dd9812d655e1fb15f777e7..6fd13771f56ef275b03f71d0f5a6118c74e04106 100644
--- a/en/application-dev/reference/apis/js-apis-system-app.md
+++ b/en/application-dev/reference/apis/js-apis-system-app.md
@@ -2,9 +2,7 @@
> **NOTE**
>
-> - The APIs of this module are no longer maintained since API version 7. You are advised to use the new APIs.
->
-> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version.
+> The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
@@ -14,14 +12,15 @@
import app from '@system.app'
```
+## App
-## app.getInfo
+### getInfo
-getInfo(): AppResponse
+static getInfo(): AppResponse
Obtains the declared information in the **config.json** file of an application.
-You are advised to use [@ohos.bundle](js-apis-Bundle.md) since API version 7.
+This API is deprecated since API version 9. You are advised to use [bundleManager.getApplicationInfo](js-apis-bundleManager.md#bundlemanagergetapplicationinfo) instead.
**System capability**: SystemCapability.ArkUI.ArkUI.Lite
@@ -42,9 +41,9 @@ export default {
}
```
-## app.terminate
+### terminate
-terminate(): void
+static terminate(): void
Terminates the current ability.
@@ -61,37 +60,9 @@ export default {
}
}
```
-## app.requestFullWindow
+### setImageCacheCount7+
-requestFullWindow(options?: RequestFullWindowOptions): void
-
-Requests the application to run in full window. You can call this API when the FA runs in a non-full window, for example, semi-modal FA. This API is invalid for an application already in full-window mode.
-
-You are advised to use [@ohos.window](js-apis-window.md) since API version 7.
-
-**System capability**: SystemCapability.ArkUI.ArkUI.Full
-
-**Parameters**
-
-| Name| Type| Mandatory| Description|
-| -------- | -------- | -------- | -------- |
-| options | [RequestFullWindowOptions](#requestfullwindowoptions) | No| Duration for transition from the non-full window to the full window, in milliseconds. By default, the value is in direct proportion to the distance between the non-full window and the full window.|
-
-**Example**
-
-```ts
-export default {
- requestFullWindow() {
- app.requestFullWindow({
- duration: 200
- })
- }
-}
-```
-
-## app.setImageCacheCount7+
-
-setImageCacheCount(value: number): void
+static setImageCacheCount(value: number): void
Sets the maximum number of decoded images that can be cached in the memory to speed up the loading of images from the same sources. If the input parameter is not set, the default value **0** is used, indicating that images are not cached. The built-in Least Recently Used (LRU) policy is used for caching. If the maximum number is exceeded, the images that have not been updated for the longest time will be removed. You are advised to set the parameter based on the application memory requirements. If the number of images is too large, the memory usage may be too high.
@@ -120,9 +91,9 @@ export default {
}
```
-## app.setImageRawDataCacheSize7+
+### setImageRawDataCacheSize7+
-setImageRawDataCacheSize(value: number): void
+static setImageRawDataCacheSize(value: number): void
Sets the maximum size (in bytes) of the image data cached in the memory before decoding to speed up the loading of images from the same sources. If the input parameter is not set, the default value **0** is used, indicating that images are not cached. The LRU policy is used for caching. If the maximum size is exceeded, the images that have not been updated for the longest time will be removed. You are advised to set the parameter based on the application memory requirements. If the image cache is too large, the memory usage may be too high.
@@ -152,9 +123,9 @@ export default {
}
```
-## app.setImageFileCacheSize7+
+### setImageFileCacheSize7+
-setImageFileCacheSize(value: number): void
+static setImageFileCacheSize(value: number): void
Sets the maximum size of the image file cache (in bytes) to speed up the loading of images from the same sources, especially online image sources and thumbnails. If the input parameter is not set, the default value 100 MB is used. The LRU policy is used for caching. If the maximum size is exceeded, the images that have not been updated for the longest time will be removed. You are advised to set the parameter based on the application memory requirements. If the image cache is too large, the disk usage may be too high.
@@ -184,32 +155,60 @@ export default {
}
```
-## AppResponse
+### ScreenOnVisible(deprecated)
-Defines the application response information.
+static screenOnVisible(options?: ScreenOnVisibleOptions): void
-**System capability**: The items in the table below require different system capabilities. For details, see the table.
+Defines whether to keep the application visible when the screen is woken up.
-| Name| Type| Mandatory| Description|
-| -------- | -------- | -------- |-------- |
-| appID6+ | string | Yes| Bundle name of an application. It uniquely identifies the application. **System capability**: SystemCapability.ArkUI.ArkUI.Full|
-| appName | string | Yes| Application name. **System capability**: SystemCapability.ArkUI.ArkUI.Lite|
-| versionName | string | Yes| Application version name. **System capability**: SystemCapability.ArkUI.ArkUI.Lite|
-| versionCode | number | Yes| Application version number. **System capability**: SystemCapability.ArkUI.ArkUI.Lite|
+This API is deprecated since API Version 8.
-## ScreenOnVisible(deprecated)
+**System capability**: SystemCapability.ArkUI.ArkUI.Full
-screenOnVisible(options?: ScreenOnVisibleOptions): void
+| Name | Type | Mandatory| Description |
+| ------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ |
+| options | [ScreenOnVisibleOptions](#screenonvisibleoptions) | No | With keep-alive, the system is prevented from returning to the home screen when the screen is locked, so that the application is visible when the screen is woken up.|
-Defines whether to keep the application visible when the screen is woken up.
+### requestFullWindow(deprecated)
-This API is deprecated since API Version 8.
+static requestFullWindow(options?: RequestFullWindowOptions): void
+
+Requests the application to run in full window. You can call this API when the FA runs in a non-full window, for example, semi-modal FA. This API is invalid for an application already in full-window mode.
+
+You are advised to use [@ohos.window](js-apis-window.md) since API version 7.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ |
+| options | [RequestFullWindowOptions](#requestfullwindowoptions) | No | Duration for transition from the non-full window to the full window, in milliseconds. By default, the value is in direct proportion to the distance between the non-full window and the full window.|
+
+**Example**
+
+```ts
+export default {
+ requestFullWindow() {
+ app.requestFullWindow({
+ duration: 200
+ })
+ }
+}
+```
+
+## AppResponse
+
+Defines the application response information.
+
+**System capability**: The items in the table below require different system capabilities. For details, see the table.
+
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- |-------- |
-| options | ScreenOnVisibleOptions | No| With keep-alive, the system is prevented from returning to the home screen when the screen is locked, so that the application is visible when the screen is woken up. |
+| appID6+ | string | Yes| Bundle name of an application. It uniquely identifies the application. **System capability**: SystemCapability.ArkUI.ArkUI.Full|
+| appName | string | Yes| Application name. **System capability**: SystemCapability.ArkUI.ArkUI.Lite|
+| versionName | string | Yes| Application version name. **System capability**: SystemCapability.ArkUI.ArkUI.Lite|
+| versionCode | number | Yes| Application version number. **System capability**: SystemCapability.ArkUI.ArkUI.Lite|
## ScreenOnVisibleOptions
diff --git a/en/application-dev/reference/apis/js-apis-system-prompt.md b/en/application-dev/reference/apis/js-apis-system-prompt.md
index 831a8acabb7735d67f119370155e13d1bf929ce0..6afc8a7634a31eb590d8ed9170372e7755db1e01 100644
--- a/en/application-dev/reference/apis/js-apis-system-prompt.md
+++ b/en/application-dev/reference/apis/js-apis-system-prompt.md
@@ -4,7 +4,7 @@ The **PromptAction** module provides APIs for creating and showing toasts, dialo
> **NOTE**
>
-> - The APIs of this module are no longer maintained since API version 8. You are advised to use [`@ohos.prompt`](js-apis-prompt.md) instead.
+> - The APIs of this module are deprecated since API version 8. You are advised to use [@ohos.promptAction](js-apis-promptAction.md) instead.
>
>
> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version.
diff --git a/en/application-dev/reference/apis/js-apis-taskpool.md b/en/application-dev/reference/apis/js-apis-taskpool.md
index 5e5fb1bbd6e67ef575778c601667f239b895e005..d05f7cdbed1cd756d195f442d368a73f74503c2f 100644
--- a/en/application-dev/reference/apis/js-apis-taskpool.md
+++ b/en/application-dev/reference/apis/js-apis-taskpool.md
@@ -16,6 +16,302 @@ The **TaskPool** APIs return error codes in numeric format. For details about th
```ts
import taskpool from '@ohos.taskpool';
```
+## taskpool.execute
+
+execute(func: Function, ...args: unknown[]): Promise\
+
+Places the function to be executed in the internal task queue of the task pool. The function will be distributed to the worker thread for execution. The function to be executed in this mode cannot be canceled.
+
+**System capability**: SystemCapability.Utils.Lang
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | --------- | ---- | ---------------------------------------------------------------------- |
+| func | Function | Yes | Function to be executed. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types). |
+| args | unknown[] | No | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.|
+
+**Return value**
+
+| Type | Description |
+| ----------------- | ------------------------------------ |
+| Promise\ | Promise used to return the result.|
+
+**Error codes**
+
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
+
+| ID| Error Message |
+| -------- | -------------------------------------------- |
+| 10200003 | Worker initialization failure. |
+| 10200006 | An exception occurred during serialization. |
+| 10200014 | The function is not mark as concurrent. |
+
+**Example**
+
+```ts
+@Concurrent
+function printArgs(args) {
+ console.log("printArgs: " + args);
+ return args;
+}
+
+taskpool.execute(printArgs, 100).then((value) => { // 100: test number
+ console.log("taskpool result: " + value);
+});
+```
+
+## taskpool.execute
+
+execute(task: Task, priority?: Priority): Promise\
+
+Places a task in the internal task queue of the task pool. The task will be distributed to the worker thread for execution. The task to be executed in this mode can be canceled.
+
+**System capability**: SystemCapability.Utils.Lang
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | --------------------- | ---- | ---------------------------------------- |
+| task | [Task](#task) | Yes | Task to be executed. |
+| priority | [Priority](#priority) | No | Priority of the task. The default value is **taskpool.Priority.MEDIUM**.|
+
+**Return value**
+
+| Type | Description |
+| ---------------- | ---------------- |
+| Promise\ | Promise used to return the result.|
+
+**Error codes**
+
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
+
+| ID| Error Message |
+| -------- | ------------------------------------------- |
+| 10200003 | Worker initialization failure. |
+| 10200006 | An exception occurred during serialization. |
+| 10200014 | The function is not mark as concurrent. |
+
+**Example**
+
+```ts
+@Concurrent
+function printArgs(args) {
+ console.log("printArgs: " + args);
+ return args;
+}
+
+let task = new taskpool.Task(printArgs, 100); // 100: test number
+taskpool.execute(task).then((value) => {
+ console.log("taskpool result: " + value);
+});
+```
+
+## taskpool.execute10+
+
+execute(group: TaskGroup, priority?: Priority): Promise
+
+Places a task group in the internal task queue of the task pool. The task group will be distributed to the worker thread for execution.
+
+**System capability**: SystemCapability.Utils.Lang
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| --------- | --------------------------- | ---- | -------------------------------------------------------------- |
+| group | [TaskGroup](#taskgroup) | Yes | Task group to be executed. |
+| priority | [Priority](#priority) | No | Priority of the task group. The default value is **taskpool.Priority.MEDIUM**.|
+
+**Return value**
+
+| Type | Description |
+| ---------------- | ---------------------------------- |
+| Promise\ | Promise used to return the result.|
+
+**Error codes**
+
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
+
+| ID| Error Message |
+| -------- | ------------------------------------------- |
+| 10200006 | An exception occurred during serialization. |
+
+**Example**
+
+```ts
+@Concurrent
+function printArgs(args) {
+ console.log("printArgs: " + args);
+ return args;
+}
+
+let taskGroup1 = new taskpool.TaskGroup();
+taskGroup1.addTask(printArgs, 10); // 10: test number
+taskGroup1.addTask(printArgs, 20); // 20: test number
+taskGroup1.addTask(printArgs, 30); // 30: test number
+
+let taskGroup2 = new taskpool.TaskGroup();
+let task1 = new taskpool.Task(printArgs, 100); // 100: test number
+let task2 = new taskpool.Task(printArgs, 200); // 200: test number
+let task3 = new taskpool.Task(printArgs, 300); // 300: test number
+taskGroup2.addTask(task1);
+taskGroup2.addTask(task2);
+taskGroup2.addTask(task3);
+taskpool.execute(taskGroup1).then((res) => {
+ console.info("taskpool execute res is:" + res);
+}).catch((e) => {
+ console.error("taskpool execute error is:" + e);
+});
+taskpool.execute(taskGroup2).then((res) => {
+ console.info("taskpool execute res is:" + res);
+}).catch((e) => {
+ console.error("taskpool execute error is:" + e);
+});
+```
+
+## taskpool.cancel
+
+cancel(task: Task): void
+
+Cancels a task in the task pool.
+
+**System capability**: SystemCapability.Utils.Lang
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | ------------- | ---- | -------------------- |
+| task | [Task](#task) | Yes | Task to cancel.|
+
+**Error codes**
+
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
+
+| ID| Error Message |
+| -------- | -------------------------------------------- |
+| 10200015 | The task does not exist when it is canceled. |
+| 10200016 | The task is executing when it is canceled. |
+
+Since API version 10, error code 10200016 is not reported when this API is called.
+
+**Example of canceling an ongoing task**
+
+```ts
+@Concurrent
+function inspectStatus(arg) {
+ // Check the cancellation status and return the result.
+ if (taskpool.Task.isCanceled()) {
+ console.log("task has been canceled before 2s sleep.");
+ return arg + 2;
+ }
+ // 2s sleep
+ let t = Date.now();
+ while (Date.now() - t < 2000) {
+ continue;
+ }
+ // Check the cancellation status again and return the result.
+ if (taskpool.Task.isCanceled()) {
+ console.log("task has been canceled after 2s sleep.");
+ return arg + 3;
+ }
+ return arg + 1;
+}
+
+let task1 = new taskpool.Task(inspectStatus, 100); // 100: test number
+let task2 = new taskpool.Task(inspectStatus, 200); // 200: test number
+let task3 = new taskpool.Task(inspectStatus, 300); // 300: test number
+let task4 = new taskpool.Task(inspectStatus, 400); // 400: test number
+let task5 = new taskpool.Task(inspectStatus, 500); // 500: test number
+let task6 = new taskpool.Task(inspectStatus, 600); // 600: test number
+taskpool.execute(task1).then((res)=>{
+ console.log("taskpool test result: " + res);
+}).catch((err) => {
+ console.log("taskpool test occur error: " + err);
+});
+let res2 = taskpool.execute(task2);
+let res3 = taskpool.execute(task3);
+let res4 = taskpool.execute(task4);
+let res5 = taskpool.execute(task5);
+let res6 = taskpool.execute(task6);
+// Cancel the task 1s later.
+setTimeout(()=>{
+ taskpool.cancel(task1);}, 1000);
+```
+
+## taskpool.cancel10+
+
+cancel(group: TaskGroup): void
+
+Cancels a task group in the task pool.
+
+**System capability**: SystemCapability.Utils.Lang
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ------- | ----------------------- | ---- | -------------------- |
+| group | [TaskGroup](#taskgroup) | Yes | Task group to cancel.|
+
+**Error codes**
+
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
+
+| ID| Error Message |
+| -------- | ------------------------------------------------------- |
+| 10200018 | The task group does not exist when it is canceled. |
+
+**Example**
+
+```ts
+@Concurrent
+function printArgs(args) {
+ let t = Date.now();
+ while (Date.now() - t < 2000) {
+ continue;
+ }
+ console.log("printArgs: " + args);
+ return args;
+}
+
+let taskGroup1 = new taskpool.TaskGroup();
+taskGroup1.addTask(printArgs, 10); // 10: test number
+let taskGroup2 = new taskpool.TaskGroup();
+taskGroup2.addTask(printArgs, 100); // 100: test number
+taskpool.execute(taskGroup1).then((res)=>{
+ console.info("taskGroup1 res is:" + res)
+});
+taskpool.execute(taskGroup2).then((res)=>{
+ console.info("taskGroup2 res is:" + res)
+});
+setTimeout(()=>{
+ try {
+ taskpool.cancel(taskGroup2);
+ } catch (e) {
+ console.log("taskGroup.cancel occur error:" + e);
+ }
+}, 1000);
+```
+
+
+## taskpool.getTaskPoolInfo10+
+
+getTaskPoolInfo(): TaskPoolInfo
+
+Obtains the internal information about this task pool.
+
+**System capability**: SystemCapability.Utils.Lang
+
+**Return value**
+
+| Type | Description |
+| ----------------------------------- | ------------------ |
+| [TaskPoolInfo](#taskpoolinfo10) | Internal information about the task pool. |
+
+**Example**
+
+```ts
+let taskpoolInfo = taskpool.getTaskPoolInfo();
+```
## Priority
@@ -67,7 +363,7 @@ for (let i = 0; i < allCount; i++) {
## Task
-Implements a task. Before using any of the following APIs, you must create a **Task** instance.
+Implements a task. Before calling any APIs in **Task**, you must use [constructor](#constructor) to create a **Task** instance.
### constructor
@@ -108,7 +404,7 @@ let task = new taskpool.Task(printArgs, "this is my first Task");
static isCanceled(): boolean
-Checks whether the running task is canceled.
+Checks whether the running task is canceled. Before using this API, you must create a **Task** instance.
**System capability**: SystemCapability.Utils.Lang
@@ -174,7 +470,7 @@ taskpool.execute(task).then((res)=>{
setTransferList(transfer?: ArrayBuffer[]): void
-Sets the task transfer list.
+Sets the task transfer list. Before using this API, you must create a **Task** instance.
> **NOTE**
>
@@ -212,183 +508,58 @@ taskpool.execute(task).then((res)=>{
console.error("test catch: " + e);
})
console.info("testTransfer view byteLength: " + view.byteLength);
-console.info("testTransfer view1 byteLength: " + view1.byteLength);
-```
-
-### Attributes
-
-**System capability**: SystemCapability.Utils.Lang
-
-| Name | Type | Readable| Writable| Description |
-| --------- | --------- | ---- | ---- | ------------------------------------------------------------------------- |
-| function | Function | Yes | Yes | Function to be passed in during task creation. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types). |
-| arguments | unknown[] | Yes | Yes | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).|
-
-## TaskGroup10+
-
-Implements a task group. Before using any of the following APIs, you must create a **TaskGroup** instance.
-
-### constructor10+
-
-constructor()
-
-Constructor used to create a **TaskGroup** instance.
-
-**System capability**: SystemCapability.Utils.Lang
-
-**Example**
-
-```ts
-let taskGroup = new taskpool.TaskGroup();
-```
-
-### addTask10+
-
-addTask(func: Function, ...args: unknown[]): void
-
-Adds the function to be executed to this task group.
-
-**System capability**: SystemCapability.Utils.Lang
-
-**Parameters**
-
-| Name| Type | Mandatory| Description |
-| ------ | --------- | ---- | ---------------------------------------------------------------------- |
-| func | Function | Yes | Function to be passed in for task execution. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types). |
-| args | unknown[] | No | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.|
-
-**Error codes**
-
-For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
-
-| ID| Error Message |
-| -------- | --------------------------------------- |
-| 10200014 | The function is not mark as concurrent. |
-
-**Example**
-
-```ts
-@Concurrent
-function printArgs(args) {
- console.log("printArgs: " + args);
- return args;
-}
-
-let taskGroup = new taskpool.TaskGroup();
-taskGroup.addTask(printArgs, 100); // 100: test number
-```
-
-### addTask10+
-
-addTask(task: Task): void
-
-Adds a created task to this task group.
-
-**System capability**: SystemCapability.Utils.Lang
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------- | --------------------- | ---- | ---------------------------------------- |
-| task | [Task](#task) | Yes | Task to be added to the task group. |
-
-**Error codes**
-
-For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
-
-| ID| Error Message |
-| -------- | --------------------------------------- |
-| 10200014 | The function is not mark as concurrent. |
-
-**Example**
-
-```ts
-@Concurrent
-function printArgs(args) {
- console.log("printArgs: " + args);
- return args;
-}
-
-let taskGroup = new taskpool.TaskGroup();
-let task = new taskpool.Task(printArgs, 200); // 200: test number
-taskGroup.addTask(task);
-```
-
-## taskpool.execute
-
-execute(func: Function, ...args: unknown[]): Promise\
+console.info("testTransfer view1 byteLength: " + view1.byteLength);
+```
-Places the function to be executed in the internal task queue of the task pool. The function will be distributed to the worker thread for execution. The function to be executed in this mode cannot be canceled.
+### Attributes
**System capability**: SystemCapability.Utils.Lang
-**Parameters**
+| Name | Type | Readable| Writable| Description |
+| --------- | --------- | ---- | ---- | ------------------------------------------------------------------------- |
+| function | Function | Yes | Yes | Function to be passed in during task creation. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types). |
+| arguments | unknown[] | Yes | Yes | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).|
-| Name| Type | Mandatory| Description |
-| ------ | --------- | ---- | ---------------------------------------------------------------------- |
-| func | Function | Yes | Function to be executed. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types). |
-| args | unknown[] | No | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.|
+## TaskGroup10+
-**Return value**
+Implements a task group. Before calling any APIs in **TaskGroup**, you must use [constructor](#constructor10) to create a **TaskGroup** instance.
-| Type | Description |
-| ----------------- | ------------------------------------ |
-| Promise\ | Promise used to return the result.|
+### constructor10+
-**Error codes**
+constructor()
-For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
+Constructor used to create a **TaskGroup** instance.
-| ID| Error Message |
-| -------- | -------------------------------------------- |
-| 10200003 | Worker initialization failure. |
-| 10200006 | An exception occurred during serialization. |
-| 10200014 | The function is not mark as concurrent. |
+**System capability**: SystemCapability.Utils.Lang
**Example**
```ts
-@Concurrent
-function printArgs(args) {
- console.log("printArgs: " + args);
- return args;
-}
-
-taskpool.execute(printArgs, 100).then((value) => { // 100: test number
- console.log("taskpool result: " + value);
-});
+let taskGroup = new taskpool.TaskGroup();
```
-## taskpool.execute
+### addTask10+
-execute(task: Task, priority?: Priority): Promise\
+addTask(func: Function, ...args: unknown[]): void
-Places a task in the internal task queue of the task pool. The task will be distributed to the worker thread for execution. The task to be executed in this mode can be canceled.
+Adds the function to be executed to this task group. Before using this API, you must create a **TaskGroup** instance.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | --------------------- | ---- | ---------------------------------------- |
-| task | [Task](#task) | Yes | Task to be executed. |
-| priority | [Priority](#priority) | No | Priority of the task. The default value is **taskpool.Priority.MEDIUM**.|
-
-**Return value**
-
-| Type | Description |
-| ---------------- | ---------------- |
-| Promise\ | Promise used to return the result.|
+| Name| Type | Mandatory| Description |
+| ------ | --------- | ---- | ---------------------------------------------------------------------- |
+| func | Function | Yes | Function to be passed in for task execution. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types). |
+| args | unknown[] | No | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.|
**Error codes**
For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
-| ID| Error Message |
-| -------- | ------------------------------------------- |
-| 10200003 | Worker initialization failure. |
-| 10200006 | An exception occurred during serialization. |
-| 10200014 | The function is not mark as concurrent. |
+| ID| Error Message |
+| -------- | --------------------------------------- |
+| 10200014 | The function is not mark as concurrent. |
**Example**
@@ -399,40 +570,31 @@ function printArgs(args) {
return args;
}
-let task = new taskpool.Task(printArgs, 100); // 100: test number
-taskpool.execute(task).then((value) => {
- console.log("taskpool result: " + value);
-});
+let taskGroup = new taskpool.TaskGroup();
+taskGroup.addTask(printArgs, 100); // 100: test number
```
-## taskpool.execute10+
+### addTask10+
-execute(group: TaskGroup, priority?: Priority): Promise
+addTask(task: Task): void
-Places a task group in the internal task queue of the task pool. The task group will be distributed to the worker thread for execution.
+Adds a created task to this task group. Before using this API, you must create a **TaskGroup** instance.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
-| Name | Type | Mandatory| Description |
-| --------- | --------------------------- | ---- | -------------------------------------------------------------- |
-| group | [TaskGroup](#taskgroup) | Yes | Task group to be executed. |
-| priority | [Priority](#priority) | No | Priority of the task group. The default value is **taskpool.Priority.MEDIUM**.|
-
-**Return value**
-
-| Type | Description |
-| ---------------- | ---------------------------------- |
-| Promise\ | Promise used to return the result.|
+| Name | Type | Mandatory| Description |
+| -------- | --------------------- | ---- | ---------------------------------------- |
+| task | [Task](#task) | Yes | Task to be added to the task group. |
**Error codes**
For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
-| ID| Error Message |
-| -------- | ------------------------------------------- |
-| 10200006 | An exception occurred during serialization. |
+| ID| Error Message |
+| -------- | --------------------------------------- |
+| 10200014 | The function is not mark as concurrent. |
**Example**
@@ -443,152 +605,72 @@ function printArgs(args) {
return args;
}
-let taskGroup1 = new taskpool.TaskGroup();
-taskGroup1.addTask(printArgs, 10); // 10: test number
-taskGroup1.addTask(printArgs, 20); // 20: test number
-taskGroup1.addTask(printArgs, 30); // 30: test number
-
-let taskGroup2 = new taskpool.TaskGroup();
-let task1 = new taskpool.Task(printArgs, 100); // 100: test number
-let task2 = new taskpool.Task(printArgs, 200); // 200: test number
-let task3 = new taskpool.Task(printArgs, 300); // 300: test number
-taskGroup2.addTask(task1);
-taskGroup2.addTask(task2);
-taskGroup2.addTask(task3);
-taskpool.execute(taskGroup1).then((res) => {
- console.info("taskpool execute res is:" + res);
-}).catch((e) => {
- console.error("taskpool execute error is:" + e);
-});
-taskpool.execute(taskGroup2).then((res) => {
- console.info("taskpool execute res is:" + res);
-}).catch((e) => {
- console.error("taskpool execute error is:" + e);
-});
+let taskGroup = new taskpool.TaskGroup();
+let task = new taskpool.Task(printArgs, 200); // 200: test number
+taskGroup.addTask(task);
```
-## taskpool.cancel
-cancel(task: Task): void
+## State10+
-Cancels a task in the task pool.
+Enumerates the task states.
**System capability**: SystemCapability.Utils.Lang
-**Parameters**
+| Name | Value | Description |
+| --------- | -------- | ------------- |
+| WAITING | 1 | The task is waiting.|
+| RUNNING | 2 | The task is running.|
+| CANCELED | 3 | The task is canceled.|
-| Name| Type | Mandatory| Description |
-| ------ | ------------- | ---- | -------------------- |
-| task | [Task](#task) | Yes | Task to cancel.|
-**Error codes**
+## TaskInfo10+
-For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
+Describes the internal information about a task.
-| ID| Error Message |
-| -------- | -------------------------------------------- |
-| 10200015 | The task does not exist when it is canceled. |
-| 10200016 | The task is executing when it is canceled. |
+**System capability**: SystemCapability.Utils.Lang
-Since API version 10, error code 10200016 is not reported when this API is called.
+### Attributes
-**Example of canceling an ongoing task**
+**System capability**: SystemCapability.Utils.Lang
-```ts
-@Concurrent
-function inspectStatus(arg) {
- // Check the task cancellation state and return the result.
- if (taskpool.Task.isCanceled()) {
- console.log("task has been canceled before 2s sleep.");
- return arg + 2;
- }
- // 2s sleep
- let t = Date.now();
- while (Date.now() - t < 2000) {
- continue;
- }
- // Check the task cancellation state again and return the result.
- if (taskpool.Task.isCanceled()) {
- console.log("task has been canceled after 2s sleep.");
- return arg + 3;
- }
- return arg + 1;
-}
+| Name | Type | Readable| Writable| Description |
+| -------- | ------------------ | ---- | ---- | ------------------------------------------------------------- |
+| taskId | number | Yes | No | Task ID. |
+| state | [State](#state10) | Yes | No | Task state. |
+| duration | number | Yes | No | Duration that the task has been executed, in ms. If the return value is **0**, the task is not running. If the return value is empty, no task is running. |
-let task1 = new taskpool.Task(inspectStatus, 100); // 100: test number
-let task2 = new taskpool.Task(inspectStatus, 200); // 200: test number
-let task3 = new taskpool.Task(inspectStatus, 300); // 300: test number
-let task4 = new taskpool.Task(inspectStatus, 400); // 400: test number
-let task5 = new taskpool.Task(inspectStatus, 500); // 500: test number
-let task6 = new taskpool.Task(inspectStatus, 600); // 600: test number
-taskpool.execute(task1).then((res)=>{
- console.log("taskpool test result: " + res);
-}).catch((err) => {
- console.log("taskpool test occur error: " + err);
-});
-let res2 = taskpool.execute(task2);
-let res3 = taskpool.execute(task3);
-let res4 = taskpool.execute(task4);
-let res5 = taskpool.execute(task5);
-let res6 = taskpool.execute(task6);
-// Cancel the task 1s later.
-setTimeout(()=>{
- taskpool.cancel(task1);}, 1000);
-```
+## ThreadInfo10+
-## taskpool.cancel10+
+Describes the internal information about a worker thread.
-cancel(group: TaskGroup): void
+**System capability**: SystemCapability.Utils.Lang
-Cancels a task group in the task pool.
+### Attributes
**System capability**: SystemCapability.Utils.Lang
-**Parameters**
+| Name | Type | Readable| Writable| Description |
+| -------- | ---------------------- | ---- | ---- | -------------------------------------------------------- |
+| tid | number | Yes | No | ID of the worker thread. If the return value is empty, no task is running. |
+| taskIds | number[] | Yes | No | IDs of tasks running on the calling thread. If the return value is empty, no task is running. |
+| priority | [Priority](#priority) | Yes | No | Priority of the calling thread. If the return value is empty, no task is running. |
-| Name | Type | Mandatory| Description |
-| ------- | ----------------------- | ---- | -------------------- |
-| group | [TaskGroup](#taskgroup) | Yes | Task group to cancel.|
+## TaskPoolInfo10+
-**Error codes**
+Describes the internal information about a task pool.
-For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
+**System capability**: SystemCapability.Utils.Lang
-| ID| Error Message |
-| -------- | ------------------------------------------------------- |
-| 10200018 | The task group does not exist when it is canceled. |
+### Attributes
-**Example**
+**System capability**: SystemCapability.Utils.Lang
-```ts
-@Concurrent
-function printArgs(args) {
- let t = Date.now();
- while (Date.now() - t < 2000) {
- continue;
- }
- console.log("printArgs: " + args);
- return args;
-}
+| Name | Type | Readable| Writable| Description |
+| ------------- | -------------------------------- | ---- | ---- | -------------------- |
+| threadInfos | [ThreadInfo[]](#threadinfo10) | Yes | No | Internal information about the worker threads. |
+| taskInfos | [TaskInfo[]](#taskinfo10) | Yes | No | Internal information about the tasks. |
-let taskGroup1 = new taskpool.TaskGroup();
-taskGroup1.addTask(printArgs, 10); // 10: test number
-let taskGroup2 = new taskpool.TaskGroup();
-taskGroup2.addTask(printArgs, 100); // 100: test number
-taskpool.execute(taskGroup1).then((res)=>{
- console.info("taskGroup1 res is:" + res)
-});
-taskpool.execute(taskGroup2).then((res)=>{
- console.info("taskGroup2 res is:" + res)
-});
-setTimeout(()=>{
- try {
- taskpool.cancel(taskGroup2);
- } catch (e) {
- console.log("taskGroup.cancel occur error:" + e);
- }
-}, 1000);
-```
## Additional Information
@@ -720,7 +802,7 @@ func2();
// Success in canceling a task
@Concurrent
function inspectStatus(arg) {
- // Check the task cancellation state and return the result.
+ // Check the cancellation status and return the result.
if (taskpool.Task.isCanceled()) {
console.log("task has been canceled before 2s sleep.");
return arg + 2;
@@ -730,7 +812,7 @@ function inspectStatus(arg) {
while (Date.now() - t < 2000) {
continue;
}
- // Check the task cancellation state again and return the result.
+ // Check the cancellation status again and return the result.
if (taskpool.Task.isCanceled()) {
console.log("task has been canceled after 2s sleep.");
return arg + 3;
@@ -836,3 +918,64 @@ async function taskpoolGroupCancelTest() {
taskpoolGroupCancelTest()
```
+
+**Example 8**
+
+```ts
+// Create and execute 100 tasks with different priorities, and view their information.
+@Concurrent
+function delay() {
+ let start = new Date().getTime();
+ while (new Date().getTime() - start < 500) {
+ continue;
+ }
+}
+
+let highCount = 0;
+let mediumCount = 0;
+let lowCount = 0;
+let allCount = 100;
+for (let i = 0; i < allCount; i++) {
+ let task1 = new taskpool.Task(delay);
+ let task2 = new taskpool.Task(delay);
+ let task3 = new taskpool.Task(delay);
+ taskpool.execute(task1, taskpool.Priority.LOW).then(() => {
+ lowCount++;
+ }).catch((e) => {
+ console.error("low task error: " + e);
+ })
+ taskpool.execute(task2, taskpool.Priority.MEDIUM).then(() => {
+ mediumCount++;
+ }).catch((e) => {
+ console.error("medium task error: " + e);
+ })
+ taskpool.execute(task3, taskpool.Priority.HIGH).then(() => {
+ highCount++;
+ }).catch((e) => {
+ console.error("high task error: " + e);
+ })
+}
+let start = new Date().getTime();
+while (new Date().getTime() - start < 1000) {
+ continue;
+}
+let taskpoolInfo = taskpool.getTaskPoolInfo();
+let tid = 0;
+let taskIds = [];
+let priority = 0;
+let taskId = 0;
+let state = 0;
+let duration = 0;
+for(let threadInfo of taskpoolInfo.threadInfos) {
+ tid = threadInfo.tid;
+ taskIds.length = threadInfo.taskIds.length;
+ priority = threadInfo.priority;
+ console.info("taskpool---tid is:" + tid + ", taskIds is:" + taskIds + ", priority is:" + priority);
+}
+for(let taskInfo of taskpoolInfo.taskInfos) {
+ taskId = taskInfo.taskId;
+ state = taskInfo.state;
+ duration = taskInfo.duration;
+ console.info("taskpool---taskId is:" + taskId + ", state is:" + state + ", duration is:" + duration);
+}
+```
diff --git a/en/application-dev/reference/apis/js-apis-userFileManager.md b/en/application-dev/reference/apis/js-apis-userFileManager.md
index d3732ddaf19e0014dc9f77681241253b37aa91eb..ba865a7568afeae0feb7dfbf84f080652b9dc726 100644
--- a/en/application-dev/reference/apis/js-apis-userFileManager.md
+++ b/en/application-dev/reference/apis/js-apis-userFileManager.md
@@ -1393,6 +1393,151 @@ async function example() {
}
```
+### getPhotoIndex10+
+
+getPhotoIndex(photoUri: string, albumUri: string, options: FetchOptions, callback: AsyncCallback<number>): void
+
+Obtains the index of an image or video in an album. This API uses an asynchronous callback to return the result.
+
+**System API**: This is a system API.
+
+**Required permissions**: ohos.permission.READ_IMAGEVIDEO
+
+**System capability**: SystemCapability.FileManagement.UserFileManager.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ------------------------- | ---- | ---------- |
+| photoUri | string | Yes | URI of the media asset whose index is to be obtained.|
+| albumUri | string | Yes | Album URI, which can be an empty string. If it is an empty string, all the media assets in the Gallery are obtained by default. |
+| options | [FetchOptions](#fetchoptions) | Yes | Fetch options. Only one search condition or sorting mode must be set in **predicates**. If no value is set or multiple search conditions or sorting modes are set, the API cannot be called successfully. |
+
+**Return value**
+
+| Type | Description |
+| --------------------------------------- | ----------------- |
+| AsyncCallback<number>| Callback invoked to return the index obtained.|
+
+**Error codes**
+
+For details about the error codes, see [Universal Error Codes](../errorcodes/errorcode-universal.md).
+
+| ID| Error Message|
+| -------- | ---------------------------------------- |
+| 401 | if parameter is invalid. |
+
+**Example**
+
+```ts
+import dataSharePredicates from '@ohos.data.dataSharePredicates';
+
+async function example() {
+ console.info('getPhotoIndexDemo');
+ let predicatesForGetAsset = new dataSharePredicates.DataSharePredicates();
+ let fetchOp = {
+ fetchColumns: [],
+ predicates: predicatesForGetAsset
+ };
+ //Obtain the uri of the album
+ let albumFetchResult = await mgr.getAlbums(userFileManager.AlbumType.SYSTEM, userFileManager.AlbumSubtype.FAVORITE, fetchOp);
+ let album = await albumFetchResult.getFirstObject();
+
+ let predicates = new dataSharePredicates.DataSharePredicates();
+ predicates.orderByAsc("add_modified");
+ let fetchOptions = {
+ fetchColumns: [],
+ predicates: predicates
+ };
+ let photoFetchResult = await album.getPhotoAssets(fetchOptions);
+ let expectIndex = 1;
+ //Obtain the uri of the second file
+ let photoAsset = await photoFetchResult.getPositionObject(expectIndex);
+
+ mgr.getPhotoIndex(photoAsset.uri, album.albumUri, fetchOptions, (err, index) => {
+ try {
+ if (err == undefined) {
+ console.info(`getPhotoIndex successfully and index is : ${index}`);
+ } else {
+ console.info(`getPhotoIndex failed;`);
+ }
+ } catch (error) {
+ console.info(`getPhotoIndex failed; error: ${error}`);
+ }
+ }
+}
+```
+
+### getPhotoIndex10+
+
+getPhotoIndex(photoUri: string, albumUri: string, options: FetchOptions): Promise<number>
+
+Obtains the index of an image or video in an album. This API uses a promise to return the result.
+
+**System API**: This is a system API.
+
+**Required permissions**: ohos.permission.READ_IMAGEVIDEO
+
+**System capability**: SystemCapability.FileManagement.UserFileManager.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ------------------------- | ---- | ---------- |
+| photoUri | string | Yes | URI of the media asset whose index is to be obtained.|
+| albumUri | string | Yes | Album URI, which can be an empty string. If it is an empty string, all the media assets in the Gallery are obtained by default. |
+| options | [FetchOptions](#fetchoptions) | Yes | Fetch options. Only one search condition or sorting mode must be set in **predicates**. If no value is set or multiple search conditions or sorting modes are set, the API cannot be called successfully. |
+
+**Return value**
+
+| Type | Description |
+| --------------------------------------- | ----------------- |
+| Promise<number>| Promise used to return the index obtained.|
+
+**Error codes**
+
+For details about the error codes, see [Universal Error Codes](../errorcodes/errorcode-universal.md).
+
+| ID| Error Message|
+| -------- | ---------------------------------------- |
+| 401 | if parameter is invalid. |
+
+**Example**
+
+```ts
+import dataSharePredicates from '@ohos.data.dataSharePredicates';
+
+async function example() {
+ console.info('getPhotoIndexDemo');
+ let predicatesForGetAsset = new dataSharePredicates.DataSharePredicates();
+ let fetchOp = {
+ fetchColumns: [],
+ predicates: predicatesForGetAsset
+ };
+ //Obtain the uri of the album
+ let albumFetchResult = await mgr.getAlbums(userFileManager.AlbumType.SYSTEM, userFileManager.AlbumSubtype.FAVORITE, fetchOp);
+ let album = await albumFetchResult.getFirstObject();
+
+ let predicates = new dataSharePredicates.DataSharePredicates();
+ predicates.orderByAsc("add_modified");
+ let fetchOptions = {
+ fetchColumns: [],
+ predicates: predicates
+ };
+ let photoFetchResult = await album.getPhotoAssets(fetchOptions);
+ let expectIndex = 1;
+ //Obtain the uri of the second file
+ let photoAsset = await photoFetchResult.getPositionObject(expectIndex);
+
+ mgr.getPhotoIndex(photoAsset.uri, album.albumUri, fetchOptions)
+ .then((index) => {
+ console.info(`getPhotoIndex successfully and index is : ${index}`);
+ }).catch((err) => {
+ console.info(`getPhotoIndex failed; error: ${err}`);
+ })
+}
+```
+
### release
release(callback: AsyncCallback<void>): void
@@ -1684,7 +1829,7 @@ Provides APIs for encapsulating file asset attributes.
| Name | Type | Readable| Writable| Description |
| ------------------------- | ------------------------ | ---- | ---- | ------------------------------------------------------ |
-| uri | string | Yes | No | File asset URI, for example, **file://media/image/2**. |
+| uri | string | Yes | No | File asset URI, for example, **file://media/Photo/1/IMG_datetime_0001/displayName.jpg**. |
| fileType | [FileType](#filetype) | Yes | No | Type of the file. |
| displayName | string | Yes | Yes | File name, including the file name extension, to display. |
@@ -2350,6 +2495,282 @@ async function example() {
}
```
+### getExif10+
+
+getExif(): Promise<string>
+
+Obtains a JSON string consisting of the exchangeable image file format (EXIF) tags of this JPG image. This API uses a promise to return the result.
+
+**CAUTION** This API returns a JSON string consisting of EXIF tags. The complete EXIF information consists of **all_exif** and **ImageVideoKey.USER_COMMENT**. These two fields must be passed in via **fetchColumns**.
+
+**System API**: This is a system API.
+
+**Required permissions**: ohos.permission.READ_IMAGEVIDEO
+
+**System capability**: SystemCapability.FileManagement.UserFileManager.Core
+
+**Return value**
+
+| Type | Description |
+| --------------------------------------- | ----------------- |
+| Promise<string> | Promise used to return the JSON string obtained.|
+
+**Supported EXIF tags**
+
+For details about the EXIF tags, see [image.PropertyKey](js-apis-image.md#propertykey7).
+
+| Key Value | Description |
+| --------------------------------------- | ----------------- |
+| BitsPerSample | Number of bits per pixel.|
+| Orientation | Image orientation.|
+| ImageLength | Image length.|
+| ImageWidth | Image width.|
+| GPSLatitude | GPS latitude of the image.|
+| GPSLongitude | GPS longitude of the image.|
+| GPSLatitudeRef | Longitude reference, for example, W or E.|
+| GPSLongitudeRef | Latitude reference, for example, N or S.|
+| DateTimeOriginal | Shooting time.|
+| ExposureTime | Exposure time.|
+| SceneType | Shooting scene type.|
+| ISOSpeedRatings | ISO sensitivity or speed.|
+| FNumber | f-number.|
+| DateTime | Date and time when the image was last modified.|
+| GPSTimeStamp | GPS timestamp.|
+| GPSDateStamp | GPS date stamp.|
+| ImageDescription | Image description.|
+| Make | Camera vendor.|
+| Model | Model.|
+| PhotoMode | Photo mode.|
+| SensitivityType | Sensitivity type.|
+| StandardOutputSensitivity | Standard output sensitivity.|
+| RecommendedExposureIndex | Recommended exposure index.|
+| ApertureValue | Aperture value.|
+| MeteringMode | Metering mode.|
+| LightSource | Light source.|
+| Flash | Flash status.|
+| FocalLength | Focal length.|
+| UserComment | User comment.|
+| PixelXDimension | Pixel X dimension.|
+| PixelYDimension | Pixel Y dimension.|
+| WhiteBalance | White balance.|
+| FocalLengthIn35mmFilm | Focal length in 35 mm film.|
+| ExposureBiasValue | Exposure compensation.|
+
+**Example**
+
+```ts
+import dataSharePredicates from '@ohos.data.dataSharePredicates';
+
+async function example() {
+ try {
+ console.info('getExifDemo');
+ let predicates = new dataSharePredicates.DataSharePredicates();
+ let fetchOptions = {
+ fetchColumns: [ 'all_exif', ImageVideoKey.USER_COMMENT],
+ predicates: predicates
+ };
+ let fetchResult = await mgr.getPhotoAssets(fetchOptions);
+ let fileAsset = await fetchResult.getFirstObject();
+ let exifMessage = await fileAsset.getExif();
+ let userCommentKey = 'UserComment';
+ let userComment = JSON.stringify(JSON.parse(exifMessage), [userCommentKey]);
+ fetchResult.close();
+ } catch (err) {
+ console.error('getExifDemoCallback failed with error: ' + err);
+ }
+}
+```
+
+### getExif10+
+
+getExif(callback: AsyncCallback<string>): void
+
+Obtains a JSON string consisting of the EXIF tags of this JPG image. This API uses an asynchronous callback to return the result.
+
+**CAUTION** This API returns a JSON string consisting of EXIF tags. The complete EXIF information consists of **all_exif** and **ImageVideoKey.USER_COMMENT**. These two fields must be passed in via **fetchColumns**.
+
+**System API**: This is a system API.
+
+**Required permissions**: ohos.permission.READ_IMAGEVIDEO
+
+**System capability**: SystemCapability.FileManagement.UserFileManager.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ------------------------- | ---- | ---------- |
+| callback | AsyncCallback<string> | Yes | Callback invoked to return the JSON string obtained.|
+
+**Supported EXIF tags**
+
+For details about the EXIF tags, see [image.PropertyKey](js-apis-image.md#propertykey7).
+
+| Key Value | Description |
+| --------------------------------------- | ----------------- |
+| BitsPerSample | Number of bits per pixel.|
+| Orientation | Image orientation.|
+| ImageLength | Image length.|
+| ImageWidth | Image width.|
+| GPSLatitude | GPS latitude of the image.|
+| GPSLongitude | GPS longitude of the image.|
+| GPSLatitudeRef | Longitude reference, for example, W or E.|
+| GPSLongitudeRef | Latitude reference, for example, N or S.|
+| DateTimeOriginal | Shooting time.|
+| ExposureTime | Exposure time.|
+| SceneType | Shooting scene type.|
+| ISOSpeedRatings | ISO sensitivity or speed.|
+| FNumber | f-number.|
+| DateTime | Date and time when the image was last modified.|
+| GPSTimeStamp | GPS timestamp.|
+| GPSDateStamp | GPS date stamp.|
+| ImageDescription | Image description.|
+| Make | Camera vendor.|
+| Model | Model.|
+| PhotoMode | Photo mode.|
+| SensitivityType | Sensitivity type.|
+| StandardOutputSensitivity | Standard output sensitivity.|
+| RecommendedExposureIndex | Recommended exposure index.|
+| ApertureValue | Aperture value.|
+| MeteringMode | Metering mode.|
+| LightSource | Light source.|
+| Flash | Flash status.|
+| FocalLength | Focal length.|
+| UserComment | User comment.|
+| PixelXDimension | Pixel X dimension.|
+| PixelYDimension | Pixel Y dimension.|
+| WhiteBalance | White balance.|
+| FocalLengthIn35mmFilm | Focal length in 35 mm film.|
+| ExposureBiasValue | Exposure compensation.|
+
+**Example**
+
+```ts
+import dataSharePredicates from '@ohos.data.dataSharePredicates';
+
+async function example() {
+ try {
+ console.info('getExifDemo');
+ let predicates = new dataSharePredicates.DataSharePredicates();
+ let fetchOptions = {
+ fetchColumns: [ 'all_exif', ImageVideoKey.USER_COMMENT],
+ predicates: predicates
+ };
+ let fetchResult = await mgr.getPhotoAssets(fetchOptions);
+ let fileAsset = await fetchResult.getFirstObject();
+ let userCommentKey = 'UserComment';
+ fileAsset.getExif((err, exifMessage) => {
+ if (exifMessage != undefined) {
+ let userComment = JSON.stringify(JSON.parse(exifMessage), [userCommentKey]);
+ } else {
+ console.error('getExif failed, message = ', err);
+ }
+ });
+ fetchResult.close();
+ } catch (err) {
+ console.error('getExifDemoCallback failed with error: ' + err);
+ }
+}
+```
+
+### setUserComment10+
+
+setUserComment(userComment: string): Promise<void>
+
+Sets user comment information of an image or video. This API uses a promise to return the result.
+
+**NOTE** This API can be used to modify the comment information of only images or videos.
+
+**System API**: This is a system API.
+
+**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO
+
+**System capability**: SystemCapability.FileManagement.UserFileManager.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ------------------------- | ---- | ---------- |
+| userComment | string | Yes | User comment information to set, which cannot exceed 140 characters.|
+
+**Return value**
+
+| Type | Description |
+| --------------------------------------- | ----------------- |
+|Promise<void> | Promise that returns no value.|
+
+**Example**
+
+```ts
+import dataSharePredicates from '@ohos.data.dataSharePredicates';
+
+async function example() {
+ try {
+ console.info('setUserCommentDemo')
+ let predicates = new dataSharePredicates.DataSharePredicates();
+ let fetchOptions = {
+ fetchColumns: [],
+ predicates: predicates
+ };
+ let fetchResult = await mgr.getPhotoAssets(fetchOptions);
+ let fileAsset = await fetchResult.getFirstObject();
+ let userComment = 'test_set_user_comment';
+ await fileAsset.setUserComment(userComment);
+ } catch (err) {
+ console.error('setUserCommentDemoCallback failed with error: ' + err);
+ }
+}
+```
+
+### setUserComment10+
+
+setUserComment(userComment: string, callback: AsyncCallback<void>): void
+
+Sets user comment information of an image or video. This API uses an asynchronous callback to return the result.
+
+**NOTE** This API can be used to modify the comment information of only images or videos.
+
+**System API**: This is a system API.
+
+**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO
+
+**System capability**: SystemCapability.FileManagement.UserFileManager.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ------------------------- | ---- | ---------- |
+| userComment | string | Yes | User comment information to set, which cannot exceed 140 characters.|
+| callback | AsyncCallback<void> | Yes | Callback that returns no value.|
+
+**Example**
+
+```ts
+import dataSharePredicates from '@ohos.data.dataSharePredicates';
+
+async function example() {
+ try {
+ console.info('setUserCommentDemo')
+ let predicates = new dataSharePredicates.DataSharePredicates();
+ let fetchOptions = {
+ fetchColumns: [],
+ predicates: predicates
+ };
+ let fetchResult = await mgr.getPhotoAssets(fetchOptions);
+ let fileAsset = await fetchResult.getFirstObject();
+ let userComment = 'test_set_user_comment';
+ fileAsset.setUserComment(userComment, (err) => {
+ if (err === undefined) {
+ console.info('setUserComment successfully');
+ } else {
+ console.error('setUserComment failed with error: ' + err);
+ }
+ });
+ } catch (err) {
+ console.error('setUserCommentDemoCallback failed with error: ' + err);
+ }
+}
+```
+
## FetchResult
Provides APIs to manage the file retrieval result.
@@ -3962,6 +4383,7 @@ Defines the key information about an image or video file.
| DATE_TRASHED10+ | date_trashed | Date when the file was deleted. The value is the number of seconds between the time when the file is deleted and January 1, 1970. |
| HIDDEN10+ | hidden | Whether the file is hidden. |
| CAMERA_SHOT_KEY10+ | camera_shot_key | Key for the Untra Snamshot feature, which allows the camera to take photos or record videos with the screen off. (This parameter is available only for the system camera, and the key value is defined by the system camera.) |
+| USER_COMMENT10+ | user_comment | User comment information. |
## AlbumKey
diff --git a/en/application-dev/reference/apis/js-apis-useriam-userauth.md b/en/application-dev/reference/apis/js-apis-useriam-userauth.md
index afd7b427b60c35f19e1f8f16ce68e7d8f0f19e70..84dacee24d644d4f87ecf5eb41ba3b0befaf811d 100644
--- a/en/application-dev/reference/apis/js-apis-useriam-userauth.md
+++ b/en/application-dev/reference/apis/js-apis-useriam-userauth.md
@@ -19,6 +19,8 @@ Enumerates the window types of the authentication widget.
**System capability**: SystemCapability.UserIAM.UserAuth.Core
+**System API**: This is a system API.
+
| Name | Value | Description |
| ---------- | ---- | ---------- |
| DIALOG_BOX | 1 | Dialog box.|
@@ -30,35 +32,35 @@ Defines the user authentication parameters.
**System capability**: SystemCapability.UserIAM.UserAuth.Core
-| Name | Type | Mandatory| Description |
-| -------------- | ---------------------------------- | ---- | -------------------------------------- |
-| challenge | Uint8Array | Yes | Challenge value. The maximum length is 32 bytes. The value can be **null**.|
-| authType | [UserAuthType](#userauthtype8)[] | Yes | Authentication type. |
-| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Authentication trust level. |
+| Name | Type | Mandatory| Description |
+| -------------- | ---------------------------------- | ---- | ------------------------------------------------------ |
+| challenge | Uint8Array | Yes | Challenge value, which is used to prevent replay attacks. The challenge value can be null and cannot exceed 32 bytes.|
+| authType | [UserAuthType](#userauthtype8)[] | Yes | Authentication type list, which specifies the authentications provided on the user authentication page.|
+| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Authentication trust level. |
## WidgetParam10+
-Defines the parameters of the authentication widget.
+Represents the information presented on the user authentication page.
**System capability**: SystemCapability.UserIAM.UserAuth.Core
-| Name | Type | Mandatory| Description |
-| -------------------- | ----------------------------------- | ---- | -------------------- |
-| title | string | Yes | Title of the authentication component. |
-| navigationButtonText | string | No | Description text of the navigation button.|
-| windowModeType | [WindowModeType](#windowmodetype10) | No | Type of the window. |
+| Name | Type | Mandatory| Description |
+| -------------------- | ----------------------------------- | ---- | ------------------------------------------------------------ |
+| title | string | Yes | Title of the user authentication page. It cannot exceed 500 characters. |
+| navigationButtonText | string | No | Text on the navigation button. It cannot exceed 60 characters. |
+| windowMode | [WindowModeType](#windowmodetype10) | No | Display format of the user authentication page. The default value is **WindowModeType.DIALOG_BOX**. **System API**: This is a system API.|
## UserAuthResult10+
-Defines the user authentication result.
+Defines the user authentication result. If the authentication is successful, the authentication type and information about the token that has passed the authentication are returned.
**System capability**: SystemCapability.UserIAM.UserAuth.Core
| Name | Type | Mandatory| Description |
| -------- | ------------------------------ | ---- | ------------------------------------------------------------ |
| result | number | Yes | User authentication result. If the operation is successful, **0** is returned. If the operation fails, an error code is returned. For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md).|
-| token | Uint8Array | No | Authentication token information. |
-| authType | [UserAuthType](#userauthtype8) | No | Authentication type. |
+| token | Uint8Array | No | Token that has passed the authentication. |
+| authType | [UserAuthType](#userauthtype8) | No | Type of the authentication. |
## IAuthCallback10+
@@ -75,51 +77,43 @@ Called to return the authentication result.
**Parameters**
-| Name| Type | Mandatory| Description |
-| ------ | ---------------------------------- | ---- | ---------- |
-| result | [UserAuthResult](userauthresult10) | Yes | Authentication result.|
+| Name| Type | Mandatory| Description |
+| ------ | ----------------------------------- | ---- | ---------- |
+| result | [UserAuthResult](#userauthresult10) | Yes | Authentication result.|
**Example**
```js
-import userIAM_userAuth from '@ohos.userIAM.userAuth';
-
-AuthParam authParam = {
- challenge: new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
- authType: userIAM_userAuth.UserAuthType.PIN;
- authTrustLevel: userIAM_userAuth.AuthTrustLevel.ATL1;
-}
-WidgetParam widgetParam = {
- title: "Enter Password";
- windowMode: userIAM_userAuth.WindowModeType.DIALOG_BOX;
-}
-let userAuthInstance;
-try {
- userAuthInstance = userIAM_userAuth.getUserAuthInstance(authParam, widgetParam);
- console.info("get userAuth instance success");
-} catch (error) {
- console.info("get userAuth instance failed, error = " + error);
-}
-
+import userAuth from '@ohos.userIAM.userAuth';
+
+const authParam = {
+ challenge: new Uint8Array([49, 49, 49, 49, 49, 49]),
+ authType: [userAuth.UserAuthType.PIN],
+ authTrustLevel: 10000,
+};
+const widgetParam = {
+ title:'Enter password',
+ navigationButtonText: 'Back',
+ windowMode: userAuth.WindowModeType.DIALOG_BOX,
+};
try {
+ let userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
+ console.log('get userAuth instance success');
userAuthInstance.on('result', {
- callback: onResult(result) {
- console.log("authV10 result " + result.result);
- console.log("authV10 token " + result.token);
- console.log("authV10 authType " + result.authType);
+ onResult (result) {
+ console.log('userAuthInstance callback result = ' + JSON.stringify(result));
}
- });
- console.info("subscribe authentication event success");
+ });
+ console.log('auth on success');
} catch (error) {
- console.info("subscribe authentication event failed" + error);
- //do error
+ console.log('auth catch error: ' + JSON.stringify(error));
}
```
## UserAuthInstance10+
Provides APIs for user authentication. The user authentication widget is supported.
-Before using the APIs, you need to obtain a **UserAuthInstance** instance by using [getUserAuthInstance](#useriam_userauthgetuserauthinstance10).
+Before using the APIs, you need to obtain a **UserAuthInstance** instance by using [getUserAuthInstance](#getuserauthinstance10).
### on10+
@@ -131,10 +125,10 @@ Subscribes to the user authentication result.
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | -------------------------------- | ---- | ------------------------------------------ |
-| type | 'result' | Yes | Event type to subscribe to. **result** indicates the authentication result.|
-| callback | [IAuthCallback](iauthcallback10) | Yes | Callback invoked to return the user authentication result. |
+| Name | Type | Mandatory| Description |
+| -------- | --------------------------------- | ---- | ------------------------------------------ |
+| type | 'result' | Yes | Event type to subscribe to. **result** indicates the authentication result.|
+| callback | [IAuthCallback](#iauthcallback10) | Yes | Callback invoked to return the user authentication result. |
**Error codes**
@@ -148,37 +142,29 @@ For details about the error codes, see [User Authentication Error Codes](../erro
**Example**
```js
-import userIAM_userAuth from '@ohos.userIAM.userAuth';
-
-AuthParam authParam = {
- challenge: new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
- authType: userIAM_userAuth.UserAuthType.PIN;
- authTrustLevel: userIAM_userAuth.AuthTrustLevel.ATL1;
-}
-WidgetParam widgetParam = {
- title: "Enter Password";
- windowMode: userIAM_userAuth.WindowModeType.DIALOG_BOX;
-}
-let userAuthInstance;
-try {
- userAuthInstance = userIAM_userAuth.getUserAuthInstance(authParam, widgetParam);
- console.info("get userAuth instance success");
-} catch (error) {
- console.info("get userAuth instance failed, error = " + error);
-}
-
+import userAuth from '@ohos.userIAM.userAuth';
+
+const authParam = {
+ challenge: new Uint8Array([49, 49, 49, 49, 49, 49]),
+ authType: [userAuth.UserAuthType.PIN],
+ authTrustLevel: 10000,
+};
+const widgetParam = {
+ title:'Enter password',
+ navigationButtonText: 'Back',
+ windowMode: userAuth.WindowModeType.DIALOG_BOX,
+};
try {
+ let userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
+ console.log('get userAuth instance success');
userAuthInstance.on('result', {
- callback: onResult(result) {
- console.log("authV10 result " + result.result);
- console.log("authV10 token " + result.token);
- console.log("authV10 authType " + result.authType);
+ onResult (result) {
+ console.log('userAuthInstance callback result = ' + JSON.stringify(result));
}
- });
- console.info("subscribe authentication event success");
+ });
+ console.log('auth on success');
} catch (error) {
- console.info("subscribe authentication event failed" + error);
- //do error
+ console.log('auth catch error: ' + JSON.stringify(error));
}
```
@@ -194,10 +180,10 @@ Unsubscribes from the user authentication result.
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | -------------------------------- | ---- | ------------------------------------------ |
+| Name | Type | Mandatory| Description |
+| -------- | --------------------------------- | ---- | ------------------------------------------ |
| type | 'result' | Yes | Event type to unsubscribe from. **result** indicates the authentication result.|
-| callback | [IAuthCallback](iauthcallback10) | No | Callback for the user authentication result. |
+| callback | [IAuthCallback](#iauthcallback10) | No | Callback for the user authentication result. |
**Error codes**
@@ -211,46 +197,29 @@ For details about the error codes, see [User Authentication Error Codes](../erro
**Example**
```js
-import userIAM_userAuth from '@ohos.userIAM.userAuth';
-
-AuthParam authParam = {
- challenge: new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
- authType: userIAM_userAuth.UserAuthType.PIN;
- authTrustLevel: userIAM_userAuth.AuthTrustLevel.ATL1;
-}
-WidgetParam widgetParam = {
- title: "Enter Password";
- windowMode: userIAM_userAuth.WindowModeType.DIALOG_BOX;
-}
-let userAuthInstance;
-try {
- userAuthInstance = userIAM_userAuth.getUserAuthInstance(authParam, widgetParam);
- console.info("get userAuth instance success");
-} catch (error) {
- console.info("get userAuth instance failed, error = " + error);
-}
-
-// Subscribe to the authentication result.
+import userAuth from '@ohos.userIAM.userAuth';
+
+const authParam = {
+ challenge: new Uint8Array([49, 49, 49, 49, 49, 49]),
+ authType: [userAuth.UserAuthType.PIN],
+ authTrustLevel: 10000,
+};
+const widgetParam = {
+ title:'Enter password',
+ navigationButtonText: 'Back',
+ windowMode: userAuth.WindowModeType.DIALOG_BOX,
+};
try {
- userAuthInstance.on('result', {
- callback: onResult(result) {
- console.log("authV10 result " + result.result);
- console.log("authV10 token " + result.token);
- console.log("authV10 authType " + result.authType);
+ let userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
+ console.log('get userAuth instance success');
+ userAuthInstance.off('result', {
+ onResult (result) {
+ console.log('auth off result: ' + JSON.stringify(result));
}
- });
- console.info("subscribe authentication event success");
-} catch (error) {
- console.info("subscribe authentication event failed" + error);
- //do error
-}
-// Unsubscribe from the authentication result.
-try {
- userAuthInstance.off('result');
- console.info("cancel subscribe authentication event success");
+ });
+ console.log('auth off success');
} catch (error) {
- console.info("cancel subscribe authentication event failed" + error);
- //do error
+ console.log('auth catch error: ' + JSON.stringify(error));
}
```
@@ -286,31 +255,25 @@ For details about the error codes, see [User Authentication Error Codes](../erro
**Example**
```js
-import userIAM_userAuth from '@ohos.userIAM.userAuth';
-
-AuthParam authParam = {
- challenge: new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
- authType: userIAM_userAuth.UserAuthType.PIN;
- authTrustLevel: userIAM_userAuth.AuthTrustLevel.ATL1;
-}
-WidgetParam widgetParam = {
- title: "Enter Password";
- windowMode: userIAM_userAuth.WindowModeType.DIALOG_BOX;
-}
-let userAuthInstance;
-try {
- userAuthInstance = userIAM_userAuth.getUserAuthInstance(authParam, widgetParam);
- console.info("get userAuth instance success");
-} catch (error) {
- console.info("get userAuth instance failed, error = " + error);
-}
-
+import userAuth from '@ohos.userIAM.userAuth';
+
+const authParam = {
+ challenge: new Uint8Array([49, 49, 49, 49, 49, 49]),
+ authType: [userAuth.UserAuthType.PIN],
+ authTrustLevel: 10000,
+};
+const widgetParam = {
+ title:'Enter password',
+ navigationButtonText: 'Back',
+ windowMode: userAuth.WindowModeType.DIALOG_BOX,
+};
try {
+ let userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
+ console.log('get userAuth instance success');
userAuthInstance.start();
- console.info("userAuthInstanceV10 start auth success");
+ console.log('auth start success');
} catch (error) {
- console.info("userAuthInstanceV10 start auth failed, error = " + error);
- //do error
+ console.log('auth catch error: ' + JSON.stringify(error));
}
```
@@ -337,46 +300,29 @@ Cancels this authentication.
**Example**
```js
-import userIAM_userAuth from '@ohos.userIAM.userAuth';
-
-AuthParam authParam = {
- challenge: new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
- authType: userIAM_userAuth.UserAuthType.PIN;
- authTrustLevel: userIAM_userAuth.AuthTrustLevel.ATL1;
-}
-WidgetParam widgetParam = {
- title: "Enter Password";
- windowMode: userIAM_userAuth.WindowModeType.DIALOG_BOX;
-}
-
-let userAuthInstance;
-try {
- userAuthInstance = userIAM_userAuth.getUserAuthInstance(authParam, widgetParam);
- console.info("get userAuth instance success");
-} catch (error) {
- console.info("get userAuth instance failed, error = " + error);
-}
-
-// Start user authentication.
-try {
- userAuthInstance.start();
- console.info("userAuthInstanceV10 start auth success");
-} catch (error) {
- console.info("userAuthInstanceV10 start auth failed, error = " + error);
- //do error
-}
-
-// Cancel the authentication.
+import userAuth from '@ohos.userIAM.userAuth';
+
+const authParam = {
+ challenge: new Uint8Array([49, 49, 49, 49, 49, 49]),
+ authType: [userAuth.UserAuthType.PIN],
+ authTrustLevel: 10000,
+};
+const widgetParam = {
+ title:'Enter password',
+ navigationButtonText: 'Back',
+ windowMode: userAuth.WindowModeType.DIALOG_BOX,
+};
try {
+ let userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
+ console.log('get userAuth instance success');
userAuthInstance.cancel();
- console.info("cancel auth success");
+ console.log('auth cancel success');
} catch (error) {
- console.info("cancel auth failed, error = " + error);
- //do error
+ console.log('auth catch error: ' + JSON.stringify(error));
}
```
-## userIAM_userAuth.getUserAuthInstance10+
+## getUserAuthInstance10+
getUserAuthInstance(authParam: AuthParam, widgetParam: WidgetParam): UserAuthInstance
@@ -389,16 +335,16 @@ Obtains a [UserAuthInstance](#userauthinstance10) instance for user authenticati
**Parameters**
-| Name | Type | Mandatory| Description |
-| ----------- | ----------------------------- | ---- | -------------------------------------- |
-| authParam | [AuthParam](authparam10) | Yes | Challenge value. The maximum length is 32 bytes. The value can be **null**.|
-| widgetParam | [WidgetParam](#widgetparam10) | Yes | Authentication type. Only **FACE** is supported. |
+| Name | Type | Mandatory| Description |
+| ----------- | ----------------------------- | ---- | -------------------------- |
+| authParam | [AuthParam](#authparam10) | Yes | User authentication parameters. |
+| widgetParam | [WidgetParam](#widgetparam10) | Yes | Parameters on the user authentication page.|
**Return value**
-| Type | Description |
-| --------------------------------------- | ------------ |
-| [UserAuthInstance](#userauthinstance10) | **UserAuthInstance** instance obtained.|
+| Type | Description |
+| --------------------------------------- | -------------------------- |
+| [UserAuthInstance](#userauthinstance10) | **UserAuthInstance** instance that supports UI.|
**Error codes**
@@ -414,23 +360,23 @@ For details about the error codes, see [User Authentication Error Codes](../erro
**Example**
```js
-import userIAM_userAuth from '@ohos.userIAM.userAuth';
-
-AuthParam authParam = {
- challenge: new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
- authType: userIAM_userAuth.UserAuthType.PIN;
- authTrustLevel: userIAM_userAuth.AuthTrustLevel.ATL1;
-}
-WidgetParam widgetParam = {
- title: "Enter Password";
- windowMode: userIAM_userAuth.WindowModeType.DIALOG_BOX;
-}
-
+import userAuth from '@ohos.userIAM.userAuth';
+
+const authParam = {
+ challenge: new Uint8Array([49, 49, 49, 49, 49, 49]),
+ authType: [userAuth.UserAuthType.PIN],
+ authTrustLevel: 10000,
+};
+const widgetParam = {
+ title:'Enter password',
+ navigationButtonText: 'Back',
+ windowMode: userAuth.WindowModeType.DIALOG_BOX,
+};
try {
- let userAuthInstance = userIAM_userAuth.getUserAuthInstance(authParam, widgetParam);
- console.info("get userAuth instance success");
+ let userAuthInstance = userAuth.getUserAuthInstance(authParam, widgetParam);
+ console.log('get userAuth instance success');
} catch (error) {
- console.info("get userAuth instance failed, error = " + error);
+ console.log('auth catch error: ' + JSON.stringify(error));
}
```
@@ -440,11 +386,13 @@ Defines the type of the user authentication notification.
**System capability**: SystemCapability.UserIAM.UserAuth.Core
+**System API**: This is a system API.
+
| Name | Value | Description |
| ------------- | ---- | -------------------- |
| WIDGET_NOTICE | 1 | Notification from the user authentication widget.|
-## userIAM_userAuth.sendNotice10+
+## sendNotice10+
sendNotice(noticeType: NoticeType, eventData: string): void
@@ -454,12 +402,14 @@ Sends a notification from the user authentication widget.
**System capability**: SystemCapability.UserIAM.UserAuth.Core
+**System API**: This is a system API.
+
**Parameters**
-| Name | Type | Mandatory| Description |
-| ---------- | ------------------------- | ---- | ---------- |
-| noticeType | [NoticeType](#noticetype) | Yes | Notification type.|
-| eventData | string | Yes | Event data.|
+| Name | Type | Mandatory| Description |
+| ---------- | --------------------------- | ---- | ---------- |
+| noticeType | [NoticeType](#noticetype10) | Yes | Notification type.|
+| eventData | string | Yes | Event data.|
**Error codes**
@@ -475,10 +425,24 @@ For details about the error codes, see [User Authentication Error Codes](../erro
**Example**
```js
-import userIAM_userAuth from '@ohos.userIAM.userAuth';
+import userAuth from '@ohos.userIAM.userAuth';
-let noticeType = userIAM_userAuth.NoticeType.WIDGET_NOTICE;
-sendNotice(noticeType, {"eventData" : "EVENT_AUTH_TYPE_READY"});
+try {
+ const eventData = {
+ widgetContextId: 123456,
+ event: 'EVENT_AUTH_TYPE_READY',
+ version: '1',
+ payload: {
+ type: ['pin']
+ },
+ };
+ const jsonEventData = JSON.stringify(eventData);
+ let noticeType = userAuth.NoticeType.WIDGET_NOTICE;
+ userAuth.sendNotice(noticeType, jsonEventData);
+ console.log('sendNotice success');
+} catch (error) {
+ console.log('sendNotice catch error: ' + JSON.stringify(error));
+}
```
## UserAuthWidgetMgr10+
@@ -493,6 +457,8 @@ Subscribes to commands from the user authentication framework.
**System capability**: SystemCapability.UserIAM.UserAuth.Core
+**System API**: This is a system API.
+
**Parameters**
| Name | Type | Mandatory| Description |
@@ -512,26 +478,20 @@ For details about the error codes, see [User Authentication Error Codes](../erro
**Example**
```js
-import userIAM_userAuth from '@ohos.userIAM.userAuth';
-
-let version = 1;
-let userAuthWidgetMgr;
-try {
- userAuthWidgetMgr = userIAM_userAuth.getUserAuthWidgetMgr(version);
- console.info("get userAuthWidgetMgr instance success");
-} catch (error) {
- console.info("get userAuthWidgetMgr instance failed, error = " + error);
-}
+import userAuth from '@ohos.userIAM.userAuth';
+const userAuthWidgetMgrVersion = 1;
try {
+ let userAuthWidgetMgr = userAuth.getUserAuthWidgetMgr(userAuthWidgetMgrVersion);
+ console.log('get userAuthWidgetMgr instance success');
userAuthWidgetMgr.on('command', {
- callback: sendCommand(cmdData) {
- console.log("The cmdData is " + cmdData);
+ sendCommand(cmdData) {
+ console.log('The cmdData is ' + cmdData);
}
})
- console.info("subscribe authentication event success");
+ console.log('subscribe authentication event success');
} catch (error) {
- console.info("subscribe authentication event failed, error = " + error);
+ console.log('userAuth widgetMgr catch error: ' + JSON.stringify(error));
}
```
@@ -543,6 +503,8 @@ Unsubscribes from commands sent from the user authentication framework.
**System capability**: SystemCapability.UserIAM.UserAuth.Core
+**System API**: This is a system API.
+
**Parameters**
| Name | Type | Mandatory| Description |
@@ -562,38 +524,24 @@ For details about the error codes, see [User Authentication Error Codes](../erro
**Example**
```js
-import userIAM_userAuth from '@ohos.userIAM.userAuth';
-
-let version = 1;
-let userAuthWidgetMgr;
-try {
- userAuthWidgetMgr = userIAM_userAuth.getUserAuthWidgetMgr(version);
- console.info("get userAuthWidgetMgr instance success");
-} catch (error) {
- console.info("get userAuthWidgetMgr instance failed, error = " + error);
-}
+import userAuth from '@ohos.userIAM.userAuth';
-// Subscribe to the commands sent from the user authentication framework.
+const userAuthWidgetMgrVersion = 1;
try {
- userAuthWidgetMgr.on('command', {
- callback: sendCommand(cmdData) {
- console.log("The cmdData is " + cmdData);
+ let userAuthWidgetMgr = userAuth.getUserAuthWidgetMgr(userAuthWidgetMgrVersion);
+ console.log('get userAuthWidgetMgr instance success');
+ userAuthWidgetMgr.off('command', {
+ sendCommand(cmdData) {
+ console.log('The cmdData is ' + cmdData);
}
})
- console.info("subscribe authentication event success");
+ console.log('cancel subscribe authentication event success');
} catch (error) {
- console.info("subscribe authentication event failed, error = " + error);
-}
-// Unsubscribe from the commands sent from the user authentication framework.
-try {
- userAuthWidgetMgr.off('command');
- console.info("cancel subscribe authentication event success");
-} catch (error) {
- console.info("cancel subscribe authentication event failed, error = " + error);
+ console.log('userAuth widgetMgr catch error: ' + JSON.stringify(error));
}
```
-## userIAM_userAuth.getUserAuthWidgetMgr10+
+## getUserAuthWidgetMgr10+
getUserAuthWidgetMgr(version: number): UserAuthWidgetMgr
@@ -602,8 +550,12 @@ Obtains a **UserAuthWidgetMgr** instance for user authentication.
> **NOTE**
> A **UserAuthInstance** instance can be used for an authentication only once.
+**Required permissions**: ohos.permission.SUPPORT_USER_AUTH
+
**System capability**: SystemCapability.UserIAM.UserAuth.Core
+**System API**: This is a system API.
+
**Parameters**
| Name | Type | Mandatory| Description |
@@ -630,14 +582,14 @@ For details about the error codes, see [User Authentication Error Codes](../erro
**Example**
```js
-import userIAM_userAuth from '@ohos.userIAM.userAuth';
+import userAuth from '@ohos.userIAM.userAuth';
-let version = 1;
+let userAuthWidgetMgrVersion = 1;
try {
- let userAuthWidgetMgr = userIAM_userAuth.getUserAuthWidgetMgr(version);
- console.info("get userAuthWidgetMgr instance success");
+ let userAuthWidgetMgr = userAuth.getUserAuthWidgetMgr(userAuthWidgetMgrVersion);
+ console.log('get userAuthWidgetMgr instance success');
} catch (error) {
- console.info("get userAuthWidgetMgr instance failed, error = " + error);
+ console.log('userAuth widgetMgr catch error: ' + JSON.stringify(error));
}
```
@@ -653,6 +605,8 @@ Called to return the command sent from the user authentication framework to the
**System capability**: SystemCapability.UserIAM.UserAuth.Core
+**System API**: This is a system API.
+
**Parameters**
| Name | Type | Mandatory| Description |
@@ -662,19 +616,20 @@ Called to return the command sent from the user authentication framework to the
**Example**
```js
-import userIAM_userAuth from '@ohos.userIAM.userAuth';
+import userAuth from '@ohos.userIAM.userAuth';
-let version = 1;
+const userAuthWidgetMgrVersion = 1;
try {
- let userAuthWidgetMgr = userIAM_userAuth.getUserAuthWidgetMgr(version);
+ let userAuthWidgetMgr = userAuth.getUserAuthWidgetMgr(userAuthWidgetMgrVersion);
+ console.log('get userAuthWidgetMgr instance success');
userAuthWidgetMgr.on('command', {
- callback: sendCommand(cmdData) {
- console.log("The cmdData is " + cmdData);
+ sendCommand(cmdData) {
+ console.log('The cmdData is ' + cmdData);
}
})
- console.info("subscribe authentication event success");
+ console.log('subscribe authentication event success');
} catch (error) {
- console.info("subscribe authentication event failed, error = " + error);
+ console.log('userAuth widgetMgr catch error: ' + JSON.stringify(error));
}
```
@@ -1036,7 +991,7 @@ getAuthInstance(challenge : Uint8Array, authType : UserAuthType, authTrustLevel
Obtains an **AuthInstance** instance for user authentication.
> **NOTE**
-> This API is supported since API version 9 and deprecated since API version 10. Use [getUserAuthInstance](#useriam_userauthgetuserauthinstance10) instead.
+> This API is supported since API version 9 and deprecated since API version 10. Use [getUserAuthInstance](#getuserauthinstance10) instead.
> **NOTE**
> An **AuthInstance** instance can be used for an authentication only once.
@@ -1099,7 +1054,7 @@ Checks whether the specified authentication capability is supported.
| Name | Type | Mandatory| Description |
| -------------- | ---------------------------------- | ---- | -------------------------- |
-| authType | [UserAuthType](#userauthtype8) | Yes | Authentication type. Only **FACE** is supported.|
+| authType | [UserAuthType](#userauthtype8) | Yes | Authentication type.|
| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Authentication trust level. |
**Error codes**
@@ -1146,7 +1101,7 @@ Enumerates the authentication result codes.
| BUSY | 12500007 | Indicates the busy state. |
| LOCKED | 12500009 | The authentication executor is locked. |
| NOT_ENROLLED | 12500010 | The user has not entered the authentication information.|
-| CANCELED_FROM_WIDGET | 12500011 | The authentication is canceled by the user from the user authentication widget. If this error code is returned, the authentication is customized by the application.|
+| CANCELED_FROM_WIDGET10+ | 12500011 | The authentication is canceled by the user from the user authentication widget. If this error code is returned, the authentication is customized by the application.|
## UserAuth(deprecated)
diff --git a/en/application-dev/reference/apis/js-apis-wallpaper.md b/en/application-dev/reference/apis/js-apis-wallpaper.md
index 0e76092672c8aaa5b85ada2d79a95eb003ddbd2b..4e925cbc0d9c3a9d7a3038acea5ae149ee0d96e4 100644
--- a/en/application-dev/reference/apis/js-apis-wallpaper.md
+++ b/en/application-dev/reference/apis/js-apis-wallpaper.md
@@ -625,7 +625,7 @@ Subscribes to the wallpaper color change event.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to subscribe to. The value **'colorChange'** indicates subscribing to the wallpaper color change event.|
-| callback | function | Yes| Callback triggered when the wallpaper color changes. The wallpaper type and main colors are returned. - colors Main color information of the wallpaper. For details, see [RgbaColor](#rgbacolordeprecated). - wallpaperType Wallpaper type.|
+| callback | function | Yes| Callback triggered when the wallpaper color changes. The wallpaper type and main colors are returned. - **colors**: main color information of the wallpaper. For details, see [RgbaColor](#rgbacolordeprecated). - **wallpaperType**: wallpaper type. |
**Example**
@@ -657,7 +657,7 @@ Unsubscribes from the wallpaper color change event.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to unsubscribe from. The value **'colorChange'** indicates unsubscribing from the wallpaper color change event.|
-| callback | function | No| Callback for the wallpaper color change event. If this parameter is not set, this API unsubscribes from all callbacks corresponding to **type**. - colors Main color information of the wallpaper. For details, see [RgbaColor](#rgbacolordeprecated). - wallpaperType Wallpaper type.|
+| callback | function | No| Callback used for unsubscription. If this parameter is not set, this API unsubscribes from all callbacks of the specified event type. - **colors**: main color information of the wallpaper. For details, see [RgbaColor](#rgbacolordeprecated). - **wallpaperType**: wallpaper type. |
**Example**
diff --git a/en/application-dev/reference/apis/js-apis-wifiManager.md b/en/application-dev/reference/apis/js-apis-wifiManager.md
index d0a5734d47b2ada35e5d4dae36770cd58873769f..3b5ccb266a60c098525e6690e1dce15e3c1e137b 100644
--- a/en/application-dev/reference/apis/js-apis-wifiManager.md
+++ b/en/application-dev/reference/apis/js-apis-wifiManager.md
@@ -15,7 +15,7 @@ import wifiManager from '@ohos.wifiManager';
enableWifi(): void
-Enables WLAN.
+Enables WLAN. This API is an asynchronous interface. The **wifiStateChange** callback must be registered and listened for.
**System API**: This is a system API.
@@ -47,7 +47,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
disableWifi(): void
-Disables WLAN.
+Disables WLAN. This API is an asynchronous interface. The **wifiStateChange** callback must be registered and listened for.
**System API**: This is a system API.
@@ -583,7 +583,7 @@ Adds network configuration. This API uses a promise to return the result.
| **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.|
+ | 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**
@@ -959,7 +959,7 @@ Removes the configuration of a candidate network. This API uses an asynchronous
| **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.|
+ | 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**
@@ -2082,7 +2082,7 @@ Enumerates the Wi-Fi disconnection reasons.
enableHotspot(): void
-Enables this hotspot.
+Enables this hotspot. This API is an asynchronous interface. The **hotspotStateChange** callback must be registered and listened for.
**System API**: This is a system API.
@@ -2113,7 +2113,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
disableHotspot(): void
-Disables this hotspot.
+Disables this hotspot. This API is an asynchronous interface. The **hotspotStateChange** callback must be registered and listened for.
**System API**: This is a system API.
diff --git a/en/application-dev/reference/apis/js-apis-window.md b/en/application-dev/reference/apis/js-apis-window.md
index 9ac2bab02f8bf52a52e25091e1779ef255b68204..13edbc7a924ff1e0b5ad8ef7f3f6f2720eb49de2 100644
--- a/en/application-dev/reference/apis/js-apis-window.md
+++ b/en/application-dev/reference/apis/js-apis-window.md
@@ -3889,7 +3889,9 @@ try {
setWindowPrivacyMode(isPrivacyMode: boolean, callback: AsyncCallback<void>): void
-Sets whether this window is in privacy mode. This API uses an asynchronous callback to return the result. When in privacy mode, the window content cannot be captured or recorded.
+Sets whether this window is in privacy mode. This API uses an asynchronous callback to return the result.
+
+A window in privacy mode cannot be captured or recorded.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
@@ -3931,7 +3933,9 @@ try {
setWindowPrivacyMode(isPrivacyMode: boolean): Promise<void>
-Sets whether this window is in privacy mode. This API uses a promise to return the result. When in privacy mode, the window content cannot be captured or recorded.
+Sets whether this window is in privacy mode. This API uses a promise to return the result.
+
+A window in privacy mode cannot be captured or recorded.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
diff --git a/en/application-dev/reference/apis/js-apis-worker.md b/en/application-dev/reference/apis/js-apis-worker.md
index 59111203ed8ea233dcb6d579a869a258fb251f5a..5a7c798c5513747de8e9130ca90434114e8d627b 100644
--- a/en/application-dev/reference/apis/js-apis-worker.md
+++ b/en/application-dev/reference/apis/js-apis-worker.md
@@ -388,7 +388,7 @@ workerInstance.onexit = function(e) {
workerInstance.terminate();
// Worker thread:
-//parentPort.close()
+//workerPort.close()
```
@@ -429,7 +429,7 @@ workerInstance.onerror = function(e) {
onmessage?: (event: MessageEvents) => void
-Defines the event handler to be called when the host thread receives a message sent by the worker thread through **parentPort.postMessage**. The event handler is executed in the host thread.
+Defines the event handler to be called when the host thread receives a message sent by the worker thread through **workerPort.postMessage**. The event handler is executed in the host thread.
**System capability**: SystemCapability.Utils.Lang
@@ -1053,8 +1053,8 @@ const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");
```js
// worker.ts
import worker from '@ohos.worker';
-const parentPort = worker.workerPort;
-parentPort.onmessageerror = function(e) {
+const workerPort = worker.workerPort;
+workerPort.onmessageerror = function(e) {
console.log("worker.ts onmessageerror")
}
```
@@ -1744,11 +1744,11 @@ workerInstance.onmessage = function(e) {
```js
// worker.ts
import worker from '@ohos.worker';
-const parentPort = worker.parentPort;
-parentPort.onmessage = function(e){
+const workerPort = worker.workerPort;
+workerPort.onmessage = function(e){
// let data = e.data;
let buffer = new ArrayBuffer(5)
- parentPort.postMessage(buffer, [buffer]);
+ workerPort.postMessage(buffer, [buffer]);
}
```
@@ -2089,7 +2089,7 @@ Each actor concurrently processes tasks of the main thread. For each actor, ther
- Currently, a maximum of eight worker threads can co-exist.
- In API version 8 and earlier versions, when the number of **Worker** instances exceeds the upper limit, the error "Too many workers, the number of workers exceeds the maximum." is thrown.
- Since API version 9, when the number of **Worker** instances exceeds the upper limit, the business error "Worker initialization failure, the number of workers exceeds the maximum." is thrown.
-- To proactively destroy a worker thread, you can call **terminate()** or **parentPort.close()** of the newly created **Worker** instance.
+- To proactively destroy a worker thread, you can call **terminate()** or **workerPort.close()** of the newly created **Worker** instance.
- Since API version 9, if a **Worker** instance in a non-running state (such as destroyed or being destroyed) calls an API, a business error is thrown.
- Creating and terminating worker threads consume performance. Therefore, you are advised to manage available workers and reuse them.
- Do not use both **new worker.Worker** and **new worker.ThreadWorker** to create a **Worker** project. Otherwise, **Worker** functions abnormally. Since API version 9, you are advised to use [new worker.ThreadWorker](#constructor9). In API version 8 and earlier versions, you are advised to use [new worker.Worker](#constructordeprecated).
diff --git a/en/application-dev/reference/arkui-js-lite/Readme-EN.md b/en/application-dev/reference/arkui-js-lite/Readme-EN.md
index 4dbc7b08dbed8356f7cb907c3dbebff5c5b09bf5..82d21c003828d6a374fa9aeef402169fe4c0d0d5 100644
--- a/en/application-dev/reference/arkui-js-lite/Readme-EN.md
+++ b/en/application-dev/reference/arkui-js-lite/Readme-EN.md
@@ -1,37 +1,38 @@
# JavaScript-compatible Web-like Development Paradigm (ArkUI.Lite)
- Framework Overview
- - [File Organization](js-framework-file.md)
- - ["js" Tag](js-framework-js-tag.md)
- - [app.js](js-framework-js-file.md)
- - Syntax
- - [HML](js-framework-syntax-hml.md)
- - [CSS](js-framework-syntax-css.md)
- - [JavaScript](js-framework-syntax-js.md)
+ - [File Organization](js-framework-file.md)
+ - ["js" Tag](js-framework-js-tag.md)
+ - [app.js](js-framework-js-file.md)
+
+ - Syntax
+ - [HML](js-framework-syntax-hml.md)
+ - [CSS](js-framework-syntax-css.md)
+ - [JavaScript](js-framework-syntax-js.md)
- Universal Component Information
- - [Universal Events](js-common-events.md)
- - [Universal Attributes](js-common-attributes.md)
- - [Universal Styles](js-common-styles.md)
- - [Animation Styles](js-components-common-animation.md)
- - [Media Query](js-components-common-mediaquery.md)
+ - [Universal Events](js-common-events.md)
+ - [Universal Attributes](js-common-attributes.md)
+ - [Universal Styles](js-common-styles.md)
+ - [Animation Styles](js-components-common-animation.md)
+ - [Media Query](js-components-common-mediaquery.md)
- Container Components
- - [div](js-components-container-div.md)
- - [list](js-components-container-list.md)
- - [list-item](js-components-container-list-item.md)
- - [stack](js-components-container-stack.md)
- - [swiper](js-components-container-swiper.md)
+ - [div](js-components-container-div.md)
+ - [list](js-components-container-list.md)
+ - [list-item](js-components-container-list-item.md)
+ - [stack](js-components-container-stack.md)
+ - [swiper](js-components-container-swiper.md)
- Basic Components
- - [chart](js-components-basic-chart.md)
- - [image](js-components-basic-image.md)
- - [image-animator](js-components-basic-image-animator.md)
- - [input](js-components-basic-input.md)
- - [marquee](js-components-basic-marquee.md)
- - [picker-view](js-components-basic-picker-view.md)
- - [progress](js-components-basic-progress.md)
- - [qrcode](js-components-basic-qrcode.md)
- - [slider](js-components-basic-slider.md)
- - [switch](js-components-basic-switch.md)
- - [text](js-components-basic-text.md)
+ - [chart](js-components-basic-chart.md)
+ - [image](js-components-basic-image.md)
+ - [image-animator](js-components-basic-image-animator.md)
+ - [input](js-components-basic-input.md)
+ - [marquee](js-components-basic-marquee.md)
+ - [picker-view](js-components-basic-picker-view.md)
+ - [progress](js-components-basic-progress.md)
+ - [qrcode](js-components-basic-qrcode.md)
+ - [slider](js-components-basic-slider.md)
+ - [switch](js-components-basic-switch.md)
+ - [text](js-components-basic-text.md)
- Canvas Components
- - [canvas](js-components-canvas-canvas.md)
- - [CanvasRenderingContext2D](js-components-canvas-canvasrenderingcontext2d.md)
+ - [canvas](js-components-canvas-canvas.md)
+ - [CanvasRenderingContext2D](js-components-canvas-canvasrenderingcontext2d.md)
\ No newline at end of file
diff --git a/en/application-dev/reference/arkui-js-lite/figures/lite_line.PNG b/en/application-dev/reference/arkui-js-lite/figures/lite_line.PNG
index 664ade98b38a3b6ac2b3e96dc4af8b75b6749a72..6fc94377d0df58e97d531dd11695c105bf161cd8 100644
Binary files a/en/application-dev/reference/arkui-js-lite/figures/lite_line.PNG and b/en/application-dev/reference/arkui-js-lite/figures/lite_line.PNG differ
diff --git a/en/application-dev/reference/arkui-js-lite/js-components-basic-chart.md b/en/application-dev/reference/arkui-js-lite/js-components-basic-chart.md
index 2c8f4c0550f7794d975eb7014e30506c034e9a1d..fe9c388615090bcc09f42ea162063ea2f2fa0d1b 100644
--- a/en/application-dev/reference/arkui-js-lite/js-components-basic-chart.md
+++ b/en/application-dev/reference/arkui-js-lite/js-components-basic-chart.md
@@ -165,7 +165,7 @@ Not supported
strokeColor: '#0081ff',
fillColor: '#cce5ff',
data: [763, 550, 551, 554, 731, 654, 525, 696, 595, 628, 791, 505, 613, 575, 475, 553, 491, 680, 657, 716],
- gradient: true,
+ gradient: false,
}
],
lineOps: {
diff --git a/en/application-dev/reference/arkui-js-lite/js-components-basic-qrcode.md b/en/application-dev/reference/arkui-js-lite/js-components-basic-qrcode.md
index 84bbace4425c18e8ccabd8ee757f8c2fbfb3eb60..579b0a22a26b38c43513ce49bea4dc9c85e9fdb5 100644
--- a/en/application-dev/reference/arkui-js-lite/js-components-basic-qrcode.md
+++ b/en/application-dev/reference/arkui-js-lite/js-components-basic-qrcode.md
@@ -28,9 +28,9 @@ Not supported
| Name| Parameter| Description|
| -------- | -------- | -------- |
-| click | - | Triggered when the component is clicked. |
-| longpress | - | Triggered when the component is long pressed. |
-| swipe5+ | [SwipeEvent](js-common-events.md) | Triggered when a user quickly swipes on the component. |
+| click | - | Triggered when the component is clicked.|
+| longpress | - | Triggered when the component is long pressed.|
+| swipe5+ | [SwipeEvent](js-common-events.md) | Triggered when a user quickly swipes on the component.|
## Styles
@@ -39,8 +39,8 @@ Not supported
| -------- | -------- | -------- | -------- | -------- |
| color | <color> | \#000000 | No| Color of the QR code.|
| background-color | <color> | \#ffffff | No| Background color of the QR code.|
-| width | <length> \| <percentage>5+ | - | No| Component width. If this attribute is not set, the default value **0** is used. |
-| height | <length> \| <percentage>5+ | - | No| Component height. If this attribute is not set, the default value **0** is used. |
+| width | <length> \| <percentage>5+ | - | No| Component width. If this attribute is not set, the default value **0** is used.|
+| height | <length> \| <percentage>5+ | - | No| Component height. If this attribute is not set, the default value **0** is used.|
| padding | <length> | 0 | No| Shorthand attribute to set the padding for all sides. The attribute can have one to four values: - If you set only one value, it specifies the padding for all the four sides. - If you set two values, the first value specifies the top and bottom padding, and the second value specifies the left and right padding. - If you set three values, the first value specifies the top padding, the second value specifies the left and right padding, and the third value specifies the bottom padding. - If you set four values, they respectively specify the padding for top, right, bottom, and left sides (in clockwise order).|
| padding-[left\|top\|right\|bottom] | <length> | 0 | No| Left, top, right, and bottom padding.|
| margin | <length> \| <percentage>5+ | 0 | No| Shorthand attribute to set the margin for all sides. The attribute can have one to four values: - If you set only one value, it specifies the margin for all the four sides. - If you set two values, the first value specifies the top and bottom margins, and the second value specifies the left and right margins. - If you set three values, the first value specifies the top margin, the second value specifies the left and right margins, and the third value specifies the bottom margin. - If you set four values, they respectively specify the margin for top, right, bottom, and left sides (in clockwise order).|
@@ -49,7 +49,7 @@ Not supported
| border-color | <color> | black | No| Shorthand attribute to set the color for all borders.|
| border-radius | <length> | - | No| Radius of round-corner borders.|
| display | string | flex | No| How and whether to display the box containing an element. Available values are as follows: - **flex**: flexible layout - **none**: not rendered|
-| [left\|top] | <length> \| <percentage>6+ | - | No| Edge of the element. - **left**: left edge position of the element. This attribute defines the offset between the left edge of the margin area of a positioned element and left edge of its containing block. - **top**: top edge position of the element. This attribute defines the offset between the top edge of a positioned element and that of a block included in the element. |
+| [left\|top] | <length> \| <percentage>6+ | - | No| Edge of the element. - **left**: left edge position of the element. This attribute defines the offset between the left edge of the margin area of a positioned element and left edge of its containing block. - **top**: top edge position of the element. This attribute defines the offset between the top edge of a positioned element and that of a block included in the element.|
> **NOTE**
> - If the values of **width** and **height** are different, the smaller value is used as the length of the QR code. The generated QR code is center displayed.
@@ -63,10 +63,10 @@ Not supported
```html
-
- Color
- BackgroundColor
- Value
+
+ Color
+ BackgroundColor
+ Value
```
@@ -93,32 +93,32 @@ Not supported
```javascript
// xxx.js
export default {
- data: {
- qr_col: '#87ceeb',
- qr_bcol: '#f0ffff',
- qr_value: 'value'
- },
- changeColor() {
- if (this.qr_col == '#87ceeb') {
- this.qr_col = '#fa8072';
- } else {
- this.qr_col = '#87ceeb';
+ data: {
+ qr_col: '#87ceeb',
+ qr_bcol: '#f0ffff',
+ qr_value: 'value'
+ },
+ changeColor() {
+ if (this.qr_col == '#87ceeb') {
+ this.qr_col = '#fa8072';
+ } else {
+ this.qr_col = '#87ceeb';
+ }
+ },
+ changeBackgroundColor() {
+ if (this.qr_bcol == '#f0ffff') {
+ this.qr_bcol = '#ffffe0';
+ } else {
+ this.qr_bcol = '#f0ffff';
+ }
+ },
+ changeValue() {
+ if (this.qr_value == 'value') {
+ this.qr_value = 'change';
+ } else {
+ this.qr_value = 'value';
+ }
}
- },
- changeBackgroundColor() {
- if (this.qr_bcol == '#f0ffff') {
- this.qr_bcol = '#ffffe0';
- } else {
- this.qr_bcol = '#f0ffff';
- }
- },
- changeValue() {
- if (this.qr_value == 'value') {
- this.qr_value = 'change';
- } else {
- this.qr_value = 'value';
- }
- }
}
```
diff --git a/en/application-dev/reference/arkui-js-lite/js-framework-syntax-js.md b/en/application-dev/reference/arkui-js-lite/js-framework-syntax-js.md
index e9d71fc2ff680dfba5b95e7bae676854a1e68a28..8d1153d3bdaec49a99abcf0512613b3bb5f9b03c 100644
--- a/en/application-dev/reference/arkui-js-lite/js-framework-syntax-js.md
+++ b/en/application-dev/reference/arkui-js-lite/js-framework-syntax-js.md
@@ -33,7 +33,7 @@ The ECMAScript 6.0 syntax is supported. Lite wearables only support the followin
```
- import router from '@system.router';
+ import router from '@ohos.router';
```
- Code reference
@@ -51,7 +51,7 @@ The ECMAScript 6.0 syntax is supported. Lite wearables only support the followin
| Attribute | Type | Description |
| ----- | --------------- | ---------------------------------------- |
| data | Object/Function | Data model of the page. If the attribute is of the function type, the return value must be of the object type. The name cannot start with a dollar sign ($) or underscore (_). Do not use reserved words (**for**, **if**, **show**, and **tid**). |
- | $refs | Object | DOM elements or child component instances that have registered the **ref** attribute. For an example, see [Obtaining a DOM Element](#obtaining-a-dom-element). |
+ | $refs | Object | DOM elements or child component instances that have registered the **ref** attribute. For an example, see [Obtaining a DOM Element](#obtaining-a-dom-element).|
## Obtaining a DOM Element
@@ -94,7 +94,7 @@ Use **$refs** to obtain a DOM element.
## Lifecycle APIs
- Page lifecycle APIs
- | Name | Type | Parameter | Return Value | Description | Triggered When |
+ | Name | Type | Parameter | Return Value | Description | Triggered When |
| --------- | -------- | ---- | ---- | ------ | ------------------- |
| onInit | Function | N/A | N/A | Listens for page initialization. | Page initialization is complete. This API is called only once in the page lifecycle.|
| onReady | Function | N/A | N/A | Listens for page creation.| A page is created. This API is called only once in the page lifecycle. |
@@ -116,7 +116,7 @@ Use **$refs** to obtain a DOM element.
- Show background page A on the foreground: onShow()
- Application lifecycle APIs
- | Name | Type | Parameter | Return Value | Description | Triggered When |
+ | Name | Type | Parameter | Return Value | Description | Triggered When |
| --------- | -------- | ---- | ---- | ---- | --------- |
| onCreate | Function | N/A | N/A | Listens for application creation.| The application is created.|
| onDestroy | Function | N/A | N/A | Listens for application exit.| The application exits.|
diff --git a/en/application-dev/reference/arkui-ts/Readme-EN.md b/en/application-dev/reference/arkui-ts/Readme-EN.md
index dc797984418a04ea512fedca19380592545a3bea..574900a2c87c95e1cc8c8707e3c4bf2d61258185 100644
--- a/en/application-dev/reference/arkui-ts/Readme-EN.md
+++ b/en/application-dev/reference/arkui-ts/Readme-EN.md
@@ -123,6 +123,7 @@
- [GridRow](ts-container-gridrow.md)
- [Grid](ts-container-grid.md)
- [GridItem](ts-container-griditem.md)
+ - [Hyperlink](ts-container-hyperlink.md)
- [List](ts-container-list.md)
- [ListItem](ts-container-listitem.md)
- [ListItemGroup](ts-container-listitemgroup.md)
@@ -138,6 +139,7 @@
- [Swiper](ts-container-swiper.md)
- [Tabs](ts-container-tabs.md)
- [TabContent](ts-container-tabcontent.md)
+ - [UIExtensionComponent](ts-container-ui-extension-component.md)
- [WaterFlow](ts-container-waterflow.md)
- Media Components
- [Video](ts-media-components-video.md)
diff --git a/en/application-dev/reference/arkui-ts/figures/DataPickerDialog.gif b/en/application-dev/reference/arkui-ts/figures/DataPickerDialog.gif
deleted file mode 100644
index e447f0d8916e19385da7f38e1c4b15334e4a6a70..0000000000000000000000000000000000000000
Binary files a/en/application-dev/reference/arkui-ts/figures/DataPickerDialog.gif and /dev/null differ
diff --git a/en/application-dev/reference/arkui-ts/figures/DatePickerApi10.gif b/en/application-dev/reference/arkui-ts/figures/DatePickerApi10.gif
new file mode 100644
index 0000000000000000000000000000000000000000..cdb8e983b563f6b337b096d248bb33d02dc245ce
Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/DatePickerApi10.gif differ
diff --git a/en/application-dev/reference/arkui-ts/figures/DatePickerDialogApi10.gif b/en/application-dev/reference/arkui-ts/figures/DatePickerDialogApi10.gif
new file mode 100644
index 0000000000000000000000000000000000000000..7b8186f3fd474e6e3b386a97b8c30123351be6b3
Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/DatePickerDialogApi10.gif differ
diff --git a/en/application-dev/reference/arkui-ts/figures/TimePickerDialog.gif b/en/application-dev/reference/arkui-ts/figures/TimePickerDialog.gif
index 44fe3a771a01e9fec2e155663c1f2f552d202b68..f6d64bcfcf619e12431c7b431606fe85b4731470 100644
Binary files a/en/application-dev/reference/arkui-ts/figures/TimePickerDialog.gif and b/en/application-dev/reference/arkui-ts/figures/TimePickerDialog.gif differ
diff --git a/en/application-dev/reference/arkui-ts/figures/alphabet.gif b/en/application-dev/reference/arkui-ts/figures/alphabet.gif
index 5a5a3e4bab1f7f104afd27199125972c6cb611c0..de8b8bdaa8ea2cfdcef45e9620e517b49c71b18a 100644
Binary files a/en/application-dev/reference/arkui-ts/figures/alphabet.gif and b/en/application-dev/reference/arkui-ts/figures/alphabet.gif differ
diff --git a/en/application-dev/reference/arkui-ts/figures/datePicker.gif b/en/application-dev/reference/arkui-ts/figures/datePicker.gif
deleted file mode 100644
index 52ee9ca7eb42b521cf879e364c95694ca698b834..0000000000000000000000000000000000000000
Binary files a/en/application-dev/reference/arkui-ts/figures/datePicker.gif and /dev/null differ
diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001210353788.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001210353788.gif
index 38ffa5ca3c66dc3852f3a6045789473e8bdb0c41..f55a5e26c8b0dc0c11405b0b342399324afc3dbc 100644
Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001210353788.gif and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001210353788.gif differ
diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001212058482.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001212058482.gif
deleted file mode 100644
index 0ea18f82170eb3309aefb8af24ef89f886718bdd..0000000000000000000000000000000000000000
Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001212058482.gif and /dev/null differ
diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219982708.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219982708.gif
index 738e50b17cf1c20514f17034ec08bba1cadf2893..2d852ce15286468dace1661d2ef9796274aff07d 100644
Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219982708.gif and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219982708.gif differ
diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219982729.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219982729.gif
new file mode 100644
index 0000000000000000000000000000000000000000..c5f6fec069ee84ed9a59ca6e457338a59f570f39
Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219982729.gif differ
diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256858383.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256858383.gif
deleted file mode 100644
index b8a7961adce1b592b8fdbce98966c70cf1da68e8..0000000000000000000000000000000000000000
Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256858383.gif and /dev/null differ
diff --git a/en/application-dev/reference/arkui-ts/figures/hyperlink.PNG b/en/application-dev/reference/arkui-ts/figures/hyperlink.PNG
new file mode 100644
index 0000000000000000000000000000000000000000..840110d2c649008658a812bb58d61d22727f99ea
Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/hyperlink.PNG differ
diff --git a/en/application-dev/reference/arkui-ts/figures/keyEvent.gif b/en/application-dev/reference/arkui-ts/figures/keyEvent.gif
new file mode 100644
index 0000000000000000000000000000000000000000..27f4299b764f7bfda8e468ae987be57f43b701aa
Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/keyEvent.gif differ
diff --git a/en/application-dev/reference/arkui-ts/figures/keyEvent.png b/en/application-dev/reference/arkui-ts/figures/keyEvent.png
deleted file mode 100644
index defa53e2581a56c7fb0933d85c0ce1578ebbfd48..0000000000000000000000000000000000000000
Binary files a/en/application-dev/reference/arkui-ts/figures/keyEvent.png and /dev/null differ
diff --git a/en/application-dev/reference/arkui-ts/figures/list-alignListItem.gif b/en/application-dev/reference/arkui-ts/figures/list-alignListItem.gif
new file mode 100644
index 0000000000000000000000000000000000000000..60808894e3410f5c1bb92e4f241fd7b3590c150b
Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/list-alignListItem.gif differ
diff --git a/en/application-dev/reference/arkui-ts/figures/list1.gif b/en/application-dev/reference/arkui-ts/figures/list1.gif
deleted file mode 100644
index 3e09842f3905ddf22e145b044238340b07b480ca..0000000000000000000000000000000000000000
Binary files a/en/application-dev/reference/arkui-ts/figures/list1.gif and /dev/null differ
diff --git a/en/application-dev/reference/arkui-ts/figures/mouse.png b/en/application-dev/reference/arkui-ts/figures/mouse.png
index 28baf4e713b69b4bea0e9ed3498a4a2ce12fc2b3..dd458d1940316dedd65d51542a78dc598cd61adf 100644
Binary files a/en/application-dev/reference/arkui-ts/figures/mouse.png and b/en/application-dev/reference/arkui-ts/figures/mouse.png differ
diff --git a/en/application-dev/reference/arkui-ts/figures/mouse1.png b/en/application-dev/reference/arkui-ts/figures/mouse1.png
index dc3ea1fb958f1de66f6310e22b6163ebfbfb7494..aa6709fa32eb5c6a29eff6ea54588fc86e8240c6 100644
Binary files a/en/application-dev/reference/arkui-ts/figures/mouse1.png and b/en/application-dev/reference/arkui-ts/figures/mouse1.png differ
diff --git a/en/application-dev/reference/arkui-ts/figures/richEditorCustomKeyboard.png b/en/application-dev/reference/arkui-ts/figures/richEditorCustomKeyboard.png
new file mode 100644
index 0000000000000000000000000000000000000000..bbaa41c203ba5e38ced3b00d498301dd46d222bd
Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/richEditorCustomKeyboard.png differ
diff --git a/en/application-dev/reference/arkui-ts/figures/searchCustomKeyboard.png b/en/application-dev/reference/arkui-ts/figures/searchCustomKeyboard.png
new file mode 100644
index 0000000000000000000000000000000000000000..ba8371fea6802dc1b216d7bd2141f4d720d63099
Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/searchCustomKeyboard.png differ
diff --git a/en/application-dev/reference/arkui-ts/figures/tabContent3.gif b/en/application-dev/reference/arkui-ts/figures/tabContent3.gif
index 2cb1d18f9c8f726cc02a7709ad07d641016cae61..7e731b125a0b7f365be9791dc9583c217b4ff6ce 100644
Binary files a/en/application-dev/reference/arkui-ts/figures/tabContent3.gif and b/en/application-dev/reference/arkui-ts/figures/tabContent3.gif differ
diff --git a/en/application-dev/reference/arkui-ts/figures/tabs3.gif b/en/application-dev/reference/arkui-ts/figures/tabs3.gif
new file mode 100644
index 0000000000000000000000000000000000000000..05cb0c42a59d683778bdbf5db5d3d60e06127da2
Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/tabs3.gif differ
diff --git a/en/application-dev/reference/arkui-ts/figures/tabs4.gif b/en/application-dev/reference/arkui-ts/figures/tabs4.gif
new file mode 100644
index 0000000000000000000000000000000000000000..47d89944df6653ca510840f26a626457c2a6b2c0
Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/tabs4.gif differ
diff --git a/en/application-dev/reference/arkui-ts/figures/tabs5.gif b/en/application-dev/reference/arkui-ts/figures/tabs5.gif
new file mode 100644
index 0000000000000000000000000000000000000000..3829041cf21aea29248c41a0c8bc1ce9249af3db
Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/tabs5.gif differ
diff --git a/en/application-dev/reference/arkui-ts/figures/timePicker.gif b/en/application-dev/reference/arkui-ts/figures/timePicker.gif
index 57ba2404c92ca64f11dba247f081fc2da5aacf44..e8df1e6d0378e2f8dbc2054ec19f96f8cea3e606 100644
Binary files a/en/application-dev/reference/arkui-ts/figures/timePicker.gif and b/en/application-dev/reference/arkui-ts/figures/timePicker.gif differ
diff --git a/en/application-dev/reference/arkui-ts/ts-animatorproperty.md b/en/application-dev/reference/arkui-ts/ts-animatorproperty.md
index ddc44429c9b5c501af18ace6b65806d776df2942..cf020b1411cd952d2dd16330bdd30d53f501f5ed 100644
--- a/en/application-dev/reference/arkui-ts/ts-animatorproperty.md
+++ b/en/application-dev/reference/arkui-ts/ts-animatorproperty.md
@@ -16,7 +16,7 @@ Since API version 9, this API is supported in ArkTS widgets.
| ---------- | ------------------------------------------| ---- | ------------------------------------------------------------ |
| duration | number | No | Animation duration, in ms. Default value: **1000** Unit: ms Since API version 9, this API is supported in ArkTS widgets. **NOTE** - The maximum animation duration on an ArkTS widget is 1000 ms. - A value less than 0 evaluates to the value **0**. - Floating-point values will be rounded down to integers. For example, if the value set is 1.2, **1** will be used.|
| tempo | number | No | Animation playback speed. A larger value indicates a higher animation playback speed. The value **0** indicates that no animation is applied. Default value: **1** **NOTE** A value less than 0 evaluates to the value **1**.|
-| curve | string \| [Curve](ts-appendix-enums.md#curve) \| [ICurve](../apis/js-apis-curve.md#icurve)9+ | No | Animation curve. The default curve is linear. Default value: **Curve.Linear** Since API version 9, this API is supported in ArkTS widgets.|
+| curve | string \| [Curve](ts-appendix-enums.md#curve) \| [ICurve](../apis/js-apis-curve.md#icurve)9+ | No | Animation curve. Default value: **Curve.EaseInOut** Since API version 9, this API is supported in ArkTS widgets.|
| delay | number | No | Delay of animation playback, in ms. The value **0** indicates that the playback is not delayed. Default value: **0** Value range: [0, +∞) **NOTE** - A value less than 0 evaluates to the value **0**. - Floating-point values will be rounded down to integers. For example, if the value set is 1.2, **1** will be used.|
| iterations | number | No | Number of times that the animation is played. Default value: **1** Value range: [-1, +∞) **NOTE** The value **-1** indicates that the animation is played for an unlimited number of times. The value **0** indicates that no animation is applied.|
| playMode | [PlayMode](ts-appendix-enums.md#playmode) | No | Animation playback mode. By default, the animation is played from the beginning after the playback is complete. Default value: **PlayMode.Normal** Since API version 9, this API is supported in ArkTS widgets. For details about the restrictions, see **Notes about PlayMode**.|
diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md b/en/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md
index 5a8f52093e36bc198bb47b5fefdb60f0aac56cfd..732c575f94ea2e5bea7c463eeafadfcc4ad78f51 100644
--- a/en/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md
+++ b/en/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md
@@ -22,7 +22,7 @@ Since API version 9, this API is supported in ArkTS widgets.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| group | string | No| Group name.|
+| group | string | No| Group name. **NOTE** If there are multiple check box groups with the same group name, only the first check box group takes effect.|
## Attributes
diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md b/en/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md
index bb8c77dd981948116af501bcd05378fd75503200..59c35d6c4c69792801a813059688860dfe9e4c29 100644
--- a/en/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md
+++ b/en/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md
@@ -26,6 +26,26 @@ Creates a date picker in the given date range.
| end | Date | No | End date of the picker. Default value: **Date('2100-12-31')** |
| selected | Date | No | Date of the selected item. Default value: current system date Since API version 10, this parameter supports [$$](../../quick-start/arkts-two-way-sync.md) for two-way binding of variables.|
+**Handling in the case of exceptions**
+
+| Exception | Result |
+| -------- | ------------------------------------------------------------ |
+| The start date is later than the end date, and the selected date is not set. | The start date, end date, and selected date are set to the default values. |
+| The start date is later than the end date, and the selected date is earlier than the default start date. | The start date and end date are set to the default values, and the selected date is set to the default start date. |
+| The start date is later than the end date, and the selected date is later than the default end date. | The start date and end date are set to the default values, and the selected date is set to the default end date. |
+| The start date is later than the end date, and the selected date is within the range of the default start date and end date. | The start date and end date are set to the default values, and the selected date is set to the specified value.|
+| The selected date is earlier than the start date. | The selected date is set to the start date. |
+| The selected date is later than the end date. | The selected date is set to the end date. |
+| The start date is later than the current system date, and the selected date is not set. | The selected date is set to the start date. |
+| The end date is earlier than the current system date, and the selected date is not set. | The selected date is set to the end date. |
+| The set date is in invalid format, for example, **'1999-13-32'**. | The default value is used. |
+| The start date or end date is earlier than the valid date range. | The start date or end date is set to the earliest date in the valid date range. |
+| The start date or end date is later than the valid date range. | The start date or end date is set to the latest date in the valid date range. |
+
+The valid date range is from 1900-1-31 to 2100-12-31.
+
+The exception detection and handling with the selected date comes after that with the start date and end date.
+
## Attributes
In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
@@ -48,9 +68,10 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
In addition to the [universal events](ts-universal-events-click.md), the following events are supported.
-| Name | Description |
-| ---------------------------------------- | ----------- |
-| onChange(callback: (value: DatePickerResult) => void) | Triggered when a date is selected.|
+| Name | Description |
+| ------------------------------------------------------------ | ------------------------------------------------------------ |
+| onChange(callback: (value: DatePickerResult) => void)(deprecated) | Triggered when a date is selected. **NOTE** This API is supported since API version 8 and deprecated since API version 10. You are advised to use **onDateChange(callback: (value: Date) => void)** instead.|
+| onDateChange(callback: (value: Date) => void)10+ | Triggered when a date is selected. |
## DatePickerResult
@@ -84,10 +105,13 @@ struct DatePickerExample {
end: new Date('2100-1-1'),
selected: this.selectedDate
})
+ .disappearTextStyle({color: Color.Gray, font: {size: '16fp', weight: FontWeight.Bold}})
+ .textStyle({color: '#ff182431', font: {size: '18fp', weight: FontWeight.Normal}})
+ .selectedTextStyle({color: '#ff0000FF', font: {size: '26fp', weight: FontWeight.Regular}})
.lunar(this.isLunar)
- .onChange((value: DatePickerResult) => {
- this.selectedDate.setFullYear(value.year, value.month, value.day)
- console.info('select current date is: ' + JSON.stringify(value))
+ .onDateChange((value: Date) => {
+ this.selectedDate = value
+ console.info('select current date is: ' + value.toString())
})
}.width('100%')
@@ -95,4 +119,4 @@ struct DatePickerExample {
}
```
-
+
diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-formcomponent.md b/en/application-dev/reference/arkui-ts/ts-basic-components-formcomponent.md
index d75762999a60eebdcb3dc87de0aeca332cd6e6ab..3b8ae1031235123dc9490bcbbddc197828dcab67 100644
--- a/en/application-dev/reference/arkui-ts/ts-basic-components-formcomponent.md
+++ b/en/application-dev/reference/arkui-ts/ts-basic-components-formcomponent.md
@@ -12,10 +12,6 @@ The **FormComponent** is used to display widgets.
## Required Permissions
-ohos.permission.GET_BUNDLE_INFO
-
-ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
-
ohos.permission.REQUIRE_FORM
diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md b/en/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md
index d2861f650f3ede62450d477ee1904b0e29e17cf2..4bb8b494268a33881eed4810af59ea1984706ec2 100644
--- a/en/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md
+++ b/en/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md
@@ -22,10 +22,16 @@ Since API version 9, this API is supported in ArkTS widgets.
## Attributes
+In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
+
| Name| Type| Description|
| -------- | -------- | -------- |
| color | [ResourceColor](ts-types.md#resourcecolor) | Foreground color of the **\** component. Default value: **'#99666666'** Since API version 9, this API is supported in ArkTS widgets.|
-| enableLoading10+ | boolean | Whether to show the loading animation. Default value: **true** **NOTE** The component still takes up space in the layout when the loading animation is not shown. While the universal attribute **Visibility.Hidden** hides the entire component, including borders and paddings, **enableLoading=false** hides the loading animation only.|
+| enableLoading10+ | boolean | Whether to show the loading animation. Default value: **true** **NOTE** The component still takes up space in the layout when the loading animation is not shown. Unlike the universal attribute **Visibility.Hidden**, which hides the entire component, including borders and paddings, **enableLoading=false** hides the loading animation only.|
+
+## Events
+
+The [universal events](ts-universal-events-click.md) are supported.
## Example
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 e637a22e1193f0fdb727b8ffe91e042ff167b6fd..2cf2de93c45d0935ff9ebfec2fcf0eb1f29f3883 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
@@ -25,7 +25,7 @@ In addition to the [backgroundColor](ts-universal-attributes-background.md) attr
| Name | Type | Description |
| ------------ | ------------------------------------------------------------ | ------------------------------------------------------------ |
-| title | string \| [CustomBuilder](ts-types.md#custombuilder8) \| [NavigationCommonTitle](ts-basic-components-navigation.md#navigationcommontitle) \| [NavigationCustomTitle](ts-basic-components-navigation.md##navigationcustomtitle) | Page title. **NOTE** When the NavigationCustomTitle type is used to set the height, the **titleMode** attribute does not take effect. When the title string is too long: (1) If no subtitle is set, the string is scaled down, wrapped in two lines, and then clipped with an ellipsis (...); (2) If a subtitle is set, the subtitle is scaled down and then clipped with an ellipsis (...).|
+| title | string \| [CustomBuilder](ts-types.md#custombuilder8) \| [NavigationCommonTitle](ts-basic-components-navigation.md#navigationcommontitle) \| [NavigationCustomTitle](ts-basic-components-navigation.md##navigationcustomtitle) | Page title. **NOTE** When the NavigationCustomTitle type is used to set the height, the **titleMode** attribute does not take effect. When the title string is too long: (1) If no subtitle is set, the string is scaled down, wrapped in two lines, and then clipped with an ellipsis (...). (2) If a subtitle is set, the subtitle is scaled down and then clipped with an ellipsis (...). |
| hideTitleBar | boolean | Whether to hide the title bar. Default value: **false** **true**: Hide the title bar. **false**: Display the title bar.|
## Events
@@ -33,8 +33,8 @@ In addition to the [backgroundColor](ts-universal-attributes-background.md) attr
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. |
+| Name | Description |
+| ------------------------------------------------------- | ------------------------------------------------------------ |
+| onShown(callback: () => void)10+ | Called when the navigation destination page is displayed. |
+| 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-patternlock.md b/en/application-dev/reference/arkui-ts/ts-basic-components-patternlock.md
index 9ac58d5d98086229ddc723eae67a6ae43796c283..b329ce3e897475ccdae7b168c67468be2b6c3d52 100644
--- a/en/application-dev/reference/arkui-ts/ts-basic-components-patternlock.md
+++ b/en/application-dev/reference/arkui-ts/ts-basic-components-patternlock.md
@@ -22,17 +22,17 @@ PatternLock(controller?: PatternLockController)
## Attributes
-Except for **backgroundColor**, the universal attributes are not supported.
+In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| Name | Type | Description |
| --------------- | ------------------------------------- | ------------------------------------------------------------ |
-| sideLength | [Length](ts-types.md#length) | Width and height (same value) of the component. If this attribute is set to 0 or a negative value, the component is not displayed. Default value: **300vp**|
-| circleRadius | [Length](ts-types.md#length) | Radius of the grid dot. Default value: **14vp** |
-| regularColor | [ResourceColor](ts-types.md#resourcecolor) | Fill color of the grid dot in unselected state. Default value: **Color.Black**|
-| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Fill color of the grid dot in selected state. Default value: **Color.Black**|
-| activeColor | [ResourceColor](ts-types.md#resourcecolor) | Fill color of the grid dot in activated state, which is when the dot is highlighted but not selected. Default value: **Color.Black**|
+| sideLength | [Length](ts-types.md#length) | Width and height (same value) of the component. If this attribute is set to **0** or a negative number, the component is not displayed. Default value: **288vp**|
+| circleRadius | [Length](ts-types.md#length) | Radius of the grid dot. If this attribute is set to **0** or a negative value, the default value is used. Default value: **6vp** |
+| regularColor | [ResourceColor](ts-types.md#resourcecolor) | Fill color of the grid dot in the unselected state. Default value: **Color.Black**|
+| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Fill color of the grid dot in the selected state. Default value: **Color.Black**|
+| activeColor | [ResourceColor](ts-types.md#resourcecolor) | Fill color of the grid dot in the activated state, which is when the dot is highlighted but not selected. Default value: **Color.Black**|
| pathColor | [ResourceColor](ts-types.md#resourcecolor) | Path color. Default value: **Color.Blue** |
-| pathStrokeWidth | number \| string | Width of the path stroke. If this attribute is set to 0 or a negative value, the path stroke is not displayed. Default value: **34vp** |
+| pathStrokeWidth | number \| string | Width of the path stroke. If this attribute is set to **0** or a negative value, the path stroke is not displayed. Default value: **12vp** |
| autoReset | boolean | Whether to allow the user to reset the component status (that is, clear the input) by touching the component again after the input is complete. The value **true** means that the user can reset the component status by touching the component again after the input is complete, and **false** means the opposite. Default value: **true**|
## Events
diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-richeditor.md b/en/application-dev/reference/arkui-ts/ts-basic-components-richeditor.md
index 23d1dd164423c71f692e07fe8600a791f94466e7..b492893437d12229d84e45fe345b23bb5a506839 100644
--- a/en/application-dev/reference/arkui-ts/ts-basic-components-richeditor.md
+++ b/en/application-dev/reference/arkui-ts/ts-basic-components-richeditor.md
@@ -27,6 +27,15 @@ RichEditor(value: RichEditorOptions)
The [universal attributes](ts-universal-attributes-size.md) are supported.
+> **NOTE**
+>
+> The default value of the **clip** attribute is **true**.
+
+| Name | Type | Description |
+| ------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
+| customKeyboard10+ | [CustomBuilder](ts-types.md#custombuilder8) | Custom keyboard. **NOTE** When a custom keyboard is set, activating the text box opens the specified custom component, instead of the system input method. The custom keyboard's height can be set through the **height** attribute of the custom component's root node, and its width is fixed at the default value. The custom keyboard is displayed on top of the current page, without compressing or raising the page. The custom keyboard cannot obtain the focus, but it blocks gesture events. By default, the custom keyboard is closed when the input component loses the focus.|
+
+
## Events
In addition to the [universal events](ts-universal-events-click.md), the following events are supported.
@@ -209,7 +218,7 @@ Adds an image span.
updateSpanStyle(value: RichEditorUpdateTextSpanStyleOptions | RichEditorUpdateImageSpanStyleOptions): void
-Updates the text or image span style.
+Updates the text or image span style. If only part of a span is updated, the span is split into multiple spans based on the updated part and the unupdated part.
**Parameters**
@@ -299,7 +308,7 @@ Provides the text style information.
| fontColor | [ResourceColor](ts-types.md#resourcecolor) | No| Font color. Default value: **Color.Black**|
| fontSize | [Length](ts-types.md#length) \| number | No| Font size. Default value: **16fp**|
| fontStyle | [FontStyle](ts-appendix-enums.md#fontstyle) | No| Font style. Default value: **FontStyle.Normal**|
-| fontWeight | [FontWeight](ts-appendix-enums.md#fontweight) \| number \| string | No| Font weight. Default value: **FontWeight.Normal**|
+| fontWeight | [FontWeight](ts-appendix-enums.md#fontweight) \| number \| string | No| Font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. A larger value indicates a heavier font weight. The default value is **400**. For the string type, only strings of the number type are supported, for example, **"400"**, **"bold"**, **"bolder"**, **"lighter"**, **"regular"**, and **"medium"**, which correspond to the enumerated values in **FontWeight**. Default value: **FontWeight.Normal**|
| fontFamily | [ResourceStr](ts-types.md#resourcestr) \| number \| string | No| Font family. Default value: **'HarmonyOS Sans'**. Currently, only the default font is supported. Default font: **'HarmonyOS Sans'**|
| decoration | { type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype), color?: [ResourceColor](ts-types.md#resourcecolor) } | No| Style and color of the text decorative line. Default value: { type: TextDecorationType.None, color: Color.Black }|
@@ -335,6 +344,8 @@ Provides the span range information.
## Example
+### Example 1
+
```ts
// xxx.ets
@Entry
@@ -484,3 +495,47 @@ struct Index {
}
```

+
+### Example 2
+
+```ts
+// xxx.ets
+@Entry
+@Component
+struct RichEditorExample {
+ controller: RichEditorController = new RichEditorController()
+
+ // Create a custom keyboard component.
+ @Builder CustomKeyboardBuilder() {
+ Column() {
+ Grid() {
+ ForEach([1, 2, 3, 4, 5, 6, 7, 8, 9, '*', 0, '#'], (item) => {
+ GridItem() {
+ Button(item + "")
+ .width(110).onClick(() => {
+ this.controller.addTextSpan(item + '', {
+ style:
+ {
+ fontColor: Color.Orange,
+ fontSize: 30
+ }
+ })
+ })
+ }
+ })
+ }.maxCount(3).columnsGap(10).rowsGap(10).padding(5)
+ }.backgroundColor(Color.Gray)
+ }
+
+ build() {
+ Column() {
+ RichEditor({ controller: this.controller })
+ // Bind the custom keyboard.
+ .customKeyboard(this.CustomKeyboardBuilder()).margin(10).border({ width: 1 })
+ .height(200)
+ }
+ }
+}
+```
+
+
diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-search.md b/en/application-dev/reference/arkui-ts/ts-basic-components-search.md
index 10ae16a154852bbdedb8b408882852933da87f75..7c6b79a16898c80b42b96943ef522f367ba54aa2 100644
--- a/en/application-dev/reference/arkui-ts/ts-basic-components-search.md
+++ b/en/application-dev/reference/arkui-ts/ts-basic-components-search.md
@@ -12,7 +12,7 @@ Not supported
## APIs
-Search(options?: { value?: string; placeholder?: ResourceStr; icon?: string; controller?: SearchController })
+Search(options?: { value?: string, placeholder?: ResourceStr, icon?: string, controller?: SearchController })
**Parameters**
@@ -20,7 +20,7 @@ Search(options?: { value?: string; placeholder?: ResourceStr; icon?: string; con
| ----------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ |
| value | string | No | Text input in the search text box. Since API version 10, this parameter supports two-way binding through [$$](../../quick-start/arkts-two-way-sync.md).|
| placeholder | [ResourceStr](ts-types.md#resourcestr)10+ | No | Text displayed when there is no input. |
-| icon | string | No | Path to the search icon. By default, the system search icon is used. **NOTE** The icon data source can be a local or online image. - The supported formats include PNG, JPG, BMP, SVG, GIF, and pixelmap. - The Base64 string is supported in the following format: data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data], where [base64 data] is a Base64 string.|
+| icon | string | No | Path to the search icon. By default, the system search icon is used. **NOTE** The icon data source can be a local or online image. - The supported formats include PNG, JPG, BMP, SVG, GIF, and pixelmap. - The Base64 string is supported in the following format: data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data], where [base64 data] is a Base64 string. If this attribute and the **searchIcon** attribute are both set, the **searchIcon** attribute takes precedence.|
| controller | SearchController | No | Controller of the **\** component. |
## Attributes
@@ -41,11 +41,13 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| caretStyle10+ | [CaretStyle](#caretstyle10) | Caret style. Default value: { width: 1.5vp color: '#007DFF' } |
| enableKeyboardOnFocus10+ | boolean | Whether to enable the input method when the component obtains focus. Default value: **true** |
| selectionMenuHidden10+ | boolean | Whether to display the text selection menu when the text box is long-pressed or right-clicked. Default value: **false**|
+| customKeyboard10+ | [CustomBuilder](ts-types.md#custombuilder8) | Custom keyboard. **NOTE** When a custom keyboard is set, activating the text box opens the specified custom component, instead of the system input method. The custom keyboard's height can be set through the **height** attribute of the custom component's root node, and its width is fixed at the default value. The custom keyboard is displayed on top of the current page, without compressing or raising the page. The custom keyboard cannot obtain the focus, but it blocks gesture events. By default, the custom keyboard is closed when the input component loses the focus. You can also use the [stopEditing](#stopediting10) API to close the keyboard.|
+
## IconOptions10+
| Name| Type | Mandatory| Description |
| ------ | ------------------------------------------ | ---- | ----------- |
-| size | [Length](ts-types.md#length) | No | Icon size. |
+| size | [Length](ts-types.md#length) | No | Icon size. It cannot be set in percentage. |
| color | [ResourceColor](ts-types.md#resourcecolor) | No | Icon color. |
| src | [ResourceStr](ts-types.md#resourcestr) | No | Image source of the icon.|
@@ -60,7 +62,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name | Type | Mandatory| Description |
| --------- | ------------------------------------------ | ---- | ---------------- |
-| fontSize | [Length](ts-types.md#length) | No | Font size of the button.|
+| fontSize | [Length](ts-types.md#length) | No | Font size of the button. It cannot be set in percentage.|
| fontColor | [ResourceColor](ts-types.md#resourcecolor) | No | Font color of the button.|
## CancelButtonStyle10+
@@ -235,3 +237,46 @@ struct SearchButtoonExample {
```

+
+
+### Example 3
+
+```ts
+// xxx.ets
+@Entry
+@Component
+struct SearchExample {
+ controller: SearchController = new SearchController()
+ @State inputValue: string = ""
+
+ // Create a custom keyboard component.
+ @Builder CustomKeyboardBuilder() {
+ Column() {
+ Button('x').onClick(() => {
+ // Disable the custom keyboard.
+ this.controller.stopEditing()
+ })
+ Grid() {
+ ForEach([1, 2, 3, 4, 5, 6, 7, 8, 9, '*', 0, '#'], (item) => {
+ GridItem() {
+ Button(item + "")
+ .width(110).onClick(() => {
+ this.inputValue += item
+ })
+ }
+ })
+ }.maxCount(3).columnsGap(10).rowsGap(10).padding(5)
+ }.backgroundColor(Color.Gray)
+ }
+
+ build() {
+ Column() {
+ Search({ controller: this.controller, value: this.inputValue})
+ // Bind the custom keyboard.
+ .customKeyboard(this.CustomKeyboardBuilder()).margin(10).border({ width: 1 })
+ }
+ }
+}
+````
+
+
diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-slider.md b/en/application-dev/reference/arkui-ts/ts-basic-components-slider.md
index 5939f8899543cdb715d6f758821af47c6ea022f7..a9a5642fda606b7bdcd7727abdee23b6f6dc0b35 100644
--- a/en/application-dev/reference/arkui-ts/ts-basic-components-slider.md
+++ b/en/application-dev/reference/arkui-ts/ts-basic-components-slider.md
@@ -48,7 +48,7 @@ Except touch target attributes, the universal attributes are supported.
| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the selected part of the slider track. Since API version 9, this API is supported in ArkTS widgets.|
| showSteps | boolean | Whether to display the current step. Default value: **false** Since API version 9, this API is supported in ArkTS widgets.|
| showTips | value: boolean, content10+ ?: [ResourceStr](ts-types.md#resourcestr) | **value**: whether to display a tooltip when the user drags the slider. Default value: **false** **content**: text content of the tooltip. The default value is the current percentage. Since API version 9, this API is supported in ArkTS widgets. **NOTE** When **direction** is set to **Axis.Horizontal**, the tooltip is displayed right above the slider. When **direction** is set to **Axis.Vertical**, the tooltip is displayed on the left of the slider. The drawing area of the tooltip is the overlay of the slider. If no margin is set for the slider or the margin is not large enough, the tooltip will be clipped.|
-| trackThickness | [Length](ts-types.md#length) | Track thickness of the slider. Default value: **4.0vp** when **style** is set to **[SliderStyle](#sliderstyle).OutSet**; **20.0vp** when **style** is set to **[SliderStyle](#sliderstyle).InSet** Since API version 9, this API is supported in ArkTS widgets. **NOTE** A value less than 0 evaluates to the default value.|
+| trackThickness | [Length](ts-types.md#length) | Track thickness of the slider. Default value: **4.0vp** when **style** is set to **[SliderStyle](#sliderstyle).OutSet**; **20.0vp** when **style** is set to **[SliderStyle](#sliderstyle).InSet** Since API version 9, this API is supported in ArkTS widgets. **NOTE** A value less than or equal to 0 evaluates to the default value.|
| blockBorderColor10+ | [ResourceColor](ts-types.md#resourcecolor) | Border color of the slider in the block direction.|
| blockBorderWidth10+ | [Length](ts-types.md#length) | Border width of the slider in the block direction.|
| stepColor10+ | [ResourceColor](ts-types.md#resourcecolor) | Step color.|
@@ -59,7 +59,7 @@ Except touch target attributes, the universal attributes are supported.
## SliderBlockStyle10+
-Desribes the style of the slider in the block direction.
+Describes the style of the slider in the block direction.
| Name | Type | Mandatory| Description |
| ----- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md b/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md
index f8a2a0cba6a7b5dd36ff165a3df05cfd11dfede2..61accc536e8ad4a8a06ed06e879a8de4ca4028ae 100644
--- a/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md
+++ b/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md
@@ -40,7 +40,7 @@ Among the [universal attributes](ts-universal-attributes-size.md) and [universal
| inputFilter8+ | { value: [ResourceStr](ts-types.md#resourcestr), error?: (value: string) => void } | Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are filtered out. The regular expression can match single characters, but not strings. - **value**: regular expression to set. - **error**: filtered-out content to return when regular expression matching fails.|
| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed. Default value: **CopyOptions.LocalDevice** If this attribute is set to **CopyOptions.None**, the paste operation is allowed, but not the copy or cut operation.|
| showPasswordIcon9+ | boolean | Whether to display the password icon at the end of the password text box. Default value: **true**|
-| style9+ | [TextInputStyle](#textinputstyle9) \| [TextContentStyle](ts-appendix-enums.md#textcontentstyle10) | Text input style. Default value: **TextInputStyle.Default** In the case of **TextInputStyle.Inline**, setting the text alignment mode is not available.|
+| style9+ | [TextInputStyle](#textinputstyle9) \| [TextContentStyle](ts-appendix-enums.md#textcontentstyle10) | Text input style. Default value: **TextInputStyle.Default**|
| textAlign9+ | [TextAlign](ts-appendix-enums.md#textalign) | Horizontal alignment of the text. Default value: **TextAlign.Start** **NOTE** Available options are **TextAlign.Start**, **TextAlign.Center**, and **TextAlign.End**. To set vertical alignment for the text, use the [align](ts-universal-attributes-location.md) attribute. The **align** attribute alone does not control the horizontal position of the text. In other words, **Alignment.TopStart**, **Alignment.Top**, and **Alignment.TopEnd** produce the same effect, top-aligning the text; **Alignment.Start**, **Alignment.Center**, and **Alignment.End** produce the same effect, centered-aligning the text vertically; **Alignment.BottomStart**, **Alignment.Bottom**, and **Alignment.BottomEnd** produce the same effect, bottom-aligning the text. |
| selectedBackgroundColor10+ | [ResourceColor](ts-types.md#resourcecolor) | Background color of the selected text. If the opacity is not set, the color is opaque. For example, **0x80000000** indicates black with 50% opacity.|
| caretStyle10+ | { width: [Length](ts-types.md#length) } | Caret style. |
diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md b/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md
index 6a48af10416c622cbf2726655a82711202093e56..1c4f04d875cf51f6868700329791bcd2298c7226 100644
--- a/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md
+++ b/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md
@@ -76,6 +76,9 @@ struct TimePickerExample {
this.selectedTime.setHours(value.hour, value.minute)
console.info('select current date is: ' + JSON.stringify(value))
})
+ .disappearTextStyle({color: Color.Red, font: {size: 15, weight: FontWeight.Lighter}})
+ .textStyle({color: Color.Black, font: {size: 20, weight: FontWeight.Normal}})
+ .selectedTextStyle({color: Color.Blue, font: {size: 30, weight: FontWeight.Bolder}})
}.width('100%')
}
}
diff --git a/en/application-dev/reference/arkui-ts/ts-components-summary.md b/en/application-dev/reference/arkui-ts/ts-components-summary.md
index c9af135050662477b4fb47c042d7f4fe0c151a20..110692465f554d40fb00f5d2ab2068205d4068fa 100644
--- a/en/application-dev/reference/arkui-ts/ts-components-summary.md
+++ b/en/application-dev/reference/arkui-ts/ts-components-summary.md
@@ -272,36 +272,55 @@
- [ScrollBar](ts-basic-components-scrollbar.md)
A component that is used together with scrollable components, such as **\**, **\**, and **\**.
+
- [Badge](ts-container-badge.md)
A container that can be attached to another component for tagging.
+
- [AlphabetIndexer](ts-container-alphabet-indexer.md)
A component that can create a logically indexed array of items in a container for instant location.
+
- [Panel](ts-container-panel.md)
A container that presents lightweight content with flexible sizes.
+
- [Refresh](ts-container-refresh.md)
A container that provides the pull-to-refresh feature.
+
- [AbilityComponent](ts-container-ability-component.md)
A container that is used for independently displaying an ability.
+
- [RemoteWindow](ts-basic-components-remotewindow.md)
A component that is used to control the application window, providing the component animator and application window linkage animator during application startup and exit.
+
- [FormComponent](ts-basic-components-formcomponent.md)
A component that is used to display widgets.
+
- [FormLink](ts-container-formlink.md)
A component that provides interactions with static widgets.
+
+- [Hyperlink](ts-container-hyperlink.md)
+
+ A component that implements a link from a location in the component to another location.
+
- [Menu](ts-basic-components-menu.md)
A component that is used to present a vertical list of items to the user.
+
- [MenuItem](ts-basic-components-menuitem.md)
A component that is used to represent an item in a menu.
+
- [MenuItemGroup](ts-basic-components-menuitemgroup.md)
A component that is used to represent a group of menu items.
+
+- [UIExtensionComponent](ts-container-ui-extension-component.md)
+
+ A component that is used to embed UIs provided by other applications in the local application UI.
diff --git a/en/application-dev/reference/arkui-ts/ts-container-columnsplit.md b/en/application-dev/reference/arkui-ts/ts-container-columnsplit.md
index 594f3f24a30912af4e05a12d1c3dfe0a51957358..54c915981ad354d5c38f8fbb5e78dd149784ea94 100644
--- a/en/application-dev/reference/arkui-ts/ts-container-columnsplit.md
+++ b/en/application-dev/reference/arkui-ts/ts-container-columnsplit.md
@@ -1,18 +1,15 @@
# ColumnSplit
-The **\** component lays out child components vertically and inserts a horizontal divider between components.
+The **\** component lays out child components vertically and inserts a horizontal divider between every two child components.
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
-
-
## Child Components
Supported
-
## APIs
ColumnSplit()
@@ -20,17 +17,24 @@ ColumnSplit()
## Attributes
-| Name| Type| Description|
-| -------- | -------- | -------- |
-| resizeable | boolean | Whether the divider can be dragged. Default value: **false** |
+| Name | Type | Description |
+|-----------------------|-------------------------------------------------------------------|---------------------------------|
+| resizeable | boolean | Whether the divider can be dragged. Default value: **false** |
+| divider10+ | [ColumnSplitDividerStyle](#columnsplitdividerstyle10) \| null | Margin of the divider. - **DividerStyle**: distance between the divider and the child component above or below it. - Default value: **null**, indicating that the top and bottom margins of the divider are 0.|
+
+## ColumnSplitDividerStyle10+
+
+| Name | Type | Mandatory| Description |
+| ----------- | ------------- | ---- |--------------------------|
+| startMargin | [Dimension](ts-types.md#dimension10) | No | Distance between the divider and the child component above it. Default value: **0**|
+| endMargin | [Dimension](ts-types.md#dimension10) | No | Distance between the divider and the child component below it. Default value: **0**|
> **NOTE**
>
-> Similar to **\**, the divider of **\** can be dragged to a position that just fully holds a component.
->
-> Dragging is not supported in the Previewer. Check the drag effect on a real device.
+> Similar to **\**, the divider of **\