diff --git a/CODEOWNERS b/CODEOWNERS index 3598264d0126154e0a84838f393fb3864f493dd7..fffaf64564e559bbf9ca4ffd5d5a65e228b26e00 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 @@ -242,13 +241,13 @@ zh-cn/application-dev/reference/apis/js-apis-data-preferences.md @feng-aiwen @ge zh-cn/application-dev/reference/apis/js-apis-data-rdb.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 zh-cn/application-dev/reference/apis/js-apis-data-udmf.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 zh-cn/application-dev/reference/apis/js-apis-data-cloudData.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 -zh-cn/application-dev/reference/apis/js-apis-data-relationStore.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 +zh-cn/application-dev/reference/apis/js-apis-data-relationalStore.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 zh-cn/application-dev/reference/apis/js-apis-data-resultset.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 zh-cn/application-dev/reference/apis/js-apis-data-storage.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 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,3 +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 +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/Readme-EN.md b/en/application-dev/Readme-EN.md index 5147d8c5200157e6a2edc8091630bbf22a6b9fb6..6e40eb34a50e798f7ae75f7c8cba2804cb6dfc51 100644 --- a/en/application-dev/Readme-EN.md +++ b/en/application-dev/Readme-EN.md @@ -50,6 +50,7 @@ - [\@BuilderParam Decorator: \@Builder Function Reference](quick-start/arkts-builderparam.md) - [\@Styles Decorator: Definition of Resusable Styles](quick-start/arkts-style.md) - [\@Extend Decorator: Extension of Built-in Components](quick-start/arkts-extend.md) + - [\@AnimatableExtend Decorator: Definition of Animatable Attributes](quick-start/arkts-animatable-extend.md) - [stateStyles: Polymorphic Style](quick-start/arkts-statestyles.md) - State Management - [State Management Overview](quick-start/arkts-state-management-overview.md) @@ -77,6 +78,7 @@ - Development - [Application Models](application-models/Readme-EN.md) - [UI Development](ui/Readme-EN.md) + - [ArkTS Common Library](arkts-utils/Readme-EN.md) - [Web](web/Readme-EN.md) - [Notification](notification/Readme-EN.md) - [Window Manager](windowmanager/Readme-EN.md) diff --git a/en/application-dev/ai/Readme-EN.md b/en/application-dev/ai/Readme-EN.md index 525a9f3afe7e1e951d2216160cc23ba4c9b3335b..ac075993f5e8dc7ecba94e4f101f73005344b76f 100644 --- a/en/application-dev/ai/Readme-EN.md +++ b/en/application-dev/ai/Readme-EN.md @@ -1,3 +1,7 @@ # AI -- [Using MindSpore Lite for Model Inference (JS)](mindspore-lite-js-guidelines.md) +- [AI Development](ai-overview.md) +- [Using MindSpore Lite JavaScript APIs to Develop AI Applications](mindspore-guidelines-based-js.md) +- [Using MindSpore Lite Native APIs to Develop AI Applications](mindspore-guidelines-based-native.md) + + diff --git a/en/application-dev/ai/ai-overview.md b/en/application-dev/ai/ai-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..968ee3439966cf2062e35cbb7929e4783566a2c6 --- /dev/null +++ b/en/application-dev/ai/ai-overview.md @@ -0,0 +1,40 @@ +# AI Development + +## Overview + +OpenHarmony provides native distributed AI capabilities. The AI subsystem consists of the following components: +- MindSpore Lite: an AI inference framework that provides unified APIs for AI inference. +- Neural Network Runtime (NNRt): an intermediate bridge that connects the inference framework and AI hardware. + +## MindSpore Lite + +MindSpore Lite is a built-in AI inference framework of OpenHarmony. It provides AI model inference capabilities for different hardware devices and end-to-end AI model inference solutions for developers to empower intelligent applications in all scenarios. Currently, MindSpore Lite has been widely used in applications such as image classification, target recognition, facial recognition, and character recognition. + +**Figure 1** Development process for MindSpore Lite model inference +![MindSpore workflow](figures/mindspore_workflow.png) + +The MindSpore Lite development process consists of two phases: + +- Model conversion + + MindSpore Lite uses models in `.ms` format for inference. You can use the model conversion tool provided by MindSpore Lite to convert third-party framework models, such as TensorFlow, TensorFlow Lite, Caffe, and ONNX, into `.ms` models. For details, see [Converting Models for Inference](https://www.mindspore.cn/lite/docs/en/r1.8/use/converter_tool.html). + +- Model inference + + You can call the MindSpore Lite runtime APIs to implement model inference. The procedure is as follows: + + 1. Create an inference context by setting the inference hardware and number of threads. + 2. Load the **.ms** model file. + 3. Set the model input data. + 4. Perform model inference, and read the output. + +MindSpore Lite is built in the OpenHarmony standard system as a system component. You can develop AI applications based on MindSpore Lite in the following ways: + +- Method 1: [Using MindSpore Lite JavaScript APIs to develop AI applications](./mindspore-guidelines-based-js.md). You directly call MindSpore Lite JavaScript APIs in the UI code to load the AI model and perform model inference. An advantage of this method is the quick verification of the inference effect. +- Method 2: [Using MindSpore Lite native APIs to develop AI applications](./mindspore-guidelines-based-native.md). You encapsulate the algorithm models and the code for calling MindSpore Lite native APIs into a dynamic library, and then use N-API to encapsulate the dynamic library into JavaScript APIs for the UI to call. + +## Neural Network Runtime + +Neural Network Runtime (NNRt) functions as a bridge to connect the upper-layer AI inference framework and bottom-layer acceleration chip, implementing cross-chip inference computing of AI models. + +MindSpore Lite supports configuration of the NNRt backend, and therefore you can directly configure MindSpore Lite to use the NNRt hardware. The focus of this topic is about how to develop AI applications using MindSpore Lite. For details about how to use NNRt, see [Connecting the Neural Network Runtime to an AI Inference Framework](../napi/neural-network-runtime-guidelines.md). diff --git a/en/application-dev/ai/figures/mindspore_workflow.png b/en/application-dev/ai/figures/mindspore_workflow.png new file mode 100644 index 0000000000000000000000000000000000000000..babb4b4e1ec2b8961b79a324e3ac556fd1522e81 Binary files /dev/null and b/en/application-dev/ai/figures/mindspore_workflow.png differ diff --git a/en/application-dev/ai/mindspore-lite-js-guidelines.md b/en/application-dev/ai/mindspore-guidelines-based-js.md similarity index 62% rename from en/application-dev/ai/mindspore-lite-js-guidelines.md rename to en/application-dev/ai/mindspore-guidelines-based-js.md index 1f309acf19ba608ac698892ed64bb2e75ffdc437..a504d6b2c9a1936b6408d76b3d5e34ed5da23db4 100644 --- a/en/application-dev/ai/mindspore-lite-js-guidelines.md +++ b/en/application-dev/ai/mindspore-guidelines-based-js.md @@ -1,10 +1,8 @@ -# Using MindSpore Lite for Model Inference (JS) +# Using MindSpore Lite JavaScript APIs to Develop AI Applications ## Scenarios -MindSpore Lite is an AI engine that implements AI model inference for different hardware devices. It has been used in a wide range of fields, such as image classification, target recognition, facial recognition, and character recognition. - -This document describes the general development process for implementing MindSpore Lite model inference. For details about how to use native APIs to implement model inference, see [Using MindSpore Lite for Model Inference](../napi/mindspore-lite-guidelines.md). +You can use the JavaScript APIs provided by MindSpore Lite to directly integrate MindSpore Lite capabilities into the UI code. This way, you can quickly deploy AI algorithms for AI model inference. ## Basic Concepts @@ -27,16 +25,14 @@ APIs involved in MindSpore Lite model inference are categorized into context API ## How to Develop -The development process consists of the following main steps: +Assume that you have prepared a model in the **.ms** format. The key steps in model inference are model reading, model building, model inference, and memory release. The development procedure is described as follows: + +1. Create a context, and set parameters such as the number of runtime threads and device type. +2. Load the model. In this example, the model is read from the file. +3. Load data. Before executing a model, you need to obtain the model input and then fill data in the input tensor. +4. Perform model inference by calling **predict**, and read the output. -1. Prepare the required model. You can download the required model directly or obtain the model by using the model conversion tool. The required data is read from the `bin` file. - - If the downloaded model is in the `.ms` format, you can use it directly for inference. This document uses `mnet.caffemodel.ms` as an example. - - If the downloaded model uses a third-party framework, such as TensorFlow, TensorFlow Lite, Caffe, or ONNX, you can use the [model conversion tool](https://www.mindspore.cn/lite/docs/en/r2.0/use/downloads.html#1-8-1) to convert it to the `.ms` format. -2. Create a context, and set parameters such as the number of runtime threads and device type. -3. Load the model. In this example, the model is read from the file. -4. Load data. Before executing a model, you need to obtain the model input and then fill data in the input tensor. -5. Perform inference and print the output. Call the **predict** API to perform model inference. ```js @State inputName: string = 'mnet_caffemodel_nhwc.bin'; @State T_model_predict: string = 'Test_MSLiteModel_predict' @@ -49,7 +45,6 @@ build() { .fontSize(30) .fontWeight(FontWeight.Bold) .onClick(async () => { - // 1. Prepare for a model. let syscontext = globalThis.context; syscontext.resourceManager.getRawFileContent(this.inputName).then((buffer) => { this.inputBuffer = buffer; @@ -57,20 +52,24 @@ build() { }).catch(error => { console.error('Failed to get buffer, error code: ${error.code},message:${error.message}.'); }) - // 2. Create a context. + + // 1. Create a context. let context: mindSporeLite.Context = {}; context.target = ['cpu']; context.cpu = {} context.cpu.threadNum = 1; context.cpu.threadAffinityMode = 0; context.cpu.precisionMode = 'enforce_fp32'; - // 3. Load the model. + + // 2. Load the model. let modelFile = '/data/storage/el2/base/haps/entry/files/mnet.caffemodel.ms'; let msLiteModel = await mindSporeLite.loadModelFromFile(modelFile, context); - // 4. Load data. + + // 3. Set the input data. const modelInputs = msLiteModel.getInputs(); modelInputs[0].setData(this.inputBuffer.buffer); - // 5. Perform inference and print the output. + + // 4. Perform inference and print the output. console.log('=========MSLITE predict start=====') msLiteModel.predict(modelInputs).then((modelOutputs) => { let output0 = new Float32Array(modelOutputs[0].getData()); @@ -89,21 +88,21 @@ build() { ## Debugging and Verification -1. Connect to the rk3568 development board on DevEco Studio, click **Run entry**, and compile your own HAP. The following information is displayed: +1. On DevEco Studio, connect to the device, click **Run entry**, and compile your own HAP. The following information is displayed: ```shell Launching com.example.myapptfjs $ hdc uninstall com.example.myapptfjs - $ hdc install -r "D:\TVOS\JSAPI\MyAppTfjs\entry\build\default\outputs\default\entry-default-signed.hap" + $ hdc install -r "path/to/xxx.hap" $ hdc shell aa start -a EntryAbility -b com.example.myapptfjs ``` -2. Use the hdc tool to connect to the rk3568 development board and push `mnet.caffemodel.ms` to the sandbox directory on the device. `mnet\_caffemodel\_nhwc.bin` is stored in the `rawfile` directory of the local project. +2. Use hdc to connect to the device, and push **mnet.caffemodel.ms** to the sandbox directory on the device. **mnet\_caffemodel\_nhwc.bin** is stored in the **rawfile** directory of the local project. ```shell - hdc -t 7001005458323933328a00bcdf423800 file send .\mnet.caffemodel.ms /data/app/el2/100/base/com.example.myapptfjs/haps/entry/files/ + hdc -t your_device_id file send .\mnet.caffemodel.ms /data/app/el2/100/base/com.example.myapptfjs/haps/entry/files/ ``` -3. Click **Test\_MSLiteModel\_predict** on the screen of the rk3568 development board to run the test case. The following information is displayed in the HiLog printing result: +3. Click **Test\_MSLiteModel\_predict** on the device screen to run the test case. The following information is displayed in the HiLog printing result: ```shell 08-27 23:25:50.278 31782-31782/? I C03d00/JSAPP: =========MSLITE predict start===== diff --git a/en/application-dev/ai/mindspore-guidelines-based-native.md b/en/application-dev/ai/mindspore-guidelines-based-native.md new file mode 100644 index 0000000000000000000000000000000000000000..8294ad4c3213ecd7815962cb96751e2af72a77d5 --- /dev/null +++ b/en/application-dev/ai/mindspore-guidelines-based-native.md @@ -0,0 +1,244 @@ +# Using MindSpore Lite Native APIs to Develop AI Applications + +## Scenarios + +You can use the native APIs provided by MindSpore Lite to deploy AI algorithms and provides APIs for the UI layer to invoke the algorithms for model inference. A typical scenario is the AI SDK development. + +## Basic concepts + +- [N-API](../reference/native-lib/third_party_napi/napi.md): a set of native APIs used to build JavaScript components. N-APIs can be used to encapsulate libraries developed using C/C++ into JavaScript modules. + +## Preparing the Environment + +- Install DevEco Studio 3.1.0.500 or later, and update the SDK to API version 10 or later. + +## How to Develop + +1. Create a native C++ project. + +Open DevEco Studio, choose **File** > **New** > **Create Project** to create a native C++ template project. By default, the **entry/src/main/** directory of the created project contains the **cpp/** directory. You can store C/C++ code in this directory and provide JavaScript APIs for the UI layer to call the code. + +2. Compile the C++ inference code. + +Assume that you have prepared a model in the **.ms** format. + +Before using the Native APIs provided by MindSpore Lite for development, you need to reference the corresponding header files. + +```c +#include +#include +#include +#include +``` + +(1). Read model files. + +```C++ +void *ReadModelFile(NativeResourceManager *nativeResourceManager, const std::string &modelName, size_t *modelSize) { + auto rawFile = OH_ResourceManager_OpenRawFile(nativeResourceManager, modelName.c_str()); + if (rawFile == nullptr) { + LOGE("Open model file failed"); + return nullptr; + } + long fileSize = OH_ResourceManager_GetRawFileSize(rawFile); + void *modelBuffer = malloc(fileSize); + if (modelBuffer == nullptr) { + LOGE("Get model file size failed"); + } + int ret = OH_ResourceManager_ReadRawFile(rawFile, modelBuffer, fileSize); + if (ret == 0) { + LOGI("Read model file failed"); + OH_ResourceManager_CloseRawFile(rawFile); + return nullptr; + } + OH_ResourceManager_CloseRawFile(rawFile); + *modelSize = fileSize; + return modelBuffer; +} +``` + +(2). Create a context, set parameters such as the number of threads and device type, and load the model. + +```c++ +OH_AI_ModelHandle CreateMSLiteModel(void *modelBuffer, size_t modelSize) { + // Create a context. + auto context = OH_AI_ContextCreate(); + if (context == nullptr) { + DestroyModelBuffer(&modelBuffer); + LOGE("Create MSLite context failed.\n"); + return nullptr; + } + auto cpu_device_info = OH_AI_DeviceInfoCreate(OH_AI_DEVICETYPE_CPU); + OH_AI_ContextAddDeviceInfo(context, cpu_device_info); + + // Load the .ms model file. + auto model = OH_AI_ModelCreate(); + if (model == nullptr) { + DestroyModelBuffer(&modelBuffer); + LOGE("Allocate MSLite Model failed.\n"); + return nullptr; + } + + auto build_ret = OH_AI_ModelBuild(model, modelBuffer, modelSize, OH_AI_MODELTYPE_MINDIR, context); + DestroyModelBuffer(&modelBuffer); + if (build_ret != OH_AI_STATUS_SUCCESS) { + OH_AI_ModelDestroy(&model); + LOGE("Build MSLite model failed.\n"); + return nullptr; + } + LOGI("Build MSLite model success.\n"); + return model; +} +``` + +(3). Set the model input data, perform model inference, and obtain the output data. + +```js +void RunMSLiteModel(OH_AI_ModelHandle model) { + // Set the model input data. + auto inputs = OH_AI_ModelGetInputs(model); + FillInputTensors(inputs); + + auto outputs = OH_AI_ModelGetOutputs(model); + + // Perform inference and print the output. + auto predict_ret = OH_AI_ModelPredict(model, inputs, &outputs, nullptr, nullptr); + if (predict_ret != OH_AI_STATUS_SUCCESS) { + OH_AI_ModelDestroy(&model); + LOGE("Predict MSLite model error.\n"); + return; + } + LOGI("Run MSLite model success.\n"); + + LOGI("Get model outputs:\n"); + for (size_t i = 0; i < outputs.handle_num; i++) { + auto tensor = outputs.handle_list[i]; + LOGI("- Tensor %{public}d name is: %{public}s.\n", static_cast(i), OH_AI_TensorGetName(tensor)); + LOGI("- Tensor %{public}d size is: %{public}d.\n", static_cast(i), (int)OH_AI_TensorGetDataSize(tensor)); + auto out_data = reinterpret_cast(OH_AI_TensorGetData(tensor)); + std::cout << "Output data is:"; + for (int i = 0; (i < OH_AI_TensorGetElementNum(tensor)) && (i <= kNumPrintOfOutData); i++) { + std::cout << out_data[i] << " "; + } + std::cout << std::endl; + } + OH_AI_ModelDestroy(&model); +} +``` + + +(4). Implement a complete model inference process. + +```C++ +static napi_value RunDemo(napi_env env, napi_callback_info info) +{ + LOGI("Enter runDemo()"); + GET_PARAMS(env, info, 2); + napi_value error_ret; + napi_create_int32(env, -1, &error_ret); + + const std::string modelName = "ml_headpose.ms"; + size_t modelSize; + auto resourcesManager = OH_ResourceManager_InitNativeResourceManager(env, argv[1]); + auto modelBuffer = ReadModelFile(resourcesManager, modelName, &modelSize); + if (modelBuffer == nullptr) { + LOGE("Read model failed"); + return error_ret; + } + LOGI("Read model file success"); + + auto model = CreateMSLiteModel(modelBuffer, modelSize); + if (model == nullptr) { + OH_AI_ModelDestroy(&model); + LOGE("MSLiteFwk Build model failed.\n"); + return error_ret; + } + + RunMSLiteModel(model); + + napi_value success_ret; + napi_create_int32(env, 0, &success_ret); + + LOGI("Exit runDemo()"); + return success_ret; +} +``` + +(5). Write the **CMake** script to link the MindSpore Lite dynamic library `libmindspore_lite_ndk.so`. + +```cmake +cmake_minimum_required(VERSION 3.4.1) +project(OHOSMSLiteNapi) + +set(NATIVERENDER_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}) + +include_directories(${NATIVERENDER_ROOT_PATH} + ${NATIVERENDER_ROOT_PATH}/include) + +add_library(mslite_napi SHARED mslite_napi.cpp) +target_link_libraries(mslite_napi PUBLIC mindspore_lite_ndk) # MindSpore Lite dynamic library to link +target_link_libraries(mslite_napi PUBLIC hilog_ndk.z) +target_link_libraries(mslite_napi PUBLIC rawfile.z) +target_link_libraries(mslite_napi PUBLIC ace_napi.z) +``` + + +3. Use N-APIs to encapsulate C++ dynamic libraries into JavaScript modules. + + +Create the **libmslite_api/** subdirectory in **entry/src/main/cpp/types/**, and create the **index.d.ts** file in the subdirectory. The file content is as follows: + +```js +export const runDemo: (a:String, b:Object) => number; +``` + +Use the preceding code to define the JavaScript API `runDemo()`. + +In addition, add the **oh-package.json5** file to associate the API with the **.so** file to form a complete JavaScript module. + +```json +{ + "name": "libmslite_napi.so", + "types": "./index.d.ts" +} +``` + +4. Invoke the encapsulated MindSpore module in the UI code. + +In **entry/src/ets/MainAbility/pages/index.ets**, define the **onClick()** event and call the encapsulated **runDemo()** API in the event callback. + +```js +import msliteNapi from'libmslite_napi.so' // Import the msliteNapi module. + +// Certain code omitted + +// Trigger the event when the text on the UI is tapped. +.onClick(() => { + resManager.getResourceManager().then(mgr => { + hilog.info(0x0000, TAG, '*** Start MSLite Demo ***'); + let ret = 0; + ret = msliteNapi.runDemo("", mgr); // Call runDemo() to perform AI model inference. + if (ret == -1) { + hilog.info(0x0000, TAG, 'Error when running MSLite Demo!'); + } + hilog.info(0x0000, TAG, '*** Finished MSLite Demo ***'); + }) +}) +``` + +## Debugging and Verification + +On DevEco Studio, connect to the device and click **Run entry**. The following log is generated for the application process: + +```text +08-08 16:55:33.766 1513-1529/com.mslite.native_demo I A00000/MSLiteNativeDemo: *** Start MSLite Demo *** +08-08 16:55:33.766 1513-1529/com.mslite.native_demo I A00000/[MSLiteNapi]: Enter runDemo() +08-08 16:55:33.772 1513-1529/com.mslite.native_demo I A00000/[MSLiteNapi]: Read model file success +08-08 16:55:33.799 1513-1529/com.mslite.native_demo I A00000/[MSLiteNapi]: Build MSLite model success. +08-08 16:55:33.818 1513-1529/com.mslite.native_demo I A00000/[MSLiteNapi]: Run MSLite model success. +08-08 16:55:33.818 1513-1529/com.mslite.native_demo I A00000/[MSLiteNapi]: Get model outputs: +08-08 16:55:33.818 1513-1529/com.mslite.native_demo I A00000/[MSLiteNapi]: - Tensor 0 name is: output_node_0. +08-08 16:55:33.818 1513-1529/com.mslite.native_demo I A00000/[MSLiteNapi]: - Tensor 0 size is: 12. +08-08 16:55:33.826 1513-1529/com.mslite.native_demo I A00000/[MSLiteNapi]: Exit runDemo() +08-08 16:55:33.827 1513-1529/com.mslite.native_demo I A00000/MSLiteNativeDemo: *** Finished MSLite Demo *** +``` diff --git a/en/application-dev/application-dev-guide-for-gitee.md b/en/application-dev/application-dev-guide-for-gitee.md index 2a5ff1426182d415f09b55868c48d4238974ba64..9770de4b35a7e23d38a0266e5e0daf826e656e00 100644 --- a/en/application-dev/application-dev-guide-for-gitee.md +++ b/en/application-dev/application-dev-guide-for-gitee.md @@ -25,7 +25,8 @@ All applications should be developed on top of these frameworks. Then, equip yourself for developing the key features, with the following guidelines: -- [Web](web/web-component-overview.md) +- [ArkTS Common Library](arkts-utils/Readme-EN.md) +- [Web](web/Readme-EN.md) - [Notification](notification/Readme-EN.md) - [Window Manager](windowmanager/Readme-EN.md) - [WebGL](webgl/Readme-EN.md) diff --git a/en/application-dev/application-dev-guide.md b/en/application-dev/application-dev-guide.md index d8bf473f9527e26eaf61c1a19757623879c4ef1d..5aef516bfc51bbe842ecd6be64f2be3b0b7a1653 100644 --- a/en/application-dev/application-dev-guide.md +++ b/en/application-dev/application-dev-guide.md @@ -25,13 +25,14 @@ All applications should be developed on top of these frameworks. Then, equip yourself for developing the key features, with the following guidelines: +- [ArkTS Common Library](arkts-utils/arkts-commonlibrary-overview.md) - [Web](web/web-component-overview.md) - [Notification](notification/notification-overview.md) - [Window Manager](windowmanager/window-overview.md) - [WebGL](webgl/webgl-overview.md) - [Media](media/media-application-overview.md) - [Security](security/userauth-overview.md) -- [AI](ai/mindspore-lite-js-guidelines.md) +- [AI](ai/ai-overview.md) - [Connectivity](connectivity/ipc-rpc-overview.md) - [Telephony Service](telephony/telephony-overview.md) - [Data Management](database/data-mgmt-overview.md) diff --git a/en/application-dev/application-models/Readme-EN.md b/en/application-dev/application-models/Readme-EN.md index 522a2d8e0de1280a26f0d416348aa665fd5062f6..7c320ef8068cd15bd0694f454c054b425d9841fd 100644 --- a/en/application-dev/application-models/Readme-EN.md +++ b/en/application-dev/application-models/Readme-EN.md @@ -21,6 +21,7 @@ - [EnterpriseAdminExtensionAbility](enterprise-extensionAbility.md) - [InputMethodExtensionAbility](inputmethodextentionability.md) - [WindowExtensionAbility (for System Applications Only)](windowextensionability.md) + - [DriverExtensionAbility](driverextensionability.md) - Service Widget Development in Stage Model - [Service Widget Overview](service-widget-overview.md) - Developing an ArkTS Widget @@ -43,6 +44,7 @@ - Widget Data Interaction - [Widget Data Interaction Overview](arkts-ui-widget-interaction-overview.md) - [Configuring a Widget to Update Periodically](arkts-ui-widget-update-by-time.md) + - [Updating Widget Content Through a Proxy](arkts-ui-widget-update-by-proxy.md) - [Updating Local and Online Images in the Widget](arkts-ui-widget-image-update.md) - [Updating Widget Content by State](arkts-ui-widget-update-by-status.md) - [Updating Widget Content by Widget Host (for System Applications Only)](arkts-ui-widget-content-update.md) @@ -59,10 +61,9 @@ - [Component Startup Rules (Stage Model)](component-startup-rules.md) - Inter-Device Application Component Interaction (Continuation) - [Continuation Overview](inter-device-interaction-hop-overview.md) - - [Cross-Device Migration (for System Applications Only)](hop-cross-device-migration.md) + - [Cross-Device Migration](hop-cross-device-migration.md) - [Multi-device Collaboration (for System Applications Only)](hop-multi-device-collaboration.md) - [Subscribing to System Environment Variable Changes](subscribe-system-environment-variable-changes.md) - - [Setting Atomic Services to Support Sharing](atomic-services-support-sharing.md) - Process Model - [Process Model Overview](process-model-stage.md) - Common Events diff --git a/en/application-dev/application-models/accessibilityextensionability.md b/en/application-dev/application-models/accessibilityextensionability.md index a76742c142bfccdd015665478aadbaedf19ff39e..94c4429c5b2a4b49ba4dbae48f813dce16bba68a 100644 --- a/en/application-dev/application-models/accessibilityextensionability.md +++ b/en/application-dev/application-models/accessibilityextensionability.md @@ -118,7 +118,12 @@ After developing the custom logic for an accessibility extension service, you mu ``` ## Enabling or Disabling a Custom Accessibility Extension Service -To enable or disable an accessibility extension service, run the following command: +You can enable or disable a custom accessibility extension service through the command line interface or the device settings. + +**Method 1**: through the command line interface + +Run the **hdc shell** command, then the following system command: + - To enable the service: **accessibility enable -a AccessibilityExtAbility -b com.example.demo -c rg** - To disable the service: **accessibility disable -a AccessibilityExtAbility -b com.example.demo** @@ -126,3 +131,9 @@ In the preceding commands, **AccessibilityExtAbility** indicates the name of the If the service is enabled or disabled successfully, the message "enable ability successfully" or "disable ability successfully" is displayed. + + **Method 2**: through the device settings +- From the device settings screen, access the list of installed extended services under accessibility. +If an extended service is not installed, it is grayed out, and "No service" is displayed. +- Select the target extended service, and toggle on or off the switch to enable or disable it. +- If you opt to enable a service, a security reminder is displayed. Wait until the countdown ends and then select the check box indicating that you are aware of and willing to assume the listed risks. diff --git a/en/application-dev/application-models/application-context-stage.md b/en/application-dev/application-models/application-context-stage.md index 17fe99577ab5cd782bcd4154274555bb8064da24..47fdeeedf1fe5238b0f0a2e56945be35208e0391 100644 --- a/en/application-dev/application-models/application-context-stage.md +++ b/en/application-dev/application-models/application-context-stage.md @@ -86,13 +86,13 @@ The application file paths obtained by the preceding contexts are different. | Name| Path| | -------- | -------- | - | bundleCodeDir | \/el1/bundle/| - | cacheDir | \/\/base/cache/| - | filesDir | \/\/base/files/| - | preferencesDir | \/\/base/preferences/| - | tempDir | \/\/base/temp/| - | databaseDir | \/\/database/| - | distributedFilesDir | \/el2/distributedFiles/| + | bundleCodeDir | \/el1/bundle| + | cacheDir | \/\/base/cache| + | filesDir | \/\/base/files| + | preferencesDir | \/\/base/preferences| + | tempDir | \/\/base/temp| + | databaseDir | \/\/database| + | distributedFilesDir | \/el2/distributedFiles| The sample code is as follows: @@ -110,6 +110,9 @@ The application file paths obtained by the preceding contexts are different. let distributedFilesDir = applicationContext.distributedFilesDir; let preferencesDir = applicationContext.preferencesDir; ... + // Obtain the application file path. + let filePath = tempDir + 'test.txt'; + console.info(`filePath: ${filePath}`); } } ``` @@ -118,13 +121,13 @@ The application file paths obtained by the preceding contexts are different. | Name| Path| | -------- | -------- | - | bundleCodeDir | \/el1/bundle/| - | cacheDir | \/\/base/**haps/\**/cache/| - | filesDir | \/\/base/**haps/\**/files/| - | preferencesDir | \/\/base/**haps/\**/preferences/| - | tempDir | \/\/base/**haps/\**/temp/| - | databaseDir | \/\/database/**\**/| - | distributedFilesDir | \/el2/distributedFiles/**\**/| + | bundleCodeDir | \/el1/bundle| + | cacheDir | \/\/base/**haps/\**/cache| + | filesDir | \/\/base/**haps/\**/files| + | preferencesDir | \/\/base/**haps/\**/preferences| + | tempDir | \/\/base/**haps/\**/temp| + | databaseDir | \/\/database/**\**| + | distributedFilesDir | \/el2/distributedFiles/**\**| The sample code is as follows: @@ -141,6 +144,9 @@ The application file paths obtained by the preceding contexts are different. let distributedFilesDir = this.context.distributedFilesDir; let preferencesDir = this.context.preferencesDir; ... + // Obtain the application file path. + let filePath = tempDir + 'test.txt'; + console.info(`filePath: ${filePath}`); } } ``` diff --git a/en/application-dev/application-models/arkts-ui-widget-configuration.md b/en/application-dev/application-models/arkts-ui-widget-configuration.md index f0f003e608c995461ad1e84c65ed2a09b87febb7..d86c3b6991460a25c0ea6a177a8aec8c4607364c 100644 --- a/en/application-dev/application-models/arkts-ui-widget-configuration.md +++ b/en/application-dev/application-models/arkts-ui-widget-configuration.md @@ -16,7 +16,7 @@ Widget-related configuration includes **FormExtensionAbility** configuration and "extensionAbilities": [ { "name": "EntryFormAbility", - "srcEntry": "./ets/entryformability/EntryFormAbility.ts", + "srcEntry": "./ets/entryformability/EntryFormAbility.ets", "label": "$string:EntryFormAbility_label", "description": "$string:EntryFormAbility_desc", "type": "form", @@ -42,9 +42,9 @@ Widget-related configuration includes **FormExtensionAbility** configuration and | description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| | src | Full path of the UI code corresponding to the widget. For an ArkTS widget, the full path must contain the widget file name extension, for example, **./ets/widget/pages/WidgetCard.ets**. For a JS widget, the full path does not need to contain the widget file name extension, for example, **./js/widget/pages/WidgetCard**.| String| No| | uiSyntax | Type of the widget.
- **arkts**: ArkTS widget
- **hml**: JS widget| String| Yes (initial value: **hml**)| - | window | Window-related configurations.| Object| Yes| + | window | Window-related configurations.| Object| YYes (initial value: see Table 2)| | isDefault | Whether the widget is a default one. Each UIAbility has only one default widget.
- **true**: The widget is the default one.
- **false**: The widget is not the default one.| Boolean| No| - | colorMode | Color mode of the widget.
- **auto**: auto-adaptive color mode
- **dark**: dark color mode
- **light**: light color mode| String| Yes (initial value: **auto**)| + | colorMode | Color mode of the widget.
- **auto**: following the system color mode
- **dark**: dark color mode
- **light**: light color mode| String| Yes (initial value: **auto**)| | supportDimensions | Grid styles supported by the widget.
- **1 * 2**: indicates a grid with one row and two columns.
- **2 * 2**: indicates a grid with two rows and two columns.
- **2 * 4**: indicates a grid with two rows and four columns.
- **4 * 4**: indicates a grid with four rows and four columns.| String array| No| | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String| No| | updateEnabled | Whether the widget can be updated periodically.
- **true**: The widget can be updated at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.
- **false**: The widget cannot be updated periodically.| Boolean| No| @@ -54,7 +54,14 @@ Widget-related configuration includes **FormExtensionAbility** configuration and | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification.| String| Yes (initial value: left empty)| | metadata | Metadata of the widget. This field contains the array of the **customizeData** field.| Object| Yes (initial value: left empty)| | dataProxyEnabled | Whether the widget supports the [update-through-proxy](./arkts-ui-widget-update-by-proxy.md) feature.
- **true**: The widget supports the update-through-proxy feature.
- **false**: The widget does not support the update-through-proxy feature.
If this tag is set to **true**, the settings for the scheduled update time will still take effect, but the settings for the update interval and next update time will not.| Boolean| Yes (initial value: **false**)| - | isDynamic | Whether the widget is a dynamic widget. This tag only applies to ArkTS widgets.
- **true**: The widget is a dynamic widget.
- **false**: The widget is a static widget. In this case, the widget is displayed as a static image after being added.| Boolean| Yes (initial value: **true**)| + | isDynamic | Whether the widget is a dynamic widget. This tag applies only to ArkTS widgets.
- **true**: The widget is a dynamic widget.
- **false**: The widget is a static widget. In this case, the widget is displayed as a static image after being added.| Boolean| Yes (initial value: **true**)| + + **Table 2** Internal structure of the window object + + | Field| Description| Data Type| Default Value Allowed| + | -------- | -------- | -------- | -------- | + | designWidth | Baseline width for page design. The size of an element is scaled by the actual device width.| Number| Yes (initial value: **720px**)| + | autoDesignWidth | Whether to automatically calculate the baseline width for page design. If it is set to **true**, the **designWidth** attribute will be ignored, and the baseline width will be calculated based on the device width and screen density.| Boolean| Yes (initial value: **false**)| Example configuration: diff --git a/en/application-dev/application-models/arkts-ui-widget-page-animation.md b/en/application-dev/application-models/arkts-ui-widget-page-animation.md index 0cb8e356c61155d367e55c0f39bbf491d03e2e12..ff479a47e17cadc04c38ecdc3931b5aa1b3d687f 100644 --- a/en/application-dev/application-models/arkts-ui-widget-page-animation.md +++ b/en/application-dev/application-models/arkts-ui-widget-page-animation.md @@ -1,7 +1,7 @@ # Using Animations in the Widget -To make your ArkTS widget more engaging, you can apply animations to it, including [explicit animation](../reference/arkui-ts/ts-explicit-animation.md), [attribute animation](../reference/arkui-ts/ts-animatorproperty.md), and [component transition](../reference/arkui-ts/ts-transition-animation-component.md). Just note the following restrictions when using the animations in ArkTS widgets. +To make your ArkTS widget more engaging, you can apply animations to it, including [explicit animation](../reference/arkui-ts/ts-explicit-animation.md), [property animation](../reference/arkui-ts/ts-animatorproperty.md), and [component transition](../reference/arkui-ts/ts-transition-animation-component.md). Just note the following restrictions when using the animations in ArkTS widgets. **Table 1** Restrictions on animation parameters diff --git a/en/application-dev/application-models/arkts-ui-widget-update-by-proxy.md b/en/application-dev/application-models/arkts-ui-widget-update-by-proxy.md index c655582af7834992c42025823b94ecab71eaa4ab..b7c1c93d21ec24673b3d07c4e971eadd7cd13661 100644 --- a/en/application-dev/application-models/arkts-ui-widget-update-by-proxy.md +++ b/en/application-dev/application-models/arkts-ui-widget-update-by-proxy.md @@ -89,7 +89,7 @@ The update-through-proxy configuration varies by the type of shared data. } ``` -- In the widget page code file **widgets.abc**, use the variable in LocalStorage to obtain the subscribed data. The variable in LocalStorage is bound to a string and updates the subscribed data in the key:value pair format. The key must be the same as that subscribed to by the widget provider. In this example, the subscribed data is obtained through **'detail'** and displayed in the **\** component. +- In the [widget page code file](arkts-ui-widget-creation.md), use the variable in LocalStorage to obtain the subscribed data. The variable in LocalStorage is bound to a string and updates the subscribed data in the key:value pair format. The key must be the same as that subscribed to by the widget provider. In this example, the subscribed data is obtained through **'detail'** and displayed in the **\** component. ```ts let storage = new LocalStorage(); @Entry(storage) @@ -178,7 +178,7 @@ The update-through-proxy configuration varies by the type of shared data. } ``` -- In the widget page code file (generally the .ets file in the **pages** folder under the widget directory of the project), use the variable in LocalStorage to obtain the subscribed data. The variable in LocalStorage is bound to a string and updates the subscribed data in the key:value pair format. The key must be the same as that subscribed to by the widget provider. In the example, the subscribed data is obtained through **'list'**, and the value of the first element is displayed on the **\** component. +- In the [widget page code file](arkts-ui-widget-creation.md), use the variable in LocalStorage to obtain the subscribed data. The variable in LocalStorage is bound to a string and updates the subscribed data in the key:value pair format. The key must be the same as that subscribed to by the widget provider. In the example, the subscribed data is obtained through **'list'**, and the value of the first element is displayed on the **\** component. ```ts let storage = new LocalStorage(); @Entry(storage) @@ -215,4 +215,4 @@ The update-through-proxy configuration varies by the type of shared data. ## Data Provider Development -For details, see [Data Management](../database/data-mgmt-overview.md). +For details, see [Data Management](../database/share-data-by-silent-access.md). diff --git a/en/application-dev/application-models/arkts-ui-widget-working-principles.md b/en/application-dev/application-models/arkts-ui-widget-working-principles.md index b1b09dc409380da8e530f571b2e5711ec63edd10..a8599ca8827c2d41c3ff1be032151c1f6debead9 100644 --- a/en/application-dev/application-models/arkts-ui-widget-working-principles.md +++ b/en/application-dev/application-models/arkts-ui-widget-working-principles.md @@ -15,10 +15,11 @@ - Widget rendering service: a service that manages widget rendering instances. Widget rendering instances are bound to the [widget components](../reference/arkui-ts/ts-basic-components-formcomponent.md) on the widget host on a one-to-one basis. The widget rendering service runs the widget page code **widgets.abc** for rendering, and sends the rendered data to the corresponding widget component on the widget host. - **Figure 2** Working principles of the ArkTS widget rendering service -![WidgetRender](figures/WidgetRender.png) + **Figure 2** Working principles of the ArkTS widget rendering service -Unlike JS widgets, ArkTS widgets support logic code running. The widget page code **widgets.abc** is executed by the widget rendering service, which is managed by the Widget Manager. Each widget component of a widget host corresponds to a rendering instance in the widget rendering service. Rendering instances of a widget provider run in the same virtual machine operating environment, and rendering instances of different widget providers run in different virtual machine operating environments. In this way, the resources and state data are isolated between widgets of different widget providers. During development, pay attention to the use of the [globalThis](uiability-data-sync-with-ui.md#using-globalthis-between-uiability-and-page) object. Use one **globalThis** object for widgets from the same widget provider, and different **globalThis** objects for widgets from different widget providers. + ![WidgetRender](figures/WidgetRender.png) + +Unlike JS widgets, ArkTS widgets support logic code execution. The widget page code **widgets.abc** is executed by the widget rendering service, which is managed by the Widget Manager. Each widget component of a widget host corresponds to a rendering instance in the widget rendering service. Rendering instances of a widget provider run in the same virtual machine operating environment, and rendering instances of different widget providers run in different virtual machine operating environments. In this way, the resources and state data are isolated between widgets of different widget providers. During development, pay attention to the use of the [globalThis](uiability-data-sync-with-ui.md#using-globalthis-between-uiability-and-ui-page) object. Use one **globalThis** object for widgets from the same widget provider, and different **globalThis** objects for widgets from different widget providers. ## Advantages of ArkTS Widgets @@ -34,7 +35,7 @@ As a quick entry to applications, ArkTS widgets outperform JS widgets in the fol ![WidgetProject](figures/WidgetProject.png) - More widget features - - Animation: ArkTS widgets support the [attribute animation](../reference/arkui-ts/ts-animatorproperty.md) and [explicit animation](../reference/arkui-ts/ts-explicit-animation.md) capabilities, which can be leveraged to deliver a more engaging experience. + - Animation: ArkTS widgets support the [property animation](../reference/arkui-ts/ts-animatorproperty.md) and [explicit animation](../reference/arkui-ts/ts-explicit-animation.md) capabilities, which can be leveraged to deliver a more engaging experience. - Custom drawing: ArkTS widgets allow you to draw graphics with the [\](../reference/arkui-ts/ts-components-canvas-canvas.md) component to present information more vividly. - Logic code execution: The capability to run logic code in widgets means that service logic can be self-closed in widgets, expanding the use cases of widgets. @@ -57,6 +58,8 @@ In addition, ArkTS widgets do not support the following features: - Instant preview -- Breakpoint debugging. +- Breakpoint debugging - Hot reload + +- **setTimeOut** diff --git a/en/application-dev/application-models/atomic-services-support-sharing.md b/en/application-dev/application-models/atomic-services-support-sharing.md deleted file mode 100644 index ba99573b28c4e25ef5ed2c8ca472e559a00f4713..0000000000000000000000000000000000000000 --- a/en/application-dev/application-models/atomic-services-support-sharing.md +++ /dev/null @@ -1,33 +0,0 @@ -# Setting Atomic Services to Support Sharing -## How to Develop - -1. An application calls [UIAbility.onShare()](../reference/apis/js-apis-app-ability-uiAbility.md#onshare), a lifecycle callback provided by the UIAbility component, to set the data to share. In this lifecycle callback, **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. - - ```ts - 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"}; - } - } - ``` - -2. A system dialog box calls [abilityManager.acquireShareData()](../reference/apis/js-apis-app-ability-abilityManager.md#acquiresharedata) to obtain data shared through atomic service sharing. Specifically, the system finds the UIAbility based on the mission ID and calls the **OnShare()** lifecycle of the UIAbility to obtain the shared data. - - ```ts - import abilityManager from '@ohos.app.ability.abilityManager'; - try { - abilityManager.acquireShareData(1, (err, wantParam) => { - if (err) { - console.error(`acquireShareData fail, err: ${JSON.stringify(err)}`); - } else { - console.log(`acquireShareData success, data: ${JSON.stringify(wantParam)}`); - } - }); - } catch (paramError) { - console.error(`error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}`); - } - ``` diff --git a/en/application-dev/application-models/component-startup-rules.md b/en/application-dev/application-models/component-startup-rules.md index bddf63dbc69ea243733e6f60f67f92a854833bf7..2db47d35f24df7d3eb155bb4ab2540f4a1af7ce0 100644 --- a/en/application-dev/application-models/component-startup-rules.md +++ b/en/application-dev/application-models/component-startup-rules.md @@ -26,7 +26,7 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol - If the **exported** field of the target component is **false**, verify the **ohos.permission.START_INVISIBLE_ABILITY** permission. - For details, see [Component exported Configuration](../quick-start/module-configuration-file.md#abilities). -- **Before starting a component of a background application, verify the BACKGROUND permission.** +- **Before starting a UIAbility component of a background application, verify the BACKGROUND permission.** - An application is considered as a foreground application only when the application process gains focus or its UIAbility component is running in the foreground. - Verify the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. @@ -45,7 +45,9 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol The rules for starting components on the same device vary in the following scenarios: -- Starting or connecting to the UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility components +- Starting the UIAbility component + +- Starting the ServiceExtensionAbility and DataShareExtensionAbility components - Using **startAbilityByCall()** to start the UIAbility component @@ -56,9 +58,10 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol The rules for starting components on a different device vary in the following scenarios: -- Starting or connecting to the UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility components +- Starting the UIAbility component + +- Starting the ServiceExtensionAbility and DataShareExtensionAbility components - Using **startAbilityByCall()** to start the UIAbility component ![component-startup-rules](figures/component-startup-inter-stage.png) - 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/figures/component-startup-inner-stage.png b/en/application-dev/application-models/figures/component-startup-inner-stage.png index 00514276f4ac3eb8ead650e5858cebb0a344d2c6..9761b9879e513f0e1ad942b5fe18997f1331c9e5 100644 Binary files a/en/application-dev/application-models/figures/component-startup-inner-stage.png and b/en/application-dev/application-models/figures/component-startup-inner-stage.png differ diff --git a/en/application-dev/application-models/figures/component-startup-inter-stage.png b/en/application-dev/application-models/figures/component-startup-inter-stage.png index a6f79e6803edc160e5570729456569f46cc80967..517407f6b557648db78a0de89431d8b18f8e2b59 100644 Binary files a/en/application-dev/application-models/figures/component-startup-inter-stage.png and b/en/application-dev/application-models/figures/component-startup-inter-stage.png differ diff --git a/en/application-dev/application-models/hop-cross-device-migration.md b/en/application-dev/application-models/hop-cross-device-migration.md index 92c254514d82cbcfe800f5b35bfefb96411a8f92..b452d8ea493bbfe060094f13073b9bdd9eac4f65 100644 --- a/en/application-dev/application-models/hop-cross-device-migration.md +++ b/en/application-dev/application-models/hop-cross-device-migration.md @@ -53,9 +53,9 @@ The table below describes the main APIs used for cross-device migration. For det | **API**| Description| | -------- | -------- | -| onContinue(wantParam : {[key: string]: any}): OnContinueResult | Called by the initiator to store the data required for migration and indicate whether the migration is accepted.
- **AGREE**: The migration is accepted.
- **REJECT**: The migration is rejected, for example, when an application is abnormal in **onContinue()**.
- **MISMATCH**: The version does not match. The application on the initiator can obtain the version number of the target application from **onContinue()**. If the migration cannot be performed due to version mismatch, this error code is returned.| -| onCreate(want: Want, param: AbilityConstant.LaunchParam): void; | Called by the target to restore the data and UI page in the multiton migration scenario. For details, see [UIAbility Component Launch Type](uiability-launch-type.md).| -| onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void; | Called by the target to restore the data and UI page in the singleton migration scenario. For details, see [UIAbility Component Launch Type](uiability-launch-type.md).| +| onContinue(wantParam : {[key: string]: Object}): OnContinueResult | Called by the initiator to store the data required for migration and indicate whether the migration is accepted.
- **AGREE**: The migration is accepted.
- **REJECT**: The migration is rejected, for example, when an application is abnormal in **onContinue()**.
- **MISMATCH**: The version does not match. The application on the initiator can obtain the version number of the target application from **onContinue()**. If the migration cannot be performed due to version mismatch, this error code is returned.| +| onCreate(want: Want, param: AbilityConstant.LaunchParam): void; | Called by the target to restore the data and UI page when the target uses cold start or the target is a multiton application and uses hot start. For details, see [UIAbility Component Launch Type](uiability-launch-type.md).| +| onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void; | Called by the target to restore the data and UI page when the target is a singleton application and uses hot start. For details, see [UIAbility Component Launch Type](uiability-launch-type.md).| @@ -90,7 +90,7 @@ The table below describes the main APIs used for cross-device migration. For det 4. Implement [onContinue()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue) in the UIAbility of the initiator. - [onContinue()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue) is called on the initiator. You can save the data in this method to implement application compatibility check and migration decision. + [onContinue()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue) is called on the initiator. You can save the data in this method to implement application compatibility check and migration decision. - Saving migrated data: You can save the data to be migrated in key-value pairs in **wantParam**. - Checking application compatibility: You can obtain the version number of the target application from **wantParam** and that of the current application from **wantParam.version** of the **onContinue()** callback. Then you can check the compatibility between the two. @@ -114,7 +114,7 @@ The table below describes the main APIs used for cross-device migration. For det ``` 5. Implement **onCreate()** and **onNewWant()** in the UIAbility of the target application to implement data restoration. - - Implementation example of **onCreate** in the multiton scenario + - Implementation example of **onCreate** - The target device determines whether the startup is **LaunchReason.CONTINUATION** based on **launchReason** in **onCreate()**. - You can obtain the saved migration data from the **want** parameter. - After data restoration is complete, call **restoreWindowStage** to trigger page restoration, including page stack information. @@ -139,11 +139,29 @@ The table below describes the main APIs used for cross-device migration. For det } } ``` - - For a singleton ability, use **onNewWant()** to achieve the same implementation. + - For a singleton application, you must also implement **onNewWant()**, in the same way as **onCreate()**. + - Determine the migration scenario in **onNewWant()**, restore data, and trigger page restoration. + ```ts + export default class EntryAbility extends UIAbility { + storage : LocalStorage; + onNewWant(want, launchParam) { + console.info(`EntryAbility onNewWant ${AbilityConstant.LaunchReason.CONTINUATION}`) + if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { + // Obtain the user data from the want parameter. + let workInput = want.parameters.work + console.info(`work input ${workInput}`) + AppStorage.SetOrCreate('ContinueWork', workInput) + this.storage = new LocalStorage(); + this.context.restoreWindowStage(this.storage); + } + } + } + ``` + 6. (Optional) Call [setMissionContinueState](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissioncontinuestate10) to set the mission continuation state. - For an application that supports migration, mission migration is enabled by default, and the system notifies peripheral trusted devices that a mission can be migrated or canceled based on the gain/loss focus state of the mission. If you want the system to send a notification to peripheral devices only when your application is in a specific scenario, set the migration continuation state to **INACTIVE** when the application is started and change it to **ACTIVE** when the application enters that specific scenario. For details about the API, see [setMissionContinueState](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissioncontinuestate10). + For an application that supports migration, mission migration is enabled by default, and the system notifies peripheral trusted devices that a mission can be migrated or canceled based on the gain/loss focus state of the mission. If you want the system to send a notification to peripheral devices only when your application is in a specific scenario, set the migration continuation state to **INACTIVE** when the application is started and change it to **ACTIVE** when the application enters that specific scenario. - Example: An application does not require migration during startup. @@ -180,7 +198,7 @@ The table below describes the main APIs used for cross-device migration. For det onContinue(wantParam : {[key: string]: any}) { console.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`) - wantParam[wantConstant.SUPPORT_CONTINUE_PAGE_STACK_KEY] = false; + wantParam[wantConstant.Params.SUPPORT_CONTINUE_PAGE_STACK_KEY] = false; return AbilityConstant.OnContinueResult.AGREE; } @@ -202,7 +220,7 @@ The table below describes the main APIs used for cross-device migration. For det onContinue(wantParam : {[key: string]: any}) { console.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`) - wantParam[wantConstant.SUPPORT_CONTINUE_SOURCE_EXIT_KEY] = false; + wantParam[wantConstant.Params.SUPPORT_CONTINUE_SOURCE_EXIT_KEY] = false; return AbilityConstant.OnContinueResult.AGREE; } ``` 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/medialibrary-switch.md b/en/application-dev/application-models/medialibrary-switch.md index dc671d1b61b467f98d7d01f43703b165df4c1e52..b5c8891f21fd2a554a2905f0f1cce59847e7f8ad 100644 --- a/en/application-dev/application-models/medialibrary-switch.md +++ b/en/application-dev/application-models/medialibrary-switch.md @@ -1,6 +1,6 @@ # mediaLibrary Switching - | API in the FA Model| Corresponding .d.ts File in the Stage Model| Corresponding API in the Stage Model| +| API in the FA Model| Corresponding .d.ts File in the Stage Model| Corresponding API in the Stage Model| | -------- | -------- | -------- | -| [getMediaLibrary(): MediaLibrary;](../reference/apis/js-apis-medialibrary.md#medialibrarygetmedialibrary) | \@ohos.multimedia.mediaLibrary.d.ts | [getMediaLibrary(context: Context): MediaLibrary;](../reference/apis/js-apis-medialibrary.md#medialibrarygetmedialibrary8) | +| [getMediaLibrary(): MediaLibrary;](../reference/apis/js-apis-medialibrary.md#medialibrarygetmedialibrary) | \@ohos.file.photoAccessHelper.d.ts | [getPhotoAccessHelper(context: Context): PhotoAccessHelper;](../reference/apis/js-apis-photoAccessHelper.md#photoaccesshelpergetphotoaccesshelper) | 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/start-pageability-from-stage.md b/en/application-dev/application-models/start-pageability-from-stage.md index bd6a11187fdfbc81c63bcc6601f8a8e82b0dbe4c..123e15c45614f83ece1c11db87827535b2ac4937 100644 --- a/en/application-dev/application-models/start-pageability-from-stage.md +++ b/en/application-dev/application-models/start-pageability-from-stage.md @@ -8,6 +8,10 @@ This topic describes how the two application components of the stage model start A UIAbility starts a PageAbility in the same way as it starts another UIAbility. +> **NOTE** +> +> In the FA model, **abilityName** consists of **bundleName** and **AbilityName**. For details, see the code snippet below. + ```ts import UIAbility from '@ohos.app.ability.UIAbility'; @@ -25,7 +29,7 @@ export default class EntryAbility extends UIAbility { }); let want = { bundleName: "com.ohos.fa", - abilityName: "EntryAbility", + abilityName: "com.ohos.fa.EntryAbility", }; this.context.startAbility(want).then(() => { console.info('Start Ability successfully.'); diff --git a/en/application-dev/application-models/start-uiability-from-fa.md b/en/application-dev/application-models/start-uiability-from-fa.md index 42d8e034cd6519643423bb289217d1aa140a18d4..8520cf94be0d0d21999af3175848a37edac85c52 100644 --- a/en/application-dev/application-models/start-uiability-from-fa.md +++ b/en/application-dev/application-models/start-uiability-from-fa.md @@ -14,7 +14,7 @@ import featureAbility from '@ohos.ability.featureAbility'; let parameter = { "want": { bundleName: "com.ohos.stage", - abilityName: "com.ohos.stage.EntryAbility" + abilityName: "EntryAbility" } }; featureAbility.startAbility(parameter).then((code) => { 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. + ![](figures/uiability-intra-device-interaction.png) 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. ![](figures/start-uiability-floating-window.png) @@ -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. +``` -![uiability_not_first_started](figures/uiability_not_first_started.png) +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/want-overview.md b/en/application-dev/application-models/want-overview.md index cf5cac43999a5efbe59659252b6b3db325cacd8a..9260c71666f3c47181756ba205c265391d989b05 100644 --- a/en/application-dev/application-models/want-overview.md +++ b/en/application-dev/application-models/want-overview.md @@ -12,7 +12,7 @@ ## Types of Want -- **Explicit Want**: If **abilityName** and **bundleName** are specified in the **want** parameter when starting an an application component, explicit Want is used. +- **Explicit Want**: If **abilityName** and **bundleName** are specified in the **want** parameter when starting an application component, explicit Want is used. Explicit Want is usually used to start a known target application component in the same application. The target application component is started by specifying **bundleName** of the application where the target application component is located and **abilityName** in the **Want** object. When there is an explicit object to process the request, explicit Want is a simple and effective way to start the target application component. @@ -24,7 +24,7 @@ } ``` -- **Implicit Want**: If **abilityName** is not specified in the **want** parameter when starting the an application component, implicit Want is used. +- **Implicit Want**: If **abilityName** is not specified in the **want** parameter when starting an application component, implicit Want is used. Implicit Want can be used when the object used to process the request is unclear and the current application wants to use a capability (defined by the [skills tag](../quick-start/module-configuration-file.md#skills)) provided by another application. The system matches all applications that declare to support the capability. For example, for a link open request, the system matches all applications that support the request and provides the available ones for users to select. @@ -47,6 +47,7 @@ > - An application component that meets the conditions is matched. That application component is started. > - Multiple application components that meet the conditions are matched. A dialog box is displayed for users to select one of them. > - > - If the **want** parameter passed does not contain **abilityName** or **bundleName**, the ServiceExtensionAbility components of all applications cannot be started through implicit Want. + > - In the scenario for starting the ServiceExtensionAbility component: + > - If the **want** parameter passed in contains **abilityName**, the ServiceExtensionAbility component cannot be started through implicit Want. > - > - If the **want** parameter passed contains **bundleName**, the **startServiceExtensionAbility()** method can be used to implicitly start ServiceExtensionAbility. By default, ServiceExtensionAbility with the highest priority is returned. If all the matching ServiceExtensionAbility components have the same priority, the first ServiceExtensionAbility is returned. + > - If the **want** parameter passed in contains **bundleName**, the **startServiceExtensionAbility()** method can be used to implicitly start the ServiceExtensionAbility component. By default, the ServiceExtensionAbility component with the highest priority is returned. If all the matching ServiceExtensionAbility components have the same priority, the first ServiceExtensionAbility component is returned. 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/Readme-EN.md b/en/application-dev/arkts-utils/Readme-EN.md new file mode 100644 index 0000000000000000000000000000000000000000..a574b494aea8d5bc7b62a000044fa81ae269b43e --- /dev/null +++ b/en/application-dev/arkts-utils/Readme-EN.md @@ -0,0 +1,23 @@ +# ArkTS Common Library + +- [Overview of ArkTS Common Library](arkts-commonlibrary-overview.md) +- Concurrency + - [Concurrency Overview](concurrency-overview.md) + - Using Asynchronous Concurrency for Development + - [Asynchronous Concurrency Overview](async-concurrency-overview.md) + - [Single I/O Task Development](single-io-development.md) + - Using Multithread Concurrency for Development + - [Multithread Concurrency Overview](multi-thread-concurrency-overview.md) + - [Comparison Between TaskPool and Worker](taskpool-vs-worker.md) + - [CPU Intensive Task Development](cpu-intensive-task-development.md) + - [I/O Intensive Task Development](io-intensive-task-development.md) + - [Synchronous Task Development](sync-task-development.md) +- Container + - [Container Overview](container-overview.md) + - [Linear Containers](linear-container.md) + - [Nonlinear Containers](nonlinear-container.md) +- XML Generation, Parsing, and Conversion + - [XML Overview](xml-overview.md) + - [XML Generation](xml-generation.md) + - [XML Parsing](xml-parsing.md) + - [XML Conversion](xml-conversion.md) diff --git a/en/application-dev/arkts-utils/arkts-commonlibrary-overview.md b/en/application-dev/arkts-utils/arkts-commonlibrary-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..708f14c78da7c7bd53d66cd62826ff01c5d6e212 --- /dev/null +++ b/en/application-dev/arkts-utils/arkts-commonlibrary-overview.md @@ -0,0 +1,31 @@ +# Overview of ArkTS Common Library + + +The ArkTS common library provides common basic capabilities, as illustrated in the figure below. + + +**Figure 1** Capabilities of the ArkTS common library + +![arkts-commonlibrary](figures/arkts-commonlibrary.png) + + +- Supporting [asynchronous concurrency and multithread concurrency](concurrency-overview.md) + - Supports standard JavaScript asynchronous concurrency capabilities such as Promise and async/await. + - Uses **TaskPool** to provide a multithread running environment for applications. The use of **TaskPool** helps reduce resource consumption and improve system performance. It also frees you from caring about the lifecycle of thread instances. + - Uses **Worker** to support multithread concurrency. The worker thread can communicate with the host thread. You need to proactively create and close a worker thread. + +- Providing common capabilities of [adding, deleting, modifying, and querying elements in containers](container-overview.md) + +- Constructing and parsing XML files, URLs, and URIs + - Extensible Markup Language (XML) is designed for data transmission and storage. The common library provides APIs for [XML generation, parsing, and conversion](xml-overview.md). + - [URI](../reference/apis/js-apis-uri.md) is a uniform resource identifier that uniquely identifies a resource. [URL](../reference/apis/js-apis-url.md) is a uniform resource locator that provides a path for locating a resource. + +- Supporting common [string and binary data processing](../reference/apis/js-apis-util.md) and [logging](../reference/apis/js-apis-logs.md) + - Provides APIs to encode and decode strings. + - Provides APIs to encode and decode Base64-encoded bytes. + - Supports common rational number operations, including comparing rational numbers and obtaining numerators and denominators. + - Provides **Scope** APIs to define the valid range of a field. + - Provides APIs to process binary data in scenarios such as TCP flows or file system operations. + - Supports logging using the console. + +- Providing the capability of [obtaining process information and operating processes](../reference/apis/js-apis-process.md) \ No newline at end of file diff --git a/en/application-dev/arkts-utils/async-concurrency-overview.md b/en/application-dev/arkts-utils/async-concurrency-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..32bed2f143b9dbf32369fb439290d762269e055a --- /dev/null +++ b/en/application-dev/arkts-utils/async-concurrency-overview.md @@ -0,0 +1,87 @@ +# Asynchronous Concurrency Overview + + +Promise and async/await are standard JavaScript syntax that provides asynchronous concurrency. Asynchronous code ensures that actions initiated now finish later. It allows the execution of only one segment of code at a time and is therefore applicable to the development of a single I/O task, for example, a network request or a file read/write operation. + + +Promise and async/await allow an application to perform other operations without waiting for the completion of certain actions. + + +## Promise + +Promise is an object used to process asynchronous operations. It converts asynchronous operations into a style similar to synchronous operations for easier code writing and maintenance. Promise provides a state mechanism to manage different phases of asynchronous operations. It also provides methods to register callback functions to handle the success or failure of these operations. + +Promise has three states: pending, fulfilled, and rejected. After being created, a Promise object is in the pending state and changes to the fulfilled or rejected state when the asynchronous operation is complete. + +The most common usage for Promise is to instantiate a Promise object through a constructor and pass in a function (usually named **executor**) with two parameters. The **executor** function receives two parameters: **resolve** and **reject**, which represent the callback functions that should be called when the asynchronous operation succeeds and fails, respectively. The code snippet below creates a Promise object and simulates an asynchronous operation: + + +```js +const promise = new Promise((resolve, reject) => { + setTimeout(() => { + const randomNumber = Math.random(); + if (randomNumber > 0.5) { + resolve(randomNumber); + } else { + reject(new Error('Random number is too small')); + } + }, 1000); +}); +``` + +In the preceding code, the **setTimeout** function simulates an asynchronous operation that randomly generates a number one second later. If the random number is greater than 0.5, the **resolve** callback function is executed and the generated random number is passed in as a parameter. Otherwise, the **reject** callback function is executed and an error object is passed in as a parameter. + +After the Promise object is created, you can use the **then** and **catch** methods to register the callback functions for the fulfilled and rejected states. The **then** method can receive two parameters: one for processing the fulfilled state and the other for processing the rejected state. If only one parameter is passed in, the callback function is executed as long as the state changes. The **catch** method receives a callback function to process the failure result, that is, capture the exception thrown when the Promise state changes to **rejected** or the operation fails. The code snippet below shows the use of **then** and **catch** methods: + + +```js +promise.then(result => { + console.info(`Random number is ${result}`); +}).catch(error => { + console.error(error.message); +}); +``` + +In the preceding code, the callback function of the **then** method receives the success result of the Promise object as a parameter and outputs it to the console. If the Promise object enters the rejected state, the callback function of the **catch** method receives the error object as a parameter and outputs it to the console. + + +## Async/Await + +Async/Await is a Promise syntax sugar used to process asynchronous operations, making it easier to read and write asynchronous code. The async keyword is used to declare an asynchronous function, and the await keyword is used to wait for Promise parsing (fulfilled or rejected). In this way, the asynchronous operation logic is coded as a synchronous operation. + +The **async** function returns a Promise object to represent an asynchronous operation. Inside the **async** function, you can use the await keyword to wait for the parsing of the Promise object and return its parsed value. If an **async** function throws an exception, the Promise object returned by the function is rejected, and the exception information is passed to the **onRejected()** method of the Promise object. + +The code snippet below uses async/await to simulate an asynchronous operation that returns a string three seconds later. + + +```js +async function myAsyncFunction() { + const result = await new Promise((resolve) => { + setTimeout(() => { + resolve('Hello, world!'); + }, 3000); + }); + console.info(String(result)); // Output: Hello, world! +} + +myAsyncFunction(); +``` + +In the preceding code, the await keyword is used to wait for the parsing of the Promise object and store its parsed value in the **result** variable. + +Note that the entire operation must be packaged in the **async** function because the code needs to wait for the asynchronous operation to complete. In addition to **await**, you can use the try/catch block to capture exceptions in asynchronous operations. + + +```js +async function myAsyncFunction() { + try { + const result = await new Promise((resolve) => { + resolve('Hello, world!'); + }); + } catch (e) { + console.error(`Get exception: ${e}`); + } +} + +myAsyncFunction(); +``` diff --git a/en/application-dev/arkts-utils/concurrency-overview.md b/en/application-dev/arkts-utils/concurrency-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..3f091f42ea1257468aba5ba9ed94e64c92f661bb --- /dev/null +++ b/en/application-dev/arkts-utils/concurrency-overview.md @@ -0,0 +1,15 @@ +# Concurrency Overview + +Concurrency refers to the capability of processing multiple tasks in the same period. To improve the response speed and frame rate of applications and prevent time-consuming tasks from blocking the main thread, OpenHarmony provides two policies: asynchronous concurrency and multithread concurrency. + +- Asynchronous concurrency means that an action in asynchronous code is suspended and will continue later. Only one segment of code is being executed at a time. + +- Multithread concurrency allows multiple segments of code to be executed at a time. When the main thread continues to respond to user operations and update the UI, time-consuming operations are performed in the background to avoid application freezing. + +Concurrency is used in a variety of scenarios, including a single I/O task, CPU intensive task, I/O intensive task, synchronous task, and the like. You can select a concurrency policy based on your scenario. + +ArkTS provides the following mechanisms to support asynchronous concurrency and multithread concurrency: + +- Promise and async/await: provide asynchronous concurrency and apply to the development of a single I/O task. For details, see [Asynchronous Concurrency Overview](async-concurrency-overview.md). + +- **TaskPool** and **Worker**: provide multithread concurrency and apply to the development of CPU intensive tasks, I/O intensive tasks, and synchronous tasks. For details, see [Multithread Concurrency Overview](multi-thread-concurrency-overview.md). diff --git a/en/application-dev/arkts-utils/container-overview.md b/en/application-dev/arkts-utils/container-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..8a317e23167644ad72287c05672c3aa4a641cd29 --- /dev/null +++ b/en/application-dev/arkts-utils/container-overview.md @@ -0,0 +1,7 @@ +# Overview of Containers + +The container classes provide a set of methods to process elements of various data types stored in containers. + +The container classes are implemented in a way similar to static languages. By restricting storage locations and attributes, they remove redundant logic for each type of data while providing the complete functionalities, ensuring efficient data access and improving application performance. + +Currently, OpenHarmony provides 14 types of linear and non-linear containers, each of which has its own features and uses cases. For details, see [Linear Containers](linear-container.md) and [Nonlinear Containers](nonlinear-container.md). diff --git a/en/application-dev/arkts-utils/cpu-intensive-task-development.md b/en/application-dev/arkts-utils/cpu-intensive-task-development.md new file mode 100644 index 0000000000000000000000000000000000000000..da11a1866dbeb1d374972fde6579676387d97ada --- /dev/null +++ b/en/application-dev/arkts-utils/cpu-intensive-task-development.md @@ -0,0 +1,190 @@ +# CPU Intensive Task Development + + +CPU intensive tasks occupy lots of system computing resources for a long period of time, during which other events of the thread are blocked. Example CPU intensive tasks are image processing, video encoding, and data analysis. + + +OpenHarmony uses multithread concurrency to process CPU intensive tasks. This improves CPU utilization and application response speed. + + +If a task does not need to occupy a background thread for a long time (3 minutes), you are advised to use **TaskPool**. Otherwise, use **Worker**. The following uses histogram processing and a time-consuming model prediction task in the background as examples. + + +## Using TaskPool to Process Histograms + +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. + + +```ts +import taskpool from '@ohos.taskpool'; + +@Concurrent +function imageProcessing(dataSlice: ArrayBuffer) { + // Step 1: Perform specific image processing operations and other time-consuming operations. + return dataSlice; +} + +function histogramStatistic(pixelBuffer: ArrayBuffer) { + // Step 2: Perform concurrent scheduling for data in three segments. + let number = pixelBuffer.byteLength / 3; + let buffer1 = pixelBuffer.slice(0, number); + let buffer2 = pixelBuffer.slice(number, number * 2); + let buffer3 = pixelBuffer.slice(number * 2); + + let group = new taskpool.TaskGroup(); + group.addTask(imageProcessing, buffer1); + group.addTask(imageProcessing, buffer2); + group.addTask(imageProcessing, buffer3); + + taskpool.execute(group, taskpool.Priority.HIGH).then((ret: ArrayBuffer[]) => { + // Step 3: Summarize and process the result arrays. + }) +} + +@Entry +@Component +struct Index { + @State message: string = 'Hello World' + + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + .onClick(() => { + let data: ArrayBuffer; + histogramStatistic(data); + }) + } + .width('100%') + } + .height('100%') + } +} +``` + + +## Using Worker for Time-Consuming Data Analysis + +The following uses the training of a region-specific house price prediction model as an example. This model can be used to predict house prices in the region based on the house area and number of rooms. The model needs to run for a long time, and the prediction will use the previous running result. Due to these considerations, **Worker** is used for the development. + +1. Add the worker creation template provided on DevEco Studio to your project, and name it **MyWorker**. + + ![newWorker](figures/newWorker.png) + +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'; + + const workerInstance = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts'); + ``` + +3. In the host thread, call [onmessage()](../reference/apis/js-apis-worker.md#onmessage9) to receive messages from the worker thread, and call [postMessage()](../reference/apis/js-apis-worker.md#postmessage9) to send messages to the worker thread. + + For example, the host thread sends training and prediction messages to the worker thread, and receives messages sent back by the worker thread. + + + ```js + // Receive the result of the worker thread. + workerInstance.onmessage = function(e) { + // data carries the information sent by the main thread. + let data = e.data; + console.info('MyWorker.ts onmessage'); + // Perform time-consuming operations in the worker thread. + } + + workerInstance.onerror = function (d) { + // Receive error information of the worker thread. + } + + // Send a training message to the worker thread. + workerInstance.postMessage({ 'type': 0 }); + // Send a prediction message to the worker thread. + workerInstance.postMessage({ 'type': 1, 'value': [90, 5] }); + ``` + +4. Bind the **Worker** object in the **MyWorker.ts** file. The calling thread is the worker thread. + + ```js + import worker, { ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@ohos.worker'; + + let workerPort: ThreadWorkerGlobalScope = worker.workerPort; + ``` + +5. In the worker thread, call [onmessage()](../reference/apis/js-apis-worker.md#onmessage9-1) to receive messages sent by the host thread, and call [postMessage()](../reference/apis/js-apis-worker.md#postmessage9-2) to send messages to the host thread. + + For example, the prediction model and its training process are defined in the worker thread, and messages are exchanged with the main thread. + + + ```js + import worker, { ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@ohos.worker'; + + let workerPort: ThreadWorkerGlobalScope = worker.workerPort; + + // Define the training model and result. + let result; + + // Define the prediction function. + function predict(x) { + return result[x]; + } + + // Define the optimizer training process. + function optimize() { + result = {}; + } + + // onmessage logic of the worker thread. + workerPort.onmessage = function (e: MessageEvents) { + let data = e.data + // Perform operations based on the type of data to transmit. + switch (data.type) { + case 0: + // Perform training. + optimize(); + // Send a training success message to the main thread after training is complete. + workerPort.postMessage({ type: 'message', value: 'train success.' }); + break; + case 1: + // Execute the prediction. + const output = predict(data.value); + // Send the prediction result to the main thread. + workerPort.postMessage({ type: 'predict', value: output }); + break; + default: + workerPort.postMessage({ type: 'message', value: 'send message is invalid' }); + break; + } + } + ``` + +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"); + } + ``` + + 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. + workerInstance.terminate(); + ``` + + 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/figures/arkts-commonlibrary.png b/en/application-dev/arkts-utils/figures/arkts-commonlibrary.png new file mode 100644 index 0000000000000000000000000000000000000000..e8590f0115429b7857e3d7d44b7dceb821857515 Binary files /dev/null and b/en/application-dev/arkts-utils/figures/arkts-commonlibrary.png differ diff --git a/en/application-dev/arkts-utils/figures/newWorker.png b/en/application-dev/arkts-utils/figures/newWorker.png new file mode 100644 index 0000000000000000000000000000000000000000..c1b47bb4a885cf793ed467db43151a99720ea48d Binary files /dev/null and b/en/application-dev/arkts-utils/figures/newWorker.png differ diff --git a/en/application-dev/arkts-utils/figures/taskpool.png b/en/application-dev/arkts-utils/figures/taskpool.png new file mode 100644 index 0000000000000000000000000000000000000000..f5ae190d4dece65d196fd635b08ae6b420b6033b Binary files /dev/null and b/en/application-dev/arkts-utils/figures/taskpool.png differ diff --git a/en/application-dev/arkts-utils/figures/worker.png b/en/application-dev/arkts-utils/figures/worker.png new file mode 100644 index 0000000000000000000000000000000000000000..5feb2f6e5a01e4686a3cb3fe2451d72ae80c8685 Binary files /dev/null and b/en/application-dev/arkts-utils/figures/worker.png differ diff --git a/en/application-dev/arkts-utils/io-intensive-task-development.md b/en/application-dev/arkts-utils/io-intensive-task-development.md new file mode 100644 index 0000000000000000000000000000000000000000..562f749fd99daff42359af2598bc42483dc5595c --- /dev/null +++ b/en/application-dev/arkts-utils/io-intensive-task-development.md @@ -0,0 +1,51 @@ +# I/O Intensive Task Development + + +Asynchronous concurrency can solve the problem of a single blocking I/O operation. In the case of I/O intensive tasks, the execution of other tasks in the thread is still blocked. To resolve this issue, multithread concurrency is introduced. + + +The performance focus of I/O intensive tasks is not the CPU processing capability, but the speed and efficiency of I/O operations, since such a task usually requires frequent operations such as disk read/write and network communication. The following uses frequent read/write operations on a system file to simulate concurrency processing of I/O intensive tasks. + + +1. Define a concurrency function that internally calls I/O capabilities intensively. + + ```ts + import fs from '@ohos.file.fs'; + + // Define a concurrency function that internally calls I/O capabilities intensively. + @Concurrent + async function concurrentTest(fileList: string[]) { + // Implement file writing. + async function write(data, filePath) { + let file = await fs.open(filePath, fs.OpenMode.READ_WRITE); + await fs.write(file.fd, data); + fs.close(file); + } + // Write the file cyclically. + for (let i = 0; i < fileList.length; i++) { + write('Hello World!', fileList[i]).then(() => { + console.info(`Succeeded in writing the file. FileList: ${fileList[i]}`); + }).catch((err) => { + console.error(`Failed to write the file. Code is ${err.code}, message is ${err.message}`) + return false; + }) + } + return true; + } + ``` + +2. Use **TaskPool** to execute the concurrency function that contains the intensive I/O operations. Specifically, call [execute()](../reference/apis/js-apis-taskpool.md#taskpoolexecute) to execute the tasks and process the scheduling result in a callback. For details about how to obtain **filePath1** and **filePath2** in the example, see [Obtaining Application File Paths](../application-models/application-context-stage.md#obtaining-application-file-paths). + + ```ts + import taskpool from '@ohos.taskpool'; + + let filePath1 =...; // Application file path + let filePath2 = ...; + + // Use TaskPool to execute the concurrency function that contains the intensive I/O operations. + // In the case of a large array, the distribution of I/O intensive tasks also preempts the main thread. Therefore, multiple threads are required. + taskpool.execute(concurrentTest, [filePath1, filePath2]).then((ret) => { + // Process the scheduling result. + console.info(`The result: ${ret}`); + }) + ``` diff --git a/en/application-dev/arkts-utils/linear-container.md b/en/application-dev/arkts-utils/linear-container.md new file mode 100644 index 0000000000000000000000000000000000000000..84ed8ab890864a7d525aa24c096431b12d3d18e5 --- /dev/null +++ b/en/application-dev/arkts-utils/linear-container.md @@ -0,0 +1,253 @@ +# Linear Containers + + +Linear containers implement a data structure that enables sequential access. The bottom layer of linear containers is implemented through arrays. OpenHarmony provides the following linear containers: **ArrayList**, **Vector**, **List**, **LinkedList**, **Deque**, **Queue**, and **Stack**. + + +Fully considering the data access speed, linear containers support Create, Read, Update, and Delete (CRUD) through a bytecode instruction at runtime. + + +## ArrayList + +[ArrayList](../reference/apis/js-apis-arraylist.md) is a dynamic array that can be used to construct a global array object. You are advised to use **ArrayList** when elements in a container need to be frequently read. + +**ArrayList** uses generics and must be stored in a contiguous memory space. Its initial capacity is 10, and it increases capacity 1.5-fold in each dynamic expansion. + +**ArrayList** provides the following CRUD APIs. + +| Operation| Description| +| --------- | ------- | +| Adding elements| Use **add(element: T)** to add an element at the end of this container.| +| Adding elements| Use **insert(element: T, index: number)** to insert an element at a given position (specified by **index**).| +| Accessing elements| Use **arr\[index]** to obtain the value at a given position (specified by **index**).| +| Accessing elements| Use **forEach(callbackFn: (value: T, index?: number, arrlist?: ArrayList<T>) => void, thisArg?: Object): void** to traverse the elements in this container.| +| Accessing elements| Use **\[Symbol.iterator]():IterableIterator<T>** for data access.| +| Modifying elements| Use **arr\[index] = xxx** to change 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.| + + +## Vector + +[Vector](../reference/apis/js-apis-vector.md) is a continuous storage structure that can be used to construct a global array object. **Vector** uses generics and must be stored in a contiguous memory space. Its initial capacity is 10, and it has capacity doubled in each dynamic expansion. + +Both **Vector** and [ArrayList](../reference/apis/js-apis-arraylist.md) are implemented based on arrays, but **Vector** provides more interfaces for operating the arrays. In addition to operator access, **Vector** provides the getter and setter to provide a more complete verification and error tolerance mechanism. + +The APIs provided by **Vector** are deprecated since API version 9. You are advised to use [ArrayList](../reference/apis/js-apis-arraylist.md). + +**Vector** provides the following CRUD APIs. + +| Operation| Description| +| --------- | ------- | +| Adding elements| Use **add(element: T)** to add an element at the end of this container.| +| Adding elements| Use **insert(element: T, index: number)** to insert an element at a given position (specified by **index**).| +| 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 **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 **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.| + + +## List + +[List](../reference/apis/js-apis-list.md) can be used to construct a singly linked list, which supports access only through the head node to the tail node. **List** uses generics and can be stored in a non-contiguous memory space. + +Unlike [LinkedList](../reference/apis/js-apis-linkedlist.md), which is a doubly linked list, **List** is a singly linked list that does not support insertion or removal at both ends. + +You are advised to use **List** for frequent insertion and removal operations. + +**List** provides the following CRUD APIs. + +| Operation| Description| +| --------- | ------ | +| Adding elements| Use **add(element: T)** to add an element at the end of this container.| +| Adding elements| Use **insert(element: T, index: number)** to insert an element at a given position (specified by **index**).| +| Accessing elements| Use **list\[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 **getFirst()** to obtain the first element in this container.| +| Accessing elements| Use **getLast()** to obtain the last element in this container.| +| 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 **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.| + + +## LinkedList + +[LinkedList](../reference/apis/js-apis-linkedlist.md) can be used to construct a doubly linked list, which can be traversed at both ends. **LinkedList** uses generics and can be stored in a non-contiguous memory space. + +Unlike [List](../reference/apis/js-apis-list.md), which is a singly linked list, **LinkedList** is a doubly linked list that supports insertion and removal at both ends. + +**LinkedList** is more efficient in data insertion than [ArrayList](../reference/apis/js-apis-arraylist.md), but less efficient in data access. + +You are advised to use **LinkedList** for frequent insertion and removal operations. + +**LinkedList** provides the following CRUD APIs. + +| Operation| Description| +| ---------- | ------ | +| Adding elements| Use **add(element: T)** to add an element at the end of this container.| +| Adding elements| Use **insert(index: number, element: T)** to insert an element at a given position (specified by **index**).| +| Accessing elements| Use **list\[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 **getFirst()** to obtain the first element in this container.| +| Accessing elements| Use **getLast()** to obtain the last element in this container.| +| 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 **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.| + + +## Deque + +[Deque](../reference/apis/js-apis-deque.md) can be used to construct a double-ended queue (deque) that follows the principles of First In First Out (FIFO) and Last In First Out (LIFO). It allows insertion and removal of elements at both the ends. + +**Deque** uses generics and must be stored in a contiguous memory space. Its initial capacity is 8, and it has capacity doubled in each dynamic expansion. The bottom layer of **Deque** is implemented by cyclic queues, delivering a high efficiency in enqueuing and dequeuing. + +[Queue](../reference/apis/js-apis-queue.md) follows the principle of FIFO only and allows element removal at the front and insertion at the rear. + +[Vector](../reference/apis/js-apis-vector.md) supports insertion and deletion of elements in between, as well as at both the ends. When compared with **Vector**, **Deque** is more efficient in inserting and removing header elements, but less efficient in accessing elements. + +You are advised to use **Deque** when you need to frequently insert or remove elements at both the ends of a container. + +**Deque** provides the following CRUD APIs. + +| Operation| Description| +| ---------- | ------ | +| Adding elements| Use **insertFront(element: T)** to insert an element at the front of this container.| +| Adding elements| Use **insertEnd(element: T)** to insert an element at the end of this container.| +| Accessing elements| Use **getFirst()** to obtain the value of the first element in this container, without removing it from the container.| +| Accessing elements| Use **getLast()** to obtain the value of the last element in this container, without removing it from the container.| +| Accessing elements| Use **popFirst()** to obtain the value of the first element in this container and remove it from the container.| +| Accessing elements| Use **popLast()** to obtain the value of the last element in this container and remove it from the container.| +| Accessing elements| Use **forEach(callbackFn:(value: T, index?: number, deque?: Deque<T>) => 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, index?: number, deque?: Deque<T>)=> void, thisArg?: Object)** to modify an element in this container.| +| Deleting elements| Use **popFirst()** to remove the first element from this container.| +| Deleting elements| Use **popLast()** to remove the last element from this container.| + + +## Queue + +[Queue](../reference/apis/js-apis-queue.md) can be used to construct a queue that follows the FIFO principle. + +**Queue** uses generics and must be stored in a contiguous memory space. Its initial capacity is 8, and it has capacity doubled in each dynamic expansion. + +The bottom layer of **Queue** is implemented by cyclic queues, delivering a high efficiency in enqueuing and dequeuing. + +Unlike [Deque](../reference/apis/js-apis-deque.md), which supports insertion and removal at both the ends, **Queue** supports insertion at one end and removal at the other end. + +You are advised to use **Queue** in FIFO scenarios. + +**Queue** provides the following CRUD APIs. + +| Operation| Description| +| ---------- | ------ | +| Adding elements| Use **add(element: T)** to add an element at the end of this container.| +| Accessing elements| Use **getFirst()** to obtain the value of the first element in this container, without removing it from the container.| +| Accessing elements| Use **pop()** to obtain the value of the first element in this container and remove it from the container.| +| Accessing elements| Use **forEach(callbackFn: (value: T, index?: number, queue?: Queue<T>) => 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, index?: number, queue?: Queue<T>) => void,thisArg?: Object)** to modify an element in this container.| +| Deleting elements| Use **pop()** to remove the first element from this container.| + + +## Stack + +[Stack](../reference/apis/js-apis-stack.md) can be used to construct a stack that follows the Last Out First In (LOFI) principle. + +**Stack** uses generics and must be stored in a contiguous memory space. Its initial capacity is 8, and it increases capacity 1.5-fold in each dynamic expansion. The bottom layer of **Stack** is implemented based on arrays. It supports data insertion and removal at one end. + +Unlike [Queue](../reference/apis/js-apis-queue.md), which is implemented based on the queue data structure and supports insertion at one end and removal at the other end, **Stack** supports insertion and removal at the same end. + +You are advised to use **Stack** in LOFI scenarios. + +**Stack** provides the following CRUD APIs. + +| Operation| Description| +| ---------- | ------ | +| Adding elements| Use **push(item: T)** to add an element at the top of this container.| +| Accessing elements| Use **peek()** to obtain the value of the top element in this container, without removing it from the container.| +| Accessing elements| Use **pop()** to obtain the value of the top element in this container and remove it from the container.| +| Accessing elements| Use **forEach(callbackFn: (value: T, index?: number, stack?: Stack<T>) => void, thisArg?: Object)** to traverse the elements in this container.| +| Accessing elements| Use **\[Symbol.iterator]():IterableIterator<T>** for data access.| +| Accessing elements| Use **locate(element: T)** to obtain the index of the first occurrence of the specified element.| +| Modifying elements| Use **forEach(callbackFn:(value: T, index?: number, stack?: Stack<T>) => void, thisArg?: Object)** to modify an element in this container.| +| Deleting elements| Use **pop()** to remove the top element from this container.| + + +## Use of Linear Containers + +Refer to the code snippet below to add, access, and modify elements in **ArrayList**, **Vector**, **Deque**, **Stack**, and **List**. + + +```js +// ArrayList +import ArrayList from '@ohos.util.ArrayList'; // Import the ArrayList module. + +let arrayList = new ArrayList(); +arrayList.add('a'); +arrayList.add(1); // Add an element. +console.info(`result: ${arrayList[0]}`); // Access an element. +arrayList[0] = 'one'; // Modify an element. +console.info(`result: ${arrayList[0]}`); + +// Vector +import Vector from '@ohos.util.Vector'; // Import the Vector module. + +let vector = new Vector(); +vector.add('a'); +let b1 = [1, 2, 3]; +vector.add(b1); +vector.add(false); // Add an element. +console.info(`result: ${vector[0]}`); // Access an element. +console.info(`result: ${vector.getFirstElement()}`); // Access an element. + +// Deque +import Deque from '@ohos.util.Deque'; // Import the Deque module. + +let deque = new Deque; +deque.insertFront('a'); +deque.insertFront(1); // Add an element. +console.info(`result: ${deque[0]}`); // Access an element. +deque[0] = 'one'; // Modify an element. +console.info(`result: ${deque[0]}`); + +// Stack +import Stack from '@ohos.util.Stack'; // Import the Stack module. + +let stack = new Stack(); +stack.push('a'); +stack.push(1); // Add an element. +console.info(`result: ${stack[0]}`); // Access an element. +stack.pop(); // Remove an element. +console.info(`result: ${stack.length}`); + +// List +import List from '@ohos.util.List'; // Import the List module. + +let list = new List; +list.add('a'); +list.add(1); +let b2 = [1, 2, 3]; +list.add(b2); // Add an element. +console.info(`result: ${list[0]}`); // Access an element. +console.info(`result: ${list.get(0)}`); // Access an 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 new file mode 100644 index 0000000000000000000000000000000000000000..08451191025d01ecfcd3b70f8fb8170826c35dc4 --- /dev/null +++ b/en/application-dev/arkts-utils/multi-thread-concurrency-overview.md @@ -0,0 +1,62 @@ +# Multithread Concurrency Overview + + +## Overview + +Concurrency models are used to implement concurrent tasks in different scenarios. Common concurrency models are classified into shared memory models and message passing models. + +A typical message passing model is actor. It provides a relatively high degree of concurrency while eliminating a series of complex and occasional issues caused by locks. For these reasons, ArkTS chooses the actor model. + +Due to the memory isolation feature of the actor model, cross-thread serialization is required. + + +## Data Transfer 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 + +The structured clone algorithm is used for serialization of common objects. This algorithm recursively transfers an object by clone. It supports more object types than other serialization algorithms. + +The following object types are supported: basic types except Symbol, Date, String, RegExp, Array, Map, Set, Object (simple objects only, for example, objects created using **{}** or **new Object**), ArrayBuffer, and typedArray. (Note that only attributes can be transferred for common objects. Prototypes and methods cannot be transferred.) + + +### Transferable Objects + +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 +// Define a transferable object. +let buffer = new ArrayBuffer(100); +``` + + +### Shared Objects + +A shared object is of the **SharedArrayBuffer** type, has a fixed length, and can store any type of data including numbers and strings. + +An object of the SharedArrayBuffer type can be transferred between multiple threads. The objects before and after the transfer point to the same memory block, achieving memory sharing. + +If multiple operations are simultaneously performed to modify data stored in an object of the SharedArrayBuffer type, you must use atomics to ensure data synchronization. Atomics ensure that the current operation is complete before the next operation starts. + + +```js +// Define a shared object, which uses atomics to ensure data synchronization. +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 + +ArkTS provides two multithread concurrency capabilities: **TaskPool** and **Worker**, which differ in their implementation features and use cases. For details, see [Comparison Between TaskPool and Worker](taskpool-vs-worker.md). diff --git a/en/application-dev/arkts-utils/nonlinear-container.md b/en/application-dev/arkts-utils/nonlinear-container.md new file mode 100644 index 0000000000000000000000000000000000000000..b5c6380ae873b9dc47b69a6754b357f7dac8c1c8 --- /dev/null +++ b/en/application-dev/arkts-utils/nonlinear-container.md @@ -0,0 +1,253 @@ +# Nonlinear Containers + + +Nonlinear containers implement a data structure that enables quick search. The bottom layer of nonlinear containers is implemented through hash tables or red-black trees. OpenHarmony provides the following nonlinear containers: **HashMap**, **HashSet**, **TreeMap**, **TreeSet**, **LightWeightMap**, **LightWeightSet**, and **PlainArray**. The types of **key** and **value** in nonlinear containers must meet the ECMA standard. + + +## HashMap + +[HashMap](../reference/apis/js-apis-hashmap.md) is used to store a set of associated key-value (KV) pairs. In a hash map, each key is unique and corresponds to a value. + +**HashMap** uses generics. In a hash map, a key is located based on its hash code. The initial capacity of a hash map is 16, and it has capacity doubled in each dynamic expansion. The bottom layer of **HashMap** is implemented based on a hash table. It uses chaining to avoid collisions in hash tables. + +**HashMap** is faster in accessing data than [TreeMap](../reference/apis/js-apis-treemap.md), because the former accesses the keys based on the hash codes, whereas the latter stores and accesses the keys in sorted order. + +[HashSet](../reference/apis/js-apis-hashset.md) is implemented based on **HashMap**. The input parameter of **HashMap** consists of **key** and **value**. In **HashSet**, only the **value** object is processed. + +You are advised to use **HashMap** when you need to quickly access, remove, and insert KV pairs. + +**HashMap** provides the following Create, Read, Update, and Delete (CRUD) APIs. + +| Operation| Description| +| -------- | ------ | +| Adding elements| Use **set(key: K, value: V)** to add an element (a KV pair) to this container.| +| Accessing elements| Use **get(key: K)** to obtain the value of the specified key.| +| Accessing elements| Use **keys()** to return an iterator that contains all the keys in 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?: V, key?: K, map?: HashMap) => void, thisArg?: Object)** to traverse the elements in this container.| +| Accessing elements| Use **\[Symbol.iterator]():IterableIterator<[K,V]>** for data access.| +| Modifying elements| Use **replace(key: K, newValue: V)** to change the value of the specified key.| +| Modifying elements| Use **forEach(callbackFn: (value?: V, key?: K, map?: HashMap) => void, thisArg?: Object)** to modify an element in this container.| +| Deleting elements| Use **remove(key: K)** to remove an element with the specified key.| +| Deleting elements| Use **clear()** to clear this container.| + + +## HashSet + +[HashSet](../reference/apis/js-apis-hashset.md) is used to store a set of values, each of which is unique in a hash set. + +**HashSet** uses generics. In a hash set, a value is located based on its hash code. The initial capacity of a hash set is 16, and it has capacity doubled in each dynamic expansion. The type of **value** must comply with the ECMA standard. The bottom layer of **HashSet** is implemented based on a hash table. It uses chaining to avoid collisions in hash tables. + +**HashSet** is implemented based on [HashMap](../reference/apis/js-apis-hashmap.md). In **HashSet**, only the **value** object is processed. + +Unlike [TreeSet](../reference/apis/js-apis-treeset.md), which stores and accesses data in sorted order, **HashSet** stores data in a random order. This means that **HashSet** may use a different order when storing and accessing elements. Both of them allows only unique elements. However, null values are allowed in **HashSet**, but not allowed in **TreeSet**. + +You are advised to use **HashSet** when you need a set that has only unique elements or need to deduplicate a set. + +**HashSet** provides the following CRUD APIs. + +| Operation| Description| +| -------- | ------ | +| 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 **\[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.| +| Deleting elements| Use **remove(value: T)** to remove a value.| +| Deleting elements| Use **clear()** to clear this container.| + + +## TreeMap + +[TreeMap](../reference/apis/js-apis-treemap.md) is used to store a set of associated KV pairs. In a tree map, each key is unique and corresponds to a value. + +**TreeMap** uses generics, and the keys in a tree map are ordered. The bottom layer of **TreeMap** is a binary tree, which supports quick search of KV pairs through the children (left child and right child) of the tree. The type of **key** must comply with the ECMA standard. Keys in a tree map are stored in order. The bottom layer of **TreeMap** is implemented based on the red-black tree and supports quick insertion and removal. + +[HashMap](../reference/apis/js-apis-hashmap.md) is faster in accessing data than **TreeMap**, because the former accesses the keys based on the hash codes, whereas the latter stores and accesses the keys in sorted order. + +You are advised to use **TreeMap** when you need to store KV pairs in sorted order. + +**TreeMap** provides the following CRUD APIs. + +| Operation| Description| +| ------- | ------ | +| Adding elements| Use **set(key: K, value: V)** to add an element (a KV pair) to this container.| +| Accessing elements| Use **get(key: K)** to obtain the value of the specified key.| +| Accessing elements| Use **getFirstKey()** to obtain the first key in this container.| +| Accessing elements| Use **getLastKey()** to obtain the last key in this container.| +| Accessing elements| Use **keys()** to return an iterator that contains all the keys in 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?: V, key?: K, map?: TreeMap) => void, thisArg?: Object)** to traverse the elements in this container.| +| Accessing elements| Use **\[Symbol.iterator]():IterableIterator\<[K,V]>** for data access.| +| Modifying elements| Use **replace(key: K, newValue: V)** to change the value of the specified key.| +| Modifying elements| Use **forEach(callbackFn: (value?: V, key?: K, map?: TreeMap) => void, thisArg?: Object)** to modify an element in this container.| +| Deleting elements| Use **remove(key: K)** to remove an element with the specified key.| +| Deleting elements| Use **clear()** to clear this container.| + + +## TreeSet + +[TreeSet](../reference/apis/js-apis-treeset.md) is used to store a set of values, each of which is unique in a tree set. + +**TreeSet** uses generics, and the values in a tree set are ordered. The bottom layer of **TreeSet** is a binary tree, which supports quick search of a value through the children (left child and right child) of the tree. The type of **value** must meet the ECMA standard. Values in a tree set are stored in order. The bottom layer of **TreeSet** is implemented based on the red-black tree and supports quick insertion and removal. + +**TreeSet** is implemented based on [TreeMap](../reference/apis/js-apis-treemap.md). In **TreeSet**, only **value** objects are processed. **TreeSet** can be used to store values, each of which must be unique. + +[HashSet](../reference/apis/js-apis-hashset.md) stores data in a random order, whereas **TreeSet** stores data in sorted order. Both of them allows only unique elements. However, null values are allowed in **HashSet**, but not allowed in **TreeSet**. + +You are advised to use **TreeSet** when you need to store data in sorted order. + +**TreeSet** provides the following CRUD APIs. + +| Operation| Description| +| -------- | ------ | +| 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 **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 **\[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.| +| Deleting elements| Use **remove(value: T)** to remove a value.| +| Deleting elements| Use **clear()** to clear this container.| + + +## LightWeightMap + +[LightWeightMap](../reference/apis/js-apis-lightweightmap.md) is used to store a set of associated KV pairs. In a lightweight map, each key is unique and corresponds to a value. **LightWeightMap** uses generics and a more lightweight structure. It uses the hash code to uniquely identify a key at the bottom layer. It uses linear probing to avoid collisions. In a lightweight map, a key is located by using the hash code and binary search algorithm. The hash code is stored in an array and mapped to a key and its value in another array. The type of **key** must comply with the ECMA standard. + +The default initial capacity of a lightweight map is 8, and it has capacity doubled in each expansion. + +Compared with [HashMap](../reference/apis/js-apis-hashmap.md), which can also store KV pairs, **LightWeightMap** occupies less memory. + +You are advised to use **LightWeightMap** when you need to store and access **KV pairs**. + +**LightWeightMap** provides the following CRUD APIs. + +| Operation| Description| +| -------- | ------ | +| Adding elements| Use **set(key: K, value: V)** to add an element (a KV pair) to this container.| +| Accessing elements| Use **get(key: K)** to obtain the value of the specified key.| +| Accessing elements| Use **getIndexOfKey(key: K)** to obtain the index of the specified key.| +| Accessing elements| Use **getIndexOfValue(value: V)** to obtain the index of the first occurrence of the specified value.| +| Accessing elements| Use **keys()** to return an iterator that contains all the keys in 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 **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?: V, key?: K, map?: LightWeightMap) => void, thisArg?: Object)** to traverse the elements in this container.| +| Accessing elements| Use **\[Symbol.iterator]():IterableIterator<[K,V]>** for data access.| +| Modifying elements| Use **setValueAt(index: number, newValue: V)** to change the value of an element at a given position (specified by **index**).| +| Modifying elements| Use **forEach(callbackFn: (value?: V, key?: K, map?: LightWeightMap) => void, thisArg?: Object)** to modify an element 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.| + + +## LightWeightSet + +[LightWeightSet](../reference/apis/js-apis-lightweightset.md) is used to store a set of values, each of which is unique in a lightweight set. + +**LightWeightSet** uses generics and a lightweight structure. Its default initial capacity is 8, and it has capacity doubled in each expansion. In a lightweight set, a value is located by using the hash code and binary search algorithm. The hash code is stored in an array and mapped to a value in another array. The type of **value** must comply with the ECMA standard. + +**LightWeightSet** uses the hash code to uniquely identify a value at the bottom layer. It uses linear probing to avoid collisions and adopts the binary search algorithm. + +Compared with [HashSet](../reference/apis/js-apis-hashset.md), which can also store values, **LightWeightSet** occupies less memory. + +You are advised to use **LightWeightSet** when you need a set that has only unique elements or need to deduplicate a set. + +**LightWeightSet** provides the following CRUD APIs. + +| Operation| Description| +| -------- | ------ | +| Adding elements| Use **add(obj: T)** to add a value to this container.| +| Accessing elements| Use **getIndexOf(key: T)** to obtain the index of a key.| +| 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 **\[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.| +| 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.| + + +## PlainArray + +[PlainArray](../reference/apis/js-apis-plainarray.md) is used to store a set of associated KV pairs. In a plain array, each key is unique, corresponds to a value, and is of the number type. **PlainArray** uses generics and a more lightweight structure. In a plain array, a key is located by using the binary search algorithm and is mapped to a value in another array. + +The default initial capacity of a plain array is 16, and it has capacity doubled in each expansion. + +Both **PlainArray** and [LightWeightMap](../reference/apis/js-apis-lightweightmap.md) are used to store KV pairs in the lightweight structure. However, the key type of **PlainArray** can only be **number**. + +You are advised to use PlainArray when you need to store KV pairs whose keys are of the number type. + +**PlainArray** provides the following CRUD APIs. + +| Operation| Description| +| -------- | ------ | +| Adding elements| Use **add(key: number,value: T)** to add an element (a KV pair) to this container.| +| Accessing elements| Use **get(key: number)** to obtain the value of the specified key.| +| Accessing elements| Use **getIndexOfKey(key: number)** to obtain the index of the specified key.| +| 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 **\[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.| +| 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.| +| Deleting elements| Use **clear()** to clear this container.| + + +## Use of Nonlinear Containers + +Refer to the code snippet below to add, access, and modify elements in **HashMap**, **TreeMap**, **LightWeightMap**, **Stack**, and **PlainArray**. + + +```js +// HashMap +import HashMap from '@ohos.util.HashMap'; // Import the HashMap module. + +let hashMap = new HashMap(); +hashMap.set('a', 123); +hashMap.set (4, 123);// Add an element. +console.info(`result: ${hashMap.hasKey(4)}`); // Check whether an element is contained. +console.info(`result: ${hashMap.get('a')}`); // Access an element. + +// TreeMap +import TreeMap from '@ohos.util.TreeMap'; // Import the TreeMap module. + +let treeMap = new TreeMap(); +treeMap.set('a', 123); +treeMap.set('6', 356); // Add an element. +console.info(`result: ${treeMap.get('a')}`); // Access an element. +console.info(`result: ${treeMap.getFirstKey()}`); // Access the first element. +console.info(`result: ${treeMap.getLastKey()}`); // Access the last element. + +// LightWeightMap +import LightWeightMap from '@ohos.util.LightWeightMap'; // Import the LightWeightMap module. + +let lightWeightMap = new LightWeightMap(); +lightWeightMap.set('x', 123); +lightWeightMap.set('8', 356); // Add an element. +console.info(`result: ${lightWeightMap.get('a')}`); // Access an element. +console.info(`result: ${lightWeightMap.get('x')}`); // Access an element. +console.info(`result: ${lightWeightMap.getIndexOfKey('8')}`); // Access an element. + +// PlainArray +import PlainArray from '@ohos.util.PlainArray' // Import the PlainArray module. + +let plainArray = new PlainArray(); +plainArray.add(1, 'sdd'); +plainArray.add(2,'sff'); // Add an element. +console.info(`result: ${plainArray.get(1)}`); // Access an element. +console.info(`result: ${plainArray.getKeyAt(1)}`); // Access an element. +``` diff --git a/en/application-dev/arkts-utils/single-io-development.md b/en/application-dev/arkts-utils/single-io-development.md new file mode 100644 index 0000000000000000000000000000000000000000..b488890b42c9cb5849077fd1f00815f1a3f5ddf8 --- /dev/null +++ b/en/application-dev/arkts-utils/single-io-development.md @@ -0,0 +1,29 @@ +# Single I/O Task Development + + +Asynchronous concurrency provided by Promise and async/await is applicable to the development of a single I/O task. The following uses the asynchronous concurrency capability to write a file as an example. + + +1. Implement the logic of a single I/O task. + + ```js + import fs from '@ohos.file.fs'; + + async function write(data: string, filePath: string) { + let file = await fs.open(filePath, fs.OpenMode.READ_WRITE); + fs.write(file.fd, data).then((writeLen) => { + fs.close(file); + }).catch((err) => { + console.error(`Failed to write data. Code is ${err.code}, message is ${err.message}`); + }) + } + ``` + +2. Use the asynchronous capability to invoke the single I/O task. For details about how to obtain **filePath** in the example, see [Obtaining Application File Paths](../application-models/application-context-stage.md#obtaining-application-file-paths). + + ```js + let filePath = ...; // Application file path + write('Hello World!', filePath).then(() => { + console.info('Succeeded in writing data.'); + }) + ``` diff --git a/en/application-dev/arkts-utils/sync-task-development.md b/en/application-dev/arkts-utils/sync-task-development.md new file mode 100644 index 0000000000000000000000000000000000000000..8ce4290a5122b30955c94a1e9116c92f53e0ea7b --- /dev/null +++ b/en/application-dev/arkts-utils/sync-task-development.md @@ -0,0 +1,173 @@ +# Synchronous Task Development + + +Synchronous tasks are executed in order among multiple threads. For example, as a synchronization primitive, locks prevent data contention. + + +To implement synchronous tasks, you must consider the collaboration and synchronization between multiple threads and ensure the correctness of data and the correct execution of programs. + +If synchronous tasks are independent of each other, you are advised to use **TaskPool**, since it focuses on single independent tasks. For example, a series of imported static methods or methods implemented in singletons are independent. If synchronous tasks are associated with each other, use **Worker**, for example, methods implemented in class objects (not singleton class objects). + + +## Using TaskPool to Process Independent Synchronous Tasks + +**TaskPool** is recommended for scheduling independent synchronous tasks. Typical synchronous tasks are those using static methods. If a unique handle or class object constructed using a singleton points to multiple tasks and these tasks can be used between different worker threads, you can also use **TaskPool**. + +1. Define a concurrency function that internally calls the synchronous methods. + +2. Create a task, execute the task through **TaskPool**, and perform operations on the asynchronous result. Create a [task](../reference/apis/js-apis-taskpool.md#task) and call [execute()](../reference/apis/js-apis-taskpool.md#taskpoolexecute-1) to execute the task synchronously. + +3. Perform concurrent operations. + +Simulate a singleton class that contains synchronous calls. + + +```ts +// handle.ts code +export default class Handle { + static getInstance() { + // Return a singleton object. + } + + static syncGet() { + // Synchronous getter. + return; + } + + static syncSet(num: number) { + // Synchronous setter. + return; + } +} +``` + +Use **TaskPool** to call the related synchronous methods. + + +```ts +// Index.ets code +import taskpool from '@ohos.taskpool'; +import Handle from './Handle'; // Return a static handle. + +// Step 1: Define a concurrency function that internally calls the synchronous methods. +@Concurrent +function func(num: number) { + // Call the synchronous wait implemented in a static class object. + Handle.syncSet(num); + // Alternatively, call the synchronous wait implemented in a singleton object. + Handle.getInstance().syncGet(); + return true; +} + +// Step 2: Create and execute a task. +async function asyncGet() { + // Create a task and pass in the function func. + let task = new taskpool.Task(func, 1); + // Execute the task and obtain the result res. + let res = await taskpool.execute(task); + // Perform operations on the synchronous result. + console.info(String(res)); +} + +@Entry +@Component +struct Index { + @State message: string = 'Hello World'; + + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + .onClick(() => { + // Step 3: Perform concurrent operations. + asyncGet(); + }) + } + .width('100%') + .height('100%') + } + } +} +``` + + +## Using Worker to Process Associated Synchronous Tasks + +Use **Worker** when you want to schedule a series of synchronous tasks using the same handle or depending on the same class object. + +1. Create a **Worker** object in the main thread and receive messages from the worker thread. + + ```js + import worker from '@ohos.worker'; + + @Entry + @Component + struct Index { + @State message: string = 'Hello World'; + + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + .onClick(() => { + let w = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts'); + w.onmessage = function (d) { + // Receive the result of the worker thread. + } + w.onerror = function (d) { + // Receive error information of the worker thread. + } + // Send a Set message to the worker thread. + w.postMessage({'type': 0, 'data': 'data'}) + // Send a Get message to the worker thread. + w.postMessage({'type': 1}) + // Destroy the worker thread. + w.terminate() + }) + } + .width('100%') + } + .height('100%') + } + } + ``` + +2. Bind the **Worker** object in the worker thread and process the synchronous task logic. + + ```js + // handle.ts code + export default class Handle { + syncGet() { + return; + } + + syncSet(num: number) { + return; + } + } + + // Worker.ts code + import worker, { ThreadWorkerGlobalScope, MessageEvents } from '@ohos.worker'; + import Handle from './handle.ts' // Return a handle. + + var workerPort : ThreadWorkerGlobalScope = worker.workerPort; + + // Handle that cannot be transferred. All operations depend on this handle. + var handler = new Handle() + + // onmessage() logic of the worker thread. + workerPort.onmessage = function(e : MessageEvents) { + switch (e.data.type) { + case 0: + handler.syncSet(e.data.data); + workerPort.postMessage('success set'); + case 1: + handler.syncGet(); + workerPort.postMessage('success get'); + } + } + ``` diff --git a/en/application-dev/arkts-utils/taskpool-vs-worker.md b/en/application-dev/arkts-utils/taskpool-vs-worker.md new file mode 100644 index 0000000000000000000000000000000000000000..4a3dcd0557a3afbdcfba515752eeea5780f872ab --- /dev/null +++ b/en/application-dev/arkts-utils/taskpool-vs-worker.md @@ -0,0 +1,164 @@ +# Comparison Between TaskPool and Worker + +**TaskPool** and **Worker** provide a multithread running environment for applications to process time-consuming computing tasks or resource intensive tasks, preventing these tasks from blocking the main thread. This maximizes system utilization, reduces overall resource consumption, and improves overall system performance. + + +This topic compares **TaskPool** with **Worker** from two aspects: [implementation features](#implementation-feature-comparison) and [use cases](#use-case-comparison). It also describes their operating mechanisms and precautions. + + +## Implementation Feature Comparison + +**Table 1** Comparison between TaskPool and Worker in implementation features + +| Item| TaskPool | Worker | +| -------- | -------- | -------- | +| Memory model| Threads are isolated from each other, and memory is not shared.| Threads are isolated from each other, and memory is not shared.| +| Parameter passing mechanism| The structured clone algorithm is used for serialization and deserialization.
ArrayBuffer and SharedArrayBuffer are used for parameter passing and sharing.| The structured clone algorithm is used for serialization and deserialization.
ArrayBuffer and SharedArrayBuffer are used for parameter passing and sharing.| +| Parameter passing| Parameters are directly passed in, without being encapsulated.| Only one parameter can be carried in a message object. Therefore, you must encapsulate excess parameters.| +| Method invocation| Methods are directly passed in and called.| Messages are passed in the worker thread and the corresponding methods are called.| +| Return value| A value is returned by default after asynchronous calling.| Messages proactively sent must be parsed and assigned by calling **onmessage()**.| +| Lifecycle| The task pool manages its own lifecycle, without considering the load.| You are required to manage the number and lifecycle of worker threads.| +| Maximum number of task pools| The number is automatically managed, rather than being manually configured.| A maximum of eight worker threads are supported.| +| Maximum task execution duration| 3 minutes (excluding the time used for Promise or async/await asynchronous call, for example, the time consumed by I/O tasks such as network download and file read/write)| There is no restriction.| +| Task priority setting| Setting the task priority is supported.| Setting the task priority is not supported.| +| Task cancellation| Tasks that have been initiated can be canceled.| Tasks that have been initiated cannot be canceled.| + + +## Use Case Comparison + +Both **TaskPool** and **Worker** support multithread concurrency. **TaskPool** worker threads are bound to the system scheduling priority and support load balancing (automatic scaling). **Worker** threads are manually created and do not support scheduling priority setting. Therefore, **TaskPool** provides better performance than **Worker** and is recommended in most scenarios. + +**TaskPool** is oriented to thread-level independent tasks, and tasks running for more than 3 minutes are automatically reclaimed by the system. **Worker** is oriented to threads and supports thread execution for a long time. + +Common use cases are as follows: + +- Use **Worker** for a task that runs for more than 3 minutes (excluding the time used for Promise or async/await asynchronous call, for example, I/O tasks such as network download and file read/write). For example, use **Worker** for a 1-hour prediction algorithm training job in the background. + +- Use **Worker** for a series of associated synchronous tasks. For example, use **Worker** for a series of database operations, since the same handle is required. + +- Use **TaskPool** for a task for which the priority needs to be set. For example, in the histogram rendering scenario in Gallery, histogram data calculated in the background is used for UI display on the foreground. This requires high-priority processing. In this case, use **TaskPool**. + +- Use **TaskPool** for a task that needs to be canceled frequently. For example, in the large image browsing scenario in Gallery, both images on the left and right sides of the current image are cached. When the user slides to the next image, a cache task on one side needs to be canceled. In this case, use **TaskPool**. + +- Use **TaskPool** for a large number of tasks or tasks with scattered scheduling points. For example, a large-scale application with multiple modules has multiple time-consuming tasks, and it is inconvenient to use eight worker threads to manage load. In this case, **TaskPool** is recommended. + + +## TaskPool Operating Mechanism + +**Figure 1** TaskPool operating mechanism + +![taskpool](figures/taskpool.png) + +With **TaskPool**, you can encapsulate tasks in the main thread and throw the tasks to the task queue. The system selects proper worker threads to distribute and execute the tasks, and then returns the result to the main thread. **TaskPool** provides APIs to execute and cancel tasks, and set the task priority. It also minimizes system resource usage through unified thread management, dynamic scheduling, and load balancing algorithms. By default, the system starts a worker thread and increases the thread quantity as the number of tasks increases. The maximum number of worker threads that can be created depends on the number of physical cores of the device. The formula is max(3, Number of physical cores – 1). If no task is distributed for a long period of time, the system reduces the number of worker threads. + + +## Worker Operating Mechanism + +**Figure 2** Worker operating mechanism + +![worker](figures/worker.png) + +The thread that creates the worker thread is referred to as the host thread (not necessarily the main thread, since a worker thread can also create a worker subthread). A worker thread is also named an actor thread. Each worker thread has an independent instance from the host thread, including the infrastructure, object, and code segment. The worker thread communicates with the host thread by means of message exchange. They use the serialization technique to exchange commands and data. + + +## Precautions for TaskPool + +- A task function must be decorated with **\@Concurrent** and can be used only in .ets files. + +- A task function must be a common function or async function, but not a class member function or anonymous function. + +- A task function can use imported variables and input parameter variables only in a project created on the stage model. In a project created on the FA model, it can use input parameter variables only. + +- A task function in the **TaskPool** worker thread must finish the execution within 3 minutes (excluding the time used for Promise or async/await asynchronous call, for example, the duration of I/O tasks such as network download and file read/write). Otherwise, it forcibly exits. + +- Input parameter types in a task function must be those supported by serialization. For details, see [Common Objects](multi-thread-concurrency-overview.md#common-objects). + +- Parameters of the ArrayBuffer type are transferred in **TaskPool** by default. You can set the transfer list by calling [setTransferList()](../reference/apis/js-apis-taskpool.md#settransferlist10). + +- The context objects in different threads are different. Therefore, **TaskPool** worker threads can use only thread-safe libraries, rather than UI-related non-thread-safe libraries. + +- A maximum of 16 MB data can be serialized. + + +## Precautions for Worker + +- The rules for passing in the **Worker.ts** path during the worker creation vary in different API versions. For details, see [Precautions for File Paths](#precautions-for-file-paths). + +- After a worker thread is created, you must manually manage its lifecycle. A maximum of eight worker threads can run simultaneously. For details, see [Lifecycle Precautions](#lifecycle-precautions). + +- Modules of the [ability type](../quick-start/application-package-structure-stage.md) support **Worker**, but modules of the [library type](../quick-start/application-package-structure-stage.md) do not support **Worker**. + +- When creating a worker thread, the **Worker.ts** file of another module cannot be used. This means that a worker cannot be called across modules. + +- The context objects in different threads are different. Therefore, **Worker** threads can use only thread-safe libraries, rather than UI-related non-thread-safe libraries. + +- A maximum of 16 MB data can be serialized. + + +### Precautions for File Paths + +Before calling an API of the **Worker** module, you must create a **Worker** instance. The constructor function varies in different API versions. + +```js +// Use the following function in API version 9 and later versions: +const worker1 = new worker.ThreadWorker(scriptURL); +// Use the following function in API version 8 and earlier versions: +const worker1 = new worker.Worker(scriptURL); +``` + +The **Worker.ts** file path (specified by **scriptURL**) must be passed in the constructor function. By default, the **workers** directory (upper-level directory of the **Worker.ts** file) is at the same level as the **pages** directory. + +**Stage Model** + + +The following is an example of **scriptURL** in the constructor function: + +```js +// Method 1 +// In the stage model, the workers directory is at the same level as the pages directory in the entry module. +const worker1 = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts', {name:"first worker in Stage model"}); +// In the stage model, the workers directory is a child directory of the pages directory in the entry module. +const worker2 = new worker.ThreadWorker('entry/ets/pages/workers/MyWorker.ts'); + +// Method 2 +// In the stage model, the workers directory is at the same level as the pages directory in the entry module, and bundlename is com.example.workerdemo. +const worker3 = new worker.ThreadWorker('@bundle:com.example.workerdemo/entry/ets/workers/worker'); +// In the stage model, the workers directory is a child directory of the pages directory in the entry module, and bundlename is com.example.workerdemo. +const worker4 = new worker.ThreadWorker('@bundle:com.example.workerdemo/entry/ets/pages/workers/worker'); +``` + + +- Based on the directory structure of the stage model project, the field meanings in method 1 are as follows: + - **entry**: value of the **name** attribute under **module** in the **module.json5** file. + - **ets**: directory for storing the ArkTS source code. It is fixed. + - **workers/MyWorker.ts**: path of the worker source file in the **ets** directory. + +- Based on the directory structure of the stage model project, the field meanings in method 2 are as follows: + - **\@bundle**: fixed label. + - **bundlename**: bundle name of the current application. + - **entryname**: value of the **name** attribute under **module** in the **module.json5** file. + - **ets**: directory for storing the ArkTS source code. It is fixed. + - **workerdir/workerfile**: path of the worker source file in the **ets** directory. + + +**FA Model** + + +The following is an example of **scriptURL** in the constructor function: + +```js +// In the FA model, the workers directory is at the same level as the pages directory in the entry module. +const worker1 = new worker.ThreadWorker('workers/worker.js', {name:'first worker in FA model'}); +// In the FA model, the workers directory is at the same level as the parent directory of the pages directory in the entry module. +const worker2 = new worker.ThreadWorker('../workers/worker.js'); +``` + + +### Lifecycle Precautions + +- Creating and terminating worker threads consume performance. Therefore, you are advised to manage available workers and reuse them. The worker threads keep running even when they are idle. Therefore, when a worker thread is not required, call [terminate()](../reference/apis/js-apis-worker.md#terminate9) interface or [parentPort.close()](../reference/apis/js-apis-worker.md#close9) to destroy it. If a worker thread is destroyed or being destroyed, an error is thrown when it is called. + + +- A maximum of eight worker threads can co-exist. + - In API version 8 and earlier versions, when the number of worker threads 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 threads exceeds the upper limit, the error "Worker initialization failure, the number of workers exceeds the maximum." is thrown. diff --git a/en/application-dev/arkts-utils/xml-conversion.md b/en/application-dev/arkts-utils/xml-conversion.md new file mode 100644 index 0000000000000000000000000000000000000000..96dc727635ea4449edd3bdc41e5ec016b268eca9 --- /dev/null +++ b/en/application-dev/arkts-utils/xml-conversion.md @@ -0,0 +1,92 @@ +# XML Conversion + + +Converting XML text into JavaScript objects makes it easier to process and manipulate data. In addition, JavaScript objects are more suitable than XML text for JavaScript applications. + + +The common library provides the **ConvertXML** class to convert XML text into JavaScript objects. The input is XML strings and conversion options, and the output is a JavaScript object. For details about the conversion options, see the API reference [@ohos.convertxml (XML-to-JavaScript Conversion)](../reference/apis/js-apis-convertxml.md). + + +## Precautions + +To ensure successful XML parsing and conversion, the input XML data must comply with the standard format. + + +## How to Develop + +The following steps walk you through on how to convert an XML file into a JavaScript object to obtain the tag values. + +1. Import the **convertxml** module. + + ```js + import convertxml from '@ohos.convertxml'; + ``` + +2. Pass in an XML file to be converted and set conversion options. + + ```js + let xml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; + let options = { + // trim: false, indicating that spaces before and after the text are not deleted after conversion. + // declarationKey: "_declaration", indicating that _declaration is used to identify the file declaration after conversion. + // instructionKey: "_instruction", indicating that _instruction is used to identify instructions after conversion. + // attributesKey: "_attributes", indicating that _attributes is used to identify attributes after conversion. + // textKey: "_text", indicating that _text is used to identify tag values after conversion. + // cdataKey: "_cdata", indicating that _cdata is used to identify unparsed data after conversion. + // docTypeKey: "_doctype", indicating that _doctype is used to identify documents after conversion. + // commentKey: "_comment", indicating that _comment is used to identify comments after conversion. + // parentKey: "_parent", indicating that _parent is used to identify parent classes after conversion. + // typeKey: "_type", indicating that _type is used to identify types after conversion. + // nameKey: "_name", indicating that _name is used to identify tag names after conversion. + // elementsKey: "_elements", indicating that _elements is used to identify elements after conversion. + trim: false, + declarationKey: "_declaration", + instructionKey: "_instruction", + attributesKey: "_attributes", + textKey: "_text", + cdataKey: "_cdata", + docTypeKey: "_doctype", + commentKey: "_comment", + parentKey: "_parent", + typeKey: "_type", + nameKey: "_name", + elementsKey: "_elements" + } + ``` + +3. Call the conversion function and print the result. + + ```js + let conv = new convertxml.ConvertXML(); + let result = conv.convertToJSObject(xml, options); + let strRes = JSON.stringify(result); // Convert the JavaScript object into a JSON string for explicit output. + console.info(strRes); + // Alternatively, directly process the JavaScript object to obtain the tag values. + let title = result['_elements'][0]['_elements'][0]['_elements'][0]['_text']; // Parse the value of the tag. + let todo = result['_elements'][0]['_elements'][1]['_elements'][0]['_text']; // Parse the value of the <todo> tag. + let todo2 = result['_elements'][0]['_elements'][2]['_elements'][0]['_text']; // Parse the value of the <todo> tag. + console.info(title); // Happy + console.info(todo); // Work + console.info(todo2); // Play + ``` + + The output is as follows: + + + ```js + strRes: + {"_declaration":{"_attributes":{"version":"1.0","encoding":"utf-8"}},"_elements":[{"_type":"element","_name":"note", + "_attributes":{"importance":"high","logged":"true"},"_elements":[{"_type":"element","_name":"title", + "_elements":[{"_type":"text","_text":"Happy"}]},{"_type":"element","_name":"todo", + "_elements":[{"_type":"text","_text":"Work"}]},{"_type":"element","_name":"todo", + "_elements":[{"_type":"text","_text":"Play"}]}]}]} + title:Happy + todo:Work + todo2:Play + ``` diff --git a/en/application-dev/arkts-utils/xml-generation.md b/en/application-dev/arkts-utils/xml-generation.md new file mode 100644 index 0000000000000000000000000000000000000000..d05cd9779255c6dfa51a9d4bb4556e2467c92c1c --- /dev/null +++ b/en/application-dev/arkts-utils/xml-generation.md @@ -0,0 +1,82 @@ +# XML Generation + + +XML can be used as a data exchange format, which is supported by a wealth of systems and applications. For example, web services can transfer structured data in XML format. + + +XML can also be used as a message passing format for communication between nodes in a distributed system. + + +## Precautions + +- XML tags must appear in pairs: one start tag and one end tag. + +- XML tags are case sensitive. The start tag and end tag must use the same case. + + +## How to Develop + +The **xml** module provides the **XmlSerializer** class to generate XML files. The input is an object of the ArrayBuffer or DataView type with a fixed length, which is used to store the output XML data. + +You can call different to write different types of content. For example, call **startElement(name: string)** to write the start tag and **setText(text: string)** to write a tag value. + +For details about the APIs of the **XML** module, see [@ohos.xml (XML Parsing and Generation)](../reference/apis/js-apis-xml.md). + +The following steps walk you through on how to generate an XML file. + +1. Import the modules. + + ```js + import xml from '@ohos.xml'; + import util from '@ohos.util'; + ``` + +2. Create a buffer and create an **XmlSerializer** object, either based on an object of the ArrayBuffer or DataView type. + + ```js + // 1. Create an XmlSerializer object based on an object of the ArrayBuffer type. + let arrayBuffer = new ArrayBuffer(2048); // Create a 2048-byte object of the ArrayBuffer type. + let thatSer = new xml.XmlSerializer (arrayBuffer); // Create an XmlSerializer object based on the object of the ArrayBuffer type. + + // 2. Create an XmlSerializer object based on an object of the DataView type. + let arrayBuffer = new ArrayBuffer(2048); // Create a 2048-byte object of the ArrayBuffer type. + let dataView = new DataView(arrayBuffer); // Use an object of the DataView type to operate the object of the ArrayBuffer type. + let thatSer = new xml.XmlSerializer (dataView); // Create an XmlSerializer object based on the object of the DataView type. + ``` + +3. Call the functions to generate an XML file. + + ```js + thatSer.setDeclaration(); // Write the XML file declaration. + thatSer.startElement('bookstore'); // Write the start flag. + thatSer.startElement('book'); // Write the start tag of a nested element. + thatSer.setAttributes('category', 'COOKING'); // Write the attributes and attribute values. + thatSer.startElement('title'); + thatSer.setAttributes('lang', 'en'); + thatSer.setText('Everyday'); // Write the tag value. + thatSer.endElement(); // Write the end flag. + thatSer.startElement('author'); + thatSer.setText('Giada'); + thatSer.endElement(); + thatSer.startElement('year'); + thatSer.setText('2005'); + thatSer.endElement(); + thatSer.endElement(); + thatSer.endElement(); + ``` + +4. Use **Uint8Array** to operate the object of the ArrayBuffer type, and use **TextDecoder** to decode the Uint8Array. + + ```js + let view = new Uint8Array(arrayBuffer); // Use Uint8Array to read data from the object of the ArrayBuffer type. + let textDecoder = util.TextDecoder.create(); // Call the TextDecoder class of the util module. + let res = textDecoder.decodeWithStream (view); // Decode the view. + console.info(res); + ``` + + The output is as follows: + + + ```js + <?xml version=\"1.0\" encoding=\"utf-8\"?><bookstore>\r\n <book category=\"COOKING\">\r\n <title lang=\"en\">Everyday\r\n Giada\r\n 2005\r\n \r\n + ``` diff --git a/en/application-dev/arkts-utils/xml-overview.md b/en/application-dev/arkts-utils/xml-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..d376fea2134fbdac8a02d5a4c8e4ffdfdb99eb4d --- /dev/null +++ b/en/application-dev/arkts-utils/xml-overview.md @@ -0,0 +1,23 @@ +# XML Overview + + +Extensible Markup Language (XML) is a markup language used to describe data. It aims to provide a common way to transmit and store data, especially data frequently used in web applications. XML does not predefine tags. As a result, it is more flexible and widely used. + + +An XML file consists of elements, attributes, and content. + + +- An element refers to a tag pair that contains text, attributes, or other elements. + +- Attributes provide additional information about an element. + +- Content is the data or sub-element contained in an element. + + +XML supports the use of XML Schema Definition (XSD) or Document Type Definition (DTD) for defining the document structure. This allows you to customize rules to verify whether an XML document is in the expected format. + + +XML also supports features such as namespaces, entity references, comments, and processing instructions, making it easy to adapt to diverse data requirements. + + +The common library provides XML-related basic capabilities, including [XML generation](xml-generation.md), [XML parsing](xml-parsing.md), and [XML conversion](xml-conversion.md). diff --git a/en/application-dev/arkts-utils/xml-parsing.md b/en/application-dev/arkts-utils/xml-parsing.md new file mode 100644 index 0000000000000000000000000000000000000000..89ed22585be75803b281517d390f400ceeda9d4d --- /dev/null +++ b/en/application-dev/arkts-utils/xml-parsing.md @@ -0,0 +1,271 @@ +# XML Parsing + + +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 ArrayBuffer or DataView type containing XML text, and the output is the parsed information. + + +**Table 1** XML parsing options + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| supportDoctype | boolean | No| Whether to ignore the document type. The default value is **false**, indicating that the document type is parsed.| +| ignoreNameSpace | boolean | No| Whether to ignore the namespace. The default value is **false**, indicating that the namespace is parsed.| +| tagValueCallbackFunction | (name: string, value: string) => boolean | No| Callback used to return **tagValue**, which consists of a tag and its value. The default value is **null**, indicating that XML tags and tag values are not parsed.| +| attributeValueCallbackFunction | (name: string, value: string) => boolean | No| Callback used to return **attributeValue**, which consists of an attribute and its value. The default value is **null**, indicating that XML attributes and attribute values are not parsed.| +| tokenValueCallbackFunction | (eventType: EventType, value: ParseInfo) => boolean | No| Callback used to return **tokenValue**, which consists of the event type and the attributes of **parseInfo**. The default value is **null**, indicating that the event type and the attributes of **parseInfo** are not parsed.| + + +## Precautions + +- To ensure successful XML parsing and conversion, the input XML data must comply with the standard format. + +- Currently, parsing a given node is not supported. + + +## Parsing XML Tags and Tag Values + +1. Import the modules. + + ```js + import xml from '@ohos.xml'; + import util from '@ohos.util'; // Use the API provided by the util module to encode the file. + ``` + +2. Create an **XmlPullParser** object. + + The **XmlPullParser** object can be created based on an object of the ArrayBuffer or DataView type. + + + ```js + let strXml = + '' + + '' + + 'Play' + + 'Work' + + ''; + let textEncoder = new util.TextEncoder(); + let arrBuffer = textEncoder.encodeInto(strXml); // Encode the data to prevent garbled characters. + // 1. Create an XmlPullParser object based on an object of the ArrayBuffer type. + let that = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); + + // 2. Create an XmlPullParser object based on an object of the DataView type. + let dataView = new DataView(arrBuffer.buffer); + let that = new xml.XmlPullParser(dataView, 'UTF-8'); + ``` + +3. Customize a callback function. In this example, the tag and tag value are directly printed. + + ```js + let str = ''; + function func(name, value){ + str = name + value; + console.info(str); + return true; // The value true means to continue parsing, and false means to stop parsing. + } + ``` + +4. Set parsing options and call the **parse()** function. + + ```js + let options = {supportDoctype:true, ignoreNameSpace:true, tagValueCallbackFunction:func}; + that.parse(options); + ``` + + The output is as follows: + + + ```js + note + title + Play + title + lens + Work + lens + note + ``` + + +## Parsing XML Attributes and Attribute Values + +1. Import the modules. + + ```js + import xml from '@ohos.xml'; + import util from '@ohos.util'; // Use the API provided by the util module to encode the file. + ``` + +2. Create an **XmlPullParser** object. + + ```js + let strXml = + '' + + '' + + ' Play' + + ' Happy' + + ' Work' + + ''; + let textEncoder = new util.TextEncoder(); + let arrBuffer = textEncoder.encodeInto(strXml); // Encode the data to prevent garbled characters. + let that = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); + ``` + +3. Customize a callback function. In this example, the attribute and attribute value are directly printed. + + ```js + let str = ''; + function func(name, value){ + str += name + ' ' + value + ' '; + return true; // The value true means to continue parsing, and false means to stop parsing. + } + ``` + +4. Set parsing options and call the **parse()** function. + + ```js + let options = {supportDoctype:true, ignoreNameSpace:true, attributeValueCallbackFunction:func}; + that.parse(options); + console.info(str); // Print all attributes and their values at a time. + ``` + + The output is as follows: + + + ```js + importance high logged true // Attributes and attribute values of the note node + ``` + + +## Parsing XML Event Types and Element Depths + +1. Import the modules. + + ```js + import xml from '@ohos.xml'; + import util from '@ohos.util'; // Use the API provided by the util module to encode the file. + ``` + +2. Create an **XmlPullParser** object. + + ```js + let strXml = + '' + + '' + + 'Play' + + ''; + let textEncoder = new util.TextEncoder(); + let arrBuffer = textEncoder.encodeInto(strXml); // Encode the data to prevent garbled characters. + let that = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); + ``` + +3. Customize a callback function. In this example, the event type and element depth are directly printed. + + ```js + let str = ''; + function func(name, value){ + str = name +' ' + value.getDepth(); // getDepth is called to obtain the element depth. + console.info(str) + return true; // The value true means to continue parsing, and false means to stop parsing. + } + ``` + +4. Set parsing options and call the **parse()** function. + + ```js + let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func}; + that.parse(options); + ``` + + The output is as follows: + + + ```js + 0 0 // 0: . The event type value of START_DOCUMENT is 0. 0: The depth is 0. + 2 1 // 2: . The event type value of START_TAG is 2. 1: The depth is 1. + 2 2 // 2: . The event type value of START_TAG is 2. 2: The depth is 2. + 4 2 // 4: Play. The event type value of TEXT is 4. 2: The depth is 2. + 3 2 // 3: . The event type value of END_TAG is 3. 2: The depth is 2. + 3 1 // 3: . The event type value of END_TAG is 3. 1: The depth is 1 (corresponding to ). + 1 0 // 1: The event type value of END_DOCUMENT is 1. 0: The depth is 0. + ``` + + +## Example Scenario + +The following uses invoking all parsing options as an example to describe how to parse XML tags, attributes, and event types. + + +```js +import xml from '@ohos.xml'; +import util from '@ohos.util'; + +let strXml = + '' + + '' + + 'Everyday' + + 'Giada' + + ''; +let textEncoder = new util.TextEncoder(); +let arrBuffer = textEncoder.encodeInto(strXml); +let that = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); +let str = ''; + +function tagFunc(name, value) { + str = name + value; + console.info('tag-' + str); + return true; +} + +function attFunc(name, value) { + str = name + ' ' + value; + console.info('attri-' + str); + return true; +} + +function tokenFunc(name, value) { + str = name + ' ' + value.getDepth(); + console.info('token-' + str); + return true; +} + +let options = { + supportDocType: true, + ignoreNameSpace: true, + tagValueCallbackFunction: tagFunc, + attributeValueCallbackFunction: attFunc, + tokenValueCallbackFunction: tokenFunc +}; +that.parse(options); + +``` + +The output is as follows: + + +```js +tag- +token-0 0 +tag-book +attri-category COOKING +token-2 1 +tag-title +attri-lang en +token-2 2 +tag-Everyday +token-4 2 +tag-title +token-3 2 +tag-author +token-2 2 +tag-Giada +token-4 2 +tag-author +token-3 2 +tag-book +token-3 1 +tag- +token-1 0 +``` diff --git a/en/application-dev/connectivity/Readme-EN.md b/en/application-dev/connectivity/Readme-EN.md index c09ca21b6d0814bd1cd2cecb95b0d2896fada8c4..1a391bd7af03ae3c5d01eb01e14b66efd1f0c565 100755 --- a/en/application-dev/connectivity/Readme-EN.md +++ b/en/application-dev/connectivity/Readme-EN.md @@ -9,6 +9,8 @@ - [Ethernet Connection](net-ethernet.md) - [Network Connection Management](net-connection-manager.md) - [mDNS Management](net-mdns.md) + - [Traffic Management](net-statistics.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/http-request.md b/en/application-dev/connectivity/http-request.md index 1bb784cf96fb1d74dcbafed54498435f505814b6..a0fa4102864ba2403e7a6826f3ca3b872b5a80dd 100644 --- a/en/application-dev/connectivity/http-request.md +++ b/en/application-dev/connectivity/http-request.md @@ -1,6 +1,6 @@ # HTTP Data Request -## When to Use +## Overview An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**. @@ -18,7 +18,7 @@ The following table provides only a simple description of the related APIs. For | ----------------------------------------- | ----------------------------------- | | createHttp() | Creates an HTTP request. | | request() | Initiates an HTTP request to a given URL. | -| request2()10+ | Initiates an HTTP network request based on the URL and returns a streaming response.| +| requestInStream()10+ | Initiates an HTTP network request to a given URL and returns a streaming response.| | destroy() | Destroys an HTTP request. | | on(type: 'headersReceive') | Registers an observer for HTTP Response Header events. | | off(type: 'headersReceive') | Unregisters the observer for HTTP Response Header events.| @@ -27,8 +27,8 @@ The following table provides only a simple description of the related APIs. For | off\('dataReceive'\)10+ | Unregisters the observer for events indicating receiving of HTTP streaming responses. | | on\('dataEnd'\)10+ | Registers an observer for events indicating completion of receiving HTTP streaming responses. | | off\('dataEnd'\)10+ | Unregisters the observer for events indicating completion of receiving HTTP streaming responses.| -| on\('dataProgress'\)10+ | Registers an observer for events indicating progress of receiving HTTP streaming responses. | -| off\('dataProgress'\)10+ | Unregisters the observer for events indicating progress of receiving HTTP streaming responses.| +| on\('dataReceiveProgress'\)10+ | Registers an observer for events indicating progress of receiving HTTP streaming responses. | +| off\('dataReceiveProgress'\)10+ | Unregisters the observer for events indicating progress of receiving HTTP streaming responses.| ## How to Develop request APIs @@ -53,6 +53,7 @@ httpRequest.on('headersReceive', (header) => { }); httpRequest.request( // Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL. + "EXAMPLE_URL", { method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET. // You can add header fields based on service requirements. @@ -81,7 +82,7 @@ httpRequest.request( // Call the destroy() method to release resources after HttpRequest is complete. httpRequest.destroy(); } else { - console.info('error:' + JSON.stringify(err)); + console.error('error:' + JSON.stringify(err)); // Unsubscribe from HTTP Response Header events. httpRequest.off('headersReceive'); // Call the destroy() method to release resources after HttpRequest is complete. @@ -91,12 +92,12 @@ httpRequest.request( ); ``` -## How to Develop request2 APIs +## How to Develop requestInStream APIs 1. Import the **http** namespace from **@ohos.net.http.d.ts**. 2. Call **createHttp()** to create an **HttpRequest** object. 3. Depending on your need, call **on()** of the **HttpRequest** object to subscribe to HTTP response header events as well as events indicating receiving of HTTP streaming responses, progress of receiving HTTP streaming responses, and completion of receiving HTTP streaming responses. -4. Call **request2()** to initiate a network request. You need to pass in the URL and optional parameters of the HTTP request. +4. Call **requestInStream()** to initiate a network request. You need to pass in the URL and optional parameters of the HTTP request. 5. Parse the returned response code as needed. 6. Call **off()** of the **HttpRequest** object to unsubscribe from the related events. 7. Call **httpRequest.destroy()** to release resources after the request is processed. @@ -122,11 +123,11 @@ httpRequest.on('dataEnd', () => { console.info('No more data in response, data receive end'); }); // Subscribe to events indicating progress of receiving HTTP streaming responses. -httpRequest.on('dataProgress', (data) => { - console.log("dataProgress receiveSize:" + data.receiveSize + ", totalSize:" + data.totalSize); +httpRequest.on('dataReceiveProgress', (data) => { + console.log("dataReceiveProgress receiveSize:" + data.receiveSize + ", totalSize:" + data.totalSize); }); -httpRequest.request2( +httpRequest.requestInStream( // Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL. "EXAMPLE_URL", { @@ -146,14 +147,14 @@ httpRequest.request2( readTimeout: 60000, // Optional. The default value is 60000, in ms. If a large amount of data needs to be transmitted, you are advised to set this parameter to a larger value to ensure normal data transmission. usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system. }, (err, data) => { - console.info('error:' + JSON.stringify(err)); + console.error('error:' + JSON.stringify(err)); console.info('ResponseCode :' + JSON.stringify(data)); // Unsubscribe from HTTP Response Header events. httpRequest.off('headersReceive'); // Unregister the observer for events indicating receiving of HTTP streaming responses. httpRequest.off('dataReceive'); // Unregister the observer for events indicating progress of receiving HTTP streaming responses. - httpRequest.off('dataProgress'); + httpRequest.off('dataReceiveProgress'); // Unregister the observer for events indicating completion of receiving HTTP streaming responses. httpRequest.off('dataEnd'); // Call the destroy() method to release resources after HttpRequest is complete. @@ -161,10 +162,3 @@ httpRequest.request2( } ); ``` - -## Samples - -The following sample is provided to help you better understand how to develop the HTTP data request feature: - -- [`Http`: Data Request (ArkTS) (API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Connectivity/Http) -- [HTTP Communication (ArkTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/SmartChatEtsOH) diff --git a/en/application-dev/connectivity/ipc-rpc-development-guideline.md b/en/application-dev/connectivity/ipc-rpc-development-guideline.md index b9bbb0608dfb83ba6d2198b063e68c4b324bbd88..14016ef5da297361bd4a17a3d278357060590784 100644 --- a/en/application-dev/connectivity/ipc-rpc-development-guideline.md +++ b/en/application-dev/connectivity/ipc-rpc-development-guideline.md @@ -1,6 +1,6 @@ # IPC & RPC Development Guidelines -## When to Use +## Overview IPC/RPC enables a proxy and a stub that run on different processes to communicate with each other, regardless of whether they run on the same or different devices. diff --git a/en/application-dev/connectivity/net-connection-manager.md b/en/application-dev/connectivity/net-connection-manager.md index c443c93759caddbc5203b65022426882c0bb960b..f3b945ab0970786000ab8b04adfe90592a11e0d1 100644 --- a/en/application-dev/connectivity/net-connection-manager.md +++ b/en/application-dev/connectivity/net-connection-manager.md @@ -1,10 +1,11 @@ # Network Connection Management -## Introduction +## Overview The Network Connection Management module provides basic network management capabilities, including management of Wi-Fi/cellular/Ethernet connection priorities, network quality evaluation, subscription to network connection status changes, query of network connection information, and DNS resolution. > **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 [sms API Reference](../reference/apis/js-apis-net-connection.md). ## Basic Concepts @@ -107,7 +108,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-ethernet.md b/en/application-dev/connectivity/net-ethernet.md index 18f20a7fd7e1a4c9516386c543c9521522df5f66..76ae1ee28078520b9d70796f71fd2b9236f47959 100644 --- a/en/application-dev/connectivity/net-ethernet.md +++ b/en/application-dev/connectivity/net-ethernet.md @@ -1,10 +1,11 @@ # Ethernet Connection -## Introduction +## Overview The Ethernet Connection module allows a device to access the Internet through a network cable. After a device is connected to the Ethernet through a network cable, the device can obtain a series of network attributes, such as the dynamically allocated IP address, subnet mask, gateway, and DNS. You can manually configure and obtain the network attributes of the device in static mode. > **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 [sms API Reference](../reference/apis/js-apis-net-ethernet.md). ## **Constraints** diff --git a/en/application-dev/connectivity/net-mdns.md b/en/application-dev/connectivity/net-mdns.md index de7982a5c03908a70e4005bdc5fbea3584c435f5..75da959da8c4b1fc55aa0afca1cf0dcd945b86bb 100644 --- a/en/application-dev/connectivity/net-mdns.md +++ b/en/application-dev/connectivity/net-mdns.md @@ -1,6 +1,6 @@ # MDNS Management -## Introduction +## Overview Multicast DNS (mDNS) provides functions such as adding, removing, discovering, and resolving local services on a LAN. - Local service: a service provider on a LAN, for example, a printer or scanner. diff --git a/en/application-dev/connectivity/net-sharing.md b/en/application-dev/connectivity/net-sharing.md index 4072217d9ced5d99b2052b5db8ccb8333fcb7023..f2b2e6ac21362691ede111db8b16316fa9fd32cb 100644 --- a/en/application-dev/connectivity/net-sharing.md +++ b/en/application-dev/connectivity/net-sharing.md @@ -1,10 +1,11 @@ # Network Sharing -## Introduction +## Overview The Network Sharing module allows you to share your device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing. It also allows you to query the network sharing state and shared mobile data volume. > **NOTE** +> > 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 [sms API Reference](../reference/apis/js-apis-net-sharing.md). ## Basic Concepts diff --git a/en/application-dev/connectivity/net-statistics.md b/en/application-dev/connectivity/net-statistics.md new file mode 100644 index 0000000000000000000000000000000000000000..6df8800dd479b48c32619514b8e6b90d5c776330 --- /dev/null +++ b/en/application-dev/connectivity/net-statistics.md @@ -0,0 +1,156 @@ +# Traffic Management + +## Overview + +The traffic management module allows you to query real-time or historical data traffic by the specified network interface card (NIC) or user ID (UID). + +Its functions include: + +- Obtaining real-time traffic data by NIC or UID +- Obtaining historical traffic data by NIC or UID +- Subscribing to traffic change events by NIC or UID + +> **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-statistics.md). + +The following describes the development procedure specific to each application scenario. + +## Available APIs + +For the complete list of APIs and example code, see [Traffic Management](../reference/apis/js-apis-net-statistics.md). + +| Type| API| Description| +| ---- | ---- | ---- | +| ohos.net.statistics | getIfaceRxBytes(nic: string, callback: AsyncCallback\): void; |Obtains the real-time downlink data traffic of the specified NIC. | +| ohos.net.statistics | getIfaceTxBytes(nic: string, callback: AsyncCallback\): void; |Obtains the real-time uplink data traffic of the specified NIC. | +| ohos.net.statistics | getCellularRxBytes(callback: AsyncCallback\): void; |Obtains the real-time downlink data traffic of the cellular network.| +| ohos.net.statistics | getCellularTxBytes(callback: AsyncCallback\): void; |Obtains the real-time uplink data traffic of the cellular network.| +| ohos.net.statistics | getAllRxBytes(callback: AsyncCallback\): void; |Obtains the real-time downlink data traffic of the all NICs. | +| ohos.net.statistics | getAllTxBytes(callback: AsyncCallback\): void; |Obtains the real-time uplink data traffic of the all NICs. | +| ohos.net.statistics | getUidRxBytes(uid: number, callback: AsyncCallback\): void; |Obtains the real-time downlink data traffic of the specified application. | +| ohos.net.statistics | getUidTxBytes(uid: number, callback: AsyncCallback\): void; |Obtains the real-time uplink data traffic of the specified application. | +| ohos.net.statistics | getTrafficStatsByIface(ifaceInfo: IfaceInfo, callback: AsyncCallback\): void; |Obtains the historical data traffic of the specified NIC. | +| ohos.net.statistics | getTrafficStatsByUid(uidInfo: UidInfo, callback: AsyncCallback\): void; |Obtains the historical data traffic of the specified application. | +| ohos.net.statistics | on(type: 'netStatsChange', callback: Callback\<{ iface: string, uid?: number }>): void |Subscribes to traffic change events.| +| ohos.net.statistics | off(type: 'netStatsChange', callback?: Callback\<{ iface: string, uid?: number }>): void; |Unsubscribes from traffic change events.| + +## Obtaining Real-Time Traffic Data by NIC or UID + +1. Obtain the real-time data traffic of the specified NIC. +2. Obtain the real-time data traffic of the cellular network. +3. Obtain the real-time data traffic of all NICs. +4. Obtain the real-time data traffic of the specified application. + +```js +// Import the statistics namespace from @ohos.net.statistics. +import statistics from '@ohos.net.statistics' + +// Obtain the real-time downlink data traffic of the specified NIC. +statistics.getIfaceRxBytes("wlan0", (error, stats) => { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(stats)) +}) + +// Obtain the real-time uplink data traffic of the specified NIC. +statistics.getIfaceTxBytes("wlan0", (error, stats) => { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(stats)) +}) + +// Obtain the real-time downlink data traffic of the cellular network. +statistics.getCellularRxBytes((error, stats) => { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(stats)) +}) + +// Obtain the real-time uplink data traffic of the cellular network. +statistics.getCellularTxBytes((error, stats) => { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(stats)) +}) + +// Obtain the real-time downlink data traffic of the all NICs. +statistics.getAllRxBytes((error, stats) => { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(stats)) +}) + +// Obtain the real-time uplink data traffic of the all NICs. +statistics.getAllTxBytes((error, stats) => { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(stats)) +}) + +// Obtain the real-time downlink data traffic of the specified application. +let uid = 20010038; +statistics.getUidRxBytes(uid, (error, stats) => { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(stats)) +}) + +// Obtain the real-time uplink data traffic of the specified application. +let uid = 20010038; +statistics.getUidTxBytes(uid, (error, stats) => { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(stats)) +}) +``` + +## Obtaining Historical Traffic Data by NIC or UID + +1. Obtain the historical data traffic of the specified NIC. +2. Obtain the historical data traffic of the specified application. + +```js +let ifaceInfo = { + iface: "wlan0", + startTime: 1685948465, + endTime: 16859485670 +} +// Obtain the historical data traffic of the specified NIC. +statistics.getTrafficStatsByIface(ifaceInfo), (error, statsInfo) => { + console.log(JSON.stringify(error)) + console.log("getTrafficStatsByIface bytes of received = " + JSON.stringify(statsInfo.rxBytes)); + console.log("getTrafficStatsByIface bytes of sent = " + JSON.stringify(statsInfo.txBytes)); + console.log("getTrafficStatsByIface packets of received = " + JSON.stringify(statsInfo.rxPackets)); + console.log("getTrafficStatsByIface packets of sent = " + JSON.stringify(statsInfo.txPackets)); +}); + +let uidInfo = { + ifaceInfo: { + iface: "wlan0", + startTime: 1685948465, + endTime: 16859485670 + }, + uid: 20010037 +} +// Obtain the historical data traffic of the specified application. +statistics.getTrafficStatsByUid(uidInfo), (error, statsInfo) => { + console.log(JSON.stringify(error)) + console.log("getTrafficStatsByUid bytes of received = " + JSON.stringify(statsInfo.rxBytes)); + console.log("getTrafficStatsByUid bytes of sent = " + JSON.stringify(statsInfo.txBytes)); + console.log("getTrafficStatsByUid packets of received = " + JSON.stringify(statsInfo.rxPackets)); + console.log("getTrafficStatsByUid packets of sent = " + JSON.stringify(statsInfo.txPackets)); +}); + +``` + +## Subscribing to Traffic Change Events + +1. Subscribe to traffic change events. +2. Unsubscribe from traffic change events. + +```js + +let callback = data => { + console.log("on netStatsChange, data:" + JSON.stringify(data)); +} +// Subscribe to traffic change events. +statistics.on('netStatsChange', callback); + +// Unsubscribe from traffic change events. You can pass the callback of the **on** function if you want to unsubscribe from a certain type of event. If you do not pass the callback, you will unsubscribe from all events. +statistics.off('netStatsChange', callback); +statistics.off('netStatsChange'); + +``` diff --git a/en/application-dev/connectivity/net-vpn.md b/en/application-dev/connectivity/net-vpn.md new file mode 100644 index 0000000000000000000000000000000000000000..a93b00b932bdec33de7cb45764474c163ed456ce --- /dev/null +++ b/en/application-dev/connectivity/net-vpn.md @@ -0,0 +1,363 @@ +# 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/connectivity/socket-connection.md b/en/application-dev/connectivity/socket-connection.md index 109b63fdb5fdcae98e23882b32018d4a03435f55..fe8ab1f141e3525de46985ba113eee364adac723 100644 --- a/en/application-dev/connectivity/socket-connection.md +++ b/en/application-dev/connectivity/socket-connection.md @@ -1,8 +1,8 @@ # Socket Connection -## Introduction +## Overview -The Socket Connection module allows an application to transmit data over a Socket connection through the TCP, UDP, or TLS protocol. +The Socket Connection module allows an application to transmit data over a socket connection through the TCP, UDP, or TLS protocol. ## Basic Concepts @@ -13,10 +13,11 @@ The Socket Connection module allows an application to transmit data over a Socke ## When to Use -Applications transmit data over TCP, UDP, or TLS Socket connections. The main application scenarios are as follows: +Applications transmit data over TCP, UDP, or TLS socket connections. The main application scenarios are as follows: -- Implementing data transmission over TCP/UDP Socket connections -- Implementing encrypted data transmission over TLS Socket connections +- Implementing data transmission over TCP socket or UDP socket connections +- Implementing data transmission over TCP socket server connections +- Implementing encrypted data transmission over TLS socket connections ## Available APIs @@ -28,72 +29,75 @@ Socket connection functions are mainly implemented by the **socket** module. The | -------- | -------- | | constructUDPSocketInstance() | Creates a **UDPSocket** object.| | constructTCPSocketInstance() | Creates a **TCPSocket** object.| +| constructTCPSocketServerInstance() | Creates a **TCPSocketServer** object.| +| listen() | Listens for and accepts TCP socket connections established over the socket. (This API is applicable only to TCP.)| | bind() | Binds the IP address and port number.| | send() | Sends data.| -| close() | Closes a Socket connection.| -| getState() | Obtains the Socket connection status.| +| close() | Closes a socket connection.| +| getState() | Obtains the socket connection status.| | connect() | Connects to the specified IP address and port. This function is supported only for TCP.| -| getRemoteAddress() | Obtains the peer address of the Socket connection. This function is supported only for TCP. The **connect** API must have been called before you use this API.| -| on(type: 'message') | Subscribes to **message** events of the Socket connection.| -| off(type: 'message') | Unsubscribes from **message** events of the Socket connection.| -| on(type: 'close') | Subscribes to **close** events of the Socket connection.| -| off(type: 'close') | Unsubscribes from **close** events of the Socket connection.| -| on(type: 'error') | Subscribes to **error** events of the Socket connection.| -| off(type: 'error') | Unsubscribes from **error** events of the Socket connection.| -| on(type: 'listening') | Subscribes to **listening** events of the UDP Socket connection. | -| off(type: 'listening') | Unsubscribes from **listening** events of the UDP Socket connection. | -| on(type: 'connect') | Subscribes to **connect** events of the TCP Socket connection. | -| off(type: 'connect') | Unsubscribes from **connect** events of the TCP Socket connection.| - -TLS Socket connection functions are mainly provided by the **tls_socket** module. The following table describes the related APIs. +| getRemoteAddress() | Obtains the peer address of the socket connection. This function is supported only for TCP. The **connect** API must have been called before you use this API.| +| setExtraOptions() | Sets other properties of the socket connection.| +| on(type: 'message') | Subscribes to **message** events of the socket connection.| +| off(type: 'message') | Unsubscribes from **message** events of the socket connection.| +| on(type: 'close') | Subscribes to **close** events of the socket connection.| +| off(type: 'close') | Unsubscribes from **close** events of the socket connection.| +| on(type: 'error') | Subscribes to **error** events of the socket connection.| +| off(type: 'error') | Unsubscribes from **error** events of the socket connection.| +| on(type: 'listening') | Subscribes to **listening** events of the UDP socket connection. | +| off(type: 'listening') | Unsubscribes from **listening** events of the UDP socket connection. | +| on(type: 'connect') | Subscribes to **connect** events of the TCP socket connection. | +| off(type: 'connect') | Unsubscribes from **connect** events of the TCP socket connection.| + +TLS socket connection functions are mainly provided by the **tls_socket** module. The following table describes the related APIs. | API| Description| | -------- | -------- | | constructTLSSocketInstance() | Creates a **TLSSocket** object.| | bind() | Binds the IP address and port number.| -| close(type: 'error') | Closes a Socket connection.| +| close(type: 'error') | Closes a socket connection.| | connect() | Sets up a connection to the specified IP address and port number.| | getCertificate() | Obtains an object representing the local certificate.| | getCipherSuite() | Obtains a list containing information about the negotiated cipher suite.| | getProtocol() | Obtains a string containing the SSL/TLS protocol version negotiated for the current connection.| -| getRemoteAddress() | Obtains the peer address of the TLS Socket connection.| +| getRemoteAddress() | Obtains the peer address of the TLS socket connection.| | getRemoteCertificate() | Obtains an object representing a peer certificate.| | getSignatureAlgorithms() | Obtains a list containing signature algorithms shared between the server and client, in descending order of priority.| -| getState() | Obtains the TLS Socket connection status.| -| off(type: 'close') | Unsubscribes from **close** events of the TLS Socket connection.| -| off(type: 'error') | Unsubscribes from **error** events of the TLS Socket connection.| -| off(type: 'message') | Unsubscribes from **message** events of the TLS Socket connection.| -| on(type: 'close') | Subscribes to **close** events of the TLS Socket connection.| -| on(type: 'error') | Subscribes to **error** events of the TLS Socket connection.| -| on(type: 'message') | Subscribes to **message** events of the TLS Socket connection.| +| getState() | Obtains the TLS socket connection status.| +| off(type: 'close') | Unsubscribes from **close** events of the TLS socket connection.| +| off(type: 'error') | Unsubscribes from **error** events of the TLS socket connection.| +| off(type: 'message') | Unsubscribes from **message** events of the TLS socket connection.| +| on(type: 'close') | Subscribes to **close** events of the TLS socket connection.| +| on(type: 'error') | Subscribes to **error** events of the TLS socket connection.| +| on(type: 'message') | Subscribes to **message** events of the TLS socket connection.| | send() | Sends data.| -| setExtraOptions() | Sets other properties of the TLS Socket connection.| +| setExtraOptions() | Sets other properties of the TLS socket connection.| -## Transmitting Data over TCP/UDP Socket Connections +## Transmitting Data over TCP Socket or UDP Socket Connections -The implementation is similar for UDP Socket and TCP Socket connections. The following uses data transmission over a TCP Socket connection as an example. +The implementation is similar for UDP socket and TCP socket connections. The following uses data transmission over a TCP socket connection as an example. 1. Import the required **socket** module. -2. Create a **TCPSocket** object. +2. Create a TCP socket connection. A **TCPSocket** object is returned. -3. (Optional) Subscribe to TCP Socket connection events. +3. (Optional) Subscribe to TCP socket connection events. 4. Bind the IP address and port number. The port number can be specified or randomly allocated by the system. 5. Set up a connection to the specified IP address and port number. -6. Send data. +6. Send data over the connection. -7. Enable the TCP Socket connection to be automatically closed after use. +7. Enable the TCP socket connection to be automatically closed after use. ```js import socket from '@ohos.net.socket' -// Create a TCPSocket object. +// Create a TCP socket connection. A TCPSocket object is returned. let tcp = socket.constructTCPSocketInstance(); -// Subscribe to TCP Socket connection events. +// Subscribe to events of the TCPSocket object. tcp.on('message', value => { console.log("on message") let buffer = value.message @@ -139,7 +143,7 @@ tcp.bind(bindAddress, err => { } console.log('connect success'); - // Send data. + // Send data over the connection. tcp.send({ data: 'Hello, server!' }, err => { @@ -152,7 +156,7 @@ tcp.bind(bindAddress, err => { }); }); -// Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events. +// Enable the socket connection to be automatically closed after use. Then, unsubscribe from events of the connection. setTimeout(() => { tcp.close((err) => { console.log('close socket.') @@ -163,11 +167,92 @@ setTimeout(() => { }, 30 * 1000); ``` +## Implementing Data Transmission over TCP Socket Server Connections + +### How to Develop + +The TCP socket server connection process is described as follows: + +1. Import the required **socket** module. +2. Create a TCP socket server connection. A **TCPSocketServer** object is returned. +3. Bind the local IP address and port, and listen for and accept TCP socket connections established over the socket. +4. Subscribe to **connect** events of the **TCPSocketServer** object to listen for client connection status changes. +5. Set up a connection between the client and the server. A **TCPSocketConnection** object is returned. +6. Subscribe to events of the **TCPSocketConnection** object, and send data to the client through the **TCPSocketConnection** object. +7. Close the connection between the client and the server. +8. Unsubscribe from events of the **TCPSocketConnection** and **TCPSocketServer** objects. + +```js +import socket from '@ohos.net.socket' + +// Create a TCP socket server connection. A TCPSocketServer object is returned. +let tcpServer = socket.constructTCPSocketServerInstance(); + +// Bind the local IP address and port number for listening. +tcpServer.listen({ address: "192.168.xx.xxx", port: xxxx, family: 1 }, err => { + if (err) { + console.log("listen fail"); + return; + } + console.log("listen success"); +}) + +// Subscribe to connect events of the TCPSocketServer object. +tcpServer.on('connect', function(client) { + // Subscribe to events of the TCPSocketConnection object. + client.on('close', () => { + console.log("on close success"); + }); + client.on('message', function(value) { + let buffer = value.message; + let dataView = new DataView(buffer); + let str = ""; + for (let i = 0; i < dataView.byteLength; ++i) { + str += String.fromCharCode(dataView.getUint8(i)); + } + console.log("received message--:" + str); + console.log("received address--:" + value.remoteInfo.address); + console.log("received family--:" + value.remoteInfo.family); + console.log("received port--:" + value.remoteInfo.port); + console.log("received size--:" + value.remoteInfo.size); + }); + + // Send data to the client. + client.send({data: 'Hello, client!'}, err => { + if (err) { + console.log('send fail'); + return; + } + console.log('send success'); + }); + + // Close the connection between the client and the server. + client.close(err => { + if (err) { + console.log('close fail'); + return; + } + console.log('close success'); + }); + + // Unsubscribe from events of the TCPSocketConnection object. + setTimeout(() => { + client.off('message'); + client.off('close'); + }, 10 * 1000); +}); + +// Unsubscribe from events of the TCPSocketServer object. +setTimeout(() => { + tcpServer.off('connect'); +}, 30 * 1000); +``` + ## Implementing Encrypted Data Transmission over TLS Socket Connections ### How to Develop -TLS Socket connection process on the client: +The TLSsocket connection process on the client is described as follows: 1. Import the required **socket** module. @@ -175,21 +260,21 @@ TLS Socket connection process on the client: 3. For two-way authentication, upload the client CA certificate and digital certificate. For one-way authentication, upload the client CA certificate. -4. Create a **TLSSocket** object. +4. Create a TLS socket connection. A **TLSsocket** object is returned. -5. (Optional) Subscribe to TLS Socket connection events. +5. (Optional) Subscribe to TLS socket connection events. -6. Send data. +6. Send data over the connection. -7. Enable the TLS Socket connection to be automatically closed after use. +7. Enable the TLS socket connection to be automatically closed after use. ```js import socket from '@ohos.net.socket' -// Create a TLS Socket connection (for two-way authentication). +// Create a TLS socket connection (for two-way authentication). A TLSSocket object is returned. let tlsTwoWay = socket.constructTLSSocketInstance(); -// Subscribe to TLS Socket connection events. +// Subscribe to TLS socket connection events. tlsTwoWay.on('message', value => { console.log("on message") let buffer = value.message @@ -246,7 +331,7 @@ tlsTwoWay.connect(options, (err, data) => { console.log(data); }); -// Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events. +// Enable the socket connection to be automatically closed after use. Then, unsubscribe from events of the connection. tlsTwoWay.close((err) => { if (err) { console.log("close callback error = " + err); @@ -258,10 +343,10 @@ tlsTwoWay.close((err) => { tlsTwoWay.off('close'); }); -// Create a TLS Socket connection (for one-way authentication). +// Create a TLS socket connection (for one-way authentication). A TLSsocket object is returned. let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication -// Subscribe to TLS Socket connection events. +// Subscribe to TLS socket connection events. tlsTwoWay.on('message', value => { console.log("on message") let buffer = value.message @@ -307,7 +392,7 @@ tlsOneWay.connect(oneWayOptions, (err, data) => { console.log(data); }); -// Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events. +// Enable the socket connection to be automatically closed after use. Then, unsubscribe from events of the connection. tlsTwoWay.close((err) => { if (err) { console.log("close callback error = " + err); @@ -319,11 +404,3 @@ tlsTwoWay.close((err) => { tlsTwoWay.off('close'); }); ``` - -## Samples - -The following samples are provided to help you better understand how to develop Socket connection features: - -- [`Socket`: Socket Connection (ArkTS) (API9)] (https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Connectivity/Socket) -- [UDP Socket (ArkTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/UdpDemoOH) -- [TCP Socket (ArkTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/TcpSocketDemo) diff --git a/en/application-dev/connectivity/subscribe-remote-state.md b/en/application-dev/connectivity/subscribe-remote-state.md index 5b21750ba8b56fefcb10a5fff653d7512765c279..d23385e44752cb0945217eddc74117202ca38c5f 100755 --- a/en/application-dev/connectivity/subscribe-remote-state.md +++ b/en/application-dev/connectivity/subscribe-remote-state.md @@ -1,5 +1,7 @@ # Subscribing to State Changes of a Remote Object +## Overview + IPC/RPC allows you to subscribe to the state changes of a remote stub object. When the remote stub object dies, a death notification will be sent to your local proxy object. Such subscription and unsubscription are controlled by APIs. To be specific, you need to implement the **DeathRecipient** interface and the **onRemoteDied** API to clear resources. This callback is invoked when the process accommodating the remote stub object dies, or the device accommodating the remote stub object leaves the network. It is worth noting that these APIs should be called in the following order: The proxy object must first subscribe to death notifications of the stub object. If the stub object is in the normal state, the proxy object can cancel the subscription as required. If the process of the stub object exits or the device hosting the stub object goes offline, subsequent operations customized by the proxy object will be automatically triggered. ## When to Use diff --git a/en/application-dev/connectivity/websocket-connection.md b/en/application-dev/connectivity/websocket-connection.md index 4c373011c45be18183e4c622c3e7e35b97198a24..1b162256db5cad28aa50ca6989625f9191fb2257 100644 --- a/en/application-dev/connectivity/websocket-connection.md +++ b/en/application-dev/connectivity/websocket-connection.md @@ -1,6 +1,6 @@ # WebSocket Connection -## When to Use +## Overview You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the **createWebSocket()** API to create a **WebSocket** object and then use the **connect()** API to connect to the server. If the connection is successful, the client will receive a callback of the **open** event. Then, the client can communicate with the server using the **send()** API. When the server sends a message to the client, the client will receive a callback of the **message** event. If the client no longer needs this connection, it can call the **close()** API to disconnect from the server. Then, the client will receive a callback of the **close** event. diff --git a/en/application-dev/database/Readme-EN.md b/en/application-dev/database/Readme-EN.md index 77e1d8f9738d949ce9b0f0396bf66f99b9bf924e..74a44f63945d867ff76bb783e2ef0a6feb35861c 100644 --- a/en/application-dev/database/Readme-EN.md +++ b/en/application-dev/database/Readme-EN.md @@ -16,7 +16,11 @@ - [Database Backup and Restoration](data-backup-and-restore.md) - [Database Encryption](data-encryption.md) - [Access Control by Device and Data Level](access-control-by-device-and-data-level.md) -- Cross-Application Data Sharing (for System Applications Only) - - [Cross-Application Data Sharing Overview](share-device-data-across-apps-overview.md) - - [Sharing Data Using DataShareExtensionAbility](share-data-by-datashareextensionability.md) - - [Sharing Data in Silent Access](share-data-by-silent-access.md) +- Cross-Application Data Sharing + - [Data Sharing Overview](data-share-overview.md) + - [Unified Data Definition](unified-data-definition.md) + - One-to-Many Data Sharing (for System Applications Only) + - [Sharing Data Using DataShareExtensionAbility](share-data-by-datashareextensionability.md) + - [Silent Access via the DatamgrService](share-data-by-silent-access.md) + - Many-to-Many Data Sharing + - [Sharing Data Using Unified Data Channels](unified-data-channels.md) \ No newline at end of file diff --git a/en/application-dev/database/data-mgmt-overview.md b/en/application-dev/database/data-mgmt-overview.md index aa98d97da5acdce3a382a70d383e140463a5399a..e6b77c1d89c5cc31e6e1fb9db05e7ab8d2607a7e 100644 --- a/en/application-dev/database/data-mgmt-overview.md +++ b/en/application-dev/database/data-mgmt-overview.md @@ -3,7 +3,7 @@ ## Function -Data management provides data storage, management, and synchronization capabilities. For example, you can store the Contacts application data in database for secure management and shared access, and synchronize the contacts information with a smart watch. +Data management provides data storage, management, and synchronization capabilities. For example, you can store the Contacts application data in database for secure management and shared access, and synchronize the Contacts information with a smart watch. - Data storage: provides data persistence capabilities, which can be classified into user preferences, key-value (KV) stores, and relational database (RDB) stores by data characteristics. @@ -16,9 +16,9 @@ The database stores created by an application are saved to the application sandb ## Working Principles -The data management module includes user preferences (**Preferences**), KV data management (**KV-Store**), RDB data management (**RelationalStore**), distributed data object (**DataObject**), and cross-application data management (**DataShare**). The interface layer provides standard JavaScript APIs for application development. The Frameworks&System service layer implements storage and synchronization of component data, and provides dependencies for SQLite and other subsystems. +The data management module includes preferences, KV data management (KV-Store), relational data management (RelatoinalStore), distributed data object (DataObject), cross-application data management (DataShare), and unified data management framework (UDMF). The interface layer provides standard JavaScript APIs for application development. The Frameworks&System service layer implements storage and synchronization of component data, and provides dependencies for SQLite and other subsystems. - **Figure 1** Data management architecture +**Figure 1** Data management architecture ![dataManagement](figures/dataManagement.jpg) @@ -33,4 +33,7 @@ The data management module includes user preferences (**Preferences**), KV data - **DataShare**: provides the data provider-consumer mode to implement addition, deletion, modification, and query of cross-application data on a device, and notification subscription. **DataShare** is not bound to any database and can interact with RDB and KV stores. You can also encapsulate your own databases for C/C++ applications.
In addition to the provider-consumer mode, **DataShare** provides silent access, which allows direct access to the provider's data via the DatamgrService proxy instead of starting the provider. Currently, only the RDB stores support silent access. +- **UDMF**: defines the data language and standards for cross-application and cross-device data interaction, improving data interaction efficiency. The UDMF provides secure and standard data transmission channels and supports different levels of data access permissions and lifecycle management policies. It helps implement efficient data sharing across applications and devices. + - **DatamgrService**: implements synchronization and cross-application sharing for other components, including cross-device synchronization of **RelationalStore** and **KV-Store**, silent access to provider data of **DataShare**, and temporary storage of **DataObject** synchronization object data. + 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 f2bb5e2d4098bbb19b3c791ed61307ffd78f0ec3..5879f73dac606c956fa305e9602eb1673f1fb369 100644 --- a/en/application-dev/database/data-persistence-by-rdb-store.md +++ b/en/application-dev/database/data-persistence-by-rdb-store.md @@ -18,7 +18,7 @@ A relational database (RDB) store is used to store data in complex relational mo **RelationalStore** provides APIs for applications to perform data operations. With SQLite as the underlying persistent storage engine, **RelationalStore** provides SQLite database features, including transactions, indexes, views, triggers, foreign keys, parameterized queries, prepared SQL statements, and more. **Figure 1** Working mechanism - + ![relationStore_local](figures/relationStore_local.jpg) @@ -37,23 +37,23 @@ A relational database (RDB) store is used to store data in complex relational mo The following table lists the APIs used for RDB data persistence. Most of the APIs are executed asynchronously, using a callback or promise to return the result. The following table uses the callback-based APIs as an example. For more information about the APIs, see [RDB Store](../reference/apis/js-apis-data-relationalStore.md). -| API| Description| +| API| Description| | -------- | -------- | -| getRdbStore(context: Context, config: StoreConfig, callback: AsyncCallback<RdbStore>): void | Obtains a **RdbStore** instance to implement RDB store operations. You can set **RdbStore** parameters based on actual requirements and use **RdbStore** APIs to perform data operations.| -| executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<void>):void | Executes an SQL statement that contains specified arguments but returns no value.| -| insert(table: string, values: ValuesBucket, callback: AsyncCallback<number>):void | Inserts a row of data into a table.| -| update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback<number>):void | Updates data in the RDB store based on the specified **RdbPredicates** instance.| -| delete(predicates: RdbPredicates, callback: AsyncCallback<number>):void | Deletes data from the RDB store based on the specified **RdbPredicates** instance.| -| query(predicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void | Queries data in the RDB store based on specified conditions.| -| deleteRdbStore(context: Context, name: string, callback: AsyncCallback<void>): void | Deletes an RDB store.| +| getRdbStore(context: Context, config: StoreConfig, callback: AsyncCallback<RdbStore>): void | Obtains a **RdbStore** instance to implement RDB store operations. You can set **RdbStore** parameters based on actual requirements and use **RdbStore** APIs to perform data operations.| +| executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<void>):void | Executes an SQL statement that contains specified arguments but returns no value.| +| insert(table: string, values: ValuesBucket, callback: AsyncCallback<number>):void | Inserts a row of data into a table.| +| update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback<number>):void | Updates data in the RDB store based on the specified **RdbPredicates** instance.| +| delete(predicates: RdbPredicates, callback: AsyncCallback<number>):void | Deletes data from the RDB store based on the specified **RdbPredicates** instance.| +| query(predicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void | Queries data in the RDB store based on specified conditions.| +| deleteRdbStore(context: Context, name: string, callback: AsyncCallback<void>): void | Deletes an RDB store.| ## How to Develop -1. Obtain an **RdbStore** instance.
Example: +1. Obtain an **RdbStore** instance.
Example: Stage model: - + ```js import relationalStore from '@ohos.data.relationalStore'; // Import the module. import UIAbility from '@ohos.app.ability.UIAbility'; @@ -65,7 +65,7 @@ The following table lists the APIs used for RDB data persistence. Most of the AP securityLevel: relationalStore.SecurityLevel.S1 // Database security level. }; - // The current RDB store version is 3, and the table structure is EMPLOYEE (NAME, AGE, SALARY, CODES). + // The RDB store version is 3, and the table structure is EMPLOYEE (NAME, AGE, SALARY, CODES). const SQL_CREATE_TABLE ='CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)'; // SQL statement for creating a data table. relationalStore.getRdbStore(this.context, STORE_CONFIG, (err, store) => { @@ -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. }); } @@ -106,7 +106,7 @@ The following table lists the APIs used for RDB data persistence. Most of the AP FA model: - + ```js import relationalStore from '@ohos.data.relationalStore'; // Import the module. import featureAbility from '@ohos.ability.featureAbility'; @@ -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. }); ``` @@ -160,10 +160,12 @@ The following table lists the APIs used for RDB data persistence. Most of the AP > > - The RDB store created by an application varies with the context. Multiple RDB stores are created for the same database name with different application contexts. For example, each UIAbility has its own context. > - > - When an application calls **getRdbStore()** to obtain an RDB store instance for the first time, the corresponding database file is generated in the application sandbox. If you want to move the files of an RDB store to another place for view, you must also move the temporary files with finename extensions **-wal** or **-shm** in the same directory. Once an application is uninstalled, the database files and temporary files generated by the application on the device are also removed. + > - When an application calls **getRdbStore()** to obtain an RDB store instance for the first time, the corresponding database file is generated in the application sandbox. When the RDB store is used, temporary files ended with **-wal** and **-shm** may be generated in the same directory as the database file. If you want to move the database files to other places, you must also move these temporary files. After the application is uninstalled, the database files and temporary files generated on the device are also removed. -2. Use **insert()** to insert data to the RDB store. Example: - +2. Use **insert()** to insert data to the RDB store. + + Example: + ```js const valueBucket = { 'NAME': 'Lisa', @@ -177,13 +179,13 @@ The following table lists the APIs used for RDB data persistence. Most of the AP return; } console.info(`Succeeded in inserting data. rowId:${rowId}`); - }) +}) ``` - + > **NOTE** - > +> > **RelationalStore** does not provide explicit flush operations for data persistence. Data inserted by **insert()** is stored in files persistently. - + 3. Modify or delete data based on the specified **Predicates** instance. Use **update()** to modify data and **delete()** to delete data. @@ -258,9 +260,13 @@ The following table lists the APIs used for RDB data persistence. Most of the AP Example: + > **NOTE** + > + > After the deletion, you are advised to set the database object to null. + Stage model: - + ```js import UIAbility from '@ohos.app.ability.UIAbility'; @@ -271,6 +277,7 @@ The following table lists the APIs used for RDB data persistence. Most of the AP console.error(`Failed to delete RdbStore. Code:${err.code}, message:${err.message}`); return; } + store = null; console.info('Succeeded in deleting RdbStore.'); }); } @@ -279,7 +286,7 @@ The following table lists the APIs used for RDB data persistence. Most of the AP FA model: - + ```js import featureAbility from '@ohos.ability.featureAbility'; @@ -291,6 +298,7 @@ The following table lists the APIs used for RDB data persistence. Most of the AP console.error(`Failed to delete RdbStore. Code:${err.code}, message:${err.message}`); return; } + store = null; console.info('Succeeded in deleting RdbStore.'); }); - ``` + ``` \ No newline at end of file diff --git a/en/application-dev/database/data-share-overview.md b/en/application-dev/database/data-share-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..4a163dcc56a5592038cd497bddafa572a90628f7 --- /dev/null +++ b/en/application-dev/database/data-share-overview.md @@ -0,0 +1,71 @@ +# Cross-Application Data Sharing + +## Introduction + +OpenHarmony provides APIs for an application to manage its own data and share data with other applications. + +Data needs to be shared in a wealth of scenarios. For example, the Contacts, short message service (SMS), and Gallery data always needs to be shared with other applications. However, certain data, such as accounts and passwords, cannot be shared. Some data, such as SMS messages, can be queried but not modified by other applications. Therefore, a secure and efficient cross-application data sharing mechanism for different data sharing scenarios and data privacy protection is very important. + +Currently, OpenHarmony supports one-to-many and many-to-many cross-application data sharing, based on the number of the data provider applications involved. + +## Basic Concepts + +Before you start, understand the following concepts: + +- **Data provider**: an application that provides data and implements related services. It is also called the producer or server. + +- **Data consumer**: an application that accesses the data or services provided by the data provider. It is also called the client. + +- **ValuesBucket**: a set of data to be inserted. It can be one or more data records in key-value (KV) pairs. In each KV pair, the key must be of the string type, and the value can be a number, a string, a Boolean value, or an unsigned integer array. + +- **ResultSet**: a set of query results. It provides flexible modes for users to obtain various data. + +- **Predicates**: an object that specifies the conditions for updating, deleting, or querying data in a database. + +## Unified Data Definition + +When data needs to be shared among multiple applications, a large amount of data needs to be converted for data interaction because the data definition and format vary with applications. To reduce application/service data interaction costs, OpenHarmony uses the unified data definition as the unified data language to build cross-application data interaction standards. + +The unified data definition defines common data types. Applications can use the APIs provided by the Unified Data Management Framework (UDMF) to create and use these data types. For details, see [Unified Data Definition](unified-data-definition.md). + +## One-to-Many Cross-Application Data Sharing + +You can use **DataShare** to implement one-to-many data sharing across applications. Two implementation modes are provided, depending on whether the data provider is started in the cross-application data sharing. + +### Implementation + +The data provider can directly use **DataShare** to share data with other applications without complex encapsulation. The data consumer only needs to use a set of APIs because the **DataShare** access mode does not vary with the data provision mode. This greatly reduces the learning time and development difficulty. + +**DataShare** implements cross-application data sharing in either of the following ways: + +- [Using DataShareExtensionAbility](share-data-by-datashareextensionability.md) + + You need to implement an ExtensionAbility with callbacks in the HAP. When the data consumer calls an API, the ExtensionAbility of the data provider will be automatically started to invoke the registered callback. + + You can use **DataShareExtensionAbility** when the cross-application data access involves service operations other than mere addition, deletion, modification, and query of data in databases. + +- [Using Silent Access via the DatamgrService](share-data-by-silent-access.md) + + You need to configure database access rules in the HAP. When the data consumer calls an API, the system ability automatically obtains the access rules in the HAP and returns data without starting the data provider. + + You can use this mode when the cross-application data access involves only database operations (data addition, deletion, modification, and query) or data hosted to the DatamgrService. + +If your application is signed with a system signature, you can use both methods. When data is created for the first time, use **DataShareExtensionAbility**. When data is accessed and modified later, use the **DatamgrService** to share data. That is, the data provider is started only when the data is accessed for the first time. + +### Restrictions + +- **DataShare** is subject to the limitations on the database used by the data provider. For example, the supported data models, length of the keys and values, and maximum number of databases that can be accessed at a time by each application vary with the database in use. + +- The payloads of **ValuesBucket**, **Predicates**, and **ResultSet** are restricted by IPC. + +- Currently, **dataShare** supports development based on the stage model only. + +## Many-to-Many Cross-Application Data Sharing + +In one-to-many cross-application data sharing, there is only one data provider. In many-to-many cross-application data sharing, you need to consider data definition, data exchange, and permission management. The UDMF provides a new data sharing and interaction mode to implement many-to-many cross-application data sharing. + +### Implementation + +[Sharing Data via Unified Data Channels](unified-data-channels.md) + +Applications can call the APIs provided by the UDMF to write data that complies with the unified data definition to different data sharing channels of the UDMF. The data in these channels can be read by other applications. The data written into the UDMF is managed based on the permissions of the application, permissions of the data channels, and the permission management logic of the UDMF. Lifecycle management is also performed on the data written into the channels in the same way. In this way, the data scattered in each application is aggregated via different channels of the UDMF, improving the development efficiency and data experience of users. 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/database/figures/dataManagement.jpg b/en/application-dev/database/figures/dataManagement.jpg index a43ca576222ad1da550242ed34c5f82700d52392..6555d34202927dc202fcb0ab233bc42740f39dbe 100644 Binary files a/en/application-dev/database/figures/dataManagement.jpg and b/en/application-dev/database/figures/dataManagement.jpg differ diff --git a/en/application-dev/database/figures/udmf_type_ADT.png b/en/application-dev/database/figures/udmf_type_ADT.png new file mode 100644 index 0000000000000000000000000000000000000000..2eb1e7b94080b6d611b1ed7abaceda31b04442e7 Binary files /dev/null and b/en/application-dev/database/figures/udmf_type_ADT.png differ diff --git a/en/application-dev/database/figures/udmf_type_File.png b/en/application-dev/database/figures/udmf_type_File.png new file mode 100644 index 0000000000000000000000000000000000000000..80bbec073de7e4e75da239a8a073453545260cc1 Binary files /dev/null and b/en/application-dev/database/figures/udmf_type_File.png differ diff --git a/en/application-dev/database/figures/udmf_type_SDT.png b/en/application-dev/database/figures/udmf_type_SDT.png new file mode 100644 index 0000000000000000000000000000000000000000..026ce5bd7ae68f4dbabdcf5bac63e721454e17f5 Binary files /dev/null and b/en/application-dev/database/figures/udmf_type_SDT.png differ diff --git a/en/application-dev/database/figures/udmf_type_Text.png b/en/application-dev/database/figures/udmf_type_Text.png new file mode 100644 index 0000000000000000000000000000000000000000..d12a2390dce2d08417e7024d15ee431dde66756b Binary files /dev/null and b/en/application-dev/database/figures/udmf_type_Text.png differ diff --git a/en/application-dev/database/share-data-by-datashareextensionability.md b/en/application-dev/database/share-data-by-datashareextensionability.md index 7f70ab30d4c04c421c1e18032a0da13e590f80a7..d3c28e31c20f0aa3d6720359aa28e84af2061a63 100644 --- a/en/application-dev/database/share-data-by-datashareextensionability.md +++ b/en/application-dev/database/share-data-by-datashareextensionability.md @@ -16,8 +16,7 @@ There are two roles in **DataShare**: - Data consumer: accesses the data provided by the provider using [createDataShareHelper()](../reference/apis/js-apis-data-dataShare.md#datasharecreatedatasharehelper). -**Figure 1** Data sharing mechanism - +**Figure 1** Data sharing mechanism ![dataShare](figures/dataShare.jpg) - The **DataShareExtensionAbility** module, as the data provider, implements services related to data sharing between applications. @@ -32,7 +31,7 @@ There are two roles in **DataShare**: ## How to Develop -### Data Provider Application Development (Only for System Applications) +### Data Provider Application (Only for System Applications) [DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md) provides the following APIs. You can override these APIs as required. @@ -146,7 +145,7 @@ override the service implementation as required. For example, if the data provid "icon": "$media:icon", "description": "$string:description_datashareextability", "type": "dataShare", - "uri": "datashare://com.samples.datasharetest.DataShare", + "uri": "datashareproxy://com.samples.datasharetest.DataShare", "exported": true, "metadata": [{"name": "ohos.extension.dataShare", "resource": "$profile:data_share_config"}] } @@ -155,11 +154,11 @@ override the service implementation as required. For example, if the data provid **Table 2** Fields in the data_share_config.json file - | Field| Description | Mandatory| - | ------------ | ------------------------------------------------------------ | --- | - | tableConfig | Label configuration.| Yes| - | uri | Range for which the configuration takes effect. The URI supports the following formats in descending order by priority:
1. *****: indicates all databases and tables.
2. **datashare:///{*bundleName*}/{*moduleName*}/{*storeName*}**: specifies a database.
3. **datashare:///{*bundleName*}/{*moduleName*}/{*storeName*}/{*tableName*}**: specifies a table.
If URIs of different formats are configured, only the URI with higher priority takes effect. | Yes| - | crossUserMode | Whether data is shared by multiple users. The value **1** means to share data between multiple users, and the value **2** means the opposite. | Yes| + | Field | Description | Mandatory | + | ------------- | ---------------------------------------- | ---- | + | tableConfig | Label configuration. | Yes | + | uri | Range for which the configuration takes effect. The URI supports the following formats in descending order by priority:
- *****: indicates all databases and tables.
- **datashareproxy://{bundleName}/{moduleName}/{storeName}**: specifies a database.
- **datashareproxy://{bundleName}/{moduleName}/{storeName}/{tableName}**: specifies a table. | Yes | + | crossUserMode | Whether data is shared by multiple users.
The value **1** means to share data between multiple users, and the value **2** means the opposite. | Yes | **data_share_config.json Example** @@ -170,18 +169,18 @@ override the service implementation as required. For example, if the data provid "crossUserMode": 1 }, { - "uri": "datashare:///com.acts.datasharetest/entry/DB00", + "uri": "datashareproxy://com.acts.datasharetest/entry/DB00", "crossUserMode": 1 }, { - "uri": "datashare:///com.acts.datasharetest/entry/DB00/TBL00", + "uri": "datashareproxy://com.acts.datasharetest/entry/DB00/TBL00", "crossUserMode": 2 } ] ``` -### Data Consumer Application Development +### Data Consumer Application 1. Import the dependencies. @@ -195,7 +194,7 @@ override the service implementation as required. For example, if the data provid ```js // Different from the URI defined in the module.json5 file, the URI passed in the parameter has an extra slash (/), because there is a DeviceID parameter between the second and the third slash (/). - let dseUri = ('datashare:///com.samples.datasharetest.DataShare'); + let dseUri = ('datashareproxy://com.samples.datasharetest.DataShare'); ``` 3. Create a **DataShareHelper** instance. @@ -239,3 +238,4 @@ override the service implementation as required. For example, if the data provid console.info(`dsHelper delete result:${data}`); }); ``` + diff --git a/en/application-dev/database/share-data-by-silent-access.md b/en/application-dev/database/share-data-by-silent-access.md index 50ff03f084c889a807c6caf4d7c369bfbe0d2a51..046d78b9eac73717cd16b4218f108c1a7979e54f 100644 --- a/en/application-dev/database/share-data-by-silent-access.md +++ b/en/application-dev/database/share-data-by-silent-access.md @@ -1,19 +1,40 @@ -# Data Sharing Through Silent Access +# Silent Access via the DatamgrService ## When to Use -In a typical cross-application data access scenario, an application may be started multiple times. +In a typical cross-application data access scenario, the data provider may be started multiple times. -To reduce the number of application startup times and improve the access speed, OpenHarmony provides the silent access feature, which allows direct access to the database without starting the data provider. +To reduce the number of startup times of the data provider and improve the access speed, OpenHarmony provides the silent access feature, which allows access to the database without starting the data provider. -Silent access supports only basic database access. If service processing is required, implement service processing in the data consumer. +In silent data access, the DatamgrService accesses and modifies data without starting the data provider. -If the service processing is complex, use **DataShareExtensionAbility** to start the data provider. +The DatamgrService supports basic database access or data hosting only. If service processing is required, the service processing needs to be encapsulated into APIs for the data consumer to call. + +If the service processing is too complex to be processed by the data consumer, use **DataShareExtensionAbility** to start the data provider. ## Working Principles +The DatamgrService can serve as a proxy to access the following types of data: + +- Persistent data + + Persistent data belongs to the database of the data provider. It is stored in the sandbox of the data provider and can be shared in declaration mode by the data provider. Persistent data is configured as data tables for access. + + +- Process data + + The process data managed by the **DatamgrService** is stored in the DatamgrService sandbox in JSON or byte format. This type of data is automatically deleted 10 days after no subscription. + + +| Type | Storage Location | Data Format | Validity Period | Application Scenario | +| ----- | --------- | ----------- | ------------ | --------------------------------- | +| Persistent data| Sandbox of the data provider | Tables in the database | Permanent storage | RDB data applications, such as schedules and conferences. | +| Process data | DatamgrService sandbox| JSON or byte| Automatically deleted 10 days after no subscription| Applications featuring simple and time-sensitive data, such as step count, weather, and heart rate.| + + + **Figure 1** Silent access ![silent_dataShare](figures/silent_dataShare.jpg) @@ -21,26 +42,271 @@ If the service processing is complex, use **DataShareExtensionAbility** to start - In silent access, **DatamgrService** obtains the access rules configured by the data provider through directory mapping, performs preprocessing based on rules, and accesses the database. - To use silent access, the URIs must be in the following format: - datashare:///{bundleName}/{moduleName}/{storeName}/{tableName}?Proxy=true + +datashareproxy://{bundleName}/{dataPath} + +The **DatamgrService** obtains the data provider application based on **bundleName**, reads the configuration, verifies the permission, and accesses data. + + **dataPath** identifies the data. It can be customized and must be unique in the same data provider application. + - "Proxy=true" means to access data without starting the data provider. If **Proxy** is not set to **true**, the data provider is started. +## Constraints - The **DatamgrService** obtains the data provider application based on **bundleName**, reads the configuration, verifies the permission, and accesses data. +- Currently, only the RDB stores support silent data access. +- The system supports a maximum of 16 concurrent query operations. Excess query requests need to be queued for processing. +- The proxy is not allowed to create a database for persistent data. To create a database, you must start the data provider. +- If the data provider is an application with a normal signature, the data read/write permission must be system_basic or higher. -## Constraints +## Available APIs -- Currently, only RDB stores support silent access. +The following table lists the APIs for silent data access. Most of the APIs are executed asynchronously in callback or promise mode. In the following table, callback-based APIs are used as an example. For more information about the APIs, see [Data Sharing](../reference/apis/js-apis-data-dataShare.md). -- The system supports a maximum of 16 concurrent query operations. Excess query requests need to be queued for processing. +### Common API + +| API | Description | +| ---------------------------------------- | -------------------- | +| createDataShareHelper(context: Context, uri: string, options: DataShareHelperOptions, callback: AsyncCallback<DataShareHelper>): void | Creates a **DataShareHelper** instance.| + +### APIs for Persistent Data + +| API | Description | +| ---------------------------------------- | -------------------- | +| insert(uri: string, value: ValuesBucket, callback: AsyncCallback<number>): void | Inserts a row of data into a table. | +| delete(uri: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>): void | Deletes one or more data records from the database. | +| query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: AsyncCallback<DataShareResultSet>): void | Queries data in the database. | +| update(uri: string, predicates: dataSharePredicates.DataSharePredicates, value: ValuesBucket, callback: AsyncCallback<number>): void | Updates data in the database. | +| addTemplate(uri: string, subscriberId: string, template: Template): void | Adds a data template with the specified subscriber. | +| on(type: 'rdbDataChange', uris: Array<string>, templateId: TemplateId, callback: AsyncCallback<RdbDataChangeNode>): Array<OperationResult | Subscribes to the changes of the data corresponding to the specified URI and template.| + +### APIs for Process Data + +| API | Description | +| ---------------------------------------- | ------------------ | +| publish(data: Array<PublishedItem>, bundleName: string, version: number, callback: AsyncCallback<Array<OperationResult>>): void | Publish data to the **DatamgrService**.| +| on(type: 'publishedDataChange', uris: Array<string>, subscriberId: string, callback: AsyncCallback<PublishedDataChangeNode>): Array<OperationResult> | Subscribes to changes of the published data. | + + + +## Implementation of the Persistence Data + +The following describes how to share an RDB store. + +### Data Provider Application + +1. In the **module.json5** file, set the ID, read/write permissions, and basic information of the table to be shared under **proxyDatas**. + + **Table 1** Fields of proxyDatas in module.json5 + + | Field | Description | Mandatory | + | ----------------------- | ---------------------------------------- | ---- | + | uri | URI of the data, which is the unique identifier for cross-application data access. | Yes | + | requiredReadPermission | Permission required for reading data from the data proxy. If this parameter is not set, other applications are not allowed to access data. For details about the supported permissions, see [Application Permission List](../security/permission-list.md). | No | + | requiredWritePermission | Permission required for modifying data from the data proxy. If this parameter is not set, other applications are not allowed to modify the data. For details about the supported permissions, see [Application Permission List](../security/permission-list.md). | No | + | metadata | Data source information, including the **name** and **resource** fields.
The **name** field identifies the configuration, which has a fixed value of **dataProperties**.
The value of **resource** is **$profile:{fileName}**, indicating that the name of the configuration file is **{fileName}.json**.| Yes | + + **module.json5 example** + + ```json + "proxyDatas":[ + { + "uri": "datashareproxy://com.acts.ohos.data.datasharetest/test", + "requiredReadPermission": "ohos.permission.GET_BUNDLE_INFO", + "requiredWritePermission": "ohos.permission.KEEP_BACKGROUND_RUNNING", + "metadata": { + "name": "dataProperties", + "resource": "$profile:my_config" + } + } + ] + ``` + **Table 2** Fields in my_config.json + + | Field | Description | Mandatory | + | ----- | ---------------------------------------- | ---- | + | path | Data source path, in the **Database_name/Table_name** format. Currently, only RDB stores are supported. | Yes | + | type | Database type. Currently, only **rdb** is supported. | Yes | + | scope | Scope of the database.
- **module** indicates that the database is located in this module.
- **application** indicates that the database is located in this application.| No | + + **my_config.json example** + + ```json + { + "path": "DB00/TBL00", + "type": "rdb", + "scope": "application" + } + ``` + +### Data Consumer Application + + +1. Import dependencies. + + ```js + import dataShare from '@ohos.data.dataShare'; + import dataSharePredicates from '@ohos.data.dataSharePredicates'; + ``` + +2. Define the URI string for communicating with the data provider. + + ```js + let dseUri = ('datashareproxy://com.acts.ohos.data.datasharetest/test'); + ``` + +3. Create a **DataShareHelper** instance. + + ```js + let dsHelper; + let abilityContext; + + export default class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage) { + abilityContext = this.context; + dataShare.createDataShareHelper(abilityContext, "", { + isProxy: true + }, (err, data) => { + dsHelper = data; + }); + } + } + ``` + +4. Use the APIs provided by **DataShareHelper** to access the services provided by the provider, for example, adding, deleting, modifying, and querying data. + + ```js + // Construct a piece of data. + let valuesBucket = { + 'name': 'ZhangSan', 'age': 21, 'isStudent': false, 'Binary': new Uint8Array([1, 2, 3]) + }; + let updateBucket = { + 'name': 'LiSi', 'age': 18, 'isStudent': true, 'Binary': new Uint8Array([1, 2, 3]) + }; + let predicates = new dataSharePredicates.DataSharePredicates(); + let valArray = ['*']; + // Insert a piece of data. + dsHelper.insert(dseUri, valuesBucket, (err, data) => { + console.info(`dsHelper insert result:${data}`); + }); + // Update data. + dsHelper.update(dseUri, predicates, updateBucket, (err, data) => { + console.info(`dsHelper update result:${data}`); + }); + // Query data. + dsHelper.query(dseUri, predicates, valArray, (err, data) => { + console.info(`dsHelper query result:${data}`); + }); + // Delete data. + dsHelper.delete(dseUri, predicates, (err, data) => { + console.info(`dsHelper delete result:${data}`); + }); + ``` + +5. Subscribe to the specified data. + + ```js + function onCallback(err, node: dataShare.RdbDataChangeNode) { + console.info("uri " + JSON.stringify(node.uri)); + console.info("templateId " + JSON.stringify(node.templateId)); + console.info("data length " + node.data.length); + for (let i = 0; i < node.data.length; i++) { + console.info("data " + node.data[i]); + } + } + + let template = { + predicates: { + "p1": "select * from TBL00", + "p2": "select name from TBL00", + }, + scheduler: "" + } + dsProxyHelper.addTemplate(dseUri, "111", template); + let templateId: dataShare.TemplateId = { + subscriberId: "111", + bundleNameOfOwner: "com.acts.ohos.data.datasharetestclient" + } + // When the DatamgrService modifies data, onCallback is invoked to return the data queried based on the rules in the template. + let result: Array = dsProxyHelper.on("rdbDataChange", [dseUri], templateId, onCallback); + ``` + +## Implementation of the Process Data + +The following describes how to host process data. + +### (Optional) Data Provider Application + +In the **module.json5** file of the data provider, set the process data ID, read/write permissions, and basic information under **proxyDatas**. + +> **NOTE** +> +> - This step is optional. +> - If **proxyDatas** is not configured, the hosted data cannot be accessed by other applications. +> - If **proxyDatas** is not configured, you do not need to use the full data path. For example, you can use **weather** instead of **datashareproxy://com.acts.ohos.data.datasharetest/weather** when publishing, subscribing to, and querying data. + +**Table 3** Fields of proxyDatas in module.json5 + +| Field | Description | Mandatory | +| ----------------------- | ----------------------------- | ---- | +| uri | URI of the data, which is the unique identifier for cross-application data access. | Yes | +| requiredReadPermission | Permission required for reading data from the data proxy. If this parameter is not set, other applications are not allowed to access data. For details about the supported permissions, see [Application Permission List](../security/permission-list.md).| No | +| requiredWritePermission | Permission required for modifying data from the data proxy. If this parameter is not set, other applications are not allowed to access data. For details about the supported permissions, see [Application Permission List](../security/permission-list.md).| No | + +**module.json5 example** + +```json +"proxyDatas": [ + { + "uri": "datashareproxy://com.acts.ohos.data.datasharetest/weather", + "requiredReadPermission": "ohos.permission.GET_BUNDLE_INFO", + "requiredWritePermission": "ohos.permission.KEEP_BACKGROUND_RUNNING" + } +] +``` + +### Data Consumer Application + +1. Import dependencies. + + ```js + import dataShare from '@ohos.data.dataShare'; + ``` + +2. Create a **DataShareHelper** instance. + + ```js + let dsHelper; + let abilityContext; -- A proxy cannot be used to create a database. If a database needs to be created, the data provider must be started. + export default class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage) { + abilityContext = this.context; + dataShare.createDataShareHelper(abilityContext, "", {isProxy : true}, (err, data) => { + dsHelper = data; + }); + } + } + ``` +3. Use the APIs provided by **DataShareHelper** to access the services provided by the provider, for example, adding, deleting, modifying, and querying data. -## How to Develop + ```js + // Construct two pieces of data. The first data is not configured with proxyDatas and cannot be accessed by other applications. + let data : Array = [ + {key:"city", subscriberId:"11", data:"xian"}, + {key:"datashareproxy://com.acts.ohos.data.datasharetest/weather", subscriberId:"11", data:JSON.stringify("Qing")}]; + // Publish data. + let result: Array = await dsProxyHelper.publish(data, "com.acts.ohos.data.datasharetestclient"); + ``` -The URI must be in the following format: +4. Subscribe to the specified data. -datashare:///{bundleName}/{moduleName}/{storeName}/{tableName}?Proxy=true + ```js + function onPublishCallback(err, node:dataShare.PublishedDataChangeNode) { + console.info("onPublishCallback"); + } + let uris:Array = ["city", "datashareproxy://com.acts.ohos.data.datasharetest/weather"]; + let result: Array = dsProxyHelper.on("publishedDataChange", uris, "11", onPublishCallback); + ``` -For details about the development procedure and implementation, see [Sharing Data Using DataShareExtensionAbility](share-data-by-datashareextensionability.md). + diff --git a/en/application-dev/database/sync-app-data-across-devices-overview.md b/en/application-dev/database/sync-app-data-across-devices-overview.md index c2f6361786325ccd753aa8fa4afa3446d37b6e89..4a3543a44c2b9e6e7fa9a4248010254c6ce1b035 100644 --- a/en/application-dev/database/sync-app-data-across-devices-overview.md +++ b/en/application-dev/database/sync-app-data-across-devices-overview.md @@ -7,7 +7,7 @@ The distributed application data synchronization allows the data of an applicati For example, when data is added, deleted, or modified for an application on a device, the same application on another device can obtain the updated data. You can use this feature in the distributed Gallery, Notepad, Contacts, and File Manager. -For details about how to subscribe to database change notifications between different applications, see [Sharing Application Data with Other Applications](share-device-data-across-apps-overview.md). +For details about how to subscribe to database change notifications between different applications, see [Cross-Application Data Sharing](data-share-overview.md). The data storage modes vary depending on the lifecycle of data to be synchronized: @@ -24,7 +24,7 @@ In a distributed scenario, cross-device collaboration demands consistent data be The data consistency can be classified into the following types: -- Strong consistency: When data is inserted, deleted, or modified on a device, other devices in the same network can obtain the updates eventually, but may not immediately. +- Strong consistency: When data is inserted, deleted, or modified on a device, other devices in the same network will obtain the latest data immediately. Once data is modified, the devices can read the updated data eventually, but may not read the updated data immediately. - Weak consistency: When data is added, deleted, or modified on a device, other devices in the same network may or may not obtain the updates. The data on these devices may be inconsistent after a certain period of time. diff --git a/en/application-dev/database/unified-data-channels.md b/en/application-dev/database/unified-data-channels.md new file mode 100644 index 0000000000000000000000000000000000000000..b31b9532eafb700da67c2dbcc5464f8f58867d23 --- /dev/null +++ b/en/application-dev/database/unified-data-channels.md @@ -0,0 +1,165 @@ +# Sharing Data via Unified Data Channels + + +## When to Use + +In many-to-many data sharing across applications, a data channel needs to be provided to access data of different applications and share the data with other applications. + +The Unified Data Management Framework (UDMF) provides unified data channels and standard data access interfaces for different service scenarios of many-to-many cross-application data sharing. + +## Definition and Implementation of Unified Data Channels + +The unified data channel provides cross-application data access for various service scenarios. It can temporarily store the unified data objects to be shared by an application, and manage the access permissions and lifecycle of the data according to certain policies. + +The unified data channel is implemented by the system ability provided by the UDMF. When an application (data provider) needs to share data, it calls the **insert()** method provided by the UDMF to write the data to the UDMF data channel, and calls UDMF **update()** or **delete()** to update or delete the data. After passing the permission verification, the target application (data consumer) calls the UDMF **read()** to access the data. After the data is read, the UDMF performs lifecycle management of the data. + +The unified data object (**UnifiedData**) is uniquely identified by a URI in the UDMF data channel. The URI is in the **udmf://*intention*/*bundleName*/*groupId*** format, where: + ++ **udmf**: protocol used to provide the data channel. + ++ *intention*: an enum of the data channel types supported by the UDMF. + ++ *bundleName*: bundle name of the data source application. + ++ *groupId*: group ID used for batch data management. + +Currently, the UDMF provides the public data channel for cross-application data sharing. + +**Public data channel**: allows applications to write and read data. The corresponding **intention** is **DATA_HUB**. + +## Available APIs + +The following table lists the UDMF APIs. All of them are executed asynchronously in callback or promise mode. In the following table, callback-based APIs are used as an example. For more information about the APIs, see [UDMF](../reference/apis/js-apis-data-udmf.md). + +| API | Description | +|-----------------------------------------------------------------------------------------|---------------------------------------------| +| insertData(options: Options, data: UnifiedData, callback: AsyncCallback\): void | Inserts data to the UDMF public data channel. A unique data identifier is returned.| +| updateData(options: Options, data: UnifiedData, callback: AsyncCallback\): void | Updates the data in the UDMF public data channel. | +| queryData(options: Options, callback: AsyncCallback\>): void | Queries data in the UDMF public data channel. | +| deleteData(options: Options, callback: AsyncCallback\>): void | Deletes data from the UDMF public data channel. The deleted data set is returned.| + + +## How to Develop + +The following example describes how to implement many-to-many data sharing. The data provider writes data to the UMDF public data channel, and updates and deletes the data. The data consumer obtains the data shared by the data provider. + +### Data Provider + +1. Import the **@ohos.data.UDMF** module. + + ```ts + import UDMF from '@ohos.data.UDMF'; + ``` +2. Create a **UnifiedData** object and insert it into the UDMF public data channel. + + ```ts + let plainText = new UDMF.PlainText(); + plainText.textContent = 'hello world!'; + let unifiedData = new UDMF.UnifiedData(plainText); + + // Specify the type of the data channel to which the data is to be inserted. + let options = { + intention: UDMF.Intention.DATA_HUB + } + try { + UDMF.insertData(options, unifiedData, (err, data) => { + if (err === undefined) { + console.info(`Succeeded in inserting data. key = ${data}`); + } else { + console.error(`Failed to insert data. code is ${err.code},message is ${err.message} `); + } + }); + } catch(e) { + console.error(`Insert data throws an exception. code is ${e.code},message is ${e.message} `); + } + ``` +3. Update the **UnifiedData** object inserted. + + ```ts + let plainText = new UDMF.PlainText(); + plainText.textContent = 'How are you!'; + let unifiedData = new UDMF.UnifiedData(plainText); + + // Specify the URI of the UnifiedData object to update. + let options = { + key: 'udmf://DataHub/com.ohos.test/0123456789' + }; + + try { + UDMF.updateData(options, unifiedData, (err) => { + if (err === undefined) { + console.info('Succeeded in updating data.'); + } else { + console.error(`Failed to update data. code is ${err.code},message is ${err.message} `); + } + }); + } catch(e) { + console.error(`Update data throws an exception. code is ${e.code},message is ${e.message} `); + } + ``` +4. Delete the **UnifiedData** object from the UDMF public data channel. + + ```ts + // Specify the type of the data channel whose data is to be deleted. + let options = { + intention: UDMF.Intention.DATA_HUB + }; + + try { + UDMF.deleteData(options, (err, data) => { + if (err === undefined) { + console.info(`Succeeded in deleting data. size = ${data.length}`); + for (let i = 0; i < data.length; i++) { + let records = data[i].getRecords(); + for (let j = 0; j < records.length; j++) { + if (records[j].getType() === UDMF.UnifiedDataType.PLAIN_TEXT) { + let text = (records[j]); + console.info(`${i + 1}.${text.textContent}`); + } + } + } + } else { + console.error(`Failed to delete data. code is ${err.code},message is ${err.message} `); + } + }); + } catch(e) { + console.error(`Delete data throws an exception. code is ${e.code},message is ${e.message} `); + } + ``` + +### Data Consumer + +1. Import the **@ohos.data.UDMF** module. + + ```ts + import UDMF from '@ohos.data.UDMF'; + ``` +2. Query the **UnifiedData** object in the UDMF public data channel. + + ```ts + // Specify the type of the data channel whose data is to be queried. + let options = { + intention: UDMF.Intention.DATA_HUB + }; + + try { + UDMF.queryData(options, (err, data) => { + if (err === undefined) { + console.info(`Succeeded in querying data. size = ${data.length}`); + for (let i = 0; i < data.length; i++) { + let records = data[i].getRecords(); + for (let j = 0; j < records.length; j++) { + if (records[j].getType() === UDMF.UnifiedDataType.PLAIN_TEXT) { + let text = (records[j]); + console.info(`${i + 1}.${text.textContent}`); + } + } + } + } else { + console.error(`Failed to query data. code is ${err.code},message is ${err.message} `); + } + }); + } catch(e) { + console.error(`Query data throws an exception. code is ${e.code},message is ${e.message} `); + } + ``` diff --git a/en/application-dev/database/unified-data-definition.md b/en/application-dev/database/unified-data-definition.md new file mode 100644 index 0000000000000000000000000000000000000000..d0a3c100b5dadff7ef56a0938cde5b4d98b489d4 --- /dev/null +++ b/en/application-dev/database/unified-data-definition.md @@ -0,0 +1,125 @@ +# Unified Data Definition + + +## When to Use + +To streamline cross-application data interaction of OpenHarmony and minimize the application/service data interaction costs, the Unified Data Management Framework (UDMF) provides standard data definitions to define common data types. Applications can use the APIs provided by the UDMF to create and use these data types. + + +## Unified Data Types + +The UDMF provides the following unified data types: + +**Basic data types**
Basic data types include File and Text, which can be used for cross-application and cross-platform data interaction. Figure 1 and Figure 2 illustrate the basic data types. + +**Figure 1** UDMF File + +![UDMF_FILE](figures/udmf_type_File.png) + +Figure 2 UDMF Text + +![UDMF_TEXT](figures/udmf_type_Text.png) + +**System Defined Types (SDTs)**
The SDTs are specific to the platform or operating system, such as Form (UI card information), AppItem (app description information), and PixelMap (thumbnail). This type of data can be used for cross-application data interaction in a system or platform. Figure 3 illustrates the SDT data. + +**Figure 3** UDMF SDT data + +![UDMF_SDT](figures/udmf_type_SDT.png) + +**App Defined Type (ADT)**
The SDT data is application-specific. This type of data can be used for across-platform data interaction for an application. As shown in Figure 4, the MyFile file format can be defined for use in an application ecosystem. + +**Figure 4** UDMF ADT data + +![UDMF_ADT](figures/udmf_type_ADT.png) + +## Restrictions + +- The size of each data record in the UDMF cannot exceed 2 MB. +- The UDMF supports data group management. The size of each group cannot exceed 4 MB. + +## Available APIs + +The UDMF provides the unified data object **UnifiedData** to encapsulate a group of data records **UnifiedRecord**. **UnifiedRecord** is an abstract definition of data content supported by the UDMF, for example, a text record or an image record. The data content type in a data record corresponds to **UnifiedDataType**. + +The following table describes common UDMF APIs. For more information, see [UDMF](../reference/apis/js-apis-data-udmf.md). + +| Class | API | Description | +|---------------|-------------------|-----------------------------------------------------------------------------------------------| +| UnifiedRecord | getType(): string | Obtains the data type of this data record.| +| UnifiedData | constructor(record: UnifiedRecord) | A constructor used to create a **UnifiedData** object with a data record. | +| UnifiedData | addRecord(record: UnifiedRecord): void | Adds a data record to this **UnifiedRecord** object. | +| UnifiedData | getRecords(): Array\ | Obtains all data records from this **UnifiedData** object. The data obtained is of the **UnifiedRecord** type. You need to obtain the data type by using **getType** and convert the data type to a child class before using it.| + + +## How to Develop + +The following describes how to create a **UnifiedData** object containing two data records: image and plain text. + +1. Import the **@ohos.data.UDMF** module. + + ```ts + import UDMF from '@ohos.data.UDMF'; + ``` +2. Create an image data record and initialize the **UnifiedData** object with the image data record. + + (1) Create an image data record. + + ```ts + let image = new UDMF.Image(); + ``` + + (2) Modify object attributes. + + ```ts + // The Image object contains the imageUri attribute. + image.imageUri = '...'; + ``` + + (3) Access the object attributes. + + ```ts + console.info(`imageUri = ${image.imageUri}`); + ``` + + (4) Create a **UnifiedData** instance. + + ```ts + let unifiedData = new UDMF.UnifiedData(image); + ``` +3. Create a plain text data record and add it to the **UnifiedData** instance created. + + ```ts + let plainText = new UDMF.PlainText(); + plainText.textContent = 'this is textContent of plainText'; + plainText.abstract = 'abstract of plainText'; + plainText.details = { + plainKey1: 'plainValue1', + plainKey2: 'plainValue2', + }; + unifiedData.addRecord(plainText); + ``` +4. Obtain all data records in this **UnifiedData** instance. + + ```ts + let records = unifiedData.getRecords(); + ``` +5. Traverse each record, determine the data type of the record, and convert the record into a child class object to obtain the original data record. + + ```ts + for (let i = 0; i < records.length; i ++) { + // Read the type of the data record. + let type = records[i].getType(); + switch (type) { + case UDMF.UnifiedDataType.IMAGE: + // Convert the data to obtain the original image data record. + let image = (records[i]); + break; + case UDMF.UnifiedDataType.PLAIN_TEXT: + // Convert the data to obtain the original text record. + let plainText = (records[i]); + break; + default: + break; + } + } + ``` diff --git a/en/application-dev/device/figures/001.png b/en/application-dev/device/figures/001.png new file mode 100644 index 0000000000000000000000000000000000000000..0b173958ed943fb9ecebd686b4f378d93fa2a7b0 Binary files /dev/null and b/en/application-dev/device/figures/001.png differ diff --git a/en/application-dev/device/figures/002.png b/en/application-dev/device/figures/002.png new file mode 100644 index 0000000000000000000000000000000000000000..34af38f77c66cbef900a1a4e536e3873bd0d94aa Binary files /dev/null and b/en/application-dev/device/figures/002.png differ diff --git a/en/application-dev/device/figures/003.png b/en/application-dev/device/figures/003.png new file mode 100644 index 0000000000000000000000000000000000000000..3c95c64ccb305ec25b1927733615ec4553505f97 Binary files /dev/null and b/en/application-dev/device/figures/003.png differ diff --git a/en/application-dev/device/sensor-guidelines.md b/en/application-dev/device/sensor-guidelines.md index 6ff5eb7405027da0853737ba64959cec4e59ad3a..21e1b55296ac46606bf1e4c91859f4c1f03ce030 100644 --- a/en/application-dev/device/sensor-guidelines.md +++ b/en/application-dev/device/sensor-guidelines.md @@ -15,65 +15,64 @@ For details about the APIs, see [Sensor](../reference/apis/js-apis-sensor.md). | ohos.sensor | sensor.on(sensorId, callback:AsyncCallback<Response>): void | Subscribes to data changes of a type of sensor.| | ohos.sensor | sensor.once(sensorId, callback:AsyncCallback<Response>): void | Subscribes to only one data change of a type of sensor.| | ohos.sensor | sensor.off(sensorId, callback?:AsyncCallback<void>): void | Unsubscribes from sensor data changes.| +| ohos.sensor | sensor.getSensorList(callback: AsyncCallback\>): void| Obtains information about all sensors on the device. This API uses an asynchronous callback to return the result.| ## How to Develop -1. Before obtaining data from a type of sensor, check whether the required permission has been configured.
- The system provides the following sensor-related permissions: - - ohos.permission.ACCELEROMETER +The acceleration sensor is used as an example. - - ohos.permission.GYROSCOPE +1. Import the module. - - ohos.permission.ACTIVITY_MOTION - - - ohos.permission.READ_HEALTH_DATA - - For details about how to configure a permission, see [Declaring Permissions](../security/accesstoken-guidelines.md). - -2. Subscribe to data changes of a type of sensor. The following uses the acceleration sensor as an example. - ```ts import sensor from "@ohos.sensor"; - - sensor.on(sensor.SensorId.ACCELEROMETER, function (data) { - console.info("Succeeded in obtaining data. x: " + data.x + "y: " + data.y + "z: " + data.z); // Data is obtained. - }); ``` - - ![171e6f30-a8d9-414c-bafa-b430340305fb](figures/171e6f30-a8d9-414c-bafa-b430340305fb.png) -3. Unsubscribe from sensor data changes. - - ```ts - import sensor from "@ohos.sensor"; - sensor.off(sensor.SensorId.ACCELEROMETER); - ``` - - ![65d69983-29f6-4381-80a3-f9ef2ec19e53](figures/65d69983-29f6-4381-80a3-f9ef2ec19e53.png) +2. Obtain information about all sensors on the device. + + ```ts + sensor.getSensorList(function (error, data) { + if (error) { + console.info('getSensorList failed'); + } else { + console.info('getSensorList success'); + for (let i = 0; i < data.length; i++) { + console.info(JSON.stringify(data[i])); + } + } + }); + ``` -4. Subscribe to only one data change of a type of sensor. - - ```ts - import sensor from "@ohos.sensor"; + ![](figures/001.png) - sensor.once(sensor.SensorId.ACCELEROMETER, function (data) { - console.info("Succeeded in obtaining data. x: " + data.x + "y: " + data.y + "z: " + data.z); // Data is obtained. - }); - ``` - - ![db5d017d-6c1c-4a71-a2dd-f74b7f23239e](figures/db5d017d-6c1c-4a71-a2dd-f74b7f23239e.png) + The minimum and the maximum sampling periods supported by the sensor are 5000000 ns and 200000000 ns, respectively. Therefore, the value of **interval** must be within this range. + +3. Check whether the corresponding permission has been configured. For details, see [Applying for Permissions](../security/accesstoken-guidelines.md). - If the API fails to be called, you are advised to use the **try/catch** statement to capture error information that may occur in the code. Example: +4. Register a listener. You can call **on()** or **once()** to listen for sensor data changes. + +- The **on()** API is used to continuously listen for data changes of the sensor. The sensor reporting interval is set to 100000000 ns. + + ```ts + sensor.on(sensor.SensorId.ACCELEROMETER, function (data) { + console.info("Succeeded in obtaining data. x: " + data.x + " y: " + data.y + " z: " + data.z); + }, {'interval': 100000000}); + ``` + + ![](figures/002.png) + +- The **once()** API is used to listen for only one data change of the sensor. ```ts - import sensor from "@ohos.sensor"; + sensor.once(sensor.SensorId.ACCELEROMETER, function (data) { + console.info("Succeeded in obtaining data. x: " + data.x + " y: " + data.y + " z: " + data.z); + }); + ``` + + ![](figures/003.png) - try { - sensor.once(sensor.SensorId.ACCELEROMETER, function (data) { - console.info("Succeeded in obtaining data. x: " + data.x + "y: " + data.y + "z: " + data.z); // Data is obtained. - }); - } catch (error) { - console.error(`Failed to get sensor data. Code: ${error.code}, message: ${error.message}`); - } +5. Cancel continuous listening. + + ```ts + sensor.off(sensor.SensorId.ACCELEROMETER); ``` diff --git a/en/application-dev/device/vibrator-guidelines.md b/en/application-dev/device/vibrator-guidelines.md index 7d3434d680d0d1a369d4f0ccd0bc8f720bd71349..4619a52a2f91c94b06e529be68d78330b4a4719f 100644 --- a/en/application-dev/device/vibrator-guidelines.md +++ b/en/application-dev/device/vibrator-guidelines.md @@ -76,9 +76,9 @@ This JSON file contains two attributes: **MetaData** and **Channels**. - **Create**: time when the file was created. This parameter is optional. - **Description**: additional information such as the vibration effect and creation information. This parameter is optional. - **Channels** provides information about the vibration channel. It is a JSON array that holds information about each channel. It contains two attributes: **Parameters** and **Pattern**. -- **Parameters** provides parameters related to the channel. Under it, **Index** indicates the channel ID. The value is fixed at **1** for a single channel. This parameter is mandatory. + - **Parameters** provides parameters related to the channel. Under it, **Index** indicates the channel ID. The value is fixed at **1** for a single channel. This parameter is mandatory. - **Pattern** indicates the vibration sequence. It is a JSON array. Under it, **Event** indicates a vibration event, which can be either of the following types: -- **transient**: short vibration + - **transient**: short vibration - **continuous**: long vibration The table below describes the parameters under **Event**. @@ -89,7 +89,7 @@ The table below describes the parameters under **Event**. | StartTime | Start time of the vibration. This parameter is mandatory.| [0, 1800 000], in ms, without overlapping| | Duration | Duration of the vibration. This parameter is valid only when **Type** is **continuous**.| (10, 1600), in ms| | Intensity | Intensity of the vibration. This parameter is mandatory.| [0, 100], a relative value that does not represent the actual vibration strength.| -| Frequency | Frequency of the vibration. This parameter is mandatory.| [0, 100], a relative value that does not represent the actual vibration frequency| +| Frequency | Frequency of the vibration. This parameter is mandatory.| [0, 100], a relative value that does not represent the actual vibration frequency.| The following requirements must be met: @@ -221,45 +221,42 @@ The following requirements must be met: ```ts import vibrator from '@ohos.vibrator'; - const FILE_NAME = "xxx.json"; - // Obtain the file descriptor of the vibration configuration file. - let fileDescriptor = undefined; - getContext().resourceManager.getRawFd(FILE_NAME).then(value => { - fileDescriptor = { fd: value.fd, offset: value.offset, length: value.length }; - console.info('Succeed in getting resource file descriptor'); - }).catch(error => { - console.error(`Failed to get resource file descriptor. Code: ${error.code}, message: ${error.message}`); - }); - // To use startVibration and stopVibration, you must configure the ohos.permission.VIBRATE permission. - try { - // Start custom vibration. - vibrator.startVibration({ - type: "file", - hapticFd: { fd: fileDescriptor.fd, offset: fileDescriptor.offset, length: fileDescriptor.length } - }, { - usage: "alarm" - }).then(() => { - console.info('Succeed in starting vibration'); - }, (error) => { - console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); - }); - // Stop vibration in all modes. - vibrator.stopVibration(function (error) { - if (error) { - console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); - return; - } - console.info('Succeed in stopping vibration'); - }) - } catch (error) { - console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`); + async function getRawfileFd(fileName) { + let rawFd = await globalThis.getContext().resourceManager.getRawFd(fileName); + return rawFd; + } + + // Close the file descriptor of the vibration configuration file. + async function closeRawfileFd(fileName) { + await globalThis.getContext().resourceManager.closeRawFd(fileName) + } + + // Play the custom vibration. To use startVibration and stopVibration, you must configure the ohos.permission.VIBRATE permission. + async function playCustomHaptic(fileName) { + try { + let rawFd = await getRawfileFd(fileName); + vibrator.startVibration({ + type: "file", + hapticFd: { fd: rawFd.fd, offset: rawFd.offset, length: rawFd.length } + }, { + usage: "alarm" + }).then(() => { + console.info('Succeed in starting vibration'); + }, (error) => { + console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); + }); + vibrator.stopVibration(function (error) { + if (error) { + console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); + return; + } + console.info('Succeed in stopping vibration'); + }) + await closeRawfileFd(fileName); + } catch (error) { + console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`); + } } - // Close the vibration file. - getContext().resourceManager.closeRawFd(FILE_NAME).then(() => { - console.info('Succeed in closing resource file descriptor'); - }).catch(error => { - console.error(`Failed to close resource file descriptor. Code: ${error.code}, message: ${error.message}`); - }); ``` diff --git a/en/application-dev/dfx/Readme-EN.md b/en/application-dev/dfx/Readme-EN.md index 5a1b6326bae1ecb94ef7fe8d9e4cfe2cdf2c6c56..c40f752d8f85e8894eb725965f50a7614dddef36 100644 --- a/en/application-dev/dfx/Readme-EN.md +++ b/en/application-dev/dfx/Readme-EN.md @@ -1,7 +1,6 @@ # DFX - [Development of Application Event Logging](hiappevent-guidelines.md) -- [Development of Performance Tracing](hitracemeter-guidelines.md) - [Development of Distributed Call Chain Tracing](hitracechain-guidelines.md) - [HiLog Development (Native)](hilog-guidelines.md) - Performance Tracing diff --git a/en/application-dev/dfx/appfreeze-guidelines.md b/en/application-dev/dfx/appfreeze-guidelines.md index 05b52c4d8070386ec350701cefb2c6b63ef67d55..4984c95e215fe832f59abc3306bf777c6c313818 100644 --- a/en/application-dev/dfx/appfreeze-guidelines.md +++ b/en/application-dev/dfx/appfreeze-guidelines.md @@ -1,6 +1,6 @@ # Application Freeze (appfreeze) Log Analysis -## Introduction +## Overview Application freeze (appfreeze) means that an application does not respond to user operations (for example, clicking) within a given period of time. OpenHarmony provides a mechanism for detecting appfreeze faults and generates appfreeze logs for fault analysis. diff --git a/en/application-dev/dfx/apprecovery-guidelines.md b/en/application-dev/dfx/apprecovery-guidelines.md index 284de5ca6d5f6027f2cce975a29b3259b2778021..9548404b3b359ad3f6fbe6778e0ddaeb374cc2ec 100644 --- a/en/application-dev/dfx/apprecovery-guidelines.md +++ b/en/application-dev/dfx/apprecovery-guidelines.md @@ -1,6 +1,6 @@ # Application Recovery Development -## When to Use +## Overview During application running, some unexpected behaviors are inevitable. For example, unprocessed exceptions and errors are thrown, and the call or running constraints of the recovery framework are violated. @@ -99,9 +99,12 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant' - Define and register the [ErrorObserver](../reference/apis/js-apis-inner-application-errorObserver.md) callback. For details about its usage, see [errorManager](../reference/apis/js-apis-app-ability-errorManager.md). ```ts - var registerId = -1; - var callback = { - onUnhandledException(errMsg) { + export let abilityWant : Want // file1 + + import * as G form "../file1" + let registerId = -1; + let callback: Callback = { + onUnhandledException(errMsg: string): void { console.log(errMsg); appRecovery.saveAppState(); appRecovery.restartApp(); @@ -112,7 +115,7 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant' // Main window is created, set main page for this ability console.log("[Demo] MainAbility onWindowStageCreate") - globalThis.registerObserver = (() => { + G.registerObserver = (() => { registerId = errorManager.on('error', callback); }) @@ -138,13 +141,16 @@ After the callback triggers **appRecovery.saveAppState()**, **onSaveState(state, After the callback triggers **appRecovery.restartApp()**, the application is restarted. After the restart, **onCreate(want, launchParam)** of **MainAbility** is called, and the saved data is in **parameters** of **want**. ```ts +export let abilityWant : Want // file1 + +import * as GlobalWant form "../file1" storage: LocalStorage onCreate(want, launchParam) { console.log("[Demo] MainAbility onCreate") - globalThis.abilityWant = want; + GlobalWant.abilityWant = want; if (launchParam.launchReason == AbilityConstant.LaunchReason.APP_RECOVERY) { this.storage = new LocalStorage(); - let recoveryData = want.parameters["myData"]; + let recoveryData: string = want.parameters["myData"]; this.storage.setOrCreate("myData", recoveryData); this.context.restoreWindowStage(this.storage); } @@ -154,12 +160,15 @@ onCreate(want, launchParam) { - Unregister the **ErrorObserver** callback. ```ts +export let abilityWant : Want // file1 + +import * as G form "../file1" onWindowStageDestroy() { // Main window is destroyed, release UI related resources console.log("[Demo] MainAbility onWindowStageDestroy") - globalThis.unRegisterObserver = (() => { - errorManager.off('error', registerId, (err) => { + G.unRegisterObserver = (() => { + errorManager.off(type: 'error', registerId: number, (err:Error) => { console.error("[Demo] err:", err); }); }) @@ -171,20 +180,22 @@ onWindowStageDestroy() { This is triggered by the recovery framework. You do not need to register an **ErrorObserver** callback. You only need to implement **onSaveState** for application state saving and **onCreate** for data restore. ```ts +export let abilityWant : Want // file1 + +import * as GlobalWant form "../file1" export default class MainAbility extends Ability { - storage: LocalStorage - onCreate(want, launchParam) { + onCreate(want: Want, launchParam:AbilityConstant.LaunchParam):void { console.log("[Demo] MainAbility onCreate") - globalThis.abilityWant = want; + GlobalWant.abilityWant = want; if (launchParam.launchReason == AbilityConstant.LaunchReason.APP_RECOVERY) { this.storage = new LocalStorage(); - let recoveryData = want.parameters["myData"]; - this.storage.setOrCreate("myData", recoveryData); + let recoveryData: string = want.parameters["myData"]; + this.storage.setOrCreate("myData", recoveryData); this.context.restoreWindowStage(this.storage); } } - onSaveState(state, wantParams) { + onSaveState(state: AbilityConstant.StateType, wantParams: { [key: string]: Object }) : AbilityConstant.OnSaveResult{ // Ability has called to save app data console.log("[Demo] MainAbility onSaveState") wantParams["myData"] = "my1234567"; diff --git a/en/application-dev/dfx/cppcrash-guidelines.md b/en/application-dev/dfx/cppcrash-guidelines.md index 4454422fe4f3aec6c781090a2e833ee103488dab..15136518788324e23ac46c8c8b5bba327c03ea7a 100644 --- a/en/application-dev/dfx/cppcrash-guidelines.md +++ b/en/application-dev/dfx/cppcrash-guidelines.md @@ -1,6 +1,6 @@ -# cppcrash Log Analysis +# Process Crash (cppcrash) Log Analysis -## Introduction +## Overview A process crash refers to a C/C++ runtime crash. The FaultLogger module of OpenHarmony provides capabilities such as process crash detection, log collection, log storage, and log reporting, helping you to locate faults more effectively. @@ -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/dfx/errormanager-guidelines.md b/en/application-dev/dfx/errormanager-guidelines.md index 4679cfcfc78893590fe73eab770e49fc68a1a828..14d7735d731d0fb2eb3fc41f61de58f5de7f4e02 100644 --- a/en/application-dev/dfx/errormanager-guidelines.md +++ b/en/application-dev/dfx/errormanager-guidelines.md @@ -1,6 +1,6 @@ # Development of Error Manager -## When to Use +## Overview If coding specification issues or errors exist in the code of an application, the application may encounter unexpected errors, for example, uncaught exceptions or application lifecycle timeouts, while it is running. In such a case, the application may exit unexpectedly. Error logs, however, are usually stored on users' local storage, making it inconvenient to locate faults. With the APIs provided by the **errorManager** module, your application will be able to report related errors and logs to your service platform for fault locating before it exits. diff --git a/en/application-dev/dfx/hiappevent-guidelines.md b/en/application-dev/dfx/hiappevent-guidelines.md index d21d4e3fa9e0fa0b795c82e7157cd6215eab5e0c..6b0f4dd1cb8ec36288514e3f8767770f4e30105b 100644 --- a/en/application-dev/dfx/hiappevent-guidelines.md +++ b/en/application-dev/dfx/hiappevent-guidelines.md @@ -1,6 +1,6 @@ # Development of Application Event Logging -## Introduction +## Overview A traditional log system aggregates log information generated by all applications running on the entire device, making it difficult to identify key information in the log. Therefore, an effective logging mechanism is needed to evaluate mission-critical information, for example, number of visits, number of daily active users, user operation habits, and key factors that affect application usage. diff --git a/en/application-dev/dfx/hilog-guidelines.md b/en/application-dev/dfx/hilog-guidelines.md index 25b4a7f9cc5c92d9f20ed6582299d5dd65b937d0..45d46c01fb4c601241120ce9cf5d249bd0bc893f 100644 --- a/en/application-dev/dfx/hilog-guidelines.md +++ b/en/application-dev/dfx/hilog-guidelines.md @@ -1,6 +1,6 @@ # HiLog Development (Native) -## Introduction +## Overview HiLog is the log system of OpenHarmony that provides logging for the system framework, services, and applications to record information on user operations and system running status. diff --git a/en/application-dev/dfx/hitracechain-guidelines.md b/en/application-dev/dfx/hitracechain-guidelines.md index affd260b0503f3c4f4c4b748d5911d94f7fef9e3..44e2da92dfbf985f27a275ac6e02e61a934d199e 100644 --- a/en/application-dev/dfx/hitracechain-guidelines.md +++ b/en/application-dev/dfx/hitracechain-guidelines.md @@ -1,6 +1,6 @@ # Development of Distributed Call Chain Tracing -## Introduction +## Overview The hiTraceChain module provides APIs to implement call chain tracing throughout a service process. This can help you quickly obtain the run log for the call chain of a specified service process and locate faults in inter-device, inter-process, or inter-thread communications. diff --git a/en/application-dev/dfx/hitracemeter-guidelines.md b/en/application-dev/dfx/hitracemeter-guidelines.md index a4152acb7303cd672b830d80a3ba48bc54ee8d9c..195aae4b2d98dd1ab950613c6c97ed07cfcfe98e 100644 --- a/en/application-dev/dfx/hitracemeter-guidelines.md +++ b/en/application-dev/dfx/hitracemeter-guidelines.md @@ -1,6 +1,6 @@ # Development of Performance Tracing (ArkTS) -## Introduction +## Overview hiTraceMeter provides APIs for system performance tracing. You can call the APIs provided by the hiTraceMeter module in your own service logic to effectively track service processes and check the system performance. @@ -35,51 +35,7 @@ The performance tracing APIs are provided by the **hiTraceMeter** module. For de In this example, distributed call chain tracing begins when the application startup execution page is loaded and stops when the service usage is completed. -1. Create a JS application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **js** > **default** > **pages** > **index**, and double-click **index.js**. Add the code to implement performance tracing upon page loading. The sample code is as follows: - - ```js - import hiTraceMeter from '@ohos.hiTraceMeter' - - export default { - data: { - title: "" - }, - onInit() { - this.title = this.$t('strings.world'); - - // Start trace tasks with the same name concurrently. - hiTraceMeter.startTrace("business", 1); - // Keep the service process running. - console.log(`business running`); - hiTraceMeter.startTrace("business", 2); // Start the second trace task with the same name while the first task is still running. The tasks are running concurrently and therefore their taskId must be different. - // Keep the service process running. - console.log(`business running`); - hiTraceMeter.finishTrace("business", 1); - // Keep the service process running. - console.log(`business running`); - hiTraceMeter.finishTrace("business", 2); - - // Start trace tasks with the same name in serial mode. - hiTraceMeter.startTrace("business", 1); - // Keep the service process running. - console.log(`business running`); - hiTraceMeter.finishTrace("business", 1); // End the first trace task. - // Keep the service process running. - console.log(`business running`); - hiTraceMeter.startTrace("business", 1); // Start the second trace task with the same name in serial mode. - // Keep the service process running. - console.log(`business running`); - - let traceCount = 3; - hiTraceMeter.traceByValue("myTestCount", traceCount); - traceCount = 4; - hiTraceMeter.traceByValue("myTestCount", traceCount); - hiTraceMeter.finishTrace("business", 1); - } - } - ``` - -2. Create an ArkTs application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **ets** > **pages** > **index**, and double-click **index.js**. Add the code to implement performance tracing upon page loading. For example, if the name of the trace task is **HITRACE\_TAG\_APP**, the sample code is as follows: +1. Create an ArkTS application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **ets** > **pages** > **index**, and double-click **index.js**. Add the code to implement performance tracing upon page loading. For example, if the name of the trace task is **HITRACE\_TAG\_APP**, the sample code is as follows: ```ts import hitrace from '@ohos.hiTraceMeter'; diff --git a/en/application-dev/dfx/hitracemeter-native-guidelines.md b/en/application-dev/dfx/hitracemeter-native-guidelines.md index bb0274f7c4077b016061430250e7a949cf826864..912ec1c5f87b6ebfdd6f14cb4da568e251501af2 100644 --- a/en/application-dev/dfx/hitracemeter-native-guidelines.md +++ b/en/application-dev/dfx/hitracemeter-native-guidelines.md @@ -1,6 +1,6 @@ # Development of Performance Tracing (Native) -## Introduction +## Overview hiTraceMeter provides APIs for system performance tracing. You can call the APIs provided by the hiTraceMeter module in your own service logic to effectively track service processes and check the system performance. > **NOTE** diff --git a/en/application-dev/faqs/Readme-EN.md b/en/application-dev/faqs/Readme-EN.md index d7316d5a25c20f4cd076b8ebca4ed700d7c387c7..038869298ca254238293357a0c31b84c817cc9c4 100644 --- a/en/application-dev/faqs/Readme-EN.md +++ b/en/application-dev/faqs/Readme-EN.md @@ -2,7 +2,7 @@ - [Full SDK Compilation](full-sdk-compile-guide.md) - [Switching to Full SDK](full-sdk-switch-guide.md) -- [Using Native APIs (NDK) of the OpenHarmony SDK in a CMake Project](howto-migrate-cmake-with-ohosndk.md) +- [Using NDK in a CMake Project](cmake-with-ndk.md) - [Application Model Development](faqs-ability.md) - ArkUI Development (ArkTS) - [ArkTS Syntax Usage](faqs-arkui-arkts.md) diff --git a/en/application-dev/faqs/howto-migrate-cmake-with-ohosndk.md b/en/application-dev/faqs/cmake-with-ndk.md similarity index 92% rename from en/application-dev/faqs/howto-migrate-cmake-with-ohosndk.md rename to en/application-dev/faqs/cmake-with-ndk.md index 36f339529c78327f2698f90ce199e758ba06485f..60a68a9ecf05aa95680096d67a18dd37bdda74c1 100644 --- a/en/application-dev/faqs/howto-migrate-cmake-with-ohosndk.md +++ b/en/application-dev/faqs/cmake-with-ndk.md @@ -1,4 +1,4 @@ -# Using Native APIs (NDK) of the OpenHarmony SDK in a CMake Project +# Using NDK in a CMake Project ## What Is Native API @@ -10,34 +10,34 @@ You download the Native API Development Kit (NDK) by downloading the OHOS SDK, w - (Recommended) Acquire source code from mirrors for an officially released version. For details, see [release notes](../../release-notes/OpenHarmony-v3.2-release.md). - Download the SDK from the SDK Manager in DevEco Studio. -- Download the SDK from the [daily build](http://ci.openharmony.cn/dailys/dailybuilds), by clicking the download link to the **ohos-sdk-full** component. +- Download the SDK from the [daily build](http://ci.openharmony.cn/workbench/cicd/dailybuild/dailylist), by clicking the download link to the **ohos-sdk-full** component. -![Download from Daily Build](figures/ci_download.png) +![](figures/ci_download.png) ## Decompressing the NDK Place the downloaded NDK in a folder you prefer and decompress it. Below shows the directory structure after decompression. -![SDK Directory Structure](figures/sdk-structure.png) +![](figures/sdk-structure.png) Configure the Linux environment as follows: (Skip them if the NDK is downloaded from DevEco Studio.) -1. Add the CMake tool that comes with the NDK to the environment variables. +Add the CMake tool that comes with the NDK to the environment variables. ``` # Open the .bashrc file. vim ~/.bashrc - # Append the custom CMake path to the file. Save the file and exit. + # Append the custom CMake path to the file. export PATH=~/ohos-sdk/ohos-sdk/linux/native/build-tools/cmake/bin:$PATH # Run the source ~/.bashrc command to make the environment variables take effect. source ~/.bashrc ``` -2. Check the default CMake path. +Check the default CMake path. ``` # Run the which cmake command. which cmake - # The result should be the same as the custom path previously appended to the file. + # The result should be the same as the custom path previously appended to the .bashrc file. ~/ohos-sdk/ohos-sdk/linux/native/build-tools/cmake/bin/cmake ``` diff --git a/en/application-dev/faqs/faqs-ability.md b/en/application-dev/faqs/faqs-ability.md index fef66125771888f9dfe3dce2ae4297ce858d56b8..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 the Application Development Path](../application-models/application-context-stage.md#obtaining-the-application-development-path) +[cacheDir](../application-models/application-context-stage.md#obtaining-application-file-paths) ## In which JS file is the service widget lifecycle callback invoked? @@ -262,7 +262,7 @@ Obtain them from the application context. Specifically, use **this.context.getAp **Reference** -[Obtaining the Application Development Path](../application-models/application-context-stage.md#obtaining-the-application-development-path) +[Obtaining Application File Paths](../application-models/application-context-stage.md#obtaining-application-file-paths) ## Why the application is not deleted from the background mission list after it calls terminateSelf? @@ -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-dev-guide.md#development-in-the-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 fbe2594e6591bb774aa116095e721ca889490cc8..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, **\ +

@@ -3866,7 +3867,7 @@ struct WebComponent { getCertificate(): Promise> -Obtains the certificate information of the current website. When the \ component is used to load an HTTPS website, SSL certificate verification is performed. This API uses a promise to return the [X.509 certificate](./js-apis-cert.md) of the current website. +Obtains the certificate information of this website. When the **\** component is used to load an HTTPS website, SSL certificate verification is performed. This API uses a promise to return the [X.509 certificate](./js-apis-cert.md) of the current website. **System capability**: SystemCapability.Web.Webview.Core @@ -3943,7 +3944,7 @@ struct Index { } .type(ButtonType.Capsule) .onClick(() => { - //Load an HTTPS website and view the certificate information of the website. + // Load an HTTPS website and view the certificate information of the website. this.webviewCtl.loadUrl('https://www.example.com') }) .height(50) @@ -4023,7 +4024,7 @@ struct Index { getCertificate(callback: AsyncCallback>): void -Obtains the certificate information of the current website. When the \ component is used to load an HTTPS website, SSL certificate verification is performed. This API uses an asynchronous callback to return the [X.509 certificate](./js-apis-cert.md) of the current website. +Obtains the certificate information of this website. When the **\** component is used to load an HTTPS website, SSL certificate verification is performed. This API uses an asynchronous callback to return the [X.509 certificate](./js-apis-cert.md) of the website. **System capability**: SystemCapability.Web.Webview.Core @@ -4031,7 +4032,7 @@ Obtains the certificate information of the current website. When the \ comp | Name | Type | Mandatory| Description | | -------- | ---------------------------- | ---- | ---------------------------------------- | -| callback | AsyncCallback> | Yes | Callback used to obtain the X.509 certificate array of the current HTTPS website.| +| callback | AsyncCallback> | Yes | Callback used to obtain the X.509 certificate array of the current website.| **Error codes** @@ -4100,7 +4101,7 @@ struct Index { } .type(ButtonType.Capsule) .onClick(() => { - //Load an HTTPS website and view the certificate information of the website. + // Load an HTTPS website and view the certificate information of the website. this.webviewCtl.loadUrl('https://www.example.com') }) .height(50) @@ -4222,10 +4223,212 @@ struct WebComponent { } ``` +### prefetchPage10+ + +prefetchPage(url: string, additionalHeaders?: Array\): void + +Prefetches resources in the background for a page that is likely to be accessed in the near future, without executing the page JavaScript code or presenting the page. This can significantly reduce the load time for the prefetched page. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------------------| --------------------------------| ---- | ------------- | +| url | string | Yes | URL to be preloaded.| +| additionalHeaders | Array\<[WebHeader](#webheader)> | No | Additional HTTP headers of the URL.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID | Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | +| 17100002 | Invalid url. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('prefetchPopularPage') + .onClick(() => { + try { + // Replace 'https://www.example.com' with a real URL for the API to work. + this.controller.prefetchPage('https://www.example.com'); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + // Replace ''www.example1.com' with a real URL for the API to work. + Web({ src: 'www.example1.com', controller: this.controller }) + } + } +} +``` + +### prepareForPageLoad10+ + +static prepareForPageLoad(url: string, preconnectable: boolean, numSockets: number): void + +Preconnects to a URL. This API can be called before the URL is loaded, to resolve the DNS and establish a socket connection, without obtaining the resources. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------------| ------- | ---- | ------------- | +| url | string | Yes | URL to be preconnected.| +| preconnectable | boolean | Yes | Whether to perform preconnection, which involves DNS resolution and socket connection establishment. The value **true** means to perform preconnection, and **false** means the opposite.| +| numSockets | number | Yes | Number of sockets to be preconnected. The value must be greater than 0. A maximum of six socket connections are allowed.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID | Error Message | +| -------- | ------------------------------------------------------------ | +| 17100002 | Invalid url. | +| 171000013| The number of preconnect sockets is invalid. | + +**Example** + +```ts +// xxx.ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import web_webview from '@ohos.web.webview'; + +export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + console.log("EntryAbility onCreate") + web_webview.WebviewController.initializeWebEngine() + // Replace 'https://www.example.com' with a real URL for the API to work. + web_webview.WebviewController.prepareForPageLoad("https://www.example.com", true, 2); + globalThis.abilityWant = want + console.log("EntryAbility onCreate done") + } +} +``` + +### setCustomUserAgent10+ + +setCustomUserAgent(userAgent: string): void + +Set a custom user agent. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------------| ------- | ---- | ------------- | +| userAgent | string | Yes | Information about the custom user agent.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID | Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + @State userAgent: string = 'test' + + build() { + Column() { + Button('setCustomUserAgent') + .onClick(() => { + try { + this.controller.setCustomUserAgent(this.userAgent); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### getCustomUserAgent10+ + +getCustomUserAgent(): string + +Obtains a custom user agent. + +**System capability**: SystemCapability.Web.Webview.Core + +**Return value** + +| Type | Description | +| ------ | ------------------------- | +| string | Information about the custom user agent.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID | Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + @State userAgent: string = '' + + build() { + Column() { + Button('getCustomUserAgent') + .onClick(() => { + try { + this.userAgent = this.controller.getCustomUserAgent(); + console.log("userAgent: " + this.userAgent); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + ## WebCookieManager Implements a **WebCookieManager** instance to manage behavior of cookies in **\** components. All **\** components in an application share a **WebCookieManager** instance. +> **NOTE** +> +> You must load the **\** component before calling APIs in **WebCookieManager**. + ### getCookie static getCookie(url: string): string @@ -4347,7 +4550,6 @@ Saves the cookies in the memory to the drive. This API uses an asynchronous call | -------- | ---------------------- | ---- | :------------------------------------------------- | | callback | AsyncCallback\ | Yes | Callback used to return whether the cookies are successfully saved.| - **Example** ```ts @@ -4688,6 +4890,10 @@ struct WebComponent { Implements a **WebStorage** object to manage the Web SQL database and HTML5 Web Storage APIs. All **\** components in an application share a **WebStorage** object. +> **NOTE** +> +> You must load the **\** component before calling the APIs in **WebStorage**. + ### deleteOrigin static deleteOrigin(origin : string): void @@ -5148,6 +5354,10 @@ struct WebComponent { Implements a **WebDataBase** object. +> **NOTE** +> +> You must load the **\** component before calling the APIs in **WebDataBase**. + ### getHttpAuthCredentials static getHttpAuthCredentials(host: string, realm: string): Array\ @@ -5326,6 +5536,10 @@ struct WebComponent { Implements a **GeolocationPermissions** object. +> **NOTE** +> +> You must load the **\** component before calling the APIs in **GeolocationPermissions**. + ### Required Permissions **ohos.permission.LOCATION**, **ohos.permission.APPROXIMATELY_LOCATION**, and **ohos.permission.LOCATION_IN_BACKGROUND**, which are required for accessing the location information. For details about the permissions, see [@ohos.geolocation (Geolocation)](./js-apis-geolocation.md). @@ -5739,7 +5953,6 @@ Describes the type of the returned result of script execution using [runJavaScir | ARRAY_BUFFER | 4 |Raw binary data buffer.| | ARRAY | 5 |Array type.| - ## WebMessageType10+ Describes the data type supported by the [webMessagePort](#webmessageport) API. @@ -5796,7 +6009,6 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error | -------- | ------------------------------------- | | 17100014 | The type does not match with the value of the result. | - ### getNumber10+ getNumber(): number @@ -5841,7 +6053,6 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error | -------- | ------------------------------------- | | 17100014 | The type does not match with the value of the result. | - ### getArrayBuffer10+ getArrayBuffer(): ArrayBuffer @@ -5885,7 +6096,6 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error | -------- | ------------------------------------- | | 17100014 | The type does not match with the value of the result. | - ## WebMessageExt10+ Data object received and sent by the [webMessagePort](#webmessageport) interface. @@ -5904,7 +6114,6 @@ Obtains the type of the data object. | --------------| --------------------------------------------------------- | | [WebMessageType](#webmessagetype10) | Data type supported by the [webMessagePort](#webmessageport) API.| - ### getString10+ getString(): string @@ -5927,7 +6136,6 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error | -------- | ------------------------------------- | | 17100014 | The type does not match with the value of the web message. | - ### getNumber10+ getNumber(): number @@ -5950,7 +6158,6 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error | -------- | ------------------------------------- | | 17100014 | The type does not match with the value of the web message. | - ### getBoolean10+ getBoolean(): boolean @@ -5973,7 +6180,6 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error | -------- | ------------------------------------- | | 17100014 | The type does not match with the value of the web message. | - ### getArrayBuffer10+ getArrayBuffer(): ArrayBuffer @@ -6039,7 +6245,6 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error | -------- | ------------------------------------- | | 17100014 | The type does not match with the value of the web message. | - ### setType10+ setType(type: WebMessageType): void @@ -6180,7 +6385,6 @@ Sets the error-object-type data for the data object. For the complete sample cod | -------- | ------------------------------------- | | 17100014 | The type does not match with the value of the web message. | - ## WebStorageOrigin Provides usage information of the Web SQL Database. diff --git a/en/application-dev/reference/apis/js-apis-wifi.md b/en/application-dev/reference/apis/js-apis-wifi.md index e9f2fbb84b4b39521a484f2c5ffc60680223d2ac..6d62994c8e11b1801c8b04c1ff3723c0f8fec3bb 100644 --- a/en/application-dev/reference/apis/js-apis-wifi.md +++ b/en/application-dev/reference/apis/js-apis-wifi.md @@ -27,9 +27,9 @@ Enables WLAN. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -57,9 +57,9 @@ Disables WLAN. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -86,9 +86,9 @@ Checks whether WLAN is enabled. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if WLAN is enabled; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if WLAN is enabled; returns **false** otherwise.| **Example** @@ -96,8 +96,8 @@ Checks whether WLAN is enabled. import wifi from '@ohos.wifi'; try { - let isActivate = wifi.isActivate(); - console.info("isActivate:" + isActivate); + let isWifiActive = wifi.isWifiActive(); + console.info("isWifiActive:" + isWifiActive); }catch(error){ console.error("failed:" + JSON.stringify(error)); } @@ -115,9 +115,9 @@ Starts a scan for WLAN. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -143,9 +143,9 @@ Obtains the scan result. This API uses a promise to return the result. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | Promise< Array<[WifiScanInfo](#wifiscaninfo)> > | Promise used to return the detected hotspots.| +| **Type**| **Description**| +| -------- | -------- | +| Promise< Array<[WifiScanInfo](#wifiscaninfo)> > | Promise used to return the detected hotspots.| ## wifi.getScanInfos @@ -160,9 +160,9 @@ Obtains the scan result. This API uses an asynchronous callback to return the re **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback< Array<[WifiScanInfo](#wifiscaninfo)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the detected hotspots. Otherwise, **err** is a non-zero value and **data** is empty.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback< Array<[WifiScanInfo](#wifiscaninfo)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the detected hotspots. Otherwise, **err** is a non-zero value and **data** is empty.| **Example** @@ -258,15 +258,15 @@ Adds network configuration. This API uses a promise to return the result. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| **Return value** - | **Type**| **Description**| - | -------- | -------- | - | Promise<number> | Promise used to return the WLAN configuration ID. If **-1** is returned, the network configuration fails to be added.| +| **Type**| **Description**| +| -------- | -------- | +| Promise<number> | Promise used to return the WLAN configuration ID. If **-1** is returned, the network configuration fails to be added.| **Example** @@ -356,10 +356,10 @@ Adds network configuration. This API uses an asynchronous callback to return the **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| - | callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| +| callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| **Example** @@ -391,15 +391,15 @@ Adds the configuration of an untrusted network. This API uses a promise to retur **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| **Return value** - | **Type**| **Description**| - | -------- | -------- | - | Promise<boolean> | Promise used to return the result. If the operation is successful, **true** is returned; otherwise, **false** is returned.| +| **Type**| **Description**| +| -------- | -------- | +| Promise<boolean> | Promise used to return the result. If the operation is successful, **true** is returned; otherwise, **false** is returned.| **Example** ```js @@ -431,10 +431,10 @@ Adds the configuration of an untrusted network. This API uses an asynchronous ca **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| - | callback | AsyncCallback<boolean> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is **true**. If the operation fails, **data** is **false**. If **err** is not **0**, an error has occurred.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| +| callback | AsyncCallback<boolean> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is **true**. If the operation fails, **data** is **false**. If **err** is not **0**, an error has occurred.| **Example** ```js @@ -466,15 +466,15 @@ Removes the configuration of an untrusted network. This API uses a promise to re **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to remove.| **Return value** - | **Type**| **Description**| - | -------- | -------- | - | Promise<boolean> | Promise used to return the result. If the operation is successful, **true** is returned; otherwise, **false** is returned.| +| **Type**| **Description**| +| -------- | -------- | +| Promise<boolean> | Promise used to return the result. If the operation is successful, **true** is returned; otherwise, **false** is returned.| **Example** @@ -504,10 +504,10 @@ Removes the configuration of an untrusted network. This API uses an asynchronous **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to remove.| - | callback | AsyncCallback<boolean> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is **true**. If the operation fails, **data** is **false**. If **err** is not **0**, an error has occurred.| +| callback | AsyncCallback<boolean> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is **true**. If the operation fails, **data** is **false**. If **err** is not **0**, an error has occurred.| **Example** ```js @@ -537,15 +537,15 @@ Connects to the specified network. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | networkId | number | Yes| Network configuration ID.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| networkId | number | Yes| Network configuration ID.| **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -569,21 +569,21 @@ Connects to the specified network. **System API**: This is a system API. **Required permissions**: ohos.permission.SET_WIFI_INFO, ohos.permission.SET_WIFI_CONFIG, and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) - + **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration.| **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** ```js @@ -617,9 +617,9 @@ Disconnects the network. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** ```js @@ -644,16 +644,16 @@ Obtains the WLAN signal level. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | rssi | number | Yes| RSSI of the hotspot, in dBm.| - | band | number | Yes| Frequency band of the WLAN AP.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| rssi | number | Yes| RSSI of the hotspot, in dBm.| +| band | number | Yes| Frequency band of the WLAN AP.| **Return value** - | **Type**| **Description**| - | -------- | -------- | - | number | Signal level obtained. The value range is [0, 4].| +| **Type**| **Description**| +| -------- | -------- | +| number | Signal level obtained. The value range is [0, 4].| **Example** ```js @@ -682,9 +682,9 @@ Obtains WLAN connection information. This API uses a promise to return the resul **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[WifiLinkedInfo](#wifilinkedinfo)> | Promise used to return the WLAN connection information.| +| Type| Description| +| -------- | -------- | +| Promise<[WifiLinkedInfo](#wifilinkedinfo)> | Promise used to return the WLAN connection information.| ## wifi.getLinkedInfo @@ -699,9 +699,9 @@ Obtains WLAN connection information. This API uses an asynchronous callback to r **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[WifiLinkedInfo](#wifilinkedinfo)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the WLAN connection information obtained. If **err** is not **0**, an error has occurred.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[WifiLinkedInfo](#wifilinkedinfo)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the WLAN connection information obtained. If **err** is not **0**, an error has occurred.| **Example** ```js @@ -802,9 +802,9 @@ Checks whether the WLAN is connected. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the WLAN is connected; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the WLAN is connected; returns **false** otherwise.| ## wifi.getSupportedFeatures7+ @@ -821,9 +821,9 @@ Obtains the features supported by this device. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | number | Feature value. | +| **Type**| **Description**| +| -------- | -------- | +| number | Feature value. | **Feature IDs** @@ -854,15 +854,15 @@ Checks whether the device supports the specified WLAN feature. **Parameters** - | **Name**| **Type**| Mandatory| **Description**| - | -------- | -------- | -------- | -------- | - | featureId | number | Yes| Feature ID.| +| **Name**| **Type**| Mandatory| **Description**| +| -------- | -------- | -------- | -------- | +| featureId | number | Yes| Feature ID.| **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the feature is supported; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the feature is supported; returns **false** otherwise.| **Example** ```js @@ -892,9 +892,9 @@ Obtains the device MAC address. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | string[] | MAC address obtained.| +| **Type**| **Description**| +| -------- | -------- | +| string[] | MAC address obtained.| **Example** ```js @@ -921,9 +921,9 @@ Obtains IP information. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | [IpInfo](#ipinfo7) | IP information obtained.| +| **Type**| **Description**| +| -------- | -------- | +| [IpInfo](#ipinfo7) | IP information obtained.| **Example** ```js @@ -966,9 +966,9 @@ Obtains the country code. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | string | Country code obtained.| +| **Type**| **Description**| +| -------- | -------- | +| string | Country code obtained.| **Example** ```js @@ -996,9 +996,9 @@ Re-associates with the network. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** ```js @@ -1025,9 +1025,9 @@ Reconnects to the network. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** ```js @@ -1054,9 +1054,9 @@ Obtains network configuration. **Return value** - | **Type**| **Description**| - | -------- | -------- | - |  Array<[WifiDeviceConfig](#wifideviceconfig)> | Array of network configuration obtained.| +| **Type**| **Description**| +| -------- | -------- | +|  Array<[WifiDeviceConfig](#wifideviceconfig)> | Array of network configuration obtained.| **Example** ```js @@ -1084,15 +1084,15 @@ Updates network configuration. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| New WLAN configuration.| **Return value** - | **Type**| **Description**| - | -------- | -------- | - | number | ID of the updated network configuration. The value **-1** indicates that the operation has failed.| +| **Type**| **Description**| +| -------- | -------- | +| number | ID of the updated network configuration. The value **-1** indicates that the operation has failed.| **Example** ```js @@ -1125,15 +1125,15 @@ Disables network configuration. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | netId | number | Yes| ID of the network configuration to disable.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| netId | number | Yes| ID of the network configuration to disable.| **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** ```js @@ -1161,9 +1161,9 @@ Removes the configuration of all networks. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** ```js @@ -1190,15 +1190,15 @@ Removes the specified network configuration. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | | id | number | Yes| ID of the network configuration to remove.| **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** ```js @@ -1226,9 +1226,9 @@ Enables this hotspot. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** ```js @@ -1255,9 +1255,9 @@ Disables this hotspot. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** ```js @@ -1284,9 +1284,9 @@ Checks whether the hotspot supports dual band. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the feature is supported; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the feature is supported; returns **false** otherwise.| **Example** ```js @@ -1314,9 +1314,9 @@ Checks whether this hotspot is active. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the hotspot is active; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the hotspot is active; returns **false** otherwise.| **Example** ```js @@ -1344,15 +1344,15 @@ Sets hotspot configuration. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | config | [HotspotConfig](#hotspotconfig7) | Yes| Hotspot configuration to set.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| config | [HotspotConfig](#hotspotconfig7) | Yes| Hotspot configuration to set.| **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** ```js @@ -1405,9 +1405,9 @@ obtains hotspot configuration. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | [HotspotConfig](#hotspotconfig7) | Hotspot configuration obtained.| +| **Type**| **Description**| +| -------- | -------- | +| [HotspotConfig](#hotspotconfig7) | Hotspot configuration obtained.| **Example** ```js @@ -1435,9 +1435,9 @@ Obtains information about the connected stations. **Return value** - | **Type**| **Description**| - | -------- | -------- | - |  Array<[StationInfo](#stationinfo7)> | Connected stations obtained.| +| **Type**| **Description**| +| -------- | -------- | +|  Array<[StationInfo](#stationinfo7)> | Connected stations obtained.| **Example** ```js @@ -1478,9 +1478,9 @@ Obtains P2P link information. This API uses a promise to return the result. **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | Promise used to return the P2P link information obtained.| +| Type| Description| +| -------- | -------- | +| Promise<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | Promise used to return the P2P link information obtained.| @@ -1521,9 +1521,9 @@ Obtains P2P link information. This API uses an asynchronous callback to return t **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the P2P link information. If **err** is not **0**, an error has occurred.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the P2P link information. If **err** is not **0**, an error has occurred.| **Example** ```js @@ -1554,9 +1554,9 @@ Obtains the current P2P group information. This API uses a promise to return the **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> | Promise used to return the P2P group information obtained.| +| Type| Description| +| -------- | -------- | +| Promise<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> | Promise used to return the P2P group information obtained.| ## wifi.getCurrentGroup8+ @@ -1571,9 +1571,9 @@ Obtains the current P2P group information. This API uses an asynchronous callbac **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| **Example** ```js @@ -1604,9 +1604,9 @@ Obtains the peer device list in the P2P connection. This API uses a promise to r **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[WifiP2pDevice[]](#wifip2pdevice8)> | Promise used to return the peer device list.| +| Type| Description| +| -------- | -------- | +| Promise<[WifiP2pDevice[]](#wifip2pdevice8)> | Promise used to return the peer device list.| ## wifi.getP2pPeerDevices8+ @@ -1621,9 +1621,9 @@ Obtains the peer device list in the P2P connection. This API uses an asynchronou **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[WifiP2pDevice[]](#wifip2pdevice8)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the peer device list obtained. If **err** is not **0**, an error has occurred.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[WifiP2pDevice[]](#wifip2pdevice8)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the peer device list obtained. If **err** is not **0**, an error has occurred.| **Example** ```js @@ -1684,15 +1684,15 @@ Creates a P2P group. **Parameters** - | **Name**| **Type**| Mandatory| **Description**| - | -------- | -------- | -------- | -------- | - | config | [WifiP2PConfig](#wifip2pconfig8) | Yes| Group configuration.| +| **Name**| **Type**| Mandatory| **Description**| +| -------- | -------- | -------- | -------- | +| config | [WifiP2PConfig](#wifip2pconfig8) | Yes| Group configuration.| **Return value** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** ```js @@ -1753,9 +1753,9 @@ Removes this P2P group. **Return value** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** ```js @@ -1781,15 +1781,15 @@ Sets up a P2P connection. **Parameters** - | **Name**| **Type**| Mandatory| **Description**| - | -------- | -------- | -------- | -------- | - | config | [WifiP2PConfig](#wifip2pconfig8) | Yes| P2P group configuration.| +| **Name**| **Type**| Mandatory| **Description**| +| -------- | -------- | -------- | -------- | +| config | [WifiP2PConfig](#wifip2pconfig8) | Yes| P2P group configuration.| **Return value** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -1871,9 +1871,9 @@ Cancels this P2P connection. **Return value** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** ```js @@ -1898,9 +1898,9 @@ Starts to discover devices. **Return value** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** ```js @@ -1925,9 +1925,9 @@ Stops discovering devices. **Return value** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** ```js @@ -1955,15 +1955,15 @@ Deletes a persistent group. **Parameters** - | **Name**| **Type**| Mandatory| **Description**| - | -------- | -------- | -------- | -------- | - | netId | number | Yes| ID of the group to delete.| +| **Name**| **Type**| Mandatory| **Description**| +| -------- | -------- | -------- | -------- | +| netId | number | Yes| ID of the group to delete.| **Return value** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** ```js @@ -2010,15 +2010,15 @@ Sets the device name. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | devName | string | Yes| Device name to set.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| devName | string | Yes| Device name to set.| **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** ```js @@ -2044,10 +2044,10 @@ Registers the WLAN state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **wifiStateChange**.| - | callback | Callback<number> | Yes| Callback invoked to return the WLAN state.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **wifiStateChange**.| +| callback | Callback<number> | Yes| Callback invoked to return the WLAN state.| **WLAN states** @@ -2071,10 +2071,10 @@ Unregisters the WLAN state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **wifiStateChange**.| - | callback | Callback<number> | No| Callback for the WLAN state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **wifiStateChange**.| +| callback | Callback<number> | No| Callback for the WLAN state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Example** ```js @@ -2104,10 +2104,10 @@ Registers the WLAN connection state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **wifiConnectionChange**.| - | callback | Callback<number> | Yes| Callback invoked to return the WLAN connection state.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **wifiConnectionChange**.| +| callback | Callback<number> | Yes| Callback invoked to return the WLAN connection state.| **WLAN connection states** @@ -2129,10 +2129,10 @@ Unregisters the WLAN connection state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **wifiConnectionChange**.| - | callback | Callback<number> | No| Callback for the WLAN connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **wifiConnectionChange**.| +| callback | Callback<number> | No| Callback for the WLAN connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Example** ```js @@ -2161,10 +2161,10 @@ Registers the WLAN scan state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **wifiScanStateChange**.| - | callback | Callback<number> | Yes| Callback invoked to return the WLAN scan state.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **wifiScanStateChange**.| +| callback | Callback<number> | Yes| Callback invoked to return the WLAN scan state.| **WLAN scan states** @@ -2218,10 +2218,10 @@ Registers the RSSI change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **wifiRssiChange**.| - | callback | Callback<number> | Yes| Callback invoked to return the RSSI, in dBm.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **wifiRssiChange**.| +| callback | Callback<number> | Yes| Callback invoked to return the RSSI, in dBm.| ## wifi.off('wifiRssiChange')7+ @@ -2236,9 +2236,9 @@ Unregisters the RSSI change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **wifiRssiChange**.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **wifiRssiChange**.| | callback | Callback<number> | No| Callback for the RSSI. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Example** @@ -2254,7 +2254,58 @@ wifi.on("wifiRssiChange", recvWifiRssiChangeFunc); // Unregister an event. wifi.off("wifiRssiChange", recvWifiRssiChangeFunc); + +``` +## wifi.on('streamChange')7+ + +on(type: "streamChange", callback: Callback<number>): void + +Registers Wi-Fi stream changes. + +**Required permissions**: ohos.permission.MANAGE_WIFI_CONNECTION + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **streamChange**. | +| callback | Callback<number> | Yes| Callback invoked to return the Wi-Fi stream change, which can be any of the following values:
- **0**: No change.
- **1**: Downward.
- **2**: Upward.
- **3**: Bidirectional. | + +## wifi.off('streamChange')7+ + +off(type: "streamChange", callback: Callback<number>): void + +Unregisters Wi-Fi stream changes. + +**Required permissions**: ohos.permission.MANAGE_WIFI_CONNECTION + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **streamChange**. | +| callback | Callback<number> | Yes| Callback invoked to return the Wi-Fi stream change, which can be any of the following values:
- **0**: No change.
- **1**: Downward.
- **2**: Upward.
- **3**: Bidirectional. | + +**Example** +```js +import wifi from '@ohos.wifi'; + +var recvStreamChangeFunc = result => { + console.info("Receive stream change event: " + result); +} + +// Register an event. +wifi.on("streamChange", recvStreamChangeFunc); + +// Unregister an event. +wifi.off("streamChange", recvStreamChangeFunc); + ``` + ## wifi.on('hotspotStateChange')7+ on(type: "hotspotStateChange", callback: Callback<number>): void @@ -2267,10 +2318,10 @@ Registers the hotspot state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **hotspotStateChange**.| - | callback | Callback<number> | Yes| Callback invoked to return the hotspot state.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **hotspotStateChange**.| +| callback | Callback<number> | Yes| Callback invoked to return the hotspot state.| **Hotspot states** @@ -2308,11 +2359,110 @@ Unregisters the hotspot state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **hotspotStateChange**.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **hotspotStateChange**.| | callback | Callback<number> | No| Callback for the hotspot state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +## wifi.on('hotspotStaJoin')7+ + +on(type: "hotspotStaJoin", callback: Callback<StationInfo>): void + +Registers the connection of an STA to a Wi-Fi hotspot. + +**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **hotspotStaJoin**. | +| callback | Callback<StationInfo> | Yes| Callback invoked when an STA is connected to a Wi-Fi hotspot. | + +## wifi.off('hotspotStaJoin')7+ + +off(type: "hotspotStaJoin", callback: Callback<StationInfo>): void + +Unregisters the connection of an STA to a Wi-Fi hotspot. + +**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **hotspotStaJoin**. | +| callback | Callback<StationInfo> | Yes| Callback for the connection of an STA to a Wi-Fi hotspot. | + + **Example** +```js +import wifi from '@ohos.wifi'; + +var recvHotspotStaJoinFunc = result => { + console.info("Receive hotspot sta join event: " + result); +} + +// Register an event. +wifi.on("hotspotStaJoin", recvHotspotStaJoinFunc); + +// Unregister an event. +wifi.off("hotspotStaJoin", recvHotspotStaJoinFunc); + +``` + +## wifi.on('hotspotStaLeave')7+ + +on(type: "hotspotStaLeave", callback: Callback<StationInfo>): void + +Registers the disconnection of an STA from a Wi-Fi hotspot. + +**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **hotspotStaLeave**. | +| callback | Callback<StationInf]> | Yes| Callback invoked when an STA is disconnected from a Wi-Fi hotspot. | + +## wifi.off('hotspotStaLeave')7+ + +off(type: "hotspotStaLeave", callback: Callback<StationInfo>): void + +Unregisters the disconnection of an STA from a Wi-Fi hotspot. + +**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **hotspotStaLeave**. | +| callback | Callback<StationInf]> | Yes| Callback for the disconnection of an STA from a Wi-Fi hotspot. | + + **Example** +```js +import wifi from '@ohos.wifi'; + +var recvHotspotStaLeaveFunc = result => { + console.info("Receive hotspot sta leave event: " + result); +} + +// Register an event. +wifi.on("hotspotStaLeave", recvHotspotStaLeaveFunc); + +// Unregister an event. +wifi.off("hotspotStaLeave", recvHotspotStaLeaveFunc); + +``` ## wifi.on('p2pStateChange')8+ @@ -2326,10 +2476,10 @@ Registers the P2P state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pStateChange**.| - | callback | Callback<number> | Yes| Callback invoked to return the P2P state.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pStateChange**.| +| callback | Callback<number> | Yes| Callback invoked to return the P2P state.| **P2P states** @@ -2353,9 +2503,9 @@ Unregisters the P2P state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pStateChange**.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pStateChange**.| | callback | Callback<number> | No| Callback for the P2P state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Example** @@ -2373,7 +2523,7 @@ wifi.on("p2pStateChange", recvP2pStateChangeFunc); wifi.off("p2pStateChange", recvP2pStateChangeFunc); ``` - ## wifi.on('p2pConnectionChange')8+ +## wifi.on('p2pConnectionChange')8+ on(type: "p2pConnectionChange", callback: Callback<WifiP2pLinkedInfo>): void @@ -2385,10 +2535,10 @@ Registers the P2P connection state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pConnectionChange**.| - | callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | Yes| Callback invoked to return the P2P connection state.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pConnectionChange**.| +| callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | Yes| Callback invoked to return the P2P connection state.| ## wifi.off('p2pConnectionChange')8+ @@ -2403,9 +2553,9 @@ Unregisters the P2P connection state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pConnectionChange**.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pConnectionChange**.| | callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | No| Callback for the P2P connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Example** @@ -2435,10 +2585,10 @@ Registers the P2P device state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pDeviceChange**.| - | callback | Callback<[WifiP2pDevice](#wifip2pdevice8)> | Yes| Callback invoked to return the P2P device state.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pDeviceChange**.| +| callback | Callback<[WifiP2pDevice](#wifip2pdevice8)> | Yes| Callback invoked to return the P2P device state.| ## wifi.off('p2pDeviceChange')8+ @@ -2453,9 +2603,9 @@ Unregisters the P2P device state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pDeviceChange**.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pDeviceChange**.| | callback | Callback<[WifiP2pDevice](#wifip2pdevice8)> | No| Callback for the P2P device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Example** @@ -2463,7 +2613,7 @@ Unregisters the P2P device state change events. import wifi from '@ohos.wifi'; var recvP2pDeviceChangeFunc = result => { - console.info("Receive recv p2p device change event: " + result); + console.info("Receive p2p device change event: " + result); } // Register an event. @@ -2485,9 +2635,9 @@ Registers the P2P peer device state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| | callback | Callback<[WifiP2pDevice[]](#wifip2pdevice8)> | Yes| Callback invoked to return the P2P peer device state.| @@ -2503,9 +2653,9 @@ Unregisters the P2P peer device state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| | callback | Callback<[WifiP2pDevice[]](#wifip2pdevice8)> | No| Callback for the peer device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Example** @@ -2513,7 +2663,7 @@ Unregisters the P2P peer device state change events. import wifi from '@ohos.wifi'; var recvP2pPeerDeviceChangeFunc = result => { - console.info("Receive recv p2p peer device change event: " + result); + console.info("Receive p2p peer device change event: " + result); } // Register an event. @@ -2535,10 +2685,10 @@ Registers the P2P persistent group state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| - | callback | Callback<void> | Yes| Callback invoked to return the P2P persistent group state.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| +| callback | Callback<void> | Yes| Callback invoked to return the P2P persistent group state.| ## wifi.off('p2pPersistentGroupChange')8+ @@ -2553,9 +2703,9 @@ Unregisters the P2P persistent group state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| | callback | Callback<void> | No| Callback for the P2P persistent group state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Example** @@ -2563,7 +2713,7 @@ Unregisters the P2P persistent group state change events. import wifi from '@ohos.wifi'; var recvP2pPersistentGroupChangeFunc = result => { - console.info("Receive recv p2p persistent group change event: " + result); + console.info("Receive p2p persistent group change event: " + result); } // Register an event. @@ -2586,10 +2736,10 @@ Registers the P2P device discovery state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| - | callback | Callback<number> | Yes| Callback invoked to return the P2P device discovery state.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| +| callback | Callback<number> | Yes| Callback invoked to return the P2P device discovery state.| **P2P discovered device states** @@ -2611,9 +2761,9 @@ Unregisters the P2P device discovery state change events. **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| | callback | Callback<number> | No| Callback for the P2P device discovery state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Example** @@ -2621,7 +2771,7 @@ Unregisters the P2P device discovery state change events. import wifi from '@ohos.wifi'; var recvP2pDiscoveryChangeFunc = result => { - console.info("Receive recv p2p discovery change event: " + result); + console.info("Receive p2p discovery change event: " + result); } // Register an event. diff --git a/en/application-dev/reference/apis/js-apis-wifiManager.md b/en/application-dev/reference/apis/js-apis-wifiManager.md index 32a9a545a4785e4de3ab0a600c74cc23bc1f8e6d..3b5ccb266a60c098525e6690e1dce15e3c1e137b 100644 --- a/en/application-dev/reference/apis/js-apis-wifiManager.md +++ b/en/application-dev/reference/apis/js-apis-wifiManager.md @@ -11,11 +11,11 @@ The **WLAN** module provides basic wireless local area network (WLAN) functions, import wifiManager from '@ohos.wifiManager'; ``` -## wifi.enableWifi9+ +## wifiManager.enableWifi9+ 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. @@ -23,12 +23,6 @@ Enables WLAN. **System capability**: SystemCapability.Communication.WiFi.STA -**Return value** - - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). @@ -49,11 +43,11 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco } ``` -## wifi.disableWifi9+ +## wifiManager.disableWifi9+ 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. @@ -61,12 +55,6 @@ Disables WLAN. **System capability**: SystemCapability.Communication.WiFi.STA -**Return value** - - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). @@ -87,7 +75,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco } ``` -## wifi.isWifiActive9+ +## wifiManager.isWifiActive9+ isWifiActive(): boolean @@ -117,14 +105,14 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco import wifiManager from '@ohos.wifiManager'; try { - let isActivate = wifiManager.isActivate(); - console.info("isActivate:" + isActivate); + let isWifiActive = wifiManager.isWifiActive(); + console.info("isWifiActive:" + isWifiActive); }catch(error){ console.error("failed:" + JSON.stringify(error)); } ``` -## wifi.scan9+ +## wifiManager.scan9+ scan(): void @@ -134,11 +122,37 @@ Starts a scan for WLAN. **System capability**: SystemCapability.Communication.WiFi.STA -**Return value** +**Error codes** - | **Type**| **Description**| +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **ID**| **Error Message**| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| 2501000 | Operation failed.| + +**Example** + +```js + import wifiManager from '@ohos.wifiManager'; + + try { + wifiManager.scan(); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + +## wifiManager.startScan10+ + +startScan(): void + +**System API**: This is a system API. + +Starts a scan for WLAN. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION + +**System capability**: SystemCapability.Communication.WiFi.STA **Error codes** @@ -154,22 +168,164 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco import wifiManager from '@ohos.wifiManager'; try { - wifiManager.scan(); + wifiManager.startScan(); }catch(error){ console.error("failed:" + JSON.stringify(error)); } ``` +## wifiManager.getScanResults10+ -## wifi.getScanInfoList9+ +getScanResults(): Promise<Array<WifiScanInfo>> -getScanInfoList(): Array<WifiScanInfo>; +Obtains the scan result. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and (ohos.permission.GET_WIFI_PEERS_MAC or (ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION)) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + +| **Type**| **Description**| +| -------- | -------- | +| Promise< Array<[WifiScanInfo](#wifiscaninfo)> > | Promise used to return the Returns the hotspots detected.| + +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **ID**| **Error Message**| +| -------- | -------- | +| 2501000 | Operation failed.| + +## wifiManager.getScanResults10+ + +getScanResults(callback: AsyncCallback<Array<WifiScanInfo>>): void -Obtains the scan result. +Obtains the scan result. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.GET_WIFI_INFO and (ohos.permission.GET_WIFI_PEERS_MAC or (ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION)) **System capability**: SystemCapability.Communication.WiFi.STA +**Parameters** +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback< Array<[WifiScanInfo](#wifiscaninfo)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the detected hotspots. Otherwise, **err** is a non-zero value and **data** is empty.| + | Array<[WifiScanInfo](#wifiscaninfo)> | Returns the hotspots detected.| + +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **ID**| **Error Message**| +| -------- | -------- | +| 2501000 | Operation failed.| + +**Example** +```js + import wifiManager from '@ohos.wifiManager'; + + wifiManager.getScanResults((err, result) => { + if (err) { + console.error("get scan info error"); + return; + } + + var len = Object.keys(result).length; + console.log("wifi received scan info: " + len); + for (var i = 0; i < len; ++i) { + console.info("ssid: " + result[i].ssid); + console.info("bssid: " + result[i].bssid); + console.info("capabilities: " + result[i].capabilities); + console.info("securityType: " + result[i].securityType); + console.info("rssi: " + result[i].rssi); + console.info("band: " + result[i].band); + console.info("frequency: " + result[i].frequency); + console.info("channelWidth: " + result[i].channelWidth); + console.info("timestamp: " + result[i].timestamp); + } + }); + + wifiManager.getScanResults().then(result => { + var len = Object.keys(result).length; + console.log("wifi received scan info: " + len); + for (var i = 0; i < len; ++i) { + console.info("ssid: " + result[i].ssid); + console.info("bssid: " + result[i].bssid); + console.info("capabilities: " + result[i].capabilities); + console.info("securityType: " + result[i].securityType); + console.info("rssi: " + result[i].rssi); + console.info("band: " + result[i].band); + console.info("frequency: " + result[i].frequency); + console.info("channelWidth: " + result[i].channelWidth); + console.info("timestamp: " + result[i].timestamp); + } + }); +``` + +## wifiManager.getScanResultsSync10+ + +getScanResultsSync():  Array<[WifiScanInfo](#wifiscaninfo)> + +Obtains the scan result. This API returns the result synchronously. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and (ohos.permission.GET_WIFI_PEERS_MAC or (ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION)) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + +| **Type**| **Description**| +| -------- | -------- | +|  Array<[WifiScanInfo](#wifiscaninfo)> | Scan result obtained.| + +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **ID**| **Error Message**| + | -------- | -------- | +| 2501000 | Operation failed.| + +**Example** + +```js + import wifiManager from '@ohos.wifiManager'; + + try { + let scanInfoList = wifiManager.getScanResultsSync(); + console.info("scanInfoList:" + JSON.stringify(scanInfoList)); + let len = Object.keys(scanInfoList).length; + console.log("wifi received scan info: " + len); + if(len > 0){ + for (var i = 0; i < len; ++i) { + console.info("ssid: " + scanInfoList[i].ssid); + console.info("bssid: " + scanInfoList[i].bssid); + console.info("capabilities: " + scanInfoList[i].capabilities); + console.info("securityType: " + scanInfoList[i].securityType); + console.info("rssi: " + scanInfoList[i].rssi); + console.info("band: " + scanInfoList[i].band); + console.info("frequency: " + scanInfoList[i].frequency); + console.info("channelWidth: " + scanInfoList[i].channelWidth); + console.info("timestamp: " + scanInfoList[i].timestamp); + } + } + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } + +``` + +## wifiManager.getScanInfoList10+ + +getScanInfoList(): Array<WifiScanInfo>; + +Obtains the scanning result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + **Return value** | **Type**| **Description**| @@ -224,6 +380,7 @@ Represents WLAN hotspot information. | -------- | -------- | -------- | -------- | -------- | | ssid | string | Yes| No| Service set identifier (SSID) of the hotspot, in UTF-8 format.| | bssid | string | Yes| No| Basic service set identifier (BSSID) of the hotspot.| +| bssidType10+| DeviceAddressType | Yes| No| BSSID type of the hotspot.| | capabilities | string | Yes| No| Hotspot capabilities.| | securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| WLAN security type.| | rssi | number | Yes| No| Received signal strength indicator (RSSI) of the hotspot, in dBm.| @@ -235,6 +392,16 @@ Represents WLAN hotspot information. | infoElems | Array<[WifiInfoElem](#wifiinfoelem9)> | Yes| No| Information elements.| | timestamp | number | Yes| No| Timestamp.| +## DeviceAddressType 10+ + +Enumerates the Wi-Fi device address (MAC/BISSID) types. + +**System capability**: SystemCapability.Communication.WiFi.Core + +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| RANDOM_DEVICE_ADDRESS | 0 | Random device address.| +| REAL_DEVICE_ADDRESS | 1 | Read device address.| ## WifiSecurityType9+ @@ -317,7 +484,84 @@ Enumerates the WLAN channel widths. | WIDTH_80MHZ_PLUS | 4 | 80 MHz+| | WIDTH_INVALID | 5 | Invalid value| -## wifi.addDeviceConfig9+ +## wifiManager.setScanAlwaysAllowed10+ + +setScanAlwaysAllowed(isScanAlwaysAllowed: boolean): void + +Sets whether scan is always allowed. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.SET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| isScanAlwaysAllowed | boolean | Yes| Whether scan is always allowed.| + +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **ID**| **Error Message**| + | -------- | -------- | +| 2501000 | Operation failed.| + +```js + import wifiManager from '@ohos.wifiManager'; + + try { + let isScanAlwaysAllowed = true; + wifiManager.setScanAlwaysAllowed(isScanAlwaysAllowed); + }); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + +## wifiManager.getScanAlwaysAllowed10+ + +getScanAlwaysAllowed(): boolean + +Obtains whether scan is always allowed. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.SET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + +| **Type**| **Description**| +| -------- | -------- | +| boolean| Whether scan is always allowed. The value **true** means scan is allowed; the value **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **ID**| **Error Message**| + | -------- | -------- | +| 2501000 | Operation failed.| + +**Example** + +```js + import wifiManager from '@ohos.wifiManager'; + + try { + let isScanAlwaysAllowed = wifiManager.getScanAlwaysAllowed(); + console.info("isScanAlwaysAllowed:" + ret); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + +## wifiManager.addDeviceConfig9+ addDeviceConfig(config: WifiDeviceConfig): Promise<number> @@ -339,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** @@ -379,6 +623,7 @@ Represents the WLAN configuration. | -------- | -------- | -------- | -------- | -------- | | ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.| | bssid | string | Yes| No| BSSID of the hotspot.| +| bssidType10+ | DeviceAddressType | Yes| No| BSSID type of the hotspot.| | preSharedKey | string | Yes| No| PSK of the hotspot.| | isHiddenSsid | boolean | Yes| No| Whether the network is hidden.| | securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| Security type.| @@ -389,8 +634,8 @@ Represents the WLAN configuration. | randomMacAddr | string | Yes| No| Random MAC address.
**System API**: This is a system API.| | ipType | [IpType](#iptype9) | Yes| No| IP address type.
**System API**: This is a system API.| | staticIp | [IpConfig](#ipconfig9) | Yes| No| Static IP address configuration.
**System API**: This is a system API.| -| eapConfig9+ | [WifiEapConfig](#wifieapconfig9) | Yes| No| EAP configuration.
**System API**: This is a system API.| - +| eapConfig10+ | [WifiEapConfig](#wifieapconfig10) | Yes| No| EAP configuration.| +| proxyConfig10+ | WifiProxyConfig | Yes| No| Proxy configuration.
**System API**: This is a system API.| ## IpType9+ @@ -425,18 +670,16 @@ Represents IP configuration information. | domains | Array<string> | Yes| No| Domain information.| -## WifiEapConfig9+ +## WifiEapConfig10+ Represents EAP configuration information. -**System API**: This is a system API. - **System capability**: SystemCapability.Communication.WiFi.STA | **Name**| **Type**| **Readable**| **Writable**| **Description**| | -------- | -------- | -------- | -------- | -------- | -| eapMethod | [EapMethod](#eapmethod9) | Yes| No| EAP authentication method.| -| phase2Method | [Phase2Method](#phase2method9) | Yes| No| Phase 2 authentication method.| +| eapMethod | [EapMethod](#eapmethod10) | Yes| No| EAP authentication method.| +| phase2Method | [Phase2Method](#phase2method10) | Yes| No| Phase 2 authentication method.| | identity | string | Yes| No| Identity Information.| | anonymousIdentity | string | Yes| No| Anonymous identity.| | password | string | Yes| No| Password.| @@ -452,12 +695,10 @@ Represents EAP configuration information. | eapSubId | number | Yes| No| Sub-ID of the SIM card.| -## EapMethod9+ +## EapMethod10+ Enumerates the EAP authentication methods. -**System API**: This is a system API. - **System capability**: SystemCapability.Communication.WiFi.STA | Name| Value| Description| @@ -473,12 +714,10 @@ Enumerates the EAP authentication methods. | EAP_UNAUTH_TLS | 8 | UNAUTH TLS.| -## Phase2Method9+ +## Phase2Method10+ Enumerates the Phase 2 authentication methods. -**System API**: This is a system API. - **System capability**: SystemCapability.Communication.WiFi.STA | Name| Value| Description| @@ -493,7 +732,37 @@ Enumerates the Phase 2 authentication methods. | PHASE2_AKA_PRIME | 7 | AKA Prime.| -## wifi.addDeviceConfig9+ +## WifiProxyConfig 10+ + +Represents the Wi-Fi proxy configuration. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| proxyMethod | ProxyMethod | Yes| No| Proxy method.| +| pacWebAddress | string | Yes| No| PAC web address of the proxy automatically configured.| +| serverHostName | string | Yes| No| Server host name of the proxy manually configured.| +| serverPort | string | Yes| No| Server port of the proxy manually configured.| +| exclusionObjects | string | Yes| No| Excluded objects of the manually configured proxy. Multiple objects are separated by commas (,).| + +## ProxyMethod10+ + +Enumerates the Wi-Fi proxy methods. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| Name| Value| Description| +| -------- | -------- | -------- | +| METHOD_NONE | 0 | No proxy.| +| METHOD_AUTO | 1 | Use an automatically configured proxy.| +| METHOD_MANUAL | 2 | Use a manually configured proxy.| + +## wifiManager.addDeviceConfig9+ addDeviceConfig(config: WifiDeviceConfig, callback: AsyncCallback<number>): void @@ -539,7 +808,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco } ``` -## wifi.addCandidateConfig9+ +## wifiManager.addCandidateConfig9+ addCandidateConfig(config: WifiDeviceConfig): Promise<number> @@ -587,7 +856,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco } ````` -## wifi.addCandidateConfig9+ +## wifiManager.addCandidateConfig9+ addCandidateConfig(config: WifiDeviceConfig, callback: AsyncCallback<number>): void @@ -630,7 +899,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco } ````` -## wifi.removeCandidateConfig9+ +## wifiManager.removeCandidateConfig9+ removeCandidateConfig(networkId: number): Promise<void> @@ -675,7 +944,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco } ``` -## wifi.removeCandidateConfig9+ +## wifiManager.removeCandidateConfig9+ removeCandidateConfig(networkId: number, callback: AsyncCallback<void>): void @@ -690,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** @@ -714,7 +983,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco } ``` -## wifi.getCandidateConfigs9+ +## wifiManager.getCandidateConfigs9+ getCandidateConfigs():  Array<[WifiDeviceConfig](#wifideviceconfig)> @@ -760,7 +1029,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ````` -## wifi.connectToCandidateConfig9+ +## wifiManager.connectToCandidateConfig9+ connectToCandidateConfig(networkId: number): void @@ -799,7 +1068,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ``` -## wifi.connectToNetwork9+ +## wifiManager.connectToNetwork9+ connectToNetwork(networkId: number): void @@ -839,7 +1108,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco } ``` -## wifi.connectToDevice9+ +## wifiManager.connectToDevice9+ connectToDevice(config: WifiDeviceConfig): void @@ -884,7 +1153,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco } ``` -## wifi.disconnect9+ +## wifiManager.disconnect9+ disconnect(): void @@ -916,7 +1185,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco } ``` -## wifi.getSignalLevel9+ +## wifiManager.getSignalLevel9+ getSignalLevel(rssi: number, band: number): number @@ -962,7 +1231,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ``` -## wifi.getLinkedInfo9+ +## wifiManager.getLinkedInfo9+ getLinkedInfo(): Promise<WifiLinkedInfo> @@ -987,7 +1256,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco | 2501000 | Operation failed.| | 2501001 | Wifi is closed.| -## wifi.getLinkedInfo9+ +## wifiManager.getLinkedInfo9+ getLinkedInfo(callback: AsyncCallback<WifiLinkedInfo>): void @@ -1103,7 +1372,7 @@ Enumerates the supplicant states. | UNINITIALIZED | 10 | The supplicant failed to set up the connection.| | INVALID | 11 | Invalid value.| -## wifi.isConnected9+ +## wifiManager.isConnected9+ isConnected(): boolean @@ -1140,7 +1409,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ``` -## wifi.getSupportedFeatures9+ +## wifiManager.getSupportedFeatures9+ getSupportedFeatures(): number @@ -1194,7 +1463,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ``` -## wifi.isFeatureSupported9+ +## wifiManager.isFeatureSupported9+ isFeatureSupported(featureId: number): boolean @@ -1239,7 +1508,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ``` -## wifi.getDeviceMacAddress9+ +## wifiManager.getDeviceMacAddress9+ getDeviceMacAddress(): string[] @@ -1278,7 +1547,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ``` -## wifi.getIpInfo9+ +## wifiManager.getIpInfo9+ getIpInfo(): IpInfo @@ -1331,7 +1600,59 @@ Represents IP information. | leaseDuration | number | Yes| No| Lease duration of the IP address.| -## wifi.getCountryCode9+ +## wifiManager.getIpv6Info10+ + +getIpv6Info(): Ipv6Info + +Obtains IP information. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + +| **Type**| **Description**| +| -------- | -------- | +| Ipv6Info | IPv6 information obtained.| + +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **ID**| **Error Message**| + | -------- | -------- | +| 2501000 | Operation failed.| + +**Example** +```js + import wifiManager from '@ohos.wifiManager'; + + try { + let info = wifiManager.getIpv6Info(); + console.info("info:" + JSON.stringify(info)); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` +## Ipv6Info 10+ + +Represents the IPv6 information. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| linkIpv6Address | string | Yes| No| IPv6 address of the link.| +| globalIpv6Address | string | Yes| No| Global IPv6 address.| +| randomGlobalIpv6Address | number | Yes| No| Random global IPv6 address.| +| gateway | string | Yes| No| Gateway IP address.| +| netmask | string | Yes| No| Subnet mask.| +| primaryDNS | string | Yes| No| IPv6 address of the preferred DNS server.| +| secondDNS | string | Yes| No| IPv6 address of the alternate DNS server.| + + +## wifiManager.getCountryCode9+ getCountryCode(): string @@ -1367,7 +1688,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco } ``` -## wifi.reassociate9+ +## wifiManager.reassociate9+ reassociate(): void @@ -1399,7 +1720,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco } ``` -## wifi.reconnect9+ +## wifiManager.reconnect9+ reconnect(): void @@ -1431,7 +1752,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco } ``` -## wifi.getDeviceConfigs9+ +## wifiManager.getDeviceConfigs9+ getDeviceConfigs():  Array<[WifiDeviceConfig](#wifideviceconfig)> @@ -1469,9 +1790,9 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco } ``` -## wifi.updateDeviceConfig9+ +## wifiManager.updateNetwork9+ -updateDeviceConfig(config: WifiDeviceConfig): number +updateNetwork(config: WifiDeviceConfig): number Updates network configuration. @@ -1511,16 +1832,16 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco preSharedKey : "****", securityType : 3 } - let ret = wifiManager.updateDeviceConfig(config); + let ret = wifiManager.updateNetwork(config); console.error("ret:" + ret); }catch(error){ console.error("failed:" + JSON.stringify(error)); } ``` -## wifi.disableDeviceConfig9+ +## wifiManager.disableNetwork9+ -disableDeviceConfig(networkId: number): void +disableNetwork(networkId: number): void Disables network configuration. @@ -1550,15 +1871,15 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco try { let netId = 0; - wifiManager.disableDeviceConfig(netId); + wifiManager.disableNetwork(netId); }catch(error){ console.error("failed:" + JSON.stringify(error)); } ``` -## wifi.removeAllDeviceConfigs9+ +## wifiManager.removeAllNetwork9+ -removeAllDeviceConfigs(): void +removeAllNetwork(): void Removes the configuration of all networks. @@ -1581,15 +1902,15 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco import wifiManager from '@ohos.wifiManager'; try { - wifiManager.removeAllDeviceConfigs(); + wifiManager.removeAllNetwork(); }catch(error){ console.error("failed:" + JSON.stringify(error)); } ``` -## wifi.removeDeviceConfig9+ +## wifiManager.removeDevice9+ -removeDeviceConfig(networkId: number): void +removeDevice(networkId: number): void Removes the specified network configuration. @@ -1619,13 +1940,13 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco try { let id = 0; - wifiManager.removeDeviceConfig(id); + wifiManager.removeDevice(id); }catch(error){ console.error("failed:" + JSON.stringify(error)); } ``` -## wifi.isBandTypeSupported10+ +## wifiManager.isBandTypeSupported10+ isBandTypeSupported(bandType: WifiBandType): boolean @@ -1641,6 +1962,12 @@ Checks whether the current frequency band is supported. | -------- | -------- | -------- | -------- | | bandType | WifiBandType | Yes| Wi-Fi band type.| +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the feature is supported; returns **false** otherwise.| + **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). @@ -1662,7 +1989,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco } ``` -## wifi.get5GChannelList10+ +## wifiManager.get5GChannelList10+ get5GChannelList(): Array<number> @@ -1674,6 +2001,12 @@ Obtains the list of 5 GHz channels supported by this device. **System capability**: SystemCapability.Communication.WiFi.STA +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + |  Array<number> | List of 5 GHz channels supported by the device.| + **Error codes** For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). @@ -1693,7 +2026,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco console.error("failed:" + JSON.stringify(error)); } ``` -## wifi.getDisconnectedReason10+ +## wifiManager.getDisconnectedReason10+ getDisconnectedReason(): DisconnectedReason @@ -1745,11 +2078,11 @@ Enumerates the Wi-Fi disconnection reasons. | DISC_REASON_WRONG_PWD | 1 | Incorrect password.| | DISC_REASON_CONNECTION_FULL | 2 | The number of connections to the router has reached the limit.| -## wifi.enableHotspot9+ +## wifiManager.enableHotspot9+ 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. @@ -1776,11 +2109,11 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco } ``` -## wifi.disableHotspot9+ +## wifiManager.disableHotspot9+ 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. @@ -1807,7 +2140,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco } ``` -## wifi.isHotspotDualBandSupported9+ +## wifiManager.isHotspotDualBandSupported9+ isHotspotDualBandSupported(): boolean @@ -1845,7 +2178,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco } ``` -## wifi.isHotspotActive9+ +## wifiManager.isHotspotActive9+ isHotspotActive(): boolean @@ -1883,7 +2216,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco } ``` -## wifi.setHotspotConfig9+ +## wifiManager.setHotspotConfig9+ setHotspotConfig(config: HotspotConfig): void @@ -1946,7 +2279,7 @@ Represents the hotspot configuration. | preSharedKey | string | Yes| Yes| PSK of the hotspot.| | maxConn | number | Yes| Yes| Maximum number of connections allowed.| -## wifi.getHotspotConfig9+ +## wifiManager.getHotspotConfig9+ getHotspotConfig(): HotspotConfig @@ -1984,9 +2317,9 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco } ``` -## wifi.getHotspotStations9+ +## wifiManager.getStations9+ -getHotspotStations():  Array<[StationInfo](#stationinfo9)> +getStations():  Array<[StationInfo](#stationinfo9)> Obtains information about the connected stations. @@ -2015,7 +2348,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco import wifiManager from '@ohos.wifiManager'; try { - let stations = wifiManager.getHotspotStations(); + let stations = wifiManager.getStations(); console.info("result:" + JSON.stringify(stations)); }catch(error){ console.error("failed:" + JSON.stringify(error)); @@ -2034,10 +2367,11 @@ Represents the station information. | -------- | -------- | -------- | -------- | -------- | | name | string | Yes| No| Device name.| | macAddress | string | Yes| No| MAC address.| +| macAddressType10+ | DeviceAddressType | Yes| No| MAC address type.| | ipAddress | string | Yes| No| IP address.| -## wifi.getP2pLinkedInfo9+ +## wifiManager.getP2pLinkedInfo9+ getP2pLinkedInfo(): Promise<WifiP2pLinkedInfo> @@ -2104,7 +2438,7 @@ Enumerates the P2P connection states. | CONNECTED | 1 | Connected.| -## wifi.getP2pLinkedInfo9+ +## wifiManager.getP2pLinkedInfo9+ getP2pLinkedInfo(callback: AsyncCallback<WifiP2pLinkedInfo>): void @@ -2121,7 +2455,7 @@ Obtains P2P link information. This API uses an asynchronous callback to return t | callback | AsyncCallback<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the P2P link information. If **err** is not **0**, an error has occurred.| -## wifi.getCurrentP2pGroup9+ +## wifiManager.getCurrentP2pGroup9+ getCurrentP2pGroup(): Promise<WifiP2pGroupInfo> @@ -2145,7 +2479,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco | -------- | -------- | | 2801000 | Operation failed.| -## wifi.getCurrentP2pGroup9+ +## wifiManager.getCurrentP2pGroup9+ getCurrentP2pGroup(callback: AsyncCallback<WifiP2pGroupInfo>): void @@ -2186,7 +2520,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco }); ``` -## wifi.getP2pPeerDevices9+ +## wifiManager.getP2pPeerDevices9+ getP2pPeerDevices(): Promise<WifiP2pDevice[]> @@ -2210,7 +2544,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco | -------- | -------- | | 2801000 | Operation failed.| -## wifi.getP2pPeerDevices9+ +## wifiManager.getP2pPeerDevices9+ getP2pPeerDevices(callback: AsyncCallback<WifiP2pDevice[]>): void @@ -2261,6 +2595,7 @@ Represents the P2P device information. | -------- | -------- | -------- | -------- | -------- | | deviceName | string | Yes| No| Device name.| | deviceAddress | string | Yes| No| MAC address of the device.| +| deviceAddressType10+ | DeviceAddressType | Yes| No| MAC address type of the device.| | primaryDeviceType | string | Yes| No| Type of the primary device.| | deviceStatus | [P2pDeviceStatus](#p2pdevicestatus9) | Yes| No| Device status.| | groupCapabilities | number | Yes| No| Group capabilities.| @@ -2281,7 +2616,7 @@ Enumerates the P2P device states. | UNAVAILABLE | 4 | Unavailable.| -## wifi.getP2pLocalDevice9+ +## wifiManager.getP2pLocalDevice9+ getP2pLocalDevice(): Promise<WifiP2pDevice> @@ -2305,7 +2640,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco | -------- | -------- | | 2801000 | Operation failed.| -## wifi.getP2pLocalDevice9+ +## wifiManager.getP2pLocalDevice9+ getP2pLocalDevice(callback: AsyncCallback<WifiP2pDevice>): void @@ -2344,9 +2679,9 @@ Obtains the local device information in the P2P connection. This API uses an asy }); ``` -## wifi.createP2pGroup9+ +## wifiManager.createGroup9+ -createP2pGroup(config: WifiP2PConfig): void +createGroup(config: WifiP2PConfig): void Creates a P2P group. @@ -2380,7 +2715,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco groupName: "****", goBand: 0 } - wifiManager.createP2pGroup(config); + wifiManager.createGroup(config); }catch(error){ console.error("failed:" + JSON.stringify(error)); @@ -2396,6 +2731,7 @@ Represents P2P group configuration. | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | deviceAddress | string | Yes| No| Device address.| +| deviceAddressType10+| DeviceAddressType | Yes| No| Device address type.| | netId | number | Yes| No| Network ID. The value **-1** indicates a temporary group, and **-2** indicates a persistent group.| | passphrase | string | Yes| No| Passphrase of the group.| | groupName | string | Yes| No| Name of the group.| @@ -2415,9 +2751,9 @@ Enumerates the P2P group frequency bands. | GO_BAND_5GHZ | 2 | 5 GHz.| -## wifi.removeP2pGroup9+ +## wifiManager.removeGroup9+ -removeP2pGroup(): void +removeGroup(): void Removes this P2P group. @@ -2438,13 +2774,13 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco import wifiManager from '@ohos.wifiManager'; try { - wifiManager.removeP2pGroup(); + wifiManager.removeGroup(); }catch(error){ console.error("failed:" + JSON.stringify(error)); } ``` -## wifi.p2pConnect9+ +## wifiManager.p2pConnect9+ p2pConnect(config: WifiP2PConfig): void @@ -2535,7 +2871,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco console.info("start discover devices -> " + wifiManager.startDiscoverP2pDevices()); ``` -## wifi.p2pCancelConnect9+ +## wifiManager.p2pCancelConnect9+ p2pCancelConnect(): void @@ -2564,9 +2900,9 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco } ``` -## wifi.startDiscoverP2pDevices9+ +## wifiManager.startDiscoverDevices10+ -startDiscoverP2pDevices(): void +startDiscoverDevices(): void Starts to discover devices. @@ -2587,15 +2923,15 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco import wifiManager from '@ohos.wifiManager'; try { - wifiManager.startDiscoverP2pDevices(); + wifiManager.startDiscoverDevices(); }catch(error){ console.error("failed:" + JSON.stringify(error)); } ``` -## wifi.stopDiscoverP2pDevices9+ +## wifiManager.stopDiscoverDevices10+ -stopDiscoverP2pDevices(): void +stopDiscoverDevices(): void Stops discovering devices. @@ -2616,15 +2952,15 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco import wifiManager from '@ohos.wifiManager'; try { - wifiManager.stopDiscoverP2pDevices(); + wifiManager.stopDiscoverDevices(); }catch(error){ console.error("failed:" + JSON.stringify(error)); } ``` -## wifi.deletePersistentP2pGroup9+ +## wifiManager.deletePersistentGroup9+ -deletePersistentP2pGroup(netId: number): void +deletePersistentGroup(netId: number): void Deletes a persistent group. @@ -2655,13 +2991,13 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco try { let netId = 0; - wifiManager.deletePersistentP2pGroup(netId); + wifiManager.deletePersistentGroup(netId); }catch(error){ console.error("failed:" + JSON.stringify(error)); } ``` -## wifi.getP2pGroups9+ +## wifiManager.getP2pGroups9+ getP2pGroups(): Promise<Array<WifiP2pGroupInfo>> @@ -2724,7 +3060,7 @@ Represents the P2P group information. | goIpAddress | string | Yes| No| IP address of the group.| -## wifi.getP2pGroups9+ +## wifiManager.getP2pGroups9+ getP2pGroups(callback: AsyncCallback<Array<WifiP2pGroupInfo>>): void @@ -2750,9 +3086,9 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco | -------- | -------- | | 2801000 | Operation failed.| -## wifi.setP2pDeviceName9+ +## wifiManager.setDeviceName9+ -setP2pDeviceName(devName: string): void +setDeviceName(devName: string): void Sets the device name. @@ -2782,13 +3118,13 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco try { let name = "****"; - wifiManager.setP2pDeviceName(name); + wifiManager.setDeviceName(name); }catch(error){ console.error("failed:" + JSON.stringify(error)); } ``` -## wifi.on('wifiStateChange')9+ +## wifiManager.on('wifiStateChange')9+ on(type: "wifiStateChange", callback: Callback<number>): void @@ -2823,7 +3159,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco | 3 | Deactivating| -## wifi.off('wifiStateChange')9+ +## wifiManager.off('wifiStateChange')9+ off(type: "wifiStateChange", callback?: Callback<number>): void @@ -2864,7 +3200,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ``` -## wifi.on('wifiConnectionChange')9+ +## wifiManager.on('wifiConnectionChange')9+ on(type: "wifiConnectionChange", callback: Callback<number>): void @@ -2896,7 +3232,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco | -------- | -------- | | 2501000 | Operation failed.| -## wifi.off('wifiConnectionChange')9+ +## wifiManager.off('wifiConnectionChange')9+ off(type: "wifiConnectionChange", callback?: Callback<number>): void @@ -2936,7 +3272,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco wifiManager.off("wifiConnectionChange", recvWifiConnectionChangeFunc); ``` -## wifi.on('wifiScanStateChange')9+ +## wifiManager.on('wifiScanStateChange')9+ on(type: "wifiScanStateChange", callback: Callback<number>): void @@ -2968,7 +3304,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco | -------- | -------- | | 2501000 | Operation failed.| -## wifi.off('wifiScanStateChange')9+ +## wifiManager.off('wifiScanStateChange')9+ off(type: "wifiScanStateChange", callback?: Callback<number>): void @@ -3008,7 +3344,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco wifiManager.off("wifiScanStateChange", recvWifiScanStateChangeFunc); ``` -## wifi.on('wifiRssiChange')9+ +## wifiManager.on('wifiRssiChange')9+ on(type: "wifiRssiChange", callback: Callback<number>): void @@ -3033,7 +3369,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco | -------- | -------- | | 2501000 | Operation failed.| -## wifi.off('wifiRssiChange')9+ +## wifiManager.off('wifiRssiChange')9+ off(type: "wifiRssiChange", callback?: Callback<number>): void @@ -3073,7 +3409,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco wifiManager.off("wifiRssiChange", recvWifiRssiChangeFunc); ``` -## wifi.on('hotspotStateChange')9+ +## wifiManager.on('hotspotStateChange')9+ on(type: "hotspotStateChange", callback: Callback<number>): void @@ -3107,7 +3443,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco | -------- | -------- | | 2601000 | Operation failed.| -## wifi.off('hotspotStateChange')9+ +## wifiManager.off('hotspotStateChange')9+ off(type: "hotspotStateChange", callback?: Callback<number>): void @@ -3147,7 +3483,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco wifiManager.off("hotspotStateChange", recvHotspotStateChangeFunc); ``` -## wifi.on('p2pStateChange')9+ +## wifiManager.on('p2pStateChange')9+ on(type: "p2pStateChange", callback: Callback<number>): void @@ -3182,7 +3518,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco | -------- | -------- | | 2801000 | Operation failed.| -## wifi.off('p2pStateChange')9+ +## wifiManager.off('p2pStateChange')9+ off(type: "p2pStateChange", callback?: Callback<number>): void @@ -3222,7 +3558,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco wifiManager.off("p2pStateChange", recvP2pStateChangeFunc); ``` -## wifi.on('p2pConnectionChange')9+ +## wifiManager.on('p2pConnectionChange')9+ on(type: "p2pConnectionChange", callback: Callback<WifiP2pLinkedInfo>): void @@ -3247,7 +3583,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco | -------- | -------- | | 2801000 | Operation failed.| -## wifi.off('p2pConnectionChange')9+ +## wifiManager.off('p2pConnectionChange')9+ off(type: "p2pConnectionChange", callback?: Callback<WifiP2pLinkedInfo>): void @@ -3287,7 +3623,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco wifiManager.off("p2pConnectionChange", recvP2pConnectionChangeFunc); ``` -## wifi.on('p2pDeviceChange')9+ +## wifiManager.on('p2pDeviceChange')9+ on(type: "p2pDeviceChange", callback: Callback<WifiP2pDevice>): void @@ -3312,7 +3648,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco | -------- | -------- | | 2801000 | Operation failed.| -## wifi.off('p2pDeviceChange')9+ +## wifiManager.off('p2pDeviceChange')9+ off(type: "p2pDeviceChange", callback?: Callback<WifiP2pDevice>): void @@ -3342,7 +3678,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco import wifiManager from '@ohos.wifiManager'; var recvP2pDeviceChangeFunc = result => { - console.info("Receive recv p2p device change event: " + result); + console.info("Receive p2p device change event: " + result); } // Register an event. @@ -3352,7 +3688,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco wifiManager.off("p2pDeviceChange", recvP2pDeviceChangeFunc); ``` -## wifi.on('p2pPeerDeviceChange')9+ +## wifiManager.on('p2pPeerDeviceChange')9+ on(type: "p2pPeerDeviceChange", callback: Callback<WifiP2pDevice[]>): void @@ -3377,7 +3713,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco | -------- | -------- | | 2801000 | Operation failed.| -## wifi.off('p2pPeerDeviceChange')9+ +## wifiManager.off('p2pPeerDeviceChange')9+ off(type: "p2pPeerDeviceChange", callback?: Callback<WifiP2pDevice[]>): void @@ -3407,7 +3743,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco import wifiManager from '@ohos.wifiManager'; var recvP2pPeerDeviceChangeFunc = result => { - console.info("Receive recv p2p peer device change event: " + result); + console.info("Receive p2p peer device change event: " + result); } // Register an event. @@ -3417,7 +3753,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco wifiManager.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); ``` -## wifi.on('p2pPersistentGroupChange')9+ +## wifiManager.on('p2pPersistentGroupChange')9 on(type: "p2pPersistentGroupChange", callback: Callback<void>): void @@ -3442,7 +3778,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco | -------- | -------- | | 2801000 | Operation failed.| -## wifi.off('p2pPersistentGroupChange')9+ +## wifiManager.off('p2pPersistentGroupChange')9 off(type: "p2pPersistentGroupChange", callback?: Callback<void>): void @@ -3472,7 +3808,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco import wifiManager from '@ohos.wifiManager'; var recvP2pPersistentGroupChangeFunc = result => { - console.info("Receive recv p2p persistent group change event: " + result); + console.info("Receive p2p persistent group change event: " + result); } // Register an event. @@ -3482,7 +3818,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco wifiManager.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); ``` -## wifi.on('p2pDiscoveryChange')9+ +## wifiManager.on('p2pDiscoveryChange')9+ on(type: "p2pDiscoveryChange", callback: Callback<number>): void @@ -3514,7 +3850,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco | -------- | -------- | | 2801000 | Operation failed.| -## wifi.off('p2pDiscoveryChange')9+ +## wifiManager.off('p2pDiscoveryChange')9+ off(type: "p2pDiscoveryChange", callback?: Callback<number>): void @@ -3544,7 +3880,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco import wifiManager from '@ohos.wifiManager'; var recvP2pDiscoveryChangeFunc = result => { - console.info("Receive recv p2p discovery change event: " + result); + console.info("Receive p2p discovery change event: " + result); } // Register an event. diff --git a/en/application-dev/reference/apis/js-apis-window.md b/en/application-dev/reference/apis/js-apis-window.md index 83ba617046bba8de2547b82015dbfee8ce9be0a7..13edbc7a924ff1e0b5ad8ef7f3f6f2720eb49de2 100644 --- a/en/application-dev/reference/apis/js-apis-window.md +++ b/en/application-dev/reference/apis/js-apis-window.md @@ -859,6 +859,15 @@ Subscribes to the gesture navigation status change event. | type | string | Yes | Event type. The value is fixed at **'gestureNavigationEnabledChange'**, indicating the gesture navigation status change event. | | callback | Callback<boolean> | Yes | Callback used to return the gesture navigation status. The value **true** means that the gesture navigation status is changed to enabled, and **false** means that the gesture navigation status is changed to disabled.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + **Example** ```js @@ -888,6 +897,15 @@ Unsubscribes from the gesture navigation status change event. | type | string | Yes| Event type. The value is fixed at **'gestureNavigationEnabledChange'**, indicating the gesture navigation status change event.| | callback | Callback<boolean> | No| Callback function that has been used for registering the listener. If a value is passed in, the corresponding subscription is canceled. If no value is passed in, all subscriptions to the specified event are canceled.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + **Example** ```js @@ -2744,7 +2762,7 @@ try { ### on('avoidAreaChange')9+ -on(type: 'avoidAreaChange', callback: Callback<{AvoidAreaType, AvoidArea}>): void +on(type: 'avoidAreaChange', callback: Callback<{ type: AvoidAreaType, area: AvoidArea}>): void Subscribes to the event indicating changes to the area where the window cannot be displayed. @@ -2755,7 +2773,7 @@ Subscribes to the event indicating changes to the area where the window cannot b | Name | Type | Mandatory| Description | | -------- |------------------------------------------------------------------| ---- |--------------------------------------| | type | string | Yes | Event type. The value is fixed at **'avoidAreaChange'**, indicating the event of changes to the area where the window cannot be displayed.| -| callback | Callback<{[AvoidAreaType](#avoidareatype7), [AvoidArea](#avoidarea7)}> | Yes | Callback used to return the area and area type.| +| callback | Callback<{ type: [AvoidAreaType](#avoidareatype7), area: [AvoidArea](#avoidarea7) }> | Yes | Callback used to return the area and area type.| **Example** @@ -2772,7 +2790,7 @@ try { ### off('avoidAreaChange')9+ -off(type: 'avoidAreaChange', callback?: Callback<{AvoidAreaType, AvoidArea}>): void +off(type: 'avoidAreaChange', callback?: Callback<{ type: AvoidAreaType, area: AvoidArea }>): void Unsubscribes from the event indicating changes to the area where the window cannot be displayed. @@ -2783,7 +2801,7 @@ Unsubscribes from the event indicating changes to the area where the window cann | Name | Type | Mandatory | Description | | -------- |-----------------------------------------------------------------------------|-----|------------------------------------| | type | string | Yes | Event type. The value is fixed at **'avoidAreaChange'**, indicating the event of changes to the area where the window cannot be displayed.| -| callback | Callback<{[AvoidAreaType](#avoidareatype7), [AvoidArea](#avoidarea7)}> | No | Callback used to return the area and area type. If a value is passed in, the corresponding subscription is canceled. If no value is passed in, all subscriptions to the specified event are canceled.| +| callback | Callback<{ type: [AvoidAreaType](#avoidareatype7), area: [AvoidArea](#avoidarea7) }> | No | Callback used to return the area and area type. If a value is passed in, the corresponding subscription is canceled. If no value is passed in, all subscriptions to the specified event are canceled.| **Example** @@ -3122,7 +3140,16 @@ class TestRemoteObject extends rpc.RemoteObject { } let token = new TestRemoteObject('testObject'); +let windowClass = null; +let config = {name: "dialogWindow", windowType: window.WindowType.TYPE_DIALOG, ctx: this.context}; try { + window.createWindow(config, (err, data) => { + if (err.code) { + console.error('Failed to create the window. Cause: ' + JSON.stringify(err)); + return; + } + windowClass = data; + }); windowClass.bindDialogTarget(token, () => { console.info('Dialog Window Need Destroy.'); }, (err) => { @@ -3195,7 +3222,16 @@ class TestRemoteObject extends rpc.RemoteObject { } let token = new TestRemoteObject('testObject'); +let windowClass = null; +let config = {name: "dialogWindow", windowType: window.WindowType.TYPE_DIALOG, ctx: this.context}; try { + window.createWindow(config, (err, data) => { + if (err.code) { + console.error('Failed to create the window. Cause: ' + JSON.stringify(err)); + return; + } + windowClass = data; + }); let promise = windowClass.bindDialogTarget(token, () => { console.info('Dialog Window Need Destroy.'); }); @@ -3246,7 +3282,16 @@ import window from '@ohos.window'; export default class ServiceExtAbility extends ServiceExtensionAbility { onRequest(want, startId) { console.info('onRequest'); + let windowClass = null; + let config = {name: "dialogWindow", windowType: window.WindowType.TYPE_DIALOG, ctx: this.context}; try { + window.createWindow(config, (err, data) => { + if (err.code) { + console.error('Failed to create the window. Cause: ' + JSON.stringify(err)); + return; + } + windowClass = data; + }); let requestInfo = dialogRequest.getRequestInfo(want) windowClass.bindDialogTarget(requestInfo, () => { console.info('Dialog Window Need Destroy.'); @@ -3258,7 +3303,7 @@ export default class ServiceExtAbility extends ServiceExtensionAbility { console.info('Succeeded in binding dialog target.'); }); } catch(err) { - console.error('getRequestInfo err = ' + JSON.stringify(err)) + console.error('Failed to bind dialog target. Cause:' + JSON.stringify(err)) } } } @@ -3306,7 +3351,16 @@ import window from '@ohos.window'; export default class ServiceExtAbility extends ServiceExtensionAbility { onRequest(want, startId) { console.info('onRequest'); + let windowClass = null; + let config = {name: "dialogWindow", windowType: window.WindowType.TYPE_DIALOG, ctx: this.context}; try { + window.createWindow(config, (err, data) => { + if (err.code) { + console.error('Failed to create the window. Cause: ' + JSON.stringify(err)); + return; + } + windowClass = data; + }); let requestInfo = dialogRequest.getRequestInfo(want) let promise = windowClass.bindDialogTarget(requestInfo, () => { console.info('Dialog Window Need Destroy.'); @@ -3317,7 +3371,7 @@ export default class ServiceExtAbility extends ServiceExtensionAbility { console.error('Failed to bind dialog target. Cause:' + JSON.stringify(err)); }); } catch(err) { - console.error('getRequestInfo err = ' + JSON.stringify(err)) + console.error('Failed to bind dialog target. Cause:' + JSON.stringify(err)) } } } @@ -3835,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 @@ -3877,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 6d1bff42d490701f87940606d1ae4332b339b260..5a7c798c5513747de8e9130ca90434114e8d627b 100644 --- a/en/application-dev/reference/apis/js-apis-worker.md +++ b/en/application-dev/reference/apis/js-apis-worker.md @@ -89,7 +89,7 @@ const workerFAModel02 = new worker.ThreadWorker("../workers/worker.ts"); // In the stage model, the workers directory is at the same level as the pages directory in the entry module. const workerStageModel01 = new worker.ThreadWorker('entry/ets/workers/worker.ts', {name:"first worker in Stage model"}); -// In the stage model, the workers directory is at the same level as the parent directory of the pages directory in the entry module. +// In the stage model, the workers directory is a child directory of the pages directory in the entry module. const workerStageModel02 = new worker.ThreadWorker('entry/ets/pages/workers/worker.ts'); // For the script URL "entry/ets/workers/worker.ts" in the stage model: @@ -101,7 +101,7 @@ const workerStageModel02 = new worker.ThreadWorker('entry/ets/pages/workers/work // workerdir indicates the directory where the worker file is located, and workerfile indicates the worker file name. // In the stage model, the workers directory is at the same level as the pages directory in the entry module, and bundlename is com.example.workerdemo. const workerStageModel03 = new worker.ThreadWorker('@bundle:com.example.workerdemo/entry/ets/workers/worker'); -// In the stage model, the workers directory is at the same level as the parent directory of the pages directory in the entry module, and bundlename is com.example.workerdemo. +// In the stage model, the workers directory is a child directory of the pages directory in the entry module, and bundlename is com.example.workerdemo. const workerStageModel04 = new worker.ThreadWorker('@bundle:com.example.workerdemo/entry/ets/pages/workers/worker'); ``` @@ -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") } ``` @@ -1199,7 +1199,7 @@ const workerFAModel02 = new worker.Worker("../workers/worker.ts"); // In the stage model, the workers directory is at the same level as the pages directory. const workerStageModel01 = new worker.Worker('entry/ets/workers/worker.ts', {name:"first worker in Stage model"}); -// In the stage model, the workers directory is at the same level as the child directory of the pages directory. +// In the stage model, the workers directory is a child directory of the pages directory. const workerStageModel02 = new worker.Worker('entry/ets/pages/workers/worker.ts'); // For the script URL "entry/ets/workers/worker.ts" in the stage model: @@ -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]); } ``` @@ -2027,18 +2027,8 @@ parentPort.onerror = function(e){ ## More Information ### Sequenceable Data Types -| Type | Remarks | Supported| -| ------------------ | -------------------------------------- | -------- | -| All primitive types| The Symbol type is not included. | Yes | -| Date | | Yes | -| String | | Yes | -| RegExp | | Yes | -| Array | | Yes | -| Map | | Yes | -| Set | | Yes | -| Object | Only plain objects are supported. Objects with functions are not supported.| Yes | -| ArrayBuffer | The transfer capability is provided. | Yes | -| TypedArray | | Yes | + +The following object types are supported: basic types except Symbol, Date, String, RegExp, Array, Map, Set, Object (simple objects only, for example, objects created using **{}** or **new Object**), ArrayBuffer, and typedArray. (Note that only attributes can be transferred for common objects. Prototypes and methods cannot be transferred.) Exception: When an object created through a custom class is passed, no serialization error occurs. However, the attributes (such as Function) of the custom class cannot be passed through serialization. > **NOTE**
@@ -2096,10 +2086,10 @@ The worker thread is implemented based on the actor model. In the worker interac Each actor concurrently processes tasks of the main thread. For each actor, there is a message queue and a single-thread execution module. The message queue receives requests from the main thread and other actors; the single-thread execution module serially processes requests, sends requests to other actors, and creates new actors. These isolated actors use the asynchronous mode and can run concurrently. ### Precautions -- Currently, a maximum of eight workers can co-exist. +- 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/apis/js-apis-xml.md b/en/application-dev/reference/apis/js-apis-xml.md index 9554f5b07dd9f131c81c7ef8e30df9813cc303e9..4b75afc59d5190bddcef2ceda8d17014a8bd7d87 100644 --- a/en/application-dev/reference/apis/js-apis-xml.md +++ b/en/application-dev/reference/apis/js-apis-xml.md @@ -49,7 +49,7 @@ console.log(view1) // setAttributes(name: string, value: string): void -Sets an attribute. +Writes an attribute and its value. **System capability**: SystemCapability.Utils.Lang @@ -57,8 +57,8 @@ Sets an attribute. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | --------------- | -| name | string | Yes | Key of the attribute. | -| value | string | Yes | Value of the attribute.| +| name | string | Yes | Attribute to write. | +| value | string | Yes | Attribute value to write.| **Example** @@ -114,7 +114,7 @@ console.log(view1) // setDeclaration(): void -Sets a declaration. +Writes an XML file declaration. **System capability**: SystemCapability.Utils.Lang @@ -237,7 +237,7 @@ console.log(JSON.stringify(view1)) //\r\n< setComment(text: string): void -Sets the comment. +Writes a comment. **System capability**: SystemCapability.Utils.Lang @@ -245,7 +245,7 @@ Sets the comment. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------- | -| text | string | Yes | Comment to set.| +| text | string | Yes | Comment to write.| **Example** @@ -268,7 +268,7 @@ console.log(view1) //' setCDATA(text: string): void -Sets CDATA attributes. +Writes CDATA data. **System capability**: SystemCapability.Utils.Lang @@ -276,7 +276,7 @@ Sets CDATA attributes. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ----------------- | -| text | string | Yes | CDATA attribute to set.| +| text | string | Yes | CDATA data to write.| **Example** @@ -299,7 +299,7 @@ console.log(view1) //''' setText(text: string): void -Sets **Text**. +Writes a tag value. **System capability**: SystemCapability.Utils.Lang @@ -307,7 +307,7 @@ Sets **Text**. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------- | -| text | string | Yes | Content of the **Text** to set.| +| text | string | Yes | Tag value to write, which is the content of the **text** attribute.| **Example** @@ -333,7 +333,7 @@ console.log(view1) // 'Happy1' setDocType(text: string): void -Sets **DocType**. +Writes a document type. **System capability**: SystemCapability.Utils.Lang @@ -341,7 +341,7 @@ Sets **DocType**. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------- | -| text | string | Yes | Content of **DocType** to set.| +| text | string | Yes | Content of **DocType** to write.| **Example** @@ -473,11 +473,11 @@ Defines the XML parsing options. | Name | Type | Mandatory| Description | | ------------------------------ | ------------------------------------------------------------ | ---- | --------------------------------------- | -| supportDoctype | boolean | No | Whether to ignore **Doctype**. The default value is **false**.| -| ignoreNameSpace | boolean | No | Whether to ignore **Namespace**. The default value is **false**. | -| tagValueCallbackFunction | (name: string, value: string) => boolean | No | Callback used to return **tagValue**. The default value is **null**. | -| attributeValueCallbackFunction | (name: string, value: string) => boolean | No | Callback used to return **attributeValue**. The default value is **null**. | -| tokenValueCallbackFunction | (eventType: [EventType](#eventtype), value: [ParseInfo](#parseinfo)) => boolean | No | Callback used to return **tokenValue**. The default value is **null**. | +| supportDoctype | boolean | No | Whether to ignore the document type. The default value is **false**, indicating that the document type is parsed.| +| ignoreNameSpace | boolean | No | Whether to ignore the namespace. The default value is **false**, indicating that the namespace is parsed.| +| tagValueCallbackFunction | (name: string, value: string) => boolean | No | Callback used to return **tagValue** for parsing the tag and tag value. The default value is **null**, indicating that the tag and tag value are not parsed. | +| attributeValueCallbackFunction | (name: string, value: string) => boolean | No | Callback used to return **attributeValue** for parsing the attribute and attribute value. The default value is **null**, indicating that the attribute and attribute value are not parsed.| +| tokenValueCallbackFunction | (eventType: [EventType](#eventtype), value: [ParseInfo](#parseinfo)) => boolean | No | Callback used to return **tokenValue** for parsing the [EventType](#eventtype) and [ParseInfo](#parseinfo) attributes. The default value is **null**, indicating that the **EventType** and **ParseInfo** attribute are not parsed.| ## ParseInfo @@ -923,20 +923,20 @@ console.log(str); ## EventType -Enumerates the events. +Enumerates the event types. **System capability**: SystemCapability.Utils.Lang | Name | Value | Description | | ---------------- | ---- | --------------------- | -| START_DOCUMENT | 0 | Indicates a start document event. | -| END_DOCUMENT | 1 | Indicates an end document event. | -| START_TAG | 2 | Indicates a start tag event. | -| END_TAG | 3 | Indicates an end tag event. | -| TEXT | 4 | Indicates a text event. | -| CDSECT | 5 | Indicates a CDATA section event. | -| COMMENT | 6 | Indicates an XML comment event. | -| DOCDECL | 7 | Indicates an XML document type declaration event.| -| INSTRUCTION | 8 | Indicates an XML processing instruction event.| -| ENTITY_REFERENCE | 9 | Indicates an entity reference event. | -| WHITESPACE | 10 | Indicates a whitespace character event. | +| START_DOCUMENT | 0 | Start document event. | +| END_DOCUMENT | 1 | End document event. | +| START_TAG | 2 | Start tag event. | +| END_TAG | 3 | End tag event. | +| TEXT | 4 | Text event. | +| CDSECT | 5 | CDATA section event. | +| COMMENT | 6 | XML comment event. | +| DOCDECL | 7 | XML document type declaration event. | +| INSTRUCTION | 8 | XML processing instruction event. | +| ENTITY_REFERENCE | 9 | Entity reference event. | +| WHITESPACE | 10 | Whitespace character event. | diff --git a/en/application-dev/reference/apis/js-apis-zlib.md b/en/application-dev/reference/apis/js-apis-zlib.md index c1cd550641f09914fe47fafba4a38b84a03513c0..5825347718827b430b434c8cb7a41c8f3b1c4bc8 100644 --- a/en/application-dev/reference/apis/js-apis-zlib.md +++ b/en/application-dev/reference/apis/js-apis-zlib.md @@ -244,7 +244,7 @@ Decompresses a file. This API uses an asynchronous callback to return the result For details about the error codes, see [zlib Error Codes](../errorcodes/errorcode-zlib.md). -| ID| Error Message +| ID| Error Message | | -------- | --------------------------------------| | 900001 | The input source file is invalid. | | 900002 | The input destination file is invalid. | 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/image-animator.gif b/en/application-dev/reference/arkui-js-lite/figures/image-animator-lite.gif similarity index 100% rename from en/application-dev/reference/arkui-js-lite/figures/image-animator.gif rename to en/application-dev/reference/arkui-js-lite/figures/image-animator-lite.gif diff --git a/en/application-dev/reference/arkui-js-lite/figures/image.png b/en/application-dev/reference/arkui-js-lite/figures/image-lite.png similarity index 100% rename from en/application-dev/reference/arkui-js-lite/figures/image.png rename to en/application-dev/reference/arkui-js-lite/figures/image-lite.png diff --git a/en/application-dev/reference/arkui-js-lite/figures/list.png b/en/application-dev/reference/arkui-js-lite/figures/list-lite.png similarity index 100% rename from en/application-dev/reference/arkui-js-lite/figures/list.png rename to en/application-dev/reference/arkui-js-lite/figures/list-lite.png 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/figures/marquee.gif b/en/application-dev/reference/arkui-js-lite/figures/marquee-lite.gif similarity index 100% rename from en/application-dev/reference/arkui-js-lite/figures/marquee.gif rename to en/application-dev/reference/arkui-js-lite/figures/marquee-lite.gif diff --git a/en/application-dev/reference/arkui-js-lite/figures/picker-view.png b/en/application-dev/reference/arkui-js-lite/figures/picker-view-lite.png similarity index 100% rename from en/application-dev/reference/arkui-js-lite/figures/picker-view.png rename to en/application-dev/reference/arkui-js-lite/figures/picker-view-lite.png diff --git a/en/application-dev/reference/arkui-js-lite/figures/progress.png b/en/application-dev/reference/arkui-js-lite/figures/progress-lite.png similarity index 100% rename from en/application-dev/reference/arkui-js-lite/figures/progress.png rename to en/application-dev/reference/arkui-js-lite/figures/progress-lite.png diff --git a/en/application-dev/reference/arkui-js-lite/figures/qrcode.gif b/en/application-dev/reference/arkui-js-lite/figures/qrcode-lite.gif similarity index 100% rename from en/application-dev/reference/arkui-js-lite/figures/qrcode.gif rename to en/application-dev/reference/arkui-js-lite/figures/qrcode-lite.gif diff --git a/en/application-dev/reference/arkui-js-lite/figures/slider.png b/en/application-dev/reference/arkui-js-lite/figures/slider-lite.png similarity index 100% rename from en/application-dev/reference/arkui-js-lite/figures/slider.png rename to en/application-dev/reference/arkui-js-lite/figures/slider-lite.png diff --git a/en/application-dev/reference/arkui-js-lite/figures/swiper.gif b/en/application-dev/reference/arkui-js-lite/figures/swiper-lite.gif similarity index 100% rename from en/application-dev/reference/arkui-js-lite/figures/swiper.gif rename to en/application-dev/reference/arkui-js-lite/figures/swiper-lite.gif diff --git a/en/application-dev/reference/arkui-js-lite/figures/switch.gif b/en/application-dev/reference/arkui-js-lite/figures/switch-lite.gif similarity index 100% rename from en/application-dev/reference/arkui-js-lite/figures/switch.gif rename to en/application-dev/reference/arkui-js-lite/figures/switch-lite.gif diff --git a/en/application-dev/reference/arkui-js-lite/figures/text.png b/en/application-dev/reference/arkui-js-lite/figures/text-lite.png similarity index 100% rename from en/application-dev/reference/arkui-js-lite/figures/text.png rename to en/application-dev/reference/arkui-js-lite/figures/text-lite.png 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-image-animator.md b/en/application-dev/reference/arkui-js-lite/js-components-basic-image-animator.md index 226eff9f6c284140b5c671d2135dbe212b609590..4e6246baade4ed2f36f84cedec94425a0e1e85e9 100644 --- a/en/application-dev/reference/arkui-js-lite/js-components-basic-image-animator.md +++ b/en/application-dev/reference/arkui-js-lite/js-components-basic-image-animator.md @@ -204,4 +204,4 @@ export default { }; ``` -![image-animator](figures/image-animator.gif) +![image-animator](figures/image-animator-lite.gif) diff --git a/en/application-dev/reference/arkui-js-lite/js-components-basic-image.md b/en/application-dev/reference/arkui-js-lite/js-components-basic-image.md index 9dd520dcdeed71f6de216e8d5337d54aec33668d..d62d0f7d8188886ec3ca42e593029e763ed32e78 100644 --- a/en/application-dev/reference/arkui-js-lite/js-components-basic-image.md +++ b/en/application-dev/reference/arkui-js-lite/js-components-basic-image.md @@ -71,4 +71,4 @@ Not supported } ``` -![image](figures/image.png) +![image](figures/image-lite.png) diff --git a/en/application-dev/reference/arkui-js-lite/js-components-basic-marquee.md b/en/application-dev/reference/arkui-js-lite/js-components-basic-marquee.md index 8ecc7a2e41d301f03540320244425beacc39a884..7a0734964a217b089cb46e68ef75fb0db2671f49 100644 --- a/en/application-dev/reference/arkui-js-lite/js-components-basic-marquee.md +++ b/en/application-dev/reference/arkui-js-lite/js-components-basic-marquee.md @@ -115,4 +115,4 @@ export default { } ``` -![marquee](figures/marquee.gif) +![marquee](figures/marquee-lite.gif) diff --git a/en/application-dev/reference/arkui-js-lite/js-components-basic-picker-view.md b/en/application-dev/reference/arkui-js-lite/js-components-basic-picker-view.md index e9dacebc6c419bfaeca6c8aac9c1001e0725bd1f..44d4107f34e8d264488715b1dbe6e607819250fb 100644 --- a/en/application-dev/reference/arkui-js-lite/js-components-basic-picker-view.md +++ b/en/application-dev/reference/arkui-js-lite/js-components-basic-picker-view.md @@ -142,4 +142,4 @@ export default { } ``` -![picker-view](figures/picker-view.png) +![picker-view](figures/picker-view-lite.png) diff --git a/en/application-dev/reference/arkui-js-lite/js-components-basic-progress.md b/en/application-dev/reference/arkui-js-lite/js-components-basic-progress.md index 740bc136bc0a506cc6f28f883424fb2a62b15504..adc01e07389af27a21701566e8a1197dae9c0ea1 100644 --- a/en/application-dev/reference/arkui-js-lite/js-components-basic-progress.md +++ b/en/application-dev/reference/arkui-js-lite/js-components-basic-progress.md @@ -122,4 +122,4 @@ export default { } ``` -![progress](figures/progress.png) +![progress](figures/progress-lite.png) 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 16ef26d1b4263b0217c9fedfc8f04016fe7175db..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,33 +93,33 @@ 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'; - } - } } ``` -![qrcode](figures/qrcode.gif) +![qrcode](figures/qrcode-lite.gif) diff --git a/en/application-dev/reference/arkui-js-lite/js-components-basic-slider.md b/en/application-dev/reference/arkui-js-lite/js-components-basic-slider.md index 14a1804c4b47d769b5020fb820ac768a3f434316..1094ed2aa76bb9edf7ed234c1a70d58a91081653 100644 --- a/en/application-dev/reference/arkui-js-lite/js-components-basic-slider.md +++ b/en/application-dev/reference/arkui-js-lite/js-components-basic-slider.md @@ -99,4 +99,4 @@ export default { } ``` -![slider](figures/slider.png) +![slider](figures/slider-lite.png) diff --git a/en/application-dev/reference/arkui-js-lite/js-components-basic-switch.md b/en/application-dev/reference/arkui-js-lite/js-components-basic-switch.md index 42b4bddc549dcda654c2925d164e2eada3190910..a38365449f66b5c8ff0ba124d6d04ea469d8139e 100644 --- a/en/application-dev/reference/arkui-js-lite/js-components-basic-switch.md +++ b/en/application-dev/reference/arkui-js-lite/js-components-basic-switch.md @@ -96,4 +96,4 @@ export default { } ``` -![switch](figures/switch.gif) +![switch](figures/switch-lite.gif) diff --git a/en/application-dev/reference/arkui-js-lite/js-components-basic-text.md b/en/application-dev/reference/arkui-js-lite/js-components-basic-text.md index e5eab00c2eb0434932a0400d87f87f413d47c8ce..473bba31e3ac94bcafe904eeccaa6bc3721db566 100644 --- a/en/application-dev/reference/arkui-js-lite/js-components-basic-text.md +++ b/en/application-dev/reference/arkui-js-lite/js-components-basic-text.md @@ -96,4 +96,4 @@ export default { } ``` -![text](figures/text.png) +![text](figures/text-lite.png) diff --git a/en/application-dev/reference/arkui-js-lite/js-components-container-list.md b/en/application-dev/reference/arkui-js-lite/js-components-container-list.md index 6c256285ccf9894184218e179efd96089289d61d..e147741964843365863eaa99a312630e3a440504 100644 --- a/en/application-dev/reference/arkui-js-lite/js-components-container-list.md +++ b/en/application-dev/reference/arkui-js-lite/js-components-container-list.md @@ -120,4 +120,4 @@ export default { } ``` -![list](figures/list.png) +![list](figures/list-lite.png) diff --git a/en/application-dev/reference/arkui-js-lite/js-components-container-swiper.md b/en/application-dev/reference/arkui-js-lite/js-components-container-swiper.md index 34ad83a37b8d907b886427b183e99f4666e28327..ba9297bd4aebf8b8f9a2f3b95fb801bde9c1b8e2 100644 --- a/en/application-dev/reference/arkui-js-lite/js-components-container-swiper.md +++ b/en/application-dev/reference/arkui-js-lite/js-components-container-swiper.md @@ -109,4 +109,4 @@ export default { } ``` -![swiper](figures/swiper.gif) +![swiper](figures/swiper-lite.gif) 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 e0820748c9835894107fc01fa549602fca25a9b5..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) @@ -164,8 +166,8 @@ - Advanced Components - [@ohos.multimedia.avCastPicker (AVCastPicker)](ohos-multimedia-avcastpicker.md) - Animation - - [AnimatorProperty](ts-animatorproperty.md) - - [Explicit Animatio](ts-explicit-animation.md) + - [Property Animation](ts-animatorproperty.md) + - [Explicit Animation](ts-explicit-animation.md) - Transition Animation - [Page Transition](ts-page-transition-animation.md) - [Component Transition](ts-transition-animation-component.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/NestedScroll2.gif b/en/application-dev/reference/arkui-ts/figures/NestedScroll2.gif new file mode 100644 index 0000000000000000000000000000000000000000..fafe05c79f9a23c1e5f3bc3e5a8aa0a43b01648a Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/NestedScroll2.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/TextInput.png b/en/application-dev/reference/arkui-ts/figures/TextInput.png new file mode 100644 index 0000000000000000000000000000000000000000..517cbbcea01c161bb449c67d36e6cb0c199b1bd0 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/TextInput.png 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/checkbox2.gif b/en/application-dev/reference/arkui-ts/figures/checkbox2.gif new file mode 100644 index 0000000000000000000000000000000000000000..9e9f08ff19d6d94644e951e6324c37a728e5d7af Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/checkbox2.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/checkboxGroup2.gif b/en/application-dev/reference/arkui-ts/figures/checkboxGroup2.gif new file mode 100644 index 0000000000000000000000000000000000000000..6a0be72b7d13e326852225ac44071e89985adab1 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/checkboxGroup2.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_full_screen_modal_alpha.gif b/en/application-dev/reference/arkui-ts/figures/en-us_full_screen_modal_alpha.gif index 54c74793ba762946b561e869b3352db7a116b3ce..f25865fb56ce8e95854bef0f6a1fd37eca0c5dcb 100644 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_full_screen_modal_alpha.gif and b/en/application-dev/reference/arkui-ts/figures/en-us_full_screen_modal_alpha.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_full_screen_modal_default.gif b/en/application-dev/reference/arkui-ts/figures/en-us_full_screen_modal_default.gif index a2790b3cf613f7c525ba5b57d3c7b88ed41b1505..a0229af6fa82c19390c6f57ce3429c6aaca4cc15 100644 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_full_screen_modal_default.gif and b/en/application-dev/reference/arkui-ts/figures/en-us_full_screen_modal_default.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_full_screen_modal_none_1.gif b/en/application-dev/reference/arkui-ts/figures/en-us_full_screen_modal_none_1.gif index 88bc23b3df7443202ac67719d08f33e8b1006a42..904db2132184a8529b97db01c2351c02b55d783b 100644 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_full_screen_modal_none_1.gif and b/en/application-dev/reference/arkui-ts/figures/en-us_full_screen_modal_none_1.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_full_screen_modal_none_2.gif b/en/application-dev/reference/arkui-ts/figures/en-us_full_screen_modal_none_2.gif index 0a38281620329cb6a1c2f39ad9babe628950a41a..de0356ab987af9712816fce835293da7c679decd 100644 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_full_screen_modal_none_2.gif and b/en/application-dev/reference/arkui-ts/figures/en-us_full_screen_modal_none_2.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174104386.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174104386.gif new file mode 100644 index 0000000000000000000000000000000000000000..07e9d4b49ff85d3a137818b5dc6cafcf6b00640c Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174104386.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174422896.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174422896.gif new file mode 100644 index 0000000000000000000000000000000000000000..65dce0858d00df7ce62b578ce8de8b3f153d006e Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174422896.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001210111632.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001210111632.png new file mode 100644 index 0000000000000000000000000000000000000000..fcb961a33b65ed24a4a0c68312df44bd02a71bcb Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001210111632.png 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_0000001219744183.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219744183.gif index 0f974cc65ddbbef89654d62efd8391b2d72c810c..37764fe0ee06279245217b931afc0bbd84e6a739 100644 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219744183.gif and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219744183.gif 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_0000001219982726.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219982726.png new file mode 100644 index 0000000000000000000000000000000000000000..5cd212a78358d5443699725e6a963514768cb9e6 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219982726.png 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/en-us_image_0000001256978363.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256978363.gif deleted file mode 100644 index fa6a5f8e639b2b8b73bdae505da6b67800c5eb63..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256978363.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256978381.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256978381.gif deleted file mode 100644 index 1cd6ff13714a55e253e9649c007080b47f02f791..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256978381.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257058417.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257058417.png deleted file mode 100644 index 999ad44c80a018d45353044e13923a8566bf3cf0..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257058417.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001689126950.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001689126950.png new file mode 100644 index 0000000000000000000000000000000000000000..3ea634dcd914754120a8a7d6754bfe4866464320 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001689126950.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_sheet.gif b/en/application-dev/reference/arkui-ts/figures/en-us_sheet.gif index 192e22e3d28c4d56350c070fae5375d358a9abb7..1e89b5ee6696fb3b2d3e09a1049e1194f48a4275 100644 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_sheet.gif and b/en/application-dev/reference/arkui-ts/figures/en-us_sheet.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/gridDrag.png b/en/application-dev/reference/arkui-ts/figures/gridDrag.png new file mode 100644 index 0000000000000000000000000000000000000000..ab2755200c7ec3877b929c9182256f22b0cc5138 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/gridDrag.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/gridDrag1.png b/en/application-dev/reference/arkui-ts/figures/gridDrag1.png new file mode 100644 index 0000000000000000000000000000000000000000..721ec8950cc43af81afefdcd22afb14f50dfdb0e Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/gridDrag1.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/gridDrag2.png b/en/application-dev/reference/arkui-ts/figures/gridDrag2.png new file mode 100644 index 0000000000000000000000000000000000000000..5fbb5f43fbb38a3b10d6455abec94bef4c5f98aa Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/gridDrag2.png 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/imageButtonLabelStyle.png b/en/application-dev/reference/arkui-ts/figures/imageButtonLabelStyle.png new file mode 100644 index 0000000000000000000000000000000000000000..1a0f0d9cb7ec8cee7f6f01cc7e1b409f54e129ef Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/imageButtonLabelStyle.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/list4.gif b/en/application-dev/reference/arkui-ts/figures/list4.gif new file mode 100644 index 0000000000000000000000000000000000000000..d28ffc0be07801b3b8a3050cab0b5c95f6ffda01 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/list4.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/listItem3.jpeg b/en/application-dev/reference/arkui-ts/figures/listItem3.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..5188c9221033fb57e3e483ade647353097f9e4e4 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/listItem3.jpeg differ diff --git a/en/application-dev/reference/arkui-ts/figures/listItemGroup2.jpeg b/en/application-dev/reference/arkui-ts/figures/listItemGroup2.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..fa3469ab517b4e1b410fcef7a21aa9f4f1baebfa Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/listItemGroup2.jpeg 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/sidebarcontainer.png b/en/application-dev/reference/arkui-ts/figures/sidebarcontainer.png index 1cbb01859041e2028d76b49db655148cf4eb3062..d6ca07b72655b49f58047d74b0995c58fd99f607 100644 Binary files a/en/application-dev/reference/arkui-ts/figures/sidebarcontainer.png and b/en/application-dev/reference/arkui-ts/figures/sidebarcontainer.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/tabContent3.gif b/en/application-dev/reference/arkui-ts/figures/tabContent3.gif new file mode 100644 index 0000000000000000000000000000000000000000..7e731b125a0b7f365be9791dc9583c217b4ff6ce Binary files /dev/null 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/textAreaCustomKeyboard.png b/en/application-dev/reference/arkui-ts/figures/textAreaCustomKeyboard.png new file mode 100644 index 0000000000000000000000000000000000000000..6f0e9d679a5c498ee54c6ceba8b2f3675706d9d2 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/textAreaCustomKeyboard.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/textInput.gif b/en/application-dev/reference/arkui-ts/figures/textInput.gif deleted file mode 100644 index d980afbcb988222e44af1b359388a0ed6492264e..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/textInput.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/textInputCustomKeyboard.png b/en/application-dev/reference/arkui-ts/figures/textInputCustomKeyboard.png new file mode 100644 index 0000000000000000000000000000000000000000..716529aac87850e48b8befb630bfece0d2acb87d Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/textInputCustomKeyboard.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/textpicker1.gif b/en/application-dev/reference/arkui-ts/figures/textpicker1.gif new file mode 100644 index 0000000000000000000000000000000000000000..80a0ffbea07135408e9497e70cc3291e77690ab5 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/textpicker1.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 00095beb0f5a5739de8a9ab62da63a1807e475c5..cf020b1411cd952d2dd16330bdd30d53f501f5ed 100644 --- a/en/application-dev/reference/arkui-ts/ts-animatorproperty.md +++ b/en/application-dev/reference/arkui-ts/ts-animatorproperty.md @@ -1,12 +1,12 @@ -# Property Animator +# Property Animation -You can create a property animator to animate certain universal attributes of a component, including **width**, **height**, **backgroundColor**, **opacity**, **scale**, **rotate**, and **translate**. +You can animate certain properties of a component, including **width**, **height**, **backgroundColor**, **opacity**, **scale**, **rotate**, and **translate**. > **NOTE** > > This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. -animation(value: {duration?: number, tempo?: number, curve?: string | Curve | ICurve, delay?:number, iterations: number, playMode?: PlayMode, onFinish?: () => void}) +animation(value: {duration?: number, tempo?: number, curve?: string | Curve | ICurve, delay?:number, iterations?: number, playMode?: PlayMode, onFinish?: () => void}) Since API version 9, this API is supported in ArkTS widgets. @@ -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-button.md b/en/application-dev/reference/arkui-ts/ts-basic-components-button.md index 66e4eae88f46e6b63652d9ebfd8fadc24df2b529..3a3d6c0ad09cb2ec333d162a1b612b65744fc7b3 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-button.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-button.md @@ -169,3 +169,41 @@ struct SwipeGestureExample { ``` ![ifButton](figures/ifButton.gif) + +### Example 3 + +```ts +// xxx.ets +@Entry +@Component +struct buttonTestDemo { + @State txt: string = 'overflowTextOverlengthTextOverflow.Clip'; + @State widthShortSize: number = 200; + + build() { + Row() { + Column() { + Button(this.txt) + .width(this.widthShortSize) + .height(100) + .labelStyle({ overflow: TextOverflow.Clip, + maxLines: 1, + minFontSize: 20, + maxFontSize: 20, + font: { + size: 20, + weight: FontWeight.Bolder, + family: 'cursive', + style: FontStyle.Italic + } + }) + .fontSize(40) + } + .width('100%') + } + .height('100%') + } +} +``` + +![image-20230711171138661](figures/imageButtonLabelStyle.png) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-checkbox.md b/en/application-dev/reference/arkui-ts/ts-basic-components-checkbox.md index 2ad1d1ce835fe6c0fcffa7379860711cb49d396d..8760713a108b8fcdf718acb414dee0bbd54c9c7b 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-checkbox.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-checkbox.md @@ -39,9 +39,9 @@ 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 attributes are supported. -| Name | Description | +| Name | Description | | -------------------------------------------- | ------------------------------------------------------------ | -| onChange(callback: (value: boolean) => void) | Triggered when the selected status of the check box changes.
- The value **true** means that the check box is selected.
- The value **false** means that the check box is not selected.
Since API version 9, this API is supported in ArkTS widgets. | +| onChange(callback: (value: boolean) => void) | Triggered when the selected status of the check box changes.
- The value **true** means that the check box is selected.
- The value **false** means that the check box is not selected.
Since API version 9, this API is supported in ArkTS widgets.| ## MarkStyle10+ @@ -53,6 +53,8 @@ In addition to the [universal events](ts-universal-events-click.md), the followi ## Example +### Example 1 + ```ts // xxx.ets @Entry @@ -80,3 +82,51 @@ struct CheckboxExample { ![](figures/checkbox.gif) + +### Example 2 + +```ts +// xxx.ets +@Entry +@Component +struct Index { + + build() { + Row() { + Column() { + Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { + Checkbox({ name: 'checkbox1', group: 'checkboxGroup' }) + .selectedColor(0x39a2db) + .onChange((value: boolean) => { + console.info('Checkbox1 change is'+ value) + }) + .mark({ + strokeColor:Color.Black, + size: 50, + strokeWidth: 5 + }) + .unselectedColor(Color.Red) + .width(30) + .height(30) + Text('Checkbox1').fontSize(20) + } + Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { + Checkbox({ name: 'checkbox2', group: 'checkboxGroup' }) + .selectedColor(0x39a2db) + .onChange((value: boolean) => { + console.info('Checkbox2 change is' + value) + }) + .width(30) + .height(30) + Text('Checkbox2').fontSize(20) + } + } + .width('100%') + } + .height('100%') + } +} +``` + + +![](figures/checkbox2.gif) 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 37da4ad0bdf5b41ae99f617a6d06789fb075c922..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 @@ -72,6 +72,8 @@ Since API version 9, this API is supported in ArkTS widgets. ## Example +### Example 1 + ```ts // xxx.ets @Entry @@ -124,4 +126,77 @@ struct CheckboxExample { } } ``` -![checkboxgroup](figures/checkboxgroup.gif) +![checkboxGroup](figures/checkboxGroup.gif) + +### Example 2 + +```ts +// xxx.ets +@Entry +@Component +struct Index { + + build() { + Row() { + Column() { + Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { + CheckboxGroup({ group: 'checkboxGroup' }) + .selectedColor(Color.Orange) + .onChange((itemName: CheckboxGroupResult) => { + console.info("checkbox group content" + JSON.stringify(itemName)) + }) + .mark({ + strokeColor:Color.Black, + size: 40, + strokeWidth: 5 + }) + .unselectedColor(Color.Red) + .width(30) + .height(30) + Text('Select All').fontSize(20) + }.margin({right:15}) + Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { + Checkbox({ name: 'checkbox1', group: 'checkboxGroup' }) + .selectedColor(0x39a2db) + .onChange((value: boolean) => { + console.info('Checkbox1 change is'+ value) + }) + .mark({ + strokeColor:Color.Black, + size: 50, + strokeWidth: 5 + }) + .unselectedColor(Color.Red) + .width(30) + .height(30) + Text('Checkbox1').fontSize(20) + } + Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { + Checkbox({ name: 'checkbox2', group: 'checkboxGroup' }) + .selectedColor(0x39a2db) + .onChange((value: boolean) => { + console.info('Checkbox2 change is' + value) + }) + .width(30) + .height(30) + Text('Checkbox2').fontSize(20) + } + Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { + Checkbox({ name: 'checkbox3', group: 'checkboxGroup' }) + .selectedColor(0x39a2db) + .onChange((value: boolean) => { + console.info('Checkbox3 change is' + value) + }) + .width(30) + .height(30) + Text('Checkbox3').fontSize(20) + } + } + .width('100%') + } + .height('100%') + } +} +``` + +![checkboxGroup](figures/checkboxGroup2.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-datapanel.md b/en/application-dev/reference/arkui-ts/ts-basic-components-datapanel.md index e3681f6afdac7edc34bed701c1905c30857480d8..1c145a93206ecf99984346c0833750bda113d5cf 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-datapanel.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-datapanel.md @@ -44,16 +44,16 @@ Since API version 9, this API is supported in ArkTS widgets. In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. -| Name | Type| Mandatory| Description| -| ------------- | ------- | ---- | -------- | -| closeEffect | boolean | Yes| Whether to disable the rotation and shadow effects for the component.
Default value: **false**
**NOTE**
This attribute enables or disables the shadow effect only when **trackShadow** is not set.
The shadow effect enabled through this attribute is in the default style.| -| valueColors10+ | Array<[ResourceColor](ts-types.md#resourcecolor) \| [LinearGradient](#lineargradient10)> | Yes| Array of data segment colors. A value of the **ResourceColor** type indicates a solid color, and A value of the **LinearGradient** type indicates a color gradient.| -| trackBackgroundColor10+ | [ResourceColor](ts-types.md#resourcecolor) | Yes| Background color.
The value is in hexadecimal ARGB notation. The first two digits indicate opacity.
Default value: **'#08182431'**| -| strokeWidth10+ | [Length](ts-types.md#Length) | Yes| Stroke width of the border.
Default value: **24**
Unit: vp
**NOTE**
A value less than 0 evaluates to the default value.
This attribute does not take effect when the data panel type is **DataPanelType.Line**.| -| trackShadow10+ | [DataPanelShadowOption](#datapanelshadowoption10) | Yes| Shadow style.
**NOTE**
If this attribute is set to **null**, the shadow effect is disabled.| +| Name | Type| Description| +| ------------- | ------- | -------- | +| closeEffect | boolean | Whether to disable the rotation and shadow effects for the component.
Default value: **false**
**NOTE**
This attribute enables or disables the shadow effect only when **trackShadow** is not set.
The shadow effect enabled through this attribute is in the default style.| +| valueColors10+ | Array<[ResourceColor](ts-types.md#resourcecolor) \| [LinearGradient](#lineargradient10)> | Array of data segment colors. A value of the **ResourceColor** type indicates a solid color, and A value of the **LinearGradient** type indicates a color gradient.| +| trackBackgroundColor10+ | [ResourceColor](ts-types.md#resourcecolor) | Background color.
The value is in hexadecimal ARGB notation. The first two digits indicate opacity.
Default value: **'#08182431'**| +| strokeWidth10+ | [Length](ts-types.md#Length) | Stroke width of the border.
Default value: **24**
Unit: vp
**NOTE**
A value less than 0 evaluates to the default value.
This attribute does not take effect when the data panel type is **DataPanelType.Line**.| +| trackShadow10+ | [DataPanelShadowOptions](#datapanelshadowoptions10) | Shadow style.
**NOTE**
If this attribute is set to **null**, the shadow effect is disabled.| -## DataPanelShadowOption10+ +## DataPanelShadowOptions10+ | Name | Type| Mandatory| Description| | ------------- | ------- | ---- | -------- | | radius | number \| [Resource](ts-types.md#resource)| No| Shadow blur radius.
Default value: **5**
Unit: vp
**NOTE**
A value less than or equal to 0 evaluates to the default value.| 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 { } ``` -![datePicker](figures/datePicker.gif) +![datePicker](figures/DatePickerApi10.gif) 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 85870111712e90def229a040901f9ba0d41bbcf2..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 @@ -42,7 +38,7 @@ Creates a **FormComponent** instance to display the provided widget. | Name | Type | Mandatory| Description | | --------- | ------------------------------- | ---- | ----------------------------------------------------------------------- | -| id | number | Yes | Widget ID. Set this parameter to **0** for a new widget. | +| id | number | Yes | Widget ID. Set this parameter to **0** for a new widget.
**NOTE**
Different widget hosts cannot use the same ID.
If a widget host uses the same ID for two widgets, the one added later is displayed. | | name | string | Yes | Widget name. | | bundle | string | Yes | Bundle name of the widget. | | ability | string | Yes | Ability name of the widget. | diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-gauge.md b/en/application-dev/reference/arkui-ts/ts-basic-components-gauge.md index 6cf611c47dfd4d3d08b3124ec50e38b0ca1a4da7..9cbbc56e8002500fabc1bc85bb978006454cf06e 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-gauge.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-gauge.md @@ -68,7 +68,7 @@ struct GaugeExample { // Set the value parameter to 75 and the value attribute to 25. The attribute setting is used. Gauge({ value: 75 }) - .value(25) // If both the attribute and parameter are set, the parameter setting is used. + .value(25) // If both the attribute and parameter are set, the attribute setting is used. .width(200).height(200) .colors([[0x317AF7, 1], [0x5BA854, 1], [0xE08C3A, 1], [0x9C554B, 1]]) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-imagespan.md b/en/application-dev/reference/arkui-ts/ts-basic-components-imagespan.md index db8fbb1fa0a3e809409aa4afba07eb7696fc539c..9cfb2b31661b0ed834c68aeff4acce07ae0166c0 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-imagespan.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-imagespan.md @@ -25,11 +25,11 @@ ImageSpan(value: ResourceStr | PixelMap) ## Attributes -Among all the [universal events](ts-universal-attributes-size.md), only **width**, **height**, and **size** are supported. +The [universal attribute](ts-universal-attributes-size.md) methods can be used to set the size, background, and border. | Name| Type| Description| | -------- | -------- | -------- | -| verticalAlign | [ImageSpanAlignment](#imagespanalignment) | Alignment mode of the image with the text.| +| verticalAlign | [ImageSpanAlignment](#imagespanalignment) | Alignment mode of the image with the text.
Default value: **ImageSpanAlignment.BOTTOM**| | objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | Image scale type.
Default value: **ImageFit.Cover**| ## ImageSpanAlignment @@ -57,7 +57,7 @@ struct SpanExample { Text() { Span('This is the Span and ImageSpan component').fontSize(25).textCase(TextCase.Normal) .decoration({ type: TextDecorationType.None, color: Color.Pink }) - }.width('100%') + }.width('100%').textAlign(TextAlign.Center) Text() { ImageSpan($r('app.media.icon')) .width('200px') @@ -85,7 +85,6 @@ struct SpanExample { .decoration({ type: TextDecorationType.Underline, color: Color.Red }).fontSize(50) } .width('100%') - .backgroundColor(Color.Orange) .textIndent(50) }.width('100%').height('100%').padding({ left: 0, right: 0, top: 0 }) } 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-marquee.md b/en/application-dev/reference/arkui-ts/ts-basic-components-marquee.md index e14c0aee93857ea01cdec4f6e2843b273de28e97..c8b19032cf4bc784fa8159692f076b2d5ddf5a75 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-marquee.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-marquee.md @@ -30,7 +30,7 @@ Since API version 9, this API is supported in ArkTS widgets. | src | string | Yes| Text to scroll.| ## Attributes - +In addition to the universal text attributes **fontColor**, **fontSize**, **fontWeight**, and **fontFamily**, the following attributes are supported. | Name | Type| Description | | ---------- | -------- | ------------------------------------------------------------ | | allowScale | boolean | Whether to allow text to scale.
This attribute is not supported currently.
Default value: **false** | 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-navigation.md b/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md index 258657481a3284bd235a93c0a6e13c9ab9fd9088..110905369abcd03d58cccdab4380d31aadf03f33 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md @@ -13,73 +13,83 @@ Supported Since API version 9, it is recommended that this component be used together with the **[\](ts-basic-components-navrouter.md)** component. - ## APIs -**API 1**: Navigation() +### Navigation + +Navigation() + +### Navigation10+ -**API 2**: Navigation(pathInfos: NavPathStack)10+ +Navigation(pathInfos: NavPathStack)10+ Binds a navigation stack to the **\** component. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ----------------------------------- | ---- | ------------- | -| pathInfos | [NavPathStack](#navpathstack10) | No | Information about the navigation stack.| +| Name | Type | Mandatory | Description | +| --------- | ------------------------------- | ---- | ------ | +| pathInfos | [NavPathStack](#navpathstack10) | No | Information about the navigation stack.| ## Attributes In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. -| Name | Type | Description | -| ----------------------------- | ---------------------------------------- | ---------------------------------------- | -| title | [ResourceStr](ts-types.md#resourcestr)10+ \| [CustomBuilder](ts-types.md#custombuilder8)8+ \| [NavigationCommonTitle](#navigationcommontitle)9+ \| [NavigationCustomTitle](#navigationcustomtitle)9+ | Page title.
**NOTE**
When the NavigationCustomTitle type is used to set the height, the **titleMode** attribute does not take effect.
When the title string is too long: (1) If no subtitle is set, the string is scaled down, wrapped in two lines, and then clipped with an ellipsis (...); (2) If a subtitle is set, the subtitle is scaled down and then clipped with an ellipsis (...).| -| subTitle(deprecated) | string | Subtitle of the page. If this attribute is not set, no subtitle is displayed. This attribute is deprecated since API version 9. You are advised to use **title** instead.| -| menus | Array<[NavigationMenuItem](#navigationmenuitem)> \| [CustomBuilder](ts-types.md#custombuilder8)8+ | Menu items in the upper right corner of the page. If this attribute is not set, no menu item is displayed. When the value type is Array\<[NavigationMenuItem](#navigationmenuitem)>, the menu shows a maximum of three icons in portrait mode and a maximum of five icons in landscape mode, with excess icons (if any) placed under the automatically generated **More** icon.| -| titleMode | [NavigationTitleMode](#navigationtitlemode) | Display mode of the page title bar.
Default value: **NavigationTitleMode.Free**| -| toolBar(deprecated) | [object](#object) \| [CustomBuilder](ts-types.md#custombuilder8)8+ | Content of the toolbar. If this attribute is not set, no toolbar is displayed.
**items**: items on the toolbar.
**NOTE**
Items are evenly distributed on the toolbar at the bottom. Text and icons are evenly distributed in each content area. If the text is too long, it is scaled down level by level, wrapped in two lines, and then clipped with an ellipsis (...).
This API is deprecated since API version 10. You are advised to use **toolbarConfiguration** instead.| +| Name | Type | Description | +| ---------------------------------- | ---------------------------------------- | ---------------------------------------- | +| title | [ResourceStr](ts-types.md#resourcestr)10+ \| [CustomBuilder](ts-types.md#custombuilder8)8+ \| [NavigationCommonTitle](#navigationcommontitle)9+ \| [NavigationCustomTitle](#navigationcustomtitle)9+ | Page title.
**NOTE**
When the NavigationCustomTitle type is used to set the height, the **titleMode** attribute does not take effect.
When the title string is too long: (1) If no subtitle is set, the string is scaled down, wrapped in two lines, and then clipped with an ellipsis (...); (2) If a subtitle is set, the subtitle is scaled down and then clipped with an ellipsis (...).| +| subTitle(deprecated) | string | Subtitle of the page. If this attribute is not set, no subtitle is displayed. This attribute is deprecated since API version 9. You are advised to use **title** instead.| +| menus | Array<[NavigationMenuItem](#navigationmenuitem)> \| [CustomBuilder](ts-types.md#custombuilder8)8+ | Menu items in the upper right corner of the page. If this attribute is not set, no menu item is displayed. When the value type is Array<[NavigationMenuItem](#navigationmenuitem)>, the menu shows a maximum of three icons in portrait mode and a maximum of five icons in landscape mode, with excess icons (if any) placed under the automatically generated **More** icon.| +| titleMode | [NavigationTitleMode](#navigationtitlemode) | Display mode of the page title bar.
Default value: **NavigationTitleMode.Free**| +| toolBar(deprecated) | [object](#object) \| [CustomBuilder](ts-types.md#custombuilder8)8+ | Content of the toolbar. If this attribute is not set, no toolbar is displayed.
**items**: all items on the toolbar.
**NOTE**
Items are evenly distributed on the toolbar at the bottom. Text and icons are evenly distributed in each content area. If the text is too long, it is scaled down level by level, wrapped in two lines, and then clipped with an ellipsis (...).
This API is deprecated since API version 10. You are advised to use **toolbarConfiguration** instead.| | toolbarConfiguration10+ | Array<[ToolbarItem](#toolbaritem10)10+> \| [CustomBuilder](ts-types.md#custombuilder8)8+ | Content of the toolbar. If this attribute is not set, no toolbar is displayed.
**NOTE**
When the value type is Array<[ToolbarItem](#ToolbarItem>, the toolbar exhibits the following features:
Items are evenly distributed on the toolbar at the bottom. Text and icons are evenly distributed in each content area.
If any item contains overlong text and there are fewer than five items, the following measures are taken: 1. Increase the item's width to accommodate the text until it is as large as the screen width; 2. Scale down the text level by level; 3. Wrap the text in two lines; 4. Clip the text with an ellipsis (...).
The toolbar shows a maximum of five icons in portrait mode, with excess icons (if any) placed under the automatically generated **More** icon. In landscape mode, this attribute must be used together with Array<[NavigationMenuItem](#navigationmenuitem)> of the **menus** attribute; the toolbar at the bottom is automatically hidden, and all items on the toolbar are moved to the menu in the upper right corner of the screen.
When the value type is [CustomBuilder](ts-types.md#custombuilder8), and the toolbar does not exhibit the preceding features except that items are evenly distributed on the toolbar at the bottom.| -| hideToolBar | boolean | Whether to hide the toolbar.
Default value: **false**
**true**: Hide the toolbar.
**false**: Display the toolbar.| -| hideTitleBar | boolean | Whether to hide the title bar.
Default value: **false**
**true**: Hide the title bar.
**false**: Display the title bar.| -| hideBackButton | boolean | Whether to hide the back button.
Default value: **false**
**true**: Hide the back button.
**false**: Display the back button.
The back button in the title bar of the **\** component cannot be hidden.
**NOTE**
The back button works only when **titleMode** is set to **NavigationTitleMode.Mini**.| -| navBarWidth9+ | [Length](ts-types.md#length) | Width of the navigation bar.
Default value: **200**
Unit: vp
**NOTE**
This attribute is valid only when the **\** component is split.| -| navBarPosition9+ | [NavBarPosition](#navbarposition) | Position of the navigation bar.
Default value: **NavBarPosition.Start**
**NOTE**
This attribute is valid only when the **\** component is split.| -| mode9+ | [NavigationMode](#navigationmode) | Display mode of the navigation bar.
Default value: **NavigationMode.Auto**
At the default settings, the component adapts to a single column or two columns based on the component width.| -| backButtonIcon9+ | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Back button icon on the navigation bar. The back button in the title bar of the **\** component cannot be hidden.| -| hideNavBar9+ | boolean | Whether to hide the navigation bar. This attribute is valid only when **mode** is set to **NavigationMode.Split**.| -| navDestination10+ | builder: (name: string, param: unknown) => void | Creates a **\** component.
**NOTE**
The **builder** function is used, with the **name** and **param** parameters passed in. In the builder, a layer of custom components can be included outside the **\** component. However, no attributes or events can be set for the custom components. Otherwise, only blank components are displayed.| -| navBarWidthRange10+ | [[Dimension](ts-types.md#dimension10), [Dimension](ts-types.md#dimension10)] | Minimum and maximum widths of the navigation bar.
Default value: **240** for the minimum value; 40% of the component width (not greater than 432) for the maximum value
Unit: vp
Priority rules:
Custom value > Default value
Minimum value > Maximum value
navBar > content
If values conflict, the global value takes precedence, and the local minimum value depends on the container size.| -| minContentWidth10+ | [Dimension](ts-types.md#dimension10) | Minimum width of the navigation bar content area.
Default value: **360**
Unit: vp
Priority rules:
Custom value > Default value
Minimum value > Maximum value
navBar > content
If values conflict, the global value takes precedence, and the local minimum value depends on the container size.
Breakpoint calculation in Auto mode: default 600vp = minNavBarWidth (240vp) + minContentWidth (360vp)| +| hideToolBar | boolean | Whether to hide the toolbar.
Default value: **false**
**true**: Hide the toolbar.
**false**: Display the toolbar.| +| hideTitleBar | boolean | Whether to hide the title bar.
Default value: **false**
**true**: Hide the title bar.
**false**: Display the title bar.| +| hideBackButton | boolean | Whether to hide the back button.
Default value: **false**
**true**: Hide the back button.
**false**: Display the back button.
The back button in the title bar of the **\** component cannot be hidden.
**NOTE**
The back button works only when **titleMode** is set to **NavigationTitleMode.Mini**.| +| navBarWidth9+ | [Length](ts-types.md#length) | Width of the navigation bar.
Default value: **240**
Unit: vp
**NOTE**
This attribute is valid only when the **\** component is split.| +| navBarPosition9+ | [NavBarPosition](#navbarposition) | Position of the navigation bar.
Default value: **NavBarPosition.Start**
**NOTE**
This attribute is valid only when the **\** component is split.| +| mode9+ | [NavigationMode](#navigationmode) | Display mode of the navigation bar.
Default value: **NavigationMode.Auto**
At the default settings, the component adapts to a single column or two columns based on the component width.
**NOTE**
Available options are **Stack**, **Split**, and **Auto**.| +| backButtonIcon9+ | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Back button icon on the navigation bar. The back button in the title bar of the **\** component cannot be hidden.| +| hideNavBar9+ | boolean | Whether to hide the navigation bar. This attribute is valid only when **mode** is set to **NavigationMode.Split**.| +| navDestination10+ | builder: (name: string, param: unknown) => void | Creates a **\** component.
**NOTE**
The **builder** function is used, with the **name** and **param** parameters passed in. In the builder, a layer of custom components can be included outside the **\** component. However, no attributes or events can be set for the custom components. Otherwise, only blank components are displayed.| +| navBarWidthRange10+ | [[Dimension](ts-types.md#dimension10), [Dimension](ts-types.md#dimension10)] | Minimum and maximum widths of the navigation bar (valid in dual-column mode).
Default value: **240** for the minimum value; 40% of the component width (not greater than 432) for the maximum value
Unit: vp
Priority rules:
Custom value > Default value
Minimum value > Maximum value
navBar > content
If values conflict, the global value takes precedence, and the local minimum value depends on the container size.| +| minContentWidth10+ | [Dimension](ts-types.md#dimension10) | Minimum width of the navigation bar content area (valid in dual-column mode).
Default value: **360**
Unit: vp
Priority rules:
Custom value > Default value
Minimum value > Maximum value
navBar > content
If values conflict, the global value takes precedence, and the local minimum value depends on the container size.
Breakpoint calculation in Auto mode: default 600 vp = minNavBarWidth (240 vp) + minContentWidth (360 vp)| + +## Events + +| Name | Description | +| ---------------------------------------- | ---------------------------------------- | +| onTitleModeChange(callback: (titleMode: NavigationTitleMode) => void) | Called when **titleMode** is set to **NavigationTitleMode.Free** and the title bar mode changes as content scrolls.| +| onNavBarStateChange(callback: (isVisible: boolean) => void) | Called when the navigation bar visibility status changes. The value **true** means that the navigation bar is displayed, and **false** means the opposite.| ## NavPathStack10+ Implements a navigation stack. -### push10+ +### pushPath10+ -push(info: NavPathInfo): void +pushPath(info: NavPathInfo): void Pushes the NavDestination page information specified by **info** to the stack. **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| info | [NavPathInfo](#navpathinfo10) | Yes | Information about the navigation destination page. | +| Name | Type | Mandatory | Description | +| ---- | ----------------------------- | ---- | -------------------- | +| info | [NavPathInfo](#navpathinfo10) | Yes | Information about the navigation destination page.| -### pushName10+ +### pushPathByName10+ -pushName(name: string, param: unknown): void +pushPathByName(name: string, param: unknown): void Pushes the navigation destination page specified by **name** to the navigation stack. **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| name | string | Yes | Name of the navigation destination page. | -| param | unknown | Yes | Parameter information of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ----- | ------- | ---- | --------------------- | +| name | string | Yes | Name of the navigation destination page. | +| param | unknown | Yes | Parameter information of the navigation destination page.| ### pop10+ @@ -89,27 +99,27 @@ Pops the top element out of the navigation stack. **Return value** -| Type | Description | -| ------ | -------- | +| Type | Description | +| ----------- | ------------------------ | | NavPathInfo | Returns the information about the navigation destination page at the top of the stack.| -| undefined | Returns **undefined** if the navigation stack is empty.| +| undefined | Returns **undefined** if the navigation stack is empty. | -### popTo10+ +### popToName10+ -popTo(name: string): number +popToName(name: string): number Returns the navigation stack to the first navigation destination page that matches the value of **name**. **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| name | string | Yes | Name of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------------- | +| name | string | Yes | Name of the navigation destination page.| **Return value** -| Type | Description | -| ------ | -------- | +| Type | Description | +| ------ | ---------------------------------------- | | number | Returns the index of the first navigation destination page that matches the value of **name** if it exists in the navigation stack; returns **-1** otherwise.| ### popToIndex10+ @@ -120,9 +130,9 @@ Returns the navigation stack to the navigation destination page that matches the **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| index | number | Yes | Index of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------------------- | +| index | number | Yes | Index of the navigation destination page.| ### moveToTop10+ @@ -132,14 +142,14 @@ Moves to the top of the navigation stack the first navigation destination page t **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| name | string | Yes | Name of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------------- | +| name | string | Yes | Name of the navigation destination page.| **Return value** -| Type | Description | -| ------ | -------- | +| Type | Description | +| ------ | ---------------------------------------- | | number | Returns the index of the first navigation destination page that matches the value of **name** if it exists in the navigation stack; returns **-1** otherwise.| ### moveIndexToTop10+ @@ -150,9 +160,9 @@ Moves to the top of the navigation stack the navigation destination page that ma **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| index | number | Yes | Index of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------------------- | +| index | number | Yes | Index of the navigation destination page.| ### clear10+ @@ -168,8 +178,8 @@ Obtains the names of all navigation destination pages in the navigation stack. **Return value** -| Type | Description | -| ------ | -------- | +| Type | Description | +| -------------- | -------------------------- | | Array | Names of all navigation destination pages in the navigation stack.| ### getParamByIndex10+ @@ -180,16 +190,16 @@ Obtains the parameter information of the navigation destination page that matche **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| index | number | Yes | Index of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------------------- | +| index | number | Yes | Index of the navigation destination page.| **Return value** -| Type | Description | -| ------ | -------- | -| unknown | Returns the parameter information of the matching navigation destination page.| -| undefined | Returns **undefined** if the passed index is invalid.| +| Type | Description | +| --------- | -------------------------- | +| unknown | Returns the parameter information of the matching navigation destination page.| +| undefined | Returns **undefined** if the passed index is invalid. | ### getParamByName10+ @@ -199,15 +209,15 @@ Obtains the parameter information of all the navigation destination pages that m **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| name | string | Yes | Name of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------------- | +| name | string | Yes | Name of the navigation destination page.| **Return value** -| Type | Description | -| ------ | -------- | -| Array | Parameter information of all the matching navigation destination pages.| +| Type | Description | +| --------------- | --------------------------------- | +| Array | Parameter information of all the matching navigation destination pages.| ### getIndexByName10+ @@ -217,15 +227,15 @@ Obtains the indexes information of all the navigation destination pages that mat **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| name | string | Yes | Name of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------------- | +| name | string | Yes | Name of the navigation destination page.| **Return value** -| Type | Description | -| ------ | -------- | -| Array | Indexes of all the matching navigation destination pages.| +| Type | Description | +| -------------- | --------------------------------- | +| Array | Indexes of all the matching navigation destination pages.| ### size10+ @@ -235,9 +245,9 @@ Obtains the stack size. **Return value** -| Type | Description | -| ------ | -------- | -| number | Stack size.| +| Type | Description | +| ------ | ------ | +| number | Stack size.| ## NavPathInfo10+ @@ -249,52 +259,52 @@ constructor(name: string, param: unknown) **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| name | string | Yes | Name of the navigation destination page. | -| param | unknown | No | Parameter information of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ----- | ------- | ---- | --------------------- | +| name | string | Yes | Name of the navigation destination page. | +| param | unknown | No | Parameter information of the navigation destination page.| ## NavigationMenuItem -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| value | string | Yes | Text of a menu item. | -| icon | string | No | Icon path of a menu item.| +| Name | Type | Mandatory | Description | +| ------ | ------------- | ---- | --------------- | +| value | string | Yes | Text of a menu item. | +| icon | string | No | Icon path of a menu item.| | action | () => void | No | Callback invoked when a menu item is selected. | ## object -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| value | string | Yes | Text of a toolbar item. | -| icon | string | No | Icon path of a toolbar item.| +| Name | Type | Mandatory | Description | +| ------ | ------------- | ---- | --------------- | +| value | string | Yes | Text of a toolbar item. | +| icon | string | No | Icon path of a toolbar item.| | action | () => void | No | Callback invoked when a toolbar item is selected. | ## ToolbarItem10+ -| Name | Type | Mandatory| Description | -| ---------- | ------------------------------------------------- | ---- | ----------------------------------------------------------- | -| value | ResourceStr | Yes | Text of a toolbar item. | -| icon | ResourceStr | No | Icon path of a toolbar item. | -| action | () => void | No | Callback invoked when a toolbar item is selected. | -| status | [ToolbarItemStatus](#toolbaritemstatus10) | No | Status of a toolbar item.
Default value: **ToolbarItemStatus.NORMAL**| -| activeIcon | ResourceStr | No | Icon path of the toolbar item in the active state. | +| Name | Type | Mandatory | Description | +| ---------- | ---------------------------------------- | ---- | ---------------------------------------- | +| value | ResourceStr | Yes | Text of a toolbar item. | +| icon | ResourceStr | No | Icon path of a toolbar item. | +| action | () => void | No | Callback invoked when a toolbar item is selected. | +| status | [ToolbarItemStatus](#toolbaritemstatus10) | No | Status of a toolbar item.
Default value: **ToolbarItemStatus.NORMAL**| +| activeIcon | ResourceStr | No | Icon path of the toolbar item in the active state. | ## ToolbarItemStatus10+ -| Name | Description | -| -------- | ------------------------------------------------------------ | +| Name | Description | +| -------- | ---------------------------------------- | | NORMAL | Normal state. In this state, the toolbar item takes on the default style and can switch to another state-specific style by responding to the hover, press, and focus events.| | DISABLED | Disabled state. In this state, the toolbar item is disabled and does not allow for user interactions.| | ACTIVE | Active state. In this state, the toolbar item can update its icon to the one specified by **activeIcon** by responding to a click event.| ## NavigationTitleMode -| Name| Description | -| ---- | ------------------------------------------------------------ | -| Free | When the content is a scrollable component, the main title shrinks as the content scrolls down (the subtitle fades out with its size remaining unchanged) and restores when the content scrolls up to the top.
**NOTE**
The size linkage effect works only when **title** is set to **ResourceStr** or **NavigationCommonTitle**. If **title** is set to any other value type, the main title changes in mere location when pulled down.| -| Mini | The title is fixed at mini mode. | -| Full | The title is fixed at full mode. | +| Name | Description | +| ---- | ---------------------------------------- | +| Free | When the content is a scrollable component, the main title shrinks as the content scrolls down (the subtitle fades out with its size remaining unchanged) and restores as the content scrolls up to the top.
**NOTE**
The size linkage effect works only when **title** is set to **ResourceStr** or **NavigationCommonTitle**. If **title** is set to any other value type, the main title changes in mere location when pulled down.| +| Mini | The title is fixed at mini mode. | +| Full | The title is fixed at full mode. | ## NavigationCommonTitle @@ -319,11 +329,11 @@ constructor(name: string, param: unknown) ## NavigationMode -| Name | Description | -| ----- | ---------------------------------------- | +| Name | Description | +| ----- | ------------------------------------------------------------ | | Stack | The navigation bar and content area are displayed independently of each other, which are equivalent to two pages. | -| Split | The navigation bar and content area are displayed in different columns. | -| Auto | When the window width is greater than or equal to 520 vp, Split mode is used. Otherwise, the Stack mode is used.| +| Split | The navigation bar and content area are displayed in different columns.
The values of **navBarWidthRange** are represented by [minNavBarWidth,maxNavBarWidth].
1. When the value of **navBarWidth** is beyond the value range specified by **navBarWidthRange**, **navBarWidth** is set according to the following rules:
Value of **navBarWidth** < Value of **minNavBarWidth**: The value of **navBarWidth** is changed to that of **minNavBarWidth**.
Value of **navBarWidth** > Value of **maxNavBarWidth** and Component width - Value of **minContentWidth** - Divider width (1 vp) > Value of **maxNavBarWidth**: The value of **navBarWidth** is changed to that of **maxNavBarWidth**.
Value of **navBarWidth** > Value of **maxNavBarWidth** and Component width - Value of **minContentWidth** - Divider width (1 vp) < Value of **minNavBarWidth**: The value of **navBarWidth** is changed to that of **minNavBarWidth**.
Value of **navBarWidth** > Value of **maxNavBarWidth** and Component width - Value of **minContentWidth** - Divider width (1 vp) is within the value range specified by **navBarWidthRange**: The value of **navBarWidth** is changed to Component width - Value of **minContentWidth** - Divider width (1 vp).
2. When the value of **navBarWidth** is within the value range specified by **navBarWidthRange**, **navBarWidth** is set according to the following rules:
Value of **minNavBarWidth** + Value of **minContentWidth** + Divider width (1 vp) > = Component width: The value of **navBarWidth** is changed to that of **minNavBarWidth**.
Value of **minNavBarWidth** + Value of **minContentWidth** + Divider width (1 vp) < Component width and Value of **navBarWidth** + Value of **minContentWidth** + Divider width (1 vp) > = Component width: The value of **navBarWidth** is changed to Component width - Value of **minContentWidth** - Divider width (1 vp).
Value of **minNavBarWidth** + Value of **minContentWidth** + Divider width (1 vp) < Component width and Value of **navBarWidth** + Value of **minContentWidth** + Divider width (1 vp) < Component width: The value of **navBarWidth** is the set value.
3. When the component size is decreased, the content area is shrunk until its width reaches the value defined by **minContentWidth**, and then the navigation bar is shrunk until its width reaches the value defined by **minNavBarWidth**; if the component size is further decreased, the content area is further shrunk until it disappears, and then navigation bar is shrunk.
4. When the navigation bar is set to a fixed size and the component size is continuously decreased, the navigation bar is shrunk.
5. If only **navBarWidth** is set, the width of the navigation bar is fixed at the value of **navBarWidth**, and the divider cannot be dragged.| +| Auto | In API version 9 and earlier versions: When the window width is greater than or equal to 520 vp, the Split mode is used. In other cases, the Stack mode is used.
In API version 10 and later versions: When the window width is greater than or equal to 600 vp, the Split mode is used. In other cases, the Stack mode is used. 600 vp = minNavBarWidth (240 vp) + minContentWidth (360 vp).| ## TitleHeight @@ -334,17 +344,10 @@ constructor(name: string, param: unknown) > **NOTE** +> > Among the scrollable components, only **\** is supported. -## Events - -| Name | Description | -| ---------------------------------------- | ---------------------------------------- | -| onTitleModeChange(callback: (titleMode: NavigationTitleMode) => void) | Called when **titleMode** is set to **NavigationTitleMode.Free** and the title bar mode changes as content scrolls.| -| onNavBarStateChange(callback: (isVisible: boolean) => void) | Called when the navigation bar visibility status changes. The value **true** means that the navigation bar is displayed, and **false** means the opposite.| - - ## Example ```ts 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 d69ec2a9e833bec992c52ccd759519d131145487..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 @@ -1,6 +1,6 @@ # RichEditor -The \ is a component that supports interactive text editing and mixture of text and imagery. +The **\** is a component that supports interactive text editing and mixture of text and imagery. > **NOTE** > @@ -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. @@ -114,7 +123,7 @@ Provides the image span style information returned by the backend. | ------ | -------- | ---- | -------------------------------------- | | size | [number, number] | Yes| Width and height of the image.| | verticalAlign | [ImageSpanAlignment](ts-basic-components-imagespan.md#imagespanalignment) | Yes | Vertical alignment mode of the image.| -| objectFit | [ImageFit]((ts-basic-components-imagespan.md#imagefit)) | Yes| Scale mode of the image.| +| objectFit | [ImageFit](ts-basic-components-imagespan.md#imagefit) | Yes| Scale mode of the image.| ## RichEditorOptions @@ -158,7 +167,7 @@ Sets the cursor position. | Name| Type| Mandatory| Description | | ------ | -------- | ---- | -------------------------------------- | -| offset | number | Yes| Offset of the cursor.| +| offset | number | Yes| Offset of the cursor. If the value is out of the text range, the setting fails.| **Return value** @@ -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** @@ -265,8 +274,8 @@ Defines the text span style options. | Name| Type| Mandatory| Description | | ------ | -------- | ---- | -------------------------------------- | -| start | number | No| Start position of the text span whose style needs to be updated. If this parameter is omitted, the value **0** will be used.| -| end | number | No| End position of the text span whose style needs to be updated. If this parameter is omitted, it indicates the end of the text span.| +| start | number | No| Start position of the text span whose style needs to be updated. If this parameter is omitted or set to a negative value, the value **0** will be used.| +| end | number | No| End position of the text span whose style needs to be updated. If this parameter is omitted or set to a value beyond the text range, it indicates the end of the text span.| | textStyle | [RichEditorTextStyle](#richeditortextstyle) | Yes| Text style.| @@ -276,8 +285,8 @@ Defines the image span style options. | Name| Type| Mandatory| Description | | ------ | -------- | ---- | -------------------------------------- | -| start | number | No| Start position of the image span whose style needs to be updated. If this parameter is omitted, the value **0** will be used.| -| end | number | No| End position of the image span whose style needs to be updated. If this parameter is omitted, it indicates the end of the image span.| +| start | number | No| Start position of the image span whose style needs to be updated. If this parameter is omitted or set to a negative value, the value **0** will be used.| +| end | number | No| End position of the image span whose style needs to be updated. If this parameter is omitted or set to a value beyond the text range, it indicates the end of the image span.| | imageStyle | [RichEditorImageSpanStyle](#richeditorimagespanstyle) | Yes| Image style.| @@ -296,12 +305,12 @@ Provides the text style information. | Name| Type| Mandatory| Description | | ------ | -------- | ---- | -------------------------------------- | -| fontColor | [ResourceColor](ts-types.md#resourcecolor) | No| Font color.| -| fontSize | [Length](ts-types.md#length) \| number | No| Font size.| -| fontStyle | [FontStyle](ts-appendix-enums.md#fontstyle) | No| Font style.| -| fontWeight | [FontWeight](ts-appendix-enums.md#fontweight) \| number \| string | No| Font weight.| -| fontFamily | [ResourceStr](ts-types.md#resourcestr) \| number \| string | No| Font family. Default value: **'HarmonyOS Sans'**.
Currently, only the default font is supported.| -| decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: [ResourceColor](ts-types.md#resourcecolor)
} \| number \| string | No| Style and color of the text decorative line.| +| 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.
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
}| ## RichEditorImageSpanOptions @@ -320,8 +329,8 @@ Provides the image span style information. | Name| Type| Mandatory| Description | | ------ | -------- | ---- | -------------------------------------- | | size | [Dimension, Dimension] | No| Width and height of the image.| -| verticalAlign | [ImageSpanAlignment](ts-basic-components-imagespan.md#imagespanalignment) | No | Vertical alignment mode of the image.| -| objectFit | [ImageFit]((ts-basic-components-imagespan.md#imagefit)) | No| Scale mode of the image.| +| verticalAlign | [ImageSpanAlignment](ts-basic-components-imagespan.md#imagespanalignment) | No | Vertical alignment mode of the image.
Default value: **ImageSpanAlignment.BASELINE**| +| objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | No| Scale mode of the image.
Default value: **ImageFit.Cover**| ## RichEditorRange @@ -329,12 +338,14 @@ Provides the span range information. | Name| Type| Mandatory| Description | | ------ | -------- | ---- | -------------------------------------- | -| start | number | No| Start position. If this parameter is omitted, the value **0** will be used.| -| end | number | No| End position. If this parameter is omitted, it indicates the very end.| +| start | number | No| Start position. If this parameter is omitted or set to a negative value, the value **0** will be used.| +| end | number | No| End position of the image span whose style needs to be updated. If this parameter is omitted or set to a value beyond the text range, it indicates the very end.| ## Example +### Example 1 + ```ts // xxx.ets @Entry @@ -484,3 +495,47 @@ struct Index { } ``` ![richeditor](figures/richeditor.gif) + +### 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) + } + } +} +``` + +![customKeyboard](figures/richEditorCustomKeyboard.png) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-richtext.md b/en/application-dev/reference/arkui-ts/ts-basic-components-richtext.md index 032b5b61a6a49ed33eaa3b65d38321b73cac8117..e7093230c1146b5c18238ea115189f13ce8de2cf 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-richtext.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-richtext.md @@ -52,6 +52,19 @@ Among the [universal attributes](ts-universal-attributes-size.md), only the **wi | style | Defines the inline style of an element and is placed inside the tag. Use quotation marks (') to separate the styling text and use semicolons (;) to separate styles, for example, **style='width: 500px;height: 500px;border: 1px solid;margin: 0 auto;'**.| \

This is a heading\

\

This is text\

| | \ | Embeds or references a client-side script, such as JavaScript.| \ | + +## Precautions + +The underlying layer of the **\** component uses the **\** component to provide basic capabilities, including but not limited to HTML page parsing and rendering. However, the **\** component is resources consuming. In scenarios where the **\** component is repeatedly used, for example, when it is repeatedly used in a list, frame freezing or slow response may occur. + +The **\** component complies with the constraints of the **\** component. A typical scenario is as follows: + +The default viewport size of a mobile device is 980 px. This default value ensures that most web pages can be browsed properly on the mobile device. If the width of the **\** component is less than this value, the HTML content specified by **content** may generate a scrollable page that is wrapped by the **\** component. If you want to replace the default value, add the following tags to **content**: + +```html + +``` + ## Example You can preview how this component looks on a real device. The preview is not yet available in the DevEco Studio Previewer. @@ -67,7 +80,7 @@ struct RichTextExample { '

h2 heading

' + '

h3 heading

' + '

Regular paragraph


' + - '
' + + '
' + '

Font size: 35px; line height: 45px

' + '

' + '

This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text.

'; @@ -83,7 +96,7 @@ struct RichTextExample { console.info('RichText onComplete'); }) .width(500) - .height(400) + .height(500) .backgroundColor(0XBDDB69) RichText('layoutWeight(1)') .onStart(() => { @@ -111,7 +124,3 @@ struct RichTextExample { ``` ![richText](figures/richText.png) - -## Precautions - -The underlying layer of the **\** component reuses the **\** component to provide basic capabilities, including but not limited to HTML page parsing and rendering. However, the **\** component is resources consuming. In scenarios where the **\** component is repeatedly used, for example, when it is repeatedly used in a list, frame freezing or slow response may occur. 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 39a42e0e1d46103d7019f0d01770b9423380bee9..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 @@ -30,22 +30,24 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name | Type | Description | | ----------------------- | ------------------------------------------------ | ---------------------------------------------- | | searchButton10+ | value: string,
option?: [SearchButtonOptions](#searchbuttonoptions10) | Text on the search button located next to the search text box. By default, there is no search button. | -| placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | Placeholder text color. | +| placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | Placeholder text color.
Default value: **'#99182431'** | | placeholderFont | [Font](ts-types.md#font) | Placeholder text style, including the font size, font width, font family, and font style. Currently, only the default font family is supported. | | textFont | [Font](ts-types.md#font) | Style of the text entered in the search box, including the font size, font width, font family, and font style. Currently, only the default font family is supported. | | textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Text alignment mode in the search text box.
Default value: **TextAlign.Start** | -| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed. | +| 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 text can be pasted, but copy or cut is not allowed. | | searchIcon10+ | [IconOptions](#iconoptions10) | Style of the search icon on the left. | -| cancelButton10+ | {
style? : [CancelButtonStyle](#cancelbuttonstyle10)
icon?: [IconOptions](#iconoptions10)
} | Style of the Cancel button on the right. | -| fontColor10+ | [ResourceColor](ts-types.md#resourcecolor) | Font color of the input text. | -| caretStyle10+ | [CaretStyle](#caretstyle10) | Caret style. | +| cancelButton10+ | {
style? : [CancelButtonStyle](#cancelbuttonstyle10)
icon?: [IconOptions](#iconoptions10)
} | Style of the Cancel button on the right.
Default value:
{
style: CancelButtonStyle.INPUT
} | +| fontColor10+ | [ResourceColor](ts-types.md#resourcecolor) | Font color of the input text.
Default value: **'#FF182431'**
**NOTE**
[Universal text attributes](ts-universal-attributes-text-style.md) **fontSize**, **fontStyle**, **fontWeight**, and **fontFamily** are set in the **textFont** attribute.| +| 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 { ``` ![searchButton](figures/searchButton.gif) + + +### 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 }) + } + } +} +```` + +![customKeyboard](figures/searchCustomKeyboard.png) 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-stepperitem.md b/en/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md index 07b043411ed7ce7658cb575490e559e0dbd3aab0..daf26e98a24a303138f9f79c88c4340c73ba629a 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md @@ -26,6 +26,11 @@ StepperItem() | nextLabel | string | Text label of the button on the right. The default value is **Start** for the last page and **Next** for the other pages.| | status | [ItemState](#itemstate) | Display status of **nextLabel** in the stepper. Optional.
Default value: **ItemState.Normal**| +> **NOTE** +> +> - The **\** component does not support setting of the universal width attribute. By default, its width is the same as that of the parent **\** component. +> - The **\** component does not support setting of the universal height attribute. Its height is the height of the parent **\** component minus the height of the label button. +> - The **\** component does not support setting of the **aspectRadio** or **constrainSize** attribute, which may affect the length and width. ## ItemState | Name | Description| diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md b/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md index 8b904ffd03ba102894adeec6e8745ab9cdae687d..32dab9e0af0b4e4e8066358aefc1a758333899a7 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md @@ -37,11 +37,14 @@ Among the [universal attributes](ts-universal-attributes-size.md) and [universal | caretColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the caret in the text box.
Default value: **'#007DFF'** | | 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 specified 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 the copy and cut operations are not.| -| maxLength10+ | number | Maximum number of characters in the text input.
By default, there is no maximum number of characters.| +| maxLength10+ | number | Maximum number of characters in the text input.
By default, there is no maximum number of characters.
When the maximum number of characters is reached, no more characters can be entered, and the border turns red.| | showCounter10+ | boolean | Whether to show the number of entered characters when **maxLength** is set.
Default value: **false** | | style10+ | [TextContentStyle](ts-appendix-enums.md#textcontentstyle10) | Style of the component.
Default value: **TextContentStyle.DEFAULT** | | 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**| +| barState10+ | [BarState](ts-appendix-enums.md#BarState) | Scrollbar state when the inline input style is used.
Default value: **BarState.Auto**| +| maxLines10+ | number | Maximum number of lines that can be displayed when the inline input style is used.
Default value: **3**| +| 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 [TextAreaController](#textareacontroller8).[stopEditing](#stopediting10) API to close the keyboard.| > **NOTE** > @@ -225,3 +228,47 @@ struct TextAreaExample { ``` ![maxLength](figures/maxLength.png) + + +### Example 3 + +```ts +// xxx.ets +@Entry +@Component +struct TextAreaExample { + controller: TextAreaController = new TextAreaController() + @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() { + TextArea({ controller: this.controller, text: this.inputValue}) + // Bind the custom keyboard. + .customKeyboard(this.CustomKeyboardBuilder()).margin(10).border({ width: 1 }) + .height(200) + } + } +} +``` + +![customKeyboard](figures/textAreaCustomKeyboard.png) 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 c5a20c371a9ed6420cdfe33200a596bf53104806..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 @@ -45,12 +45,15 @@ Among the [universal attributes](ts-universal-attributes-size.md) and [universal | 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. | | caretPosition10+ | number | Caret position.| -| showUnit10+ | [CustomBuilder](ts-types.md#CustomBuilder8) | Unit for content in the component.
By default, there is no unit.| +| showUnit10+ | [CustomBuilder](ts-types.md#CustomBuilder8) | Unit for content in the component.
By default, there is no unit.| | showError10+ | string \| undefined | Error text displayed when an error occurs.
By default, no error text is displayed.| | showUnderline10+ | boolean | Whether to show an underline.
Default value: **false**| | passwordIcon10+ | [PasswordIcon](#passwordicon10) | Password icon to display at the end of the password text box.
By default, the system-provided icon is used.| | 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**| +| barState10+ | [BarState](ts-appendix-enums.md#BarState) | Scrollbar state when the inline input style is used.
Default value: **BarState.Auto**| +| maxLines10+ | number | Maximum number of lines that can be displayed when the inline input style is used.
Default value: **3**| +| 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, and the **enterKeyType** attribute setting for the system keyboard will not take effect.
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 [TextInputController](#textinputcontroller8).[stopEditing](#stopediting10) API to close the keyboard.| > **NOTE** > @@ -71,7 +74,7 @@ Among the [universal attributes](ts-universal-attributes-size.md) and [universal | Name | Description | | ------------------ | ------------- | | Normal | Normal input mode.
The value can contain digits, letters, underscores (_), spaces, and special characters.| -| Password | Password input mode. The value can contain digits, letters, underscores (_), spaces, and special characters. An eye icon is used to show or hide the password, and the password is hidden behind dots by default.| +| Password | Password input mode. The value can contain digits, letters, underscores (_), spaces, and special characters. An eye icon is used to show or hide the password, and the password is hidden behind dots by default. The password input mode does not support underlines.| | Email | Email address input mode. The value can contain digits, letters, underscores (_), and at signs (@). Only one at sign (@) is allowed.| | Number | Digit input mode. | | PhoneNumber9+ | Phone number input mode.
The value can contain digits, plus signs (+), hyphens (-), asterisks (*), and number signs (#). The length is not limited.| @@ -81,7 +84,7 @@ Among the [universal attributes](ts-universal-attributes-size.md) and [universal | Name | Description | | ------------------ | ------------- | | Default | Default style. The caret width is fixed at 1.5 vp, and the caret height is subject to the background height and font size of the selected text. | -| Inline | Inline input style. The background height of the selected text is the same as the height of the text box. | +| Inline | Inline input style. The background height of the selected text is the same as the height of the text box.
This style is used in scenarios where editing and non-editing states are obvious, for example, renaming in the file list view.| ## PasswordIcon10+ @@ -241,7 +244,7 @@ struct TextInputExample { } ``` -![textInput](figures/textInput.gif) +![TextInput](figures/TextInput.png) ### Example 2 @@ -294,3 +297,45 @@ struct TextInputExample { ``` ![showUnit](figures/showUnit.png) + +### Example 3 + +```ts +// xxx.ets +@Entry +@Component +struct TextInputExample { + controller: TextInputController = new TextInputController() + @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() { + TextInput({ controller: this.controller, text: this.inputValue }) + // Bind the custom keyboard. + .customKeyboard(this.CustomKeyboardBuilder()).margin(10).border({ width: 1 }) + } + } +} +``` + +![customKeyboard](figures/textInputCustomKeyboard.png) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-textpicker.md b/en/application-dev/reference/arkui-ts/ts-basic-components-textpicker.md index ac4939dac0b575bc416c3fa85a2d1c777a43947e..d33e3188d979660311d0d98df6af7593859d0420 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-textpicker.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-textpicker.md @@ -50,7 +50,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | disappearTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | Font color, font size, and font width for the top and bottom items.
Default value:
{
color: '#ff182431',
font: {
size: '14fp',
weight: FontWeight.Regular
}
} | | textStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | Font color, font size, and font width of all items except the top, bottom, and selected items.
Default value:
{
color: '#ff182431',
font: {
size: '16fp',
weight: FontWeight.Regular
}
} | | selectedTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | Font color, font size, and font width of the selected item.
Default value:
{
color: '#ff007dff',
font: {
size: '20vp',
weight: FontWeight.Medium
}
} | -| selectedIndex10+ | number \| number[] | Sets the index value of the default selected item in the array. The priority is higher than that of the selected value in options.
**NOTE**
For a single-column picker, use a value of the number type. For a multi-column (linked) picker, use a value of the number[] type.| +| selectedIndex10+ | number \| number[] | Index of the default selected item in the array. Its priority is higher than that of the selected value in **options**.
**NOTE**
For a single-column picker, use a value of the number type. For a multi-column (linked) picker, use a value of the number[] type.| +| canLoop10+ | boolean | Whether to support scroll looping. The value **true** means to support scroll looping, and **false** means the opposite.
Default value: **true**| ## Events @@ -60,11 +61,63 @@ In addition to the [universal events](ts-universal-events-click.md), the followi | -------- | -------- | | onAccept(callback: (value: string, index: number) => void)(deprecated) | Triggered when the OK button in the dialog box is clicked.
- **value**: value of the selected item.
- **index**: index of the selected item.
This API is deprecated since API version 10.
**NOTE**
This event can be triggered only in the [text picker dialog box](ts-methods-textpicker-dialog.md).| | onCancel(callback: () => void)(deprecated) | Triggered when the Cancel button in the dialog box is clicked.
This API is deprecated since API version 10.
**NOTE**
This event can be triggered only in the [text picker dialog box](ts-methods-textpicker-dialog.md).| -| onChange(callback: (value: string \| string[]10+, index: number \| number[]10+) => void) | Triggered when an item in the picker is selected.
- **value**: value of the selected item. (For a multi-column picker, **value** is of the array type.)
- **index**: index of the selected item. (For a multi-column picker, **index** is of the array type.)
**NOTE**
When the picker contains text only or both text and imagery, **value** indicates the text value of the selected item.When the picker contains imagery only, **value** is empty.| +| onChange(callback: (value: string \| string[]10+, index: number \| number[]10+) => void) | Triggered when an item in the picker is selected.
- **value**: value of the selected item. (For a multi-column picker, **value** is of the array type.)
- **index**: index of the selected item. (For a multi-column picker, **index** is of the array type.)
**NOTE**
When the picker contains text only or both text and imagery, **value** indicates the text value of the selected item. When the picker contains imagery only, **value** is empty.| ## Example +```ts +// xxx.ets +@Entry +@Component +struct TextPickerExample { + private select: number = 1 + private apfruits: string[] = ['apple1', 'apple2', 'apple3', 'apple4'] + private orfruits: string[] = ['orange1', 'orange2', 'orange3', 'orange4'] + private pefruits: string[] = ['peach1', 'peach2', 'peach3', 'peach4'] + private multi: string[][] = [this.apfruits, this.orfruits, this.pefruits] + private cascade: TextCascadePickerRangeContent[] = [ + { + text: 'Category 1', + children: [{ text: 'Subcategory 1', children: [{ text: 'Subcategory 2' }, { text: 'Subcategory 3' }, { text: 'Subcategory 4' }] }, + { text: 'Item 1', children: [{ text: ''Item 2' }, { text: ''Item 3' }, { text: ''Item 4' }] }] + }, + { + text: 'Category 2', + children: [{ text: 'Subcategory 1', children: [{ text: 'Subcategory 2' }, { text: 'Subcategory 3' }, { text: 'Subcategory 4' }] }, + { text: 'Item 1', children: [{ text: ''Item 2' }, { text: ''Item 3' }, { text: ''Item 4' }] }] + }, + { + text: 'Category 3', + children: [{ text: 'Subcategory 1', children: [{ text: 'Subcategory 2' }, { text: 'Subcategory 3' }, { text: 'Subcategory 4' }] }, + { text: 'Item 1', children: [{ text: ''Item 2' }, { text: ''Item 3' }, { text: ''Item 4' }] }] + } + ] + + build() { + Column() { + + TextPicker({ range: this.apfruits, selected: this.select }) + .onChange((value: string, index: number) => { + console.info('Picker item changed, value: ' + value + ', index: ' + index) + }).margin({ bottom: 50 }) + + TextPicker({ range: this.multi }) + .onChange((value: string | string[], index: number | number[]) => { + console.info('TextPicker multi-column: onChange' + JSON.stringify(value) + ',' + 'index:' + JSON.stringify(index)) + }).margin({ bottom: 50 }) + + TextPicker({ range: this.cascade }) + .onChange((value: string | string[], index: number | number[]) => { + console.info('TextPicker multi-column linkage: onChange' + JSON.stringify(value) + ',' + 'index:' + JSON.stringify(index)) + }) + } + } +} +``` + +![textpicker](figures/textpicker.gif) + ```ts // xxx.ets @Entry @@ -79,9 +132,12 @@ struct TextPickerExample { .onChange((value: string, index: number) => { console.info('Picker item changed, value: ' + value + ', index: ' + index) }) - } + .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%').height('100%') } } ``` -![en-us_image_0000001257058417](figures/en-us_image_0000001257058417.png) +![textpicker](figures/textpicker1.gif) 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-basic-components-toggle.md b/en/application-dev/reference/arkui-ts/ts-basic-components-toggle.md index 7a78929dca57da1194d9454042286393f8a773b2..49ca12cd0645aee4a524f2109e6998723f83b578 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-toggle.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-toggle.md @@ -31,7 +31,7 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Description | | -------- | ---------------- | -| Checkbox | Check box type.
**NOTE**
The default value of the universal attribute [margin](ts-universal-attributes-size.md) is as follows:
{
top: 12 px,
right: 12 px,
bottom: 12 px,
left: 12 px
} | +| Checkbox | Check box type.
**NOTE**
The default value of the universal attribute [margin](ts-universal-attributes-size.md) is as follows:
{
top: 14 px,
right: 14 px,
bottom: 14 px,
left: 14 px
} | | Button | Button type. The set string, if any, will be displayed inside the button. | | Switch | Switch type.
**NOTE**
The default value of the universal attribute [margin](ts-universal-attributes-size.md) is as follows:
{
top: 6px,
right: 14px,
bottom: 6 px,
left: 14 px
} | diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-web.md b/en/application-dev/reference/arkui-ts/ts-basic-components-web.md index 2d6b3bab8f6c8dfeef3c2b65b3068d1546d4b652..b3c50c96f5760173ce05f46a39423aaef86d1e3b 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-web.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-web.md @@ -107,32 +107,31 @@ Web(options: { src: ResourceStr, controller: WebviewController | WebController}) ``` 2. Modify the **EntryAbility.ts** file. + The following uses **filesDir** as an example to describe how to obtain the path of the sandbox. For details about how to obtain other paths, see [Obtaining Application File Paths](../../application-models/application-context-stage.md#obtaining-application-file-paths). + ```ts + // xxx.ts + import UIAbility from '@ohos.app.ability.UIAbility'; + import web_webview from '@ohos.web.webview'; + + export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + // Bind filesDir to the globalThis object to implement data synchronization between the UIAbility component and the UI. + globalThis.filesDir = this.context.filesDir + console.log("Sandbox path is " + globalThis.filesDir) + } + } + ``` - The following uses **filesDir** as an example to describe how to obtain the path of the sandbox. For details about how to obtain other paths, see [Obtaining Application File Paths](../../application-models/application-context-stage.md#obtaining-application-file-paths). - ```ts - // xxx.ts - import UIAbility from '@ohos.app.ability.UIAbility'; - import web_webview from '@ohos.web.webview'; - - export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - // Bind filesDir to the globalThis object to implement data synchronization between the UIAbility component and the UI. - globalThis.filesDir = this.context.filesDir - console.log("Sandbox path is " + globalThis.filesDir) - } - } - ``` - - HTML file to be loaded: - ```html - - - - -

Hello World

- - - ``` + HTML file to be loaded: + ```html + + + + +

Hello World

+ + + ``` ## Attributes @@ -672,12 +671,16 @@ Sets whether to display the vertical scrollbar, including the default system scr ``` -### password +### password(deprecated) password(password: boolean) Sets whether the password should be saved. This API is a void API. +> **NOTE** +> +> This API is deprecated since API version 10, and no new API is provided as a substitute. + ### cacheMode cacheMode(cacheMode: CacheMode) @@ -993,7 +996,6 @@ Sets the minimum logical font size for the web page. } ``` - ### webFixedFont9+ webFixedFont(family: string) @@ -1244,18 +1246,26 @@ Sets whether to enable forcible dark mode for the web page. By default, this fea } ``` -### tableData +### tableData(deprecated) tableData(tableData: boolean) Sets whether form data should be saved. This API is a void API. -### wideViewModeAccess +> **NOTE** +> +> This API is deprecated since API version 10, and no new API is provided as a substitute. + +### wideViewModeAccess(deprecated) wideViewModeAccess(wideViewModeAccess: boolean) Sets whether to support the viewport attribute of the HTML **\** tag. This API is a void API. +> **NOTE** +> +> This API is deprecated since API version 10, and no new API is provided as a substitute. + ### pinchSmooth9+ pinchSmooth(isEnabled: boolean) @@ -1386,7 +1396,6 @@ Sets the web-based media playback policy, including the validity period for auto **Example** - ```ts // xxx.ets import web_webview from '@ohos.web.webview' @@ -1941,7 +1950,6 @@ Called when an HTTP error (the response code is greater than or equal to 400) oc onPageBegin(callback: (event?: { url: string }) => void) - Called when the web page starts to be loaded. This API is called only for the main frame content, and not for the iframe or frameset content. **Parameters** @@ -1976,7 +1984,6 @@ Called when the web page starts to be loaded. This API is called only for the ma onPageEnd(callback: (event?: { url: string }) => void) - Called when the web page loading is complete. This API takes effect only for the main frame content. **Parameters** @@ -2979,7 +2986,7 @@ If opening a new window is not needed, set the parameter to **null** when callin ```ts // xxx.ets import web_webview from '@ohos.web.webview' - + // There are two components on the same page. When the WebComponent object opens a new window, the NewWebViewComp object is displayed. @CustomDialog struct NewWebViewComp { @@ -3335,8 +3342,8 @@ Called when the web page content is first rendered. Column() { Web({ src:'www.example.com', controller: this.controller }) .onFirstContentfulPaint(event => { - console.log("onFirstContentfulPaint:" + "[navigationStartTick]:" + - event.navigationStartTick + ", [firstContentfulPaintMs]:" + + console.log("onFirstContentfulPaint:" + "[navigationStartTick]:" + + event.navigationStartTick + ", [firstContentfulPaintMs]:" + event.firstContentfulPaintMs) }) } @@ -3415,7 +3422,156 @@ Called when the **\** component obtains the focus. } } ``` +### onScreenCaptureRequest10+ + +onScreenCaptureRequest(callback: (event?: { handler: ScreenCaptureHandler }) => void) + +Called when a screen capture request is received. + +**Parameters** + +| Name | Type | Description | +| ------- | ---------------------------------------- | -------------- | +| handler | [ScreenCaptureHandler](#screencapturehandler10) | User operation.| + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .onScreenCaptureRequest((event) => { + AlertDialog.show({ + title: 'title: ' + event.handler.getOrigin(), + message: 'text', + primaryButton: { + value: 'deny', + action: () => { + event.handler.deny() + } + }, + secondaryButton: { + value: 'onConfirm', + action: () => { + event.handler.grant({ captureMode: WebCaptureMode.HOME_SCREEN }) + } + }, + cancel: () => { + event.handler.deny() + } + }) + }) + } + } + } + ``` +### onOverScroll10+ + +onOverScroll(callback: (event: {xOffset: number, yOffset: number}) => void) + +Called to indicate the offset by which the web page overscrolls. + +**Parameters** + +| Name | Type | Description | +| ------- | ------ | ------------ | +| xOffset | number | Horizontal overscroll offset based on the leftmost edge of the web page.| +| yOffset | number | Vertical overscroll offset based on the top edge of the web page.| + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .onOverScroll((event) => { + console.info("x = " + event.xOffset) + console.info("y = " + event.yOffset) + }) + } + } + } + ``` + +### onControllerAttached10+ + +onControllerAttached(callback: () => void) + +Called when the controller is successfully bound to the **\** component. The controller must be WebviewController. +As the web page is not yet loaded when this callback is called, APIs for operating the web page cannot be used in the callback, for example, [zoomIn](../apis/js-apis-webview.md#zoomin) and [zoomOut]. (../apis/js-apis-webview.md#zoomout). Other APIs, such as [loadUrl] (../apis/js-apis-webview.md#loadurl) and [getWebId] (../apis/js-apis-webview.md#getwebid), which do not involve web page operations, can be used properly. + +**Example** + +The following example uses **loadUrl** in the callback to load the web page. + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + + build() { + Column() { + Web({ src: '', controller: this.controller }) + .onControllerAttached(() => { + this.controller.loadUrl($rawfile("index.html")); + }) + } + } + } + ``` +The following example uses **getWebId** in the callback + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + + build() { + Column() { + Web({ src: $rawfile("index.html"), controller: this.controller }) + .onControllerAttached(() => { + try { + let id = this.controller.getWebId(); + console.log("id: " + id); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + } + } + } + ``` + HTML file to be loaded: + ```html + + + + +

Hello World

+ + + ``` ## ConsoleMessage Implements the **ConsoleMessage** object. For the sample code, see [onConsole](#onconsole). @@ -3470,7 +3626,7 @@ Obtains the path and name of the web page source file. ## JsResult -Implements the **JsResult** object, which indicates the result returned to the **\** component to indicate the user operation performed in the dialog box. For the sample code, see [onAlert](#onalert). +Implements the **JsResult** object, which indicates the result returned to the **\** component to indicate the user operation performed in the dialog box. For the sample code, see [onAlert Event](#onalert). ### handleCancel @@ -3635,7 +3791,6 @@ Describes the request/response header returned by the **\** component. | headerKey | string | Key of the request/response header. | | headerValue | string | Value of the request/response header.| - ## WebResourceResponse Implements the **WebResourceResponse** object. For the sample code, see [onHttpErrorReceive](#onhttperrorreceive). @@ -4010,6 +4165,42 @@ Grants the permission for resources requested by the web page. | --------- | --------------- | ---- | ---- | ------------- | | resources | Array\ | Yes | - | List of resources that can be requested by the web page with the permission to grant.| +## ScreenCaptureHandler10+ + +Implements the **ScreenCaptureHandler** object for accepting or rejecting a screen capture request. For the sample code, see [onScreenCaptureRequest Event](#onscreencapturerequest10). + +### deny10+ + +deny(): void + +Rejects this screen capture request. + +### getOrigin10+ + +getOrigin(): string + +Obtains the origin of this web page. + +**Return value** + +| Type | Description | +| ------ | ------------ | +| string | Origin of the web page that requests the permission.| + +### grant10+ + +grant(config: ScreenCaptureConfig): void + +**Required permissions**: ohos.permission.MICROPHONE, ohos.permission.CAPTURE_SCREEN + +Grants the screen capture permission. + +**Parameters** + +| Name | Type | Mandatory | Default Value | Description | +| --------- | --------------- | ---- | ---- | ------------- | +| config | [ScreenCaptureConfig](#screencaptureconfig10) | Yes | - | Screen capture configuration.| + ## ContextMenuSourceType9+ | Name | Description | | -------------------- | ---------- | @@ -4327,6 +4518,7 @@ Enumerates the error codes returned by **onSslErrorEventReceive** API. | --------- | ------------- | -------------------------- | | MidiSysex | MIDI SYSEX resource.| Currently, only permission events can be reported. MIDI devices are not yet supported.| | VIDEO_CAPTURE10+ | Video capture resource, such as a camera.| | +| AUDIO_CAPTURE10+ | Audio capture resource, such as a microphone.| | ## WebDarkMode9+ | Name | Description | @@ -4335,6 +4527,12 @@ Enumerates the error codes returned by **onSslErrorEventReceive** API. | On | The web dark mode is enabled. | | Auto | The web dark mode setting follows the system settings. | +## WebCaptureMode10+ + +| Name | Description | +| --------- | ------------- | +| HOME_SCREEN | Capture of the home screen.| + ## WebMediaOptions10+ Describes the web-based media playback policy. @@ -4344,6 +4542,14 @@ Describes the web-based media playback policy. | resumeInterval | number | Yes | Yes | No |Validity period for automatically resuming a paused web audio, in seconds. The maximum validity period is 60 seconds. Due to the approximate value, the validity period may have a deviation of less than 1 second.| | audioExclusive | boolean | Yes | Yes | No | Whether the audio of multiple **\** instances in an application is exclusive. | +## ScreenCaptureConfig10+ + +Provides the web screen capture configuration. + +| Name | Type | Readable| Writable| Mandatory| Description | +| -------------- | --------- | ---- | ---- | --- | ---------------------------- | +| captureMode | [WebCaptureMode](#webcapturemode10) | Yes | Yes | Yes | Web screen capture mode.| + ## DataResubmissionHandler9+ Implements the **DataResubmissionHandler** object for resubmitting or canceling the web form data. @@ -4653,7 +4859,7 @@ This API is deprecated since API version 9. You are advised to use [forward deleteJavaScriptRegister(name: string) -Deletes a specific application JavaScript object that is registered with the window through **registerJavaScriptProxy**. The deletion takes effect immediately, with no need for invoking the[refresh](#refreshdeprecated) API. +Deletes a specific application JavaScript object that is registered with the window through **registerJavaScriptProxy**. The deletion takes effect immediately, with no need for invoking the [refresh](#refreshdeprecated) API. This API is deprecated since API version 9. You are advised to use [deleteJavaScriptRegister9+](../apis/js-apis-webview.md#deletejavascriptregister) instead. diff --git a/en/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md b/en/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md index 7f0b8291246271cef1d8b9e82394004c051cf491..5630bcc7f24f2b40dca403a2b14cba04e37a8213 100644 --- a/en/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md +++ b/en/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md @@ -40,13 +40,13 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Type | Description | | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | -| [fillStyle](#fillstyle) | string \|number10+ \|[CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](ts-components-canvas-canvaspattern.md#canvaspattern) | Style to fill an area.
- When the type is string, this attribute indicates the color of the fill area.
- When the type is number, this attribute indicates the color of the fill area.
- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.
- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.
Since API version 9, this API is supported in ArkTS widgets.| -| [lineWidth](#linewidth) | number | Line width. | -| [strokeStyle](#strokestyle) | string \|number10+ \|[CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](ts-components-canvas-canvaspattern.md#canvaspattern) | Stroke style.
- When the type is string, this attribute indicates the stroke color.
- When the type is number, this attribute indicates the stroke color.
- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.
- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.
Since API version 9, this API is supported in ArkTS widgets.| +| [fillStyle](#fillstyle) | string \|number10+ \|[CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](ts-components-canvas-canvaspattern.md#canvaspattern) | Style to fill an area.
- When the type is string, this attribute indicates the color of the fill area.
Default value: **'black'**
- When the type is number, this attribute indicates the color of the fill area.
Default value: **'#000000'**
- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.
- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.
Since API version 9, this API is supported in ArkTS widgets.| +| [lineWidth](#linewidth) | number | Line width.
Default value: **1(px)** | +| [strokeStyle](#strokestyle) | string \|number10+ \|[CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](ts-components-canvas-canvaspattern.md#canvaspattern) | Stroke style.
- When the type is string, this attribute indicates the stroke color.
Default value: **'black'**
- When the type is number, this attribute indicates the stroke color.
Default value: **'#000000'**
- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.
- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.
Since API version 9, this API is supported in ArkTS widgets.| | [lineCap](#linecap) | CanvasLineCap | Style of the line endpoints. The options are as follows:
- **'butt'**: The endpoints of the line are squared off.
- **'round'**: The endpoints of the line are rounded.
- **'square'**: The endpoints of the line are squared off by adding a box with an equal width and half the height of the line's thickness.
Default value: **'butt'**
Since API version 9, this API is supported in ArkTS widgets.| | [lineJoin](#linejoin) | CanvasLineJoin | Style of the shape used to join line segments. The options are as follows:
- **'round'**: The shape used to join line segments is a sector, whose radius at the rounded corner is equal to the line width.
- **'bevel'**: The shape used to join line segments is a triangle. The rectangular corner of each line is independent.
- **'miter'**: The shape used to join line segments has a mitered corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in **miterLimit**.
Default value: **'miter'**
Since API version 9, this API is supported in ArkTS widgets.| | [miterLimit](#miterlimit) | number | Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet.
Default value: **10**
Since API version 9, this API is supported in ArkTS widgets.| -| [font](#font) | string | Font style.
Syntax: ctx.font='font-size font-family'
- (Optional) **font-size**: font size and row height. The unit can only be pixels.
- (Optional) **font-family**: font family.
Syntax: ctx.font='font-style font-weight font-size font-family'
- (Optional) **font-style**: font style. Available values are **'normal'** and **'italic'**.
- (Optional) **font-weight**: font weight. Available values are as follows: **'normal'**, **'bold'**, **'bolder'**, **'lighter'**, **'100'**, **'200'**, **'300'**, **'400'**, **'500'**, **'600'**, **'700'**, **'800'**, **'900'**.
- (Optional) **font-size**: font size and row height. The unit must be specified and can only be px or vp.
- (Optional) **font-family**: font family. Available values are **'sans-serif'**, **'serif'**, and **'monospace'**.
Default value: **'normal normal 14px sans-serif'**
Since API version 9, this API is supported in ArkTS widgets.| +| [font](#font) | string | Font style.
Syntax: ctx.font='font-size font-family'
- (Optional) **font-size**: font size and row height. The unit can only be px.
- (Optional) **font-family**: font family.
Syntax: ctx.font='font-style font-weight font-size font-family'
- (Optional) **font-style**: font style. Available values are **'normal'** and **'italic'**.
- (Optional) **font-weight**: font weight. Available values are as follows: **'normal'**, **'bold'**, **'bolder'**, **'lighter'**, **'100'**, **'200'**, **'300'**, **'400'**, **'500'**, **'600'**, **'700'**, **'800'**, **'900'**.
- (Optional) **font-size**: font size and row height. The unit must be specified and can only be px or vp.
- (Optional) **font-family**: font family. Available values are **'sans-serif'**, **'serif'**, and **'monospace'**.
Default value: **'normal normal 14px sans-serif'**
Since API version 9, this API is supported in ArkTS widgets.| | [textAlign](#textalign) | CanvasTextAlign | Text alignment mode. Available values are as follows:
- **'left'**: The text is left-aligned.
- **'right'**: The text is right-aligned.
- **'center'**: The text is center-aligned.
- **'start'**: The text is aligned with the start bound.
- **'end'**: The text is aligned with the end bound.
In the **ltr** layout mode, the value **'start'** equals **'left'**. In the **rtl** layout mode, the value **'start'** equals **'right'**.
Default value: **'left'**
Since API version 9, this API is supported in ArkTS widgets.| | [textBaseline](#textbaseline) | CanvasTextBaseline | Horizontal alignment mode of text. Available values are as follows:
- **'alphabetic'**: The text baseline is the normal alphabetic baseline.
- **'top'**: The text baseline is on the top of the text bounding box.
- **'hanging'**: The text baseline is a hanging baseline over the text.
- **'middle'**: The text baseline is in the middle of the text bounding box.
**'ideographic'**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excess character.
- **'bottom'**: The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line.
Default value: **'alphabetic'**
Since API version 9, this API is supported in ArkTS widgets.| | [globalAlpha](#globalalpha) | number | Opacity.
**0.0**: completely transparent.
**1.0**: completely opaque.
Since API version 9, this API is supported in ArkTS widgets.| @@ -59,8 +59,8 @@ Since API version 9, this API is supported in ArkTS widgets. | [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite.
Default value: **true**
Since API version 9, this API is supported in ArkTS widgets.| | [height](#height) | number | Component height.
Unit: vp
Since API version 9, this API is supported in ArkTS widgets.| | [width](#width) | number | Component width.
Unit: vp
Since API version 9, this API is supported in ArkTS widgets.| -| [imageSmoothingQuality](#imagesmoothingquality) | ImageSmoothingQuality | Quality of image smoothing. This attribute works only when **imageSmoothingEnabled** is set to **true**. Available values are as follows:
- **'low'**: low quality.
- **'medium'**: medium quality.
- **'high'**: high quality.
Default value: **'low'**
Since API version 9, this API is supported in ArkTS widgets.| -| [direction](#direction) | CanvasDirection | Text direction used for drawing text. Available values are as follows:
- **'inherit'**: The text direction is inherited from the **\** component.
- **'ltr'**: The text direction is from left to right.
- **'rtl'**: The text direction is from right to left.
Default value: **'inherit'**
Since API version 9, this API is supported in ArkTS widgets.| +| [imageSmoothingQuality](#imagesmoothingquality) |[ImageSmoothingQuality](ts-appendix-enums.md#imagesmoothingquality8) | Quality of image smoothing. This attribute works only when **imageSmoothingEnabled** is set to **true**.
Default value: **ImageSmoothingQuality.low**
Since API version 9, this API is supported in ArkTS widgets.| +| [direction](#direction) | [CanvasDirection](ts-appendix-enums.md#canvasdirection8) | Text direction used for drawing text.
Default value: **CanvasDirection.inherit**
Since API version 9, this API is supported in ArkTS widgets.| | [filter](#filter) | string | Filter effect. Available values are as follows:
- **'none'**: no filter effect.
- **'blur'**: applies the Gaussian blur for the image.
- **'brightness'**: applies a linear multiplication to the image to make it look brighter or darker.
- **'contrast'**: adjusts the image contrast.
- **'grayscale'**: converts the image to a grayscale image.
- **'hue-rotate'**: applies hue rotation to the image.
- **'invert'**: inverts the input image.
- **'opacity'**: sets the opacity of the image.
- **'saturate'**: sets the saturation of the image.
- **'sepia'**: converts the image to dark brown.
Default value: **'none'**
Since API version 9, this API is supported in ArkTS widgets.| > **NOTE** @@ -719,6 +719,136 @@ struct WidthExample { ![en-us_image_canvas_width](figures/en-us_image_canvas_width.png) +### imageSmoothingQuality + +```ts + // xxx.ets + @Entry + @Component + struct ImageSmoothingQualityDemo { + private settings: RenderingContextSettings = new RenderingContextSettings(true); + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private img:ImageBitmap = new ImageBitmap("common/images/example.jpg"); + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + let ctx = this.context + ctx.imageSmoothingEnabled = true + ctx.imageSmoothingQuality = 'high' + ctx.drawImage(this.img, 0, 0, 400, 200) + }) + } + .width('100%') + .height('100%') + } + } +``` + +![ImageSmoothingQualityDemo](figures/ImageSmoothingQualityDemo.jpeg) + + +### direction + +```ts + // xxx.ets + @Entry + @Component + struct DirectionDemo { + private settings: RenderingContextSettings = new RenderingContextSettings(true); + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + let ctx = this.context + ctx.font = '48px serif'; + ctx.textAlign = 'start' + ctx.fillText("Hi ltr!", 200, 50); + + ctx.direction = "rtl"; + ctx.fillText("Hi rtl!", 200, 100); + }) + } + .width('100%') + .height('100%') + } + } +``` + +![directionDemo](figures/directionDemo.jpeg) + + +### filter + +```ts + // xxx.ets + @Entry + @Component + struct FilterDemo { + private settings: RenderingContextSettings = new RenderingContextSettings(true); + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private img:ImageBitmap = new ImageBitmap("common/images/example.jpg"); + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + let ctx = this.context + let img = this.img + + ctx.drawImage(img, 0, 0, 100, 100); + + ctx.filter = 'grayscale(50%)'; + ctx.drawImage(img, 100, 0, 100, 100); + + ctx.filter = 'sepia(60%)'; + ctx.drawImage(img, 200, 0, 100, 100); + + ctx.filter = 'saturate(30%)'; + ctx.drawImage(img, 0, 100, 100, 100); + + ctx.filter = 'hue-rotate(90degree)'; + ctx.drawImage(img, 100, 100, 100, 100); + + ctx.filter = 'invert(100%)'; + ctx.drawImage(img, 200, 100, 100, 100); + + ctx.filter = 'opacity(25%)'; + ctx.drawImage(img, 0, 200, 100, 100); + + ctx.filter = 'brightness(0.4)'; + ctx.drawImage(img, 100, 200, 100, 100); + + ctx.filter = 'contrast(200%)'; + ctx.drawImage(img, 200, 200, 100, 100); + + ctx.filter = 'blur(5px)'; + ctx.drawImage(img, 0, 300, 100, 100); + + let result = ctx.toDataURL() + console.info(result) + }) + } + .width('100%') + .height('100%') + } + } +``` + +![filterDemo](figures/filterDemo.jpeg) + ## Methods @@ -734,8 +864,8 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Type | Mandatory | Default Value | Description | | ------ | ------ | ---- | ---- | ------------- | -| x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle.| -| y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle.| +| x | number | Yes | 0 | X coordinate of the upper left corner of the rectangle.| +| y | number | Yes | 0 | Y coordinate of the upper left corner of the rectangle.| | width | number | Yes | 0 | Width of the rectangle. | | height | number | Yes | 0 | Height of the rectangle. | @@ -780,8 +910,8 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Type | Mandatory | Default Value | Description | | ---- | ------ | ---- | ---- | ------------ | -| x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle.| -| y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle.| +| x | number | Yes | 0 | X coordinate of the upper left corner of the rectangle.| +| y | number | Yes | 0 | Y coordinate of the upper left corner of the rectangle.| | w | number | Yes | 0 | Width of the rectangle. | | h | number | Yes | 0 | Height of the rectangle. | @@ -826,8 +956,8 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Type | Mandatory | Default Value | Description | | ---- | ------ | ---- | ---- | ------------- | -| x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle.| -| y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle.| +| x | number | Yes | 0 | X coordinate of the upper left corner of the rectangle.| +| y | number | Yes | 0 | Y coordinate of the upper left corner of the rectangle.| | w | number | Yes | 0 | Width of the rectangle. | | h | number | Yes | 0 | Height of the rectangle. | @@ -875,8 +1005,8 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Type | Mandatory | Default Value | Description | | -------- | ------ | ---- | ---- | --------------- | | text | string | Yes | '' | Text to draw. | -| x | number | Yes | 0 | X-coordinate of the lower left corner of the text.| -| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text.| +| x | number | Yes | 0 | X coordinate of the lower left corner of the text.| +| y | number | Yes | 0 | Y coordinate of the lower left corner of the text.| | maxWidth | number | No | - | Maximum width allowed for the text. | **Example** @@ -922,8 +1052,8 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Type | Mandatory | Default Value | Description | | -------- | ------ | ---- | ---- | --------------- | | text | string | Yes | '' | Text to draw. | -| x | number | Yes | 0 | X-coordinate of the lower left corner of the text.| -| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text.| +| x | number | Yes | 0 | X coordinate of the lower left corner of the text.| +| y | number | Yes | 0 | Y coordinate of the lower left corner of the text.| | maxWidth | number | No | - | Maximum width of the text to be drawn. | **Example** @@ -1130,8 +1260,8 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Type | Mandatory | Default Value | Description | | ---- | ------ | ---- | ---- | --------- | -| x | number | Yes | 0 | X-coordinate of the target position.| -| y | number | Yes | 0 | Y-coordinate of the target position.| +| x | number | Yes | 0 | X coordinate of the target position.| +| y | number | Yes | 0 | Y coordinate of the target position.| **Example** @@ -1177,8 +1307,8 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Type | Mandatory | Default Value | Description | | ---- | ------ | ---- | ---- | --------- | -| x | number | Yes | 0 | X-coordinate of the target position.| -| y | number | Yes | 0 | Y-coordinate of the target position.| +| x | number | Yes | 0 | X coordinate of the target position.| +| y | number | Yes | 0 | Y coordinate of the target position.| **Example** @@ -1319,12 +1449,12 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Type | Mandatory | Default Value | Description | | ---- | ------ | ---- | ---- | -------------- | -| cp1x | number | Yes | 0 | X-coordinate of the first parameter of the bezier curve.| -| cp1y | number | Yes | 0 | Y-coordinate of the first parameter of the bezier curve.| -| cp2x | number | Yes | 0 | X-coordinate of the second parameter of the bezier curve.| -| cp2y | number | Yes | 0 | Y-coordinate of the second parameter of the bezier curve.| -| x | number | Yes | 0 | X-coordinate of the end point on the bezier curve. | -| y | number | Yes | 0 | Y-coordinate of the end point on the bezier curve. | +| cp1x | number | Yes | 0 | X coordinate of the first parameter of the bezier curve.| +| cp1y | number | Yes | 0 | Y coordinate of the first parameter of the bezier curve.| +| cp2x | number | Yes | 0 | X coordinate of the second parameter of the bezier curve.| +| cp2y | number | Yes | 0 | Y coordinate of the second parameter of the bezier curve.| +| x | number | Yes | 0 | X coordinate of the end point on the bezier curve. | +| y | number | Yes | 0 | Y coordinate of the end point on the bezier curve. | **Example** @@ -1370,10 +1500,10 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Type | Mandatory | Default Value | Description | | ---- | ------ | ---- | ---- | ----------- | -| cpx | number | Yes | 0 | X-coordinate of the bezier curve parameter.| -| cpy | number | Yes | 0 | Y-coordinate of the bezier curve parameter.| -| x | number | Yes | 0 | X-coordinate of the end point on the bezier curve.| -| y | number | Yes | 0 | Y-coordinate of the end point on the bezier curve.| +| cpx | number | Yes | 0 | X coordinate of the bezier curve parameter.| +| cpy | number | Yes | 0 | Y coordinate of the bezier curve parameter.| +| x | number | Yes | 0 | X coordinate of the end point on the bezier curve.| +| y | number | Yes | 0 | Y coordinate of the end point on the bezier curve.| **Example** @@ -1419,8 +1549,8 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Type | Mandatory | Default Value | Description | | ---------------- | ------- | ---- | ----- | ---------- | -| x | number | Yes | 0 | X-coordinate of the center point of the arc.| -| y | number | Yes | 0 | Y-coordinate of the center point of the arc.| +| x | number | Yes | 0 | X coordinate of the center point of the arc.| +| y | number | Yes | 0 | Y coordinate of the center point of the arc.| | radius | number | Yes | 0 | Radius of the arc. | | startAngle | number | Yes | 0 | Start radian of the arc. | | endAngle | number | Yes | 0 | End radian of the arc. | @@ -1469,10 +1599,10 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Type | Mandatory | Default Value | Description | | ------ | ------ | ---- | ---- | --------------- | -| x1 | number | Yes | 0 | X-coordinate of the first point on the arc.| -| y1 | number | Yes | 0 | Y-coordinate of the first point on the arc.| -| x2 | number | Yes | 0 | X-coordinate of the second point on the arc.| -| y2 | number | Yes | 0 | Y-coordinate of the second point on the arc.| +| x1 | number | Yes | 0 | X coordinate of the first point on the arc.| +| y1 | number | Yes | 0 | Y coordinate of the first point on the arc.| +| x2 | number | Yes | 0 | X coordinate of the second point on the arc.| +| y2 | number | Yes | 0 | Y coordinate of the second point on the arc.| | radius | number | Yes | 0 | Radius of the arc. | **Example** @@ -1518,8 +1648,8 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Type | Mandatory | Default Value | Description | | ---------------- | ------- | ---- | ----- | ---------------------------------------- | -| x | number | Yes | 0 | X-coordinate of the ellipse center. | -| y | number | Yes | 0 | Y-coordinate of the ellipse center. | +| x | number | Yes | 0 | X coordinate of the ellipse center. | +| y | number | Yes | 0 | Y coordinate of the ellipse center. | | radiusX | number | Yes | 0 | Ellipse radius on the x-axis. | | radiusY | number | Yes | 0 | Ellipse radius on the y-axis. | | rotation | number | Yes | 0 | Rotation angle of the ellipse. The unit is radian. | @@ -1570,8 +1700,8 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Type | Mandatory | Default Value | Description | | ---- | ------ | ---- | ---- | ------------- | -| x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle.| -| y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle.| +| x | number | Yes | 0 | X coordinate of the upper left corner of the rectangle.| +| y | number | Yes | 0 | Y coordinate of the upper left corner of the rectangle.| | w | number | Yes | 0 | Width of the rectangle. | | h | number | Yes | 0 | Height of the rectangle. | @@ -1802,97 +1932,6 @@ Since API version 9, this API is supported in ArkTS widgets. ![en-us_image_000000127777779](figures/en-us_image_000000127777779.png) -### filter - -filter(filter: string): void - -Provides filter effects. - -Since API version 9, this API is supported in ArkTS widgets. - -**Parameters** - -| Name | Type | Mandatory | Default Value | Description | -| ------ | ------ | ---- | ---- | ---------------------------------------- | -| filter | string | Yes | - | Filter functions. Available values are as follows:
- **'none'**: no filter effect.
- **'blur'**: applies the Gaussian blur for the image.
- **'brightness'**: applies a linear multiplication to the image to make it look brighter or darker.
- **'contrast'**: adjusts the image contrast.
- **'grayscale'**: converts the image to a grayscale image.
- **'hue-rotate'**: applies hue rotation to the image.
- **'invert'**: inverts the input image.
- **'opacity'**: sets the opacity of the image.
- **'saturate'**: sets the saturation of the image.
- **'sepia'**: converts the image to dark brown.
Default value: **'none'**| - -**Example** -```ts - // xxx.ets - @Entry - @Component - struct FilterDemo { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); - private img:ImageBitmap = new ImageBitmap("common/images/example.jpg"); - - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Canvas(this.context) - .width('100%') - .height('100%') - .backgroundColor('#ffff00') - .onReady(() =>{ - let ctx = this.context - let img = this.img - - ctx.drawImage(img, 0, 0, 100, 100); - - ctx.filter = 'grayscale(50%)'; - ctx.drawImage(img, 100, 0, 100, 100); - - ctx.filter = 'sepia(60%)'; - ctx.drawImage(img, 200, 0, 100, 100); - - ctx.filter = 'saturate(30%)'; - ctx.drawImage(img, 0, 100, 100, 100); - - ctx.filter = 'hue-rotate(90degree)'; - ctx.drawImage(img, 100, 100, 100, 100); - - ctx.filter = 'invert(100%)'; - ctx.drawImage(img, 200, 100, 100, 100); - - ctx.filter = 'opacity(25%)'; - ctx.drawImage(img, 0, 200, 100, 100); - - ctx.filter = 'brightness(0.4)'; - ctx.drawImage(img, 100, 200, 100, 100); - - ctx.filter = 'contrast(200%)'; - ctx.drawImage(img, 200, 200, 100, 100); - - ctx.filter = 'blur(5px)'; - ctx.drawImage(img, 0, 300, 100, 100); - - let result = ctx.toDataURL() - console.info(result) - }) - } - .width('100%') - .height('100%') - } - } -``` - -![filterDemo](figures/filterDemo.jpeg) - - -### getTransform - -getTransform(): Matrix2D - -Obtains the current transformation matrix being applied to the context. This API is a void API. - -Since API version 9, this API is supported in ArkTS widgets. - -**Return value** - -| Type | Description | -| ---------------------------------------- | ----- | -| [Matrix2D](ts-components-canvas-matrix2d.md#Matrix2D) | **Matrix2D** object.| - - ### resetTransform resetTransform(): void @@ -1902,47 +1941,6 @@ Resets the current transform to the identity matrix. This API is a void API. Since API version 9, this API is supported in ArkTS widgets. -### direction - -direction(direction: CanvasDirection): void - -Sets the current text direction used to draw text. - -Since API version 9, this API is supported in ArkTS widgets. - -**Example** -```ts - // xxx.ets - @Entry - @Component - struct DirectionDemo { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); - - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Canvas(this.context) - .width('100%') - .height('100%') - .backgroundColor('#ffff00') - .onReady(() =>{ - let ctx = this.context - ctx.font = '48px serif'; - ctx.textAlign = 'start' - ctx.fillText("Hi ltr!", 200, 50); - - ctx.direction = "rtl"; - ctx.fillText("Hi rtl!", 200, 100); - }) - } - .width('100%') - .height('100%') - } - } -``` - -![directionDemo](figures/directionDemo.jpeg) - ### rotate rotate(angle: number): void @@ -2152,7 +2150,7 @@ Since API version 9, this API is supported in ArkTS widgets. setTransform(transform?: Matrix2D): void -Resets the current transformation to the identity matrix, and then creates a new transformation matrix based on the specified **Matrix2D** object. This API is a void API. +Resets the current transformation to the identity matrix, and then creates a new transformation matrix based on the specified **Matrix2D** object. Since API version 9, this API is supported in ArkTS widgets. @@ -2162,6 +2160,66 @@ Since API version 9, this API is supported in ArkTS widgets. | --------- | ---------------------------------------- | ---- | ---- | ----- | | transform | [Matrix2D](ts-components-canvas-matrix2d.md#Matrix2D) | No | null | Transformation matrix.| +### getTransform + +getTransform(): Matrix2D + +Obtains the current transformation matrix being applied to the context. + +Since API version 9, this API is supported in ArkTS widgets. + +**Return value** + +| Type | Description | +| ---------------------------------------- | ----- | +| [Matrix2D](ts-components-canvas-matrix2d.md#Matrix2D) | **Matrix2D** object.| + +**Example** + + ```ts + // xxx.ets + @Entry + @Component + struct TransFormDemo { + private settings: RenderingContextSettings = new RenderingContextSettings(true); + private context1: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private context2: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text('context1'); + Canvas(this.context1) + .width('230vp') + .height('120vp') + .backgroundColor('#ffff00') + .onReady(() =>{ + this.context1.fillRect(50, 50, 50, 50); + this.context1.setTransform(1.2, Math.PI/8, Math.PI/6, 0.5, 30, -25); + this.context1.fillRect(50, 50, 50, 50); + }) + Text('context2'); + Canvas(this.context2) + .width('230vp') + .height('120vp') + .backgroundColor('#0ffff0') + .onReady(() =>{ + this.context2.fillRect(50, 50, 50, 50); + let storedTransform = this.context1.getTransform(); + console.log("Matrix [scaleX = " + storedTransform.scaleX + ", scaleY = " + storedTransform.scaleY + + ", rotateX = " + storedTransform.rotateX + ", rotateY = " + storedTransform.rotateY + + ", translateX = " + storedTransform.translateX + ", translateY = " + storedTransform.translateY + "]") + this.context2.setTransform(storedTransform); + this.context2.fillRect(50,50,50,50); + }) + } + .width('100%') + .height('100%') + } + } + ``` + + ![en-us_image_0000001219982726.png](figures/en-us_image_0000001219982726.png) + ### translate translate(x: number, y: number): void @@ -2225,12 +2283,12 @@ Since API version 9, this API is supported in ArkTS widgets, except that **Pixel | Name | Type | Mandatory | Default Value | Description | | ----- | ---------------------------------------- | ---- | ---- | ---------------------------------------- | | image | [ImageBitmap](ts-components-canvas-imagebitmap.md) or [PixelMap](../apis/js-apis-image.md#pixelmap7)| Yes | null | Image resource. For details, see **ImageBitmap** or PixelMap. | -| sx | number | No | 0 | X-coordinate of the upper left corner of the rectangle used to crop the source image. | -| sy | number | No | 0 | Y-coordinate of the upper left corner of the rectangle used to crop the source image. | +| sx | number | No | 0 | X coordinate of the upper left corner of the rectangle used to crop the source image. | +| sy | number | No | 0 | Y coordinate of the upper left corner of the rectangle used to crop the source image. | | sw | number | No | 0 | Target width to crop the source image. | | sh | number | No | 0 | Target height to crop the source image. | -| dx | number | Yes | 0 | X-coordinate of the upper left corner of the drawing area on the canvas. | -| dy | number | Yes | 0 | Y-coordinate of the upper left corner of the drawing area on the canvas. | +| dx | number | Yes | 0 | X coordinate of the upper left corner of the drawing area on the canvas. | +| dy | number | Yes | 0 | Y coordinate of the upper left corner of the drawing area on the canvas. | | dw | number | No | 0 | Width of the drawing area. If the width of the drawing area is different from that of the cropped image, the latter will be stretched or compressed to the former.| | dh | number | No | 0 | Height of the drawing area. If the height of the drawing area is different from that of the cropped image, the latter will be stretched or compressed to the former.| @@ -2310,8 +2368,8 @@ Obtains the **[PixelMap](../apis/js-apis-image.md#pixelmap7)** object created wi | Name | Type | Mandatory | Default Value | Description | | ---- | ------ | ---- | ---- | --------------- | -| sx | number | Yes | 0 | X-coordinate of the upper left corner of the output area.| -| sy | number | Yes | 0 | Y-coordinate of the upper left corner of the output area.| +| sx | number | Yes | 0 | X coordinate of the upper left corner of the output area.| +| sy | number | Yes | 0 | Y coordinate of the upper left corner of the output area.| | sw | number | Yes | 0 | Width of the output area. | | sh | number | Yes | 0 | Height of the output area. | @@ -2333,8 +2391,8 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Type | Mandatory | Default Value | Description | | ---- | ------ | ---- | ---- | --------------- | -| sx | number | Yes | 0 | X-coordinate of the upper left corner of the output area.| -| sy | number | Yes | 0 | Y-coordinate of the upper left corner of the output area.| +| sx | number | Yes | 0 | X coordinate of the upper left corner of the output area.| +| sy | number | Yes | 0 | Y coordinate of the upper left corner of the output area.| | sw | number | Yes | 0 | Width of the output area. | | sh | number | Yes | 0 | Height of the output area. | @@ -2537,52 +2595,6 @@ Since API version 9, this API is supported in ArkTS widgets. ![en-us_image_000000127777778](figures/en-us_image_000000127777778.png) - -### imageSmoothingQuality - -imageSmoothingQuality(quality: imageSmoothingQuality) - -Sets the quality of image smoothing. - -Since API version 9, this API is supported in ArkTS widgets. - - **Parameters** - -| Name | Type | Description | -| ------- | --------------------- | ---------------------------------------- | -| quality | imageSmoothingQuality | Quality of image smoothing.
- **'low'**: low quality.
- **'medium'**: medium quality.
- **'high'**: high quality.| - -**Example** -```ts - // xxx.ets - @Entry - @Component - struct ImageSmoothingQualityDemo { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); - private img:ImageBitmap = new ImageBitmap("common/images/example.jpg"); - - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Canvas(this.context) - .width('100%') - .height('100%') - .backgroundColor('#ffff00') - .onReady(() =>{ - let ctx = this.context - ctx.imageSmoothingEnabled = true - ctx.imageSmoothingQuality = 'high' - ctx.drawImage(this.img, 0, 0, 400, 200) - }) - } - .width('100%') - .height('100%') - } - } -``` - -![ImageSmoothingQualityDemo](figures/ImageSmoothingQualityDemo.jpeg) - ### transferFromImageBitmap transferFromImageBitmap(bitmap: ImageBitmap): void @@ -2775,10 +2787,10 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Type | Mandatory | Default Value | Description | | ---- | ------ | ---- | ---- | -------- | -| x0 | number | Yes | 0 | X-coordinate of the start point.| -| y0 | number | Yes | 0 | Y-coordinate of the start point.| -| x1 | number | Yes | 0 | X-coordinate of the end point.| -| y1 | number | Yes | 0 | Y-coordinate of the end point.| +| x0 | number | Yes | 0 | X coordinate of the start point.| +| y0 | number | Yes | 0 | Y coordinate of the start point.| +| x1 | number | Yes | 0 | X coordinate of the end point.| +| y1 | number | Yes | 0 | Y coordinate of the end point.| **Example** @@ -2826,11 +2838,11 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Type | Mandatory | Default Value | Description | | ---- | ------ | ---- | ---- | ----------------- | -| x0 | number | Yes | 0 | X-coordinate of the center of the start circle. | -| y0 | number | Yes | 0 | Y-coordinate of the center of the start circle. | +| x0 | number | Yes | 0 | X coordinate of the center of the start circle. | +| y0 | number | Yes | 0 | Y coordinate of the center of the start circle. | | r0 | number | Yes | 0 | Radius of the start circle, which must be a non-negative finite number.| -| x1 | number | Yes | 0 | X-coordinate of the center of the end circle. | -| y1 | number | Yes | 0 | Y-coordinate of the center of the end circle. | +| x1 | number | Yes | 0 | X coordinate of the center of the end circle. | +| y1 | number | Yes | 0 | Y coordinate of the center of the end circle. | | r1 | number | Yes | 0 | Radius of the end circle, which must be a non-negative finite number.| **Example** @@ -2877,8 +2889,8 @@ Creates a conic gradient. | Name | Type | Mandatory | Default Value | Description | | ---------- | ------ | ---- | ---- | ----------------------------------- | | startAngle | number | Yes | 0 | Angle at which the gradient starts, in radians. The angle measurement starts horizontally from the right side of the center and moves clockwise.| -| x | number | Yes | 0 | X-coordinate of the center of the conic gradient, in vp. | -| y | number | Yes | 0 | X-coordinate of the center of the conic gradient, in vp. | +| x | number | Yes | 0 | X coordinate of the center of the conic gradient, in vp. | +| y | number | Yes | 0 | Y coordinate of the center of the conic gradient, in vp. | **Example** 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-badge.md b/en/application-dev/reference/arkui-ts/ts-container-badge.md index 78c8f0060a334c71b476f36fedac5d194213fb8a..649893ec00d9433b701770a2cd5bebb23cf9e5c0 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-badge.md +++ b/en/application-dev/reference/arkui-ts/ts-container-badge.md @@ -29,7 +29,7 @@ Since API version 9, this API is supported in ArkTS widgets. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | count | number | Yes| Number of notifications.
**NOTE**
If the value is less than or equal to 0, no badge is displayed.
Value range: [-2147483648, 2147483647]
If the value is not an integer, it is rounded off to the nearest integer. For example, 5.5 is rounded off to 5.| -| position | [BadgePosition](#badgeposition) | No| Position to display the badge relative to the parent component.
Default value: **BadgePosition.RightTop**| +| position | [BadgePosition](#badgeposition)\|[Position10+](ts-types.md#position8) | No| Position to display the badge relative to the parent component.
Default value: **BadgePosition.RightTop**
**NOTE**
This parameter cannot be set in percentage. If it is set to an invalid value, the default value **(0,0)** will be used.| | maxCount | number | No| Maximum number of notifications. When the maximum number is reached, only **maxCount+** is displayed.
Default value: **99**
Value range: [-2147483648, 2147483647]
If the value is not an integer, it is rounded off to the nearest integer. For example, 5.5 is rounded off to 5.| | style | [BadgeStyle](#badgestyle) | Yes| Style of the badge, including the font color, font size, badge color, and badge size.| @@ -44,7 +44,7 @@ Since API version 9, this API is supported in ArkTS widgets. | Name| Type| Mandatory| Default Value| Description| | -------- | -------- | -------- | -------- | -------- | | value | string | Yes| - | Prompt content.| -| position | [BadgePosition](#badgeposition) | No| BadgePosition.RightTop | Position to display the badge relative to the parent component.| +| position | [BadgePosition](#badgeposition)\|[Position10+](ts-types.md#position8) | No| BadgePosition.RightTop | Position to display the badge relative to the parent component.| | style | [BadgeStyle](#badgestyle) | Yes| - | Style of the badge, including the font color, font size, badge color, and badge size.| ## BadgePosition 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 **\** can change the height of the upper and lower child components, but only to the extent that the resultant height falls within the maximum and minimum heights of the child components. > -> The universal attributes **clip** and **margin** are not supported. +> Universal attributes such as **clip** and **margin** are supported. If **clip** is not set, the default value **true** is used. + ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-container-grid.md b/en/application-dev/reference/arkui-ts/ts-container-grid.md index db50a0ea98c0a306e2684a5882c1b5d5b18327a7..23e98d39e0f0eed4b1b6f9549ca1d28d283213be 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-grid.md +++ b/en/application-dev/reference/arkui-ts/ts-container-grid.md @@ -23,10 +23,11 @@ The **\** component accepts only **\<[GridItem](ts-container-griditem.md)> > > If the values of [if/else](../../quick-start/arkts-rendering-control-ifelse.md), [ForEach](../../quick-start/arkts-rendering-control-foreach.md), and [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md) change, the indexes of subnodes are updated. > -> Child components of **\** whose **visibility** attribute is set to **Hidden** or **None** are included in the index calculation. +> The child component that has the **visibility** attribute set to **Hidden** or **None** is included in the index calculation. > -> Child components of **\** whose **visibility** attribute is set to **None** are not displayed, but still take up the corresponding cells. - +> The child component that has the **visibility** attribute set to **None** is not displayed, but still takes up the corresponding cell. +> +> The child component that has the **position** attribute set takes up the corresponding cell, and is offset by the distance specified by **position** relative to the upper left corner of the grid. This child component does not scroll with the corresponding cell and is not displayed after the corresponding cell extends beyond the display range of the grid. ## APIs @@ -44,8 +45,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Description| | -------- | -------- | -------- | -| columnsTemplate | string | Number of columns in the current grid layout. If this attribute is not set, one column will be used.
For example, **'1fr 1fr 2fr'** indicates three columns, with the first column taking up 1/4 of the parent component's full width, the second column 1/4, and the third column 2/4.
**NOTE**
If this attribute is set to **'0fr'**, the column width is 0, and grid item in the column is not displayed. If this attribute is set to any other invalid value, the grid item is displayed as one column.| -| rowsTemplate | string | Number of rows in the current grid layout. If this attribute is not set, one row will be used.
For example, **'1fr 1fr 2fr'** indicates three rows, with the first row taking up 1/4 of the parent component's full height, the second row 1/4, and the third row 2/4.
**NOTE**
If this attribute is set to **'0fr'**, the row width is 0, and grid item in the row is not displayed. If this attribute is set to any other invalid value, the grid item is displayed as one row.| +| columnsTemplate | string | Number of columns or minimum column width in the grid. If this attribute is not set, one column will be used.
For example, **'1fr 1fr 2fr'** indicates three columns, with the first column taking up 1/4 of the parent component's full width, the second column 1/4, and the third column 2/4.
**'repeat(auto-fit, 90px)'** means to automatically work out the number of columns and the actual column width, with the minimum column width of 90.
**NOTE**
If this attribute is set to **'0fr'**, the column width is 0, and grid item in the column is not displayed. If this attribute is set to any other invalid value, the grid item is displayed as one column.| +| rowsTemplate | string | Number of rows or minimum row height in the grid. If this attribute is not set, one row will be used.
For example, **'1fr 1fr 2fr'** indicates three rows, with the first row taking up 1/4 of the parent component's full height, the second row 1/4, and the third row 2/4.
**'repeat(auto-fit, 90px)'** means to automatically work out the number of rows and the actual v, with the minimum row height of 90.
**NOTE**
If this attribute is set to **'0fr'**, the row width is 0, and grid item in the row is not displayed. If this attribute is set to any other invalid value, the grid item is displayed as one row.| | columnsGap | [Length](ts-types.md#length) | Gap between columns.
Default value: **0**
**NOTE**
A value less than 0 evaluates to the default value.| | rowsGap | [Length](ts-types.md#length) | Gap between rows.
Default value: **0**
**NOTE**
A value less than 0 evaluates to the default value.| | scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.
Default value: **BarState.Off**
**NOTE**
In API version 9 and earlier versions, the default value is **BarState.Off**. In API version 10, the default value is **BarState.Auto**.| @@ -54,13 +55,15 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | cachedCount | number | Number of grid items to be preloaded (cached). It works only in [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md). For details, see [Minimizing White Blocks During Swiping](../../ui/arkts-performance-improvement-recommendation.md#minimizing-white-blocks-during-swiping).
Default value: **1**
**NOTE**
The number of the grid items to be cached before and after the currently displayed one equals the value of **cachedCount** multiplied by the number of columns.
Grid items that exceed the display and cache range are released.
A value less than 0 evaluates to the default value.| | editMode 8+ | boolean | Whether to enter editing mode. In editing mode, the user can drag the **\<[GridItem](ts-container-griditem.md)>** in the **\** component.
Default value: **false**| | layoutDirection8+ | [GridDirection](#griddirection8) | Main axis direction of the grid.
Default value: **GridDirection.Row**| -| maxCount8+ | number | When **layoutDirection** is **Row** or **RowReverse**: maximum number of columns that can be displayed.
When **layoutDirection** is **Column** or **ColumnReverse**: maximum number of rows that can be displayed.
Default value: **Infinity**
**NOTE**
If the value of **maxCount** is smaller than that of **minCount**, the default values of **maxCount** and **minCount** are used.
A value less than 0 evaluates to the default value.| -| minCount8+ | number | When **layoutDirection** is **Row** or **RowReverse**: minimum number of columns that can be displayed.
When **layoutDirection** is **Column** or **ColumnReverse**: minimum number of rows that can be displayed.
Default value: **1**
**NOTE**
A value less than 0 evaluates to the default value.| +| maxCount8+ | number | When **layoutDirection** is **Row** or **RowReverse**: maximum number of columns that can be displayed.
When **layoutDirection** is **Column** or **ColumnReverse**: maximum number of rows that can be displayed.
Default value: **Infinity**
**NOTE**
If the value of **maxCount** is smaller than that of **minCount**, the default values of **maxCount** and **minCount** are used.
A value less than 1 evaluates to the default value.| +| minCount8+ | number | When **layoutDirection** is **Row** or **RowReverse**: minimum number of columns that can be displayed.
When **layoutDirection** is **Column** or **ColumnReverse**: minimum number of rows that can be displayed.
Default value: **1**
**NOTE**
A value less than 1 evaluates to the default value.| | cellLength8+ | number | When **layoutDirection** is **Row** or **RowReverse**: fixed height per row.
When **layoutDirection** is **Column** or **ColumnReverse**: fixed width per column.
Default value: size of the first element| | multiSelectable8+ | boolean | Whether to enable mouse frame selection.
Default value: **false**
- **false**: The mouse frame selection is disabled.
- **true**: The mouse frame selection is enabled.| | supportAnimation8+ | boolean | Whether to enable animation. Currently, the grid item drag animation is supported.
Default value: **false**| | edgeEffect10+ | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect. The spring effect and shadow effect are supported.
Default value: **EdgeEffect.None**
| | enableScrollInteraction10+ | boolean | Whether to support scroll gestures. When this attribute is set to **false**, scrolling by finger or mouse is not supported, but the scrolling controller API is not affected.
Default value: **true** | +| nestedScroll10+ | [NestedScrollOptions](ts-container-scroll.md#nestedscrolloptions10) | Nested scrolling options. You can set the nested scrolling mode in the forward and backward directions to implement scrolling linkage with the parent component.| +| friction10+ | number \| [Resource](ts-types.md#resource) | Friction coefficient. It applies only to gestures in the scrolling area, and it affects only indirectly the scroll chaining during the inertial scrolling process.
Default value: **0.9** for wearable devices and **0.6** for non-wearable devices
**NOTE**
A value less than or equal to 0 evaluates to the default value.| Depending on the settings of the **rowsTemplate** and **columnsTemplate** attributes, the **\** component supports the following layout modes: @@ -71,10 +74,6 @@ Depending on the settings of the **rowsTemplate** and **columnsTemplate** attrib - If the width and height of a grid are not set, the grid adapts to the size of its parent component by default. - The size of the grid rows and columns is the size of the grid content area minus the gap between rows and columns. It is allocated based on the proportion of each row and column. - By default, the grid items fill the entire grid. -- In this mode, if a grid item has both **rowStart** and **columnStart** set, it is placed in the position based on the settings. If a grid item already exists in this position, overlapping occurs. -- If a grid item has only **rowStart** or **columnStart** set, the system traverses the previous grid item layout to search for an idle position that meets the settings. If no idle position meets the requirements, the grid item is not laid out. -- If a grid item has neither **rowStart** nor **columnStart** set, the system traverses the previous grid item layout to search for an idle position. If no idle position is available, the grid item is not laid out. -- If a grid item has **rowEnd** set but not **rowStart**, **rowStart** is considered as set to the same value as **rowEnd**. If a grid item has **columnEnd** set but not **columnStart**, **columnStart** is considered as set to the same value as **columnEnd**. 2. Either **rowsTemplate** or **columnsTemplate** is set @@ -84,19 +83,14 @@ Depending on the settings of the **rowsTemplate** and **columnsTemplate** attrib - In this mode, the following attributes do not take effect: **layoutDirection**, **maxCount**, minCount, and **cellLength**. - The cross axis size of the grid is the cross axis size of the grid content area minus the gaps along the cross axis. It is allocated based on the proportion of each row and column. - The main axis size of the grid is the maximum height of all grid items in the cross axis direction of the current grid. -- In this mode, if a grid item has both **rowStart** and **columnStart** set, it is placed in the position based on the settings. If a grid item already exists in this position, overlapping occurs. -- If a grid item has only **rowStart** or **columnStart** set, the system traverses the previous grid item layout to search for an idle position that meets the settings. -- If a grid item has neither **rowStart** nor **columnStart** set, the system traverses the previous grid item layout to search for an idle position. -- If a grid item has **rowEnd** set but not **rowStart**, **rowStart** is considered as set to the same value as **rowEnd**. If a grid item has **columnEnd** set but not **columnStart**, **columnStart** is considered as set to the same value as **columnEnd**. 3. Neither **rowsTemplate** nor **columnsTemplate** is set - The **\** component arranges elements in the direction specified by **layoutDirection**. The number of columns is jointly determined by the grid width, width of the first element, **minCount**, **maxCount**, and **columnsGap**. - The number of rows is jointly determined by the grid height, height of the first element, **cellLength**, and **rowsGap**. Elements outside the determined range of rows and columns are not displayed and cannot be viewed through scrolling. - In this mode, only the following attributes take effect: **layoutDirection**, **maxCount**, **minCount**, **cellLength**, **editMode**, **columnsGap**, and **rowsGap**. -- When **layoutDirection** is set to **Row**, elements are arranged from left to right. When a row is full, a new row will be added. If the remaining height is insufficient, no more elements will be laid out, and the top of the content is centered. -- When **layoutDirection** is set to **Column**, elements are arranged from top to bottom. When a column is full, a new column will be added. If the remaining height is insufficient, no more elements will be laid out, and the top of the content is centered. -- In this mode, **rowStart** and **columnStart** of the grid item do not take effect. +- When **layoutDirection** is set to **Row**, elements are arranged row by row from left to right. If the remaining height is insufficient, no more elements will be laid out, and the whole content is centered at the top. +- When **layoutDirection** is set to **Column**, elements are arranged column by column from top to bottom. If the remaining height is insufficient, no more elements will be laid out, and the whole content is centered at the top. ## GridDirection8+ @@ -118,7 +112,7 @@ In addition to the [universal events](ts-universal-events-click.md), the followi | Name| Description| | -------- | -------- | | onScrollIndex(event: (first: number) => void) | Triggered when the first item displayed in the grid changes. It is triggered once when the grid is initialized.
- **first**: index of the first item of the grid.
If it changes, this event will be triggered.| -| onItemDragStart(event: (event: ItemDragInfo, itemIndex: number) => (() => any) \| void) | Triggered when a grid item starts to be dragged.
- **event**: See [ItemDragInfo](#itemdraginfo).
- **itemIndex**: index of the dragged item.
**NOTE**
If **void** is returned, the drag operation cannot be performed.
This event is triggered when the user long presses a grid item.| +| onItemDragStart(event: (event: ItemDragInfo, itemIndex: number) => (() => any) \| void) | Triggered when a grid item starts to be dragged.
- **event**: See [ItemDragInfo](#itemdraginfo).
- **itemIndex**: index of the dragged item.
**NOTE**
If **void** is returned, the drag operation cannot be performed.
This event is triggered when the user long presses a grid item.
Drag detection also requires long press, and the event processing mechanism preferentially triggers child component events. Therefore, when **LongPressGesture** is bound to the grid item, the drag operation cannot be performed. In light of this, if both long press and drag operations are required, you can use universal drag events.| | onItemDragEnter(event: (event: ItemDragInfo) => void) | Triggered when the dragged item enters the drop target of the grid.
- **event**: See [ItemDragInfo](#itemdraginfo).| | onItemDragMove(event: (event: ItemDragInfo, itemIndex: number, insertIndex: number) => void) | Triggered when the dragged item moves over the drop target of the grid.
- **event**: See [ItemDragInfo](#itemdraginfo).
- **itemIndex**: initial position of the dragged item.
- **insertIndex**: index of the position to which the dragged item will be dropped.| | onItemDragLeave(event: (event: ItemDragInfo, itemIndex: number) => void) | Triggered when the dragged item leaves the drop target of the grid.
- **event**: See [ItemDragInfo](#itemdraginfo).
- **itemIndex**: index of the dragged item.| @@ -141,6 +135,8 @@ In addition to the [universal events](ts-universal-events-click.md), the followi ## Example +### Example 1 + ```ts // xxx.ets @Entry @@ -191,17 +187,18 @@ struct GridExample { .columnsTemplate('1fr 1fr 1fr 1fr 1fr') .columnsGap(10) .rowsGap(10) + .friction(0.6) .edgeEffect(EdgeEffect.Spring) + .scrollBar(BarState.On) .onScrollIndex((first: number) => { console.info(first.toString()) }) .onScrollBarUpdate((index: number, offset: number) => { - return {totalOffset: (index / 5) * (80 + 10) - 10 + offset, totalLength: 80 * 5 + 10 * 4} + return {totalOffset: (index / 5) * (80 + 10) - offset, totalLength: 80 * 5 + 10 * 4} }) .width('90%') .backgroundColor(0xFAEEE0) .height(300) - .scrollBar(BarState.Off) Button('next page') .onClick(() => {// Click to go to the next page. this.scroller.scrollPage({ next: true }) @@ -212,3 +209,95 @@ struct GridExample { ``` ![en-us_image_0000001219744183](figures/en-us_image_0000001219744183.gif) + +### Example 2 + +1. Set **editMode\(true\)** to enable the grid to enter editing mode, where the user can drag the grid items. + +2. Through [onItemDragStart](#events), set the image to be displayed during dragging. + +3. Through [onItemDrop](#events), obtain the initial position of the dragged item and the position to which the dragged item will be dropped. Through [onDrag](#events), complete the array position exchange logic. + +```ts +@Entry +@Component +struct GridExample { + @State numbers: string[] = [] + scroller: Scroller = new Scroller() + @State text: string = 'drag' + + @Builder pixelMapBuilder () { // Style for the drag event. + Column() { + Text(this.text) + .fontSize(16) + .backgroundColor(0xF9CF93) + .width(80) + .height(80) + .textAlign(TextAlign.Center) + } + } + + aboutToAppear() { + for (let i = 1;i <= 15; i++) { + this.numbers.push(i + '') + } + } + + changeIndex(index1: number, index2: number) { // Exchange the array position. + [this.numbers[index1], this.numbers[index2]] = [this.numbers[index2], this.numbers[index1]]; + } + + build() { + Column({ space: 5 }) { + Grid(this.scroller) { + ForEach(this.numbers, (day: string) => { + GridItem() { + Text(day) + .fontSize(16) + .backgroundColor(0xF9CF93) + .width(80) + .height(80) + .textAlign(TextAlign.Center) + } + }) + } + .columnsTemplate('1fr 1fr 1fr') + .columnsGap(10) + .rowsGap(10) + .onScrollIndex((first: number) => { + console.info(first.toString()) + }) + .width('90%') + .backgroundColor(0xFAEEE0) + .height(300) + .editMode(true) // Enable the grid to enter editing mode, where the user can drag the grid items. + .onItemDragStart((event: ItemDragInfo, itemIndex: number) => { // Triggered when a grid item starts to be dragged. + this.text = this.numbers[itemIndex] + return this.pixelMapBuilder() // Set the image to be displayed during dragging. + }) + .onItemDrop((event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => { // Triggered when the dragged item is dropped on the drop target of the grid. + // If isSuccess is set to false, the item is dropped outside of the grid. If the value of insertIndex is greater than that of length, an item adding event occurs. + if (!isSuccess || insertIndex >= this.numbers.length) { + return + } + console.info('beixiang' + itemIndex + '', insertIndex + '') // itemIndex indicates the initial position of the dragged item. insertIndex indicates the position to which the dragged item will be dropped. + this.changeIndex(itemIndex, insertIndex) + }) + }.width('100%').margin({ top: 5 }) + } +} +``` + +Below are some examples. + +Below shows how the grid looks when dragging of grid items starts. + +![gridDrag](figures/gridDrag.png) + +Below shows how the grid looks when dragging of grid items is in progress. + +![gridDrag](figures/gridDrag1.png) + +Below shows how the grid looks after grid item 1 and grid item 6 swap their positions. + +![gridDrag](figures/gridDrag2.png) diff --git a/en/application-dev/reference/arkui-ts/ts-container-hyperlink.md b/en/application-dev/reference/arkui-ts/ts-container-hyperlink.md new file mode 100644 index 0000000000000000000000000000000000000000..fc83d1f08de051852ed3a568ac900185b0e9d39a --- /dev/null +++ b/en/application-dev/reference/arkui-ts/ts-container-hyperlink.md @@ -0,0 +1,66 @@ +# Hyperlink + +The **\** component implements a link from a location in the component to another location. + +> **NOTE** +> +> - This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. +> - This component must be used with the system browser. + +## Required Permissions + +If Internet access is required, you need to apply for the **ohos.permission.INTERNET** permission. For details about how to apply for a permission, see [Declaring Permissions](../../security/accesstoken-guidelines.md). + +## Child Components + +Supported + + +## APIs + +Hyperlink(address: string | Resource, content?: string | Resource) + +Since API version 9, this API is supported in ArkTS widgets. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| address | string \| [Resource](ts-types.md#resource) | Yes| Web page to which the hyperlink is redirected.| +| content | string \| [Resource](ts-types.md#resource) | No| Text displayed in the hyperlink.
**NOTE**
If this component has child components, the hyperlink text is not displayed.| + +## Attributes + +Only the following attributes are supported. + +| Name| Type| Description| +| -------- | -------- | -------- | +| color | [ResourceColor](ts-types.md#resourcecolor) | Color of the hyperlink text.| + +## Example + +```ts +@Entry +@Component +struct HyperlinkExample { + build() { + Column() { + Column() { + Hyperlink('https://example.com/') { + Image($r('app.media.bg')) + .width(200) + .height(100) + } + } + + Column() { + Hyperlink('https://example.com/', 'Go to the developer website') { + } + .color(Color.Blue) + } + }.width('100%').height('100%').justifyContent(FlexAlign.Center) + } +} +``` + +![hyperlink](figures/hyperlink.PNG) diff --git a/en/application-dev/reference/arkui-ts/ts-container-list.md b/en/application-dev/reference/arkui-ts/ts-container-list.md index 0456b0eabd821d1df0d4996900b88b98d8aed26d..38195901492db82a74671c4dcdbaff902f44e707 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-list.md +++ b/en/application-dev/reference/arkui-ts/ts-container-list.md @@ -41,7 +41,7 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Type | Mandatory | Description | | ------------ | ---------------------------------------- | ---- | ---------------------------------------- | -| space | number \| string | No | Spacing between list items along the main axis.
Default value: **0**
**NOTE**
If the set value is a negative number, the default value will be used.
If the value of **space** is less than the width of the list divider, the latter is used as the spacing.| +| space | number \| string | No | Spacing between list items along the main axis.
Default value: **0**
**NOTE**
If this parameter is set to a negative number or a value greater than or equal to the length of the list content area, the default value is used.
If this parameter is set to a value less than the width of the list divider, the width of the list divider is used as the spacing.| | initialIndex | number | No | Item displayed at the beginning of the viewport when the current list is loaded for the first time, that is, the first item to be displayed.
Default value: **0**
**NOTE**
If the set value is a negative number or is greater than the index of the last item in the list, the value is invalid. In this case, the default value will be used.| | scroller | [Scroller](ts-container-scroll.md#scroller) | No | Scroller, which can be bound to scrollable components.
**NOTE**
The scroller cannot be bound to other scrollable components.| @@ -49,21 +49,24 @@ Since API version 9, this API is supported in ArkTS widgets. In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. -| Name | Type | Description | -| ----------------------------------- | ---------------------------------------- | ---------------------------------------- | -| listDirection | [Axis](ts-appendix-enums.md#axis) | Direction in which the list items are arranged.
Default value: **Axis.Vertical**
Since API version 9, this API is supported in ArkTS widgets.| -| divider | {
strokeWidth: [Length](ts-types.md#length),
color?:[ResourceColor](ts-types.md#resourcecolor),
startMargin?: Length,
endMargin?: Length
} \| null | Style of the divider for the list items. By default, there is no divider.
- **strokeWidth**: stroke width of the divider.
- **color**: color of the divider.
- **startMargin**: distance between the divider and the start edge of the list.
- **endMargin**: distance between the divider and the end edge of the list.
Since API version 9, this API is supported in ArkTS widgets.
The sum of **endMargin** and **startMargin** cannot exceed the column width.
**startMargin** and **endMargin** cannot be set in percentage.
The divider is drawn between list items along the main axis, and not above the first list item and below the last list item.
In multi-column mode, the value of **startMargin** is calculated from the start edge of the cross axis of each column. In other cases, it is calculated from the start edge of the cross axis of the list.| -| scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.
Default value: **BarState.Off**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
In API version 9 and earlier versions, the default value is **BarState.Off**. In API version 10, the default value is **BarState.Auto**.| -| cachedCount | number | Number of list items or list item groups to be preloaded (cached). It works only in [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md). A list item group is calculated as a whole, and all list items of the group are preloaded at the same time. For details, see [Minimizing White Blocks During Swiping](../../ui/arkts-performance-improvement-recommendation.md#minimizing-white-blocks-during-swiping).
Default value: **1**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
In single-column mode, the number of the list items to be cached before and after the currently displayed one equals the value of **cachedCount**.
In multi-column mode, the number of the list items to be cached is the value of **cachedCount** multiplied by the number of columns.| -| editMode(deprecated) | boolean | Whether to enter editing mode.
This API is deprecated since API version 9. For details about how to implement deletion of a selected list item, see [Example 3](#example-3).
Default value: **false**| -| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect. The spring effect and shadow effect are supported.
Default value: **EdgeEffect.Spring**
Since API version 9, this API is supported in ArkTS widgets.| -| chainAnimation | boolean | Whether to display chained animations on this list when it slides or its top or bottom is dragged. The list items are separated with even space, and one item animation starts after the previous animation during basic sliding interactions. The chained animation effect is similar with spring physics.
Default value: **false**
- **false**: No chained animations are displayed.
- **true**: Chained animations are displayed.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
When chained animations are in motion, the list divider is not displayed.
The following prerequisites must be met for the chained animations to take effect:
- The edge effect of the list is of the Spring type.
- The multi-column mode is not enabled for the list.| -| chainAnimationOptions10+ | [ChainAnimationOptions](#chainanimationoptions10) | Chained animation settings.
**System API**: This is a system API. | -| multiSelectable8+ | boolean | Whether to enable mouse frame selection.
Default value: **false**
- **false**: The mouse frame selection is disabled.
- **true**: The mouse frame selection is enabled.
Since API version 9, this API is supported in ArkTS widgets.| -| lanes9+ | number \| [LengthConstrain](ts-types.md#lengthconstrain) | In the following description, **listDirection** is set to **Axis.Vertical**:
Number of columns in which the list items are arranged along the cross axis.
Default value: **1**
The rules are as follows:
- If the value is set to a number, the column width is calculated by dividing the cross-axis width of the **\** component by the specified number.
- If the value is set to {minLength, maxLength}, the number of columns is adjusted adaptively based on the width of the **\** component, ensuring that the width respects the {minLength, maxLength} constraints during adaptation. The **minLength** constraint is prioritized.
- If the value is set to {minLength, maxLength}, and the cross-axis width constraint of the parent component is infinite, the parent component is arranged by column, and the column width is calculated based on the largest list item in the display area.
- Each list item group occupies one row in multi-column mode. Its child list items are arranged based on the **lanes** attribute of the list.
- If the value is set to {minLength, maxLength}, the number of columns is calculated based on the cross-axis width of the list item group. If the cross-axis width of the list item group is different from that of the list, the number of columns in the list item group may be different from that in the list.
This API is supported in ArkTS widgets.| -| alignListItem9+ | [ListItemAlign](#listitemalign9) | Alignment mode of list items along the cross axis when: Cross-axis width of the **\** component > Cross-axis width of list items x Value of **lanes**.
Default value: **ListItemAlign.Start**
This API is supported in ArkTS widgets.| -| sticky9+ | [StickyStyle](#stickystyle9) | Whether to pin the header to the top or the footer to the bottom in the **\** component. This attribute is used together with the **[\](ts-container-listitemgroup.md)** component.
Default value: **StickyStyle.None**
This API is supported in ArkTS widgets.
**NOTE**
The **sticky** attribute can be set to **StickyStyle.Header** or \| **StickyStyle.Footer** to support both the pin-to-top and pin-to-bottom features.| -| enableScrollInteraction10+ | boolean | Whether to support scroll gestures. When this attribute is set to **false**, scrolling by finger or mouse is not supported, but the scrolling controller API is not affected.
Default value: **true** | +| Name | Type | Description | +| ------------------------------------- | ---------------------------------------- | ---------------------------------------- | +| listDirection | [Axis](ts-appendix-enums.md#axis) | Direction in which the list items are arranged.
Default value: **Axis.Vertical**
Since API version 9, this API is supported in ArkTS widgets.| +| divider | {
strokeWidth: [Length](ts-types.md#length),
color?:[ResourceColor](ts-types.md#resourcecolor),
startMargin?: Length,
endMargin?: Length
} \| null | Style of the divider for the list items. By default, there is no divider.
- **strokeWidth**: stroke width of the divider.
- **color**: color of the divider.
- **startMargin**: distance between the divider and the start edge of the list.
- **endMargin**: distance between the divider and the end edge of the list.
Since API version 9, this API is supported in ArkTS widgets.
The sum of **endMargin** and **startMargin** cannot exceed the column width.
**startMargin** and **endMargin** cannot be set in percentage.
The divider is drawn between list items along the main axis, and not above the first list item and below the last list item.
In multi-column mode, the value of **startMargin** is calculated from the start edge of the cross axis of each column. In other cases, it is calculated from the start edge of the cross axis of the list.| +| scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.
Default value: **BarState.Off**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
In API version 9 and earlier versions, the default value is **BarState.Off**. In API version 10, the default value is **BarState.Auto**.| +| cachedCount | number | Number of list items or list item groups to be preloaded (cached). It works only in [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md). A list item group is calculated as a whole, and all list items of the group are preloaded at the same time. For details, see [Minimizing White Blocks During Swiping](../../ui/arkts-performance-improvement-recommendation.md#minimizing-white-blocks-during-swiping).
Default value: **1**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
In single-column mode, the number of the list items to be cached before and after the currently displayed one equals the value of **cachedCount**.
In multi-column mode, the number of the list items to be cached is the value of **cachedCount** multiplied by the number of columns.| +| editMode(deprecated) | boolean | Whether to enter editing mode.
This API is deprecated since API version 9. For details about how to implement deletion of a selected list item, see [Example 3](#example-3).
Default value: **false**| +| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Edge scrolling effect. The spring effect and shadow effect are supported.
Default value: **EdgeEffect.Spring**
Since API version 9, this API is supported in ArkTS widgets.| +| chainAnimation | boolean | Whether to display chained animations on this list when it slides or its top or bottom is dragged. The list items are separated with even space, and one item animation starts after the previous animation during basic sliding interactions. The chained animation effect is similar with spring physics.
Default value: **false**
- **false**: No chained animations are displayed.
- **true**: Chained animations are displayed.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
When chained animations are in motion, the list divider is not displayed.
The following prerequisites must be met for the chained animations to take effect:
- The edge scrolling effect of the list is of the Spring type.
- The multi-column mode is not enabled for the list.| +| chainAnimationOptions10+ | [ChainAnimationOptions](#chainanimationoptions10) | Chained animation settings.
**System API**: This is a system API. | +| multiSelectable8+ | boolean | Whether to enable mouse frame selection.
Default value: **false**
- **false**: The mouse frame selection is disabled.
- **true**: The mouse frame selection is enabled.
Since API version 9, this API is supported in ArkTS widgets.| +| lanes9+ | number \| [LengthConstrain](ts-types.md#lengthconstrain),
gutter10+?:[Dimension](ts-types.md#dimension10) | In the following description, **listDirection** is set to **Axis.Vertical**:
Number of columns in which the list items are arranged along the cross axis.
Default value: **1**
The rules are as follows:
- If the value is set to a number, the column width is calculated by dividing the cross-axis width of the **\** component by the specified number.
- If the value is set to {minLength, maxLength}, the number of columns is adjusted adaptively based on the width of the **\** component, ensuring that the width respects the {minLength, maxLength} constraints during adaptation. The **minLength** constraint is prioritized.
- If the value is set to {minLength, maxLength}, and the cross-axis width constraint of the parent component is infinite, the parent component is arranged by column, and the column width is calculated based on the largest list item in the display area.
- Each list item group occupies one row in multi-column mode. Its child list items are arranged based on the **lanes** attribute of the list.
- If the value is set to {minLength, maxLength}, the number of columns is calculated based on the cross-axis width of the list item group. If the cross-axis width of the list item group is different from that of the list, the number of columns in the list item group may be different from that in the list.
If the value is set to the **gutter** type, it indicates the column spacing. It takes effect when the number of columns is greater than 1.
Default value: **0**
This API is supported in ArkTS widgets.| +| alignListItem9+ | [ListItemAlign](#listitemalign9) | Alignment mode of list items along the cross axis when: Cross-axis width of the **\** component > Cross-axis width of list items x Value of **lanes**.
Default value: **ListItemAlign.Start**
This API is supported in ArkTS widgets.| +| sticky9+ | [StickyStyle](#stickystyle9) | Whether to pin the header to the top or the footer to the bottom in the **\** component. This attribute is used together with the **[\](ts-container-listitemgroup.md)** component.
Default value: **StickyStyle.None**
This API is supported in ArkTS widgets.
**NOTE**
The **sticky** attribute can be set to **StickyStyle.Header** or \| **StickyStyle.Footer** to support both the pin-to-top and pin-to-bottom features.| +| scrollSnapAlign10+ | [ScrollSnapAlign](#scrollsnapalign10) | Alignment mode of list items when scrolling ends.
Default value: **ScrollSnapAlign.NONE**
**NOTE**
This attribute is available only when the heights of list items are the same.| +| enableScrollInteraction10+ | boolean | Whether to support scroll gestures. When this attribute is set to **false**, scrolling by finger or mouse is not supported, but the scrolling controller API is not affected.
Default value: **true**| +| nestedScroll10+ | [NestedScrollOptions](ts-container-scroll.md#nestedscrolloptions10) | Nested scrolling options. You can set the nested scrolling mode in the forward and backward directions to implement scrolling linkage with the parent component. | +| friction10+ | number \| [Resource](ts-types.md#resource) | Friction coefficient. It applies only to gestures in the scrolling area, and it affects only indirectly the scroll chaining during the inertial scrolling process.
Default value: **0.9** for wearable devices and **0.6** for non-wearable devices
**NOTE**
A value less than or equal to 0 evaluates to the default value.| ## ListItemAlign9+ @@ -87,7 +90,7 @@ This API is supported in ArkTS widgets. ## ChainEdgeEffect10+ -Describes the chained animation edge effect. +Describes the chained animation edge scrolling effect. **System API**: This is a system API. @@ -98,7 +101,7 @@ Describes the chained animation edge effect. ## chainAnimationOptions10+ -Provides the chained animation settings, which cover the maximum spacing, minimum spacing, intensity, conductivity, and edge effect. +Provides the chained animation settings, which cover the maximum spacing, minimum spacing, intensity, conductivity, and edge scrolling effect. **System API**: This is a system API. @@ -108,22 +111,38 @@ Provides the chained animation settings, which cover the maximum spacing, minimu | maxSpace | [Length](ts-types.md#length) | Yes | Maximum spacing between the chained animations. | | conductivity | number | No | Conductivity of the chained animations. The value range is [0,1]. A larger value indicates higher conductivity.
Default value: **0.7**| | intensity | number | No | Intensity of the chained animations. The value range is [0,1]. A larger value indicates more obvious animations.
Default value: **0.3**| -| edgeEffect | [ChainEdgeEffect](#chainedgeeffect10)| No | Chained animation edge effect.
Default value: **ChainEdgeEffect.DEFAULT**| +| edgeEffect | [ChainEdgeEffect](#chainedgeeffect10)| No | Chained animation edge scrolling effect.
Default value: **ChainEdgeEffect.DEFAULT**| > **NOTE** > > The default value of the universal attribute [clip](ts-universal-attributes-sharp-clipping.md) is **true** for the **\** component. +## ScrollSnapAlign10+ + +Enumerates the alignment modes of list items when scrolling ends. + +Since API version 10, this API is supported in ArkTS widgets. + +When list items are left-, right-, top-, or bottom-aligned, the items at the end must be completely displayed, without exposure of any blank area of the boundary; the items at the other end can be out of alignment. + +This API is available only when the heights of list items are the same. + +| Name | Description | +| ------ | ---------------------------------------- | +| NONE | No alignment. This is the default value. When scrolling ends, the list items are not aligned. | +| START | The first item in the view is aligned at the start of the list.
**NOTE**
When the list hits the end, the items at the end must be completely displayed. In this case, the items at the start may not be aligned.| +| CENTER | The middle items in the view are aligned in the center of the list.
**NOTE**
The items at the start and end can be aligned in the center of the list. In this case, the list may have a blank area exposed, and the first or last item is aligned to the center.| +| END | The last item in the view is aligned at the end of the list.
**NOTE**
When the list hits the start, the items at the start must be completely displayed. In this case, the items at the end may not be aligned.| ## Events | Name | Description | | ---------------------------------------- | ---------------------------------------- | | onItemDelete(deprecated)(event: (index: number) => boolean) | Triggered when a list item is deleted.
This API is deprecated since API version 9.
- **index**: index of the deleted list item.| -| onScroll(event: (scrollOffset: number, scrollState: ScrollState) => void) | Triggered when the list scrolls.
- **scrollOffset**: scroll offset of each frame. The offset is positive when the list is scrolled up and negative when the list is scrolled down.
- **[scrollState](#scrollstate)**: current scroll state.
This event is not triggered when **ScrollEdge** and **ScrollToIndex** are called by using the controller. In other cases, this event is triggered when scrolling occurs.
Since API version 9, this API is supported in ArkTS widgets.| -| onScrollIndex(event: (start: number, end: number) => void) | Triggered when a child component enters or leaves the list display area.
During index calculation, each **\** component is taken as a whole and assigned an index, and the indexes of the list items within are not included in the calculation.
- **start**: index of the scroll start position.
- **end**: index of the scroll end position.
This event is triggered once when the list is initialized and when the index of the first list item or the next list item in the list display area changes.
When the list edge effect is the spring effect, the **onScrollIndex** event is not triggered when the user scrolls the list to the edge or releases the list to rebound.
Since API version 9, this API is supported in ArkTS widgets.| -| onReachStart(event: () => void) | Triggered when the list reaches the start position.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This event is triggered once when **initialIndex** is **0** during list initialization and once when the list scrolls to the start position. When the list edge effect is the spring effect, this event is triggered once when the list passes the start position and is triggered again when the list returns to the start position.| -| onReachEnd(event: () => void) | Triggered when the list reaches the end position.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
When the list edge effect is the spring effect, this event is triggered once when the list passes the end position and is triggered again when the list returns to the end position.| -| onScrollFrameBegin9+(event: (offset: number, state: ScrollState) => { offsetRemain }) | Triggered when the list starts to scroll. The input parameters indicate the amount by which the list will scroll. The event handler then works out the amount by which the list needs to scroll based on the real-world situation and returns the result.
\- **offset**: amount to scroll by, in vp.
\- **state**: current sliding status.
- **offsetRemain**: actual amount by which the list scrolls, in vp.
This event is triggered when the user starts dragging the list or the list starts inertial scrolling. This event is not triggered when the list rebounds or the scrolling controller is used.
This API is supported in ArkTS widgets.
**NOTE**
If **listDirection** is set to **Axis.Vertical**, the return value is the amount by which the list needs to scroll in the vertical direction. If **listDirection** is set to **Axis.Horizontal**, the return value is the amount by which the list needs to scroll in the horizontal direction.| +| onScroll(event: (scrollOffset: number, scrollState: ScrollState) => void) | Triggered when the list scrolls.
- **scrollOffset**: scroll offset of each frame. The offset is positive when the list is scrolled up and negative when the list is scrolled down.
- **[scrollState](#scrollstate)**: current scroll state.
Since API version 9, this API is supported in ArkTS widgets.| +| onScrollIndex(event: (start: number, end: number, center10+: number) => void) | Triggered when a child component enters or leaves the list display area. Since API version 10, this event is also triggered when the child component in the center of the list display area changes.
During index calculation, each **\** component is taken as a whole and assigned an index, and the indexes of the list items within are not included in the calculation.
- **start**: index of the first child component in the list display area.
- **end**: index of the last child component in the list display area.
- **center**: index of the center child component in the list display area.
This event is triggered once when the list is initialized and when the index of the first list item or the next list item in the list display area changes. Since API version 10, this event is also triggered when the child component in the center of the list display area changes.
When the list edge scrolling effect is the spring effect, the **onScrollIndex** event is not triggered when the user scrolls the list to the edge or releases the list to rebound.
Since API version 9, this API is supported in ArkTS widgets.| +| onReachStart(event: () => void) | Triggered when the list reaches the start position.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This event is triggered once when **initialIndex** is **0** during list initialization and once when the list scrolls to the start position. When the list edge scrolling effect is the spring effect, this event is triggered once when the list passes the start position and is triggered again when the list returns to the start position.| +| onReachEnd(event: () => void) | Triggered when the list reaches the end position.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
When the list edge scrolling effect is the spring effect, this event is triggered once when the list passes the end position and is triggered again when the list returns to the end position.| +| onScrollFrameBegin9+(event: (offset: number, state: ScrollState) => { offsetRemain }) | Triggered when the list starts to scroll. The input parameters indicate the amount by which the list will scroll. The event handler then works out the amount by which the list needs to scroll based on the real-world situation and returns the result.
\- **offset**: amount to scroll by, in vp.
\- **state**: current scrolling state.
- **offsetRemain**: actual amount by which the list scrolls, in vp.
This event is triggered when the user starts dragging the list or the list starts inertial scrolling. This event is not triggered when the list rebounds or the scrolling controller is used.
This API is supported in ArkTS widgets.
**NOTE**
If **listDirection** is set to **Axis.Vertical**, the return value is the amount by which the list needs to scroll in the vertical direction. If **listDirection** is set to **Axis.Horizontal**, the return value is the amount by which the list needs to scroll in the horizontal direction.| | onScrollStart9+(event: () => void) | Triggered when the list starts scrolling initiated by the user's finger dragging the **\** component or its scrollbar. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](ts-container-scroll.md#scroller) starts.
This API is supported in ArkTS widgets.| | onScrollStop(event: () => void) | Triggered when the list stops scrolling after the user's finger leaves the screen. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](ts-container-scroll.md#scroller) stops.
Since API version 9, this API is supported in ArkTS widgets.| | onItemMove(event: (from: number, to: number) => boolean) | Triggered when a list item moves.
- **from**: index of the item before moving.
- **to**: index of the item after moving.| @@ -137,11 +156,23 @@ Provides the chained animation settings, which cover the maximum spacing, minimu Since API version 9, this API is supported in ArkTS widgets. -| Name | Description | -| ------ | ------------------------------ | -| Idle | Not scrolling. Triggered when the API provided by the controller is used to scroll the list or when the scrollbar is dragged. | -| Scroll | Finger dragging. Triggered when the user drags the list to scroll. | -| Fling | Inertial scrolling. Triggered when inertial scrolling occurs or when the list bounces back after being released from a quick swipe.| +| Name | Description | +| ------ | ---------------------------------------- | +| Idle | Idle. The list enters this state when an API in the controller is used to scroll the list or when the scrollbar is dragged.
**NOTE**
Since API version 10, the list enters this state when it is not scrolling or an API in the controller that does not apply an animation is called.| +| Scroll | Scrolling. The list enters this state when the user drags the list to scroll.
**NOTE**
Since API version 10, the list also enters this state when the user drags the scrollbar or the mouse wheel to scroll the list.| +| Fling | Inertial scrolling. The list enters this state when inertial scrolling occurs or when the list bounces back after being released from a fling.
**NOTE**
Since API version 10, the list enters this state when: inertial scrolling occurs after a fling; the list bounces back after being released from a fling; inertial scrolling occurs after quick dragging of the built-in scrollbar; scrolling occurs after an API in the controller that applies an animation is called.| + +The table below lists the changes in the **ScrollState** enums. + +| Scenario | API Version 9 and Earlier| API Version 10 and Later| +| ------------- | ---------------- | ---------------- | +| Finger dragging | Scroll | Scroll | +| Inertial scrolling | Fling | Fling | +| Cross-boundary bouncing | Fling | Fling | +| Scrolling by mouse wheel | Idle | Scroll | +| Scrollbar dragging | Idle | Scroll | +| Scrolling by the scrolling controller (with animation) | Idle | Fling | +| Scrolling by the scrolling controller (without animation)| Idle | Idle | > **NOTE** > @@ -183,11 +214,16 @@ struct ListExample { } .listDirection(Axis.Vertical) // Arrangement direction .scrollBar(BarState.Off) + .friction(0.6) .divider({ strokeWidth: 2, color: 0xFFFFFF, startMargin: 20, endMargin: 20 }) // Divider - .edgeEffect(EdgeEffect.Spring) // No effect when the list scrolls to the edge. - .onScrollIndex((firstIndex: number, lastIndex: number) => { + .edgeEffect(EdgeEffect.Spring) // Set the edge scrolling effect to Spring. + .onScrollIndex((firstIndex: number, lastIndex: number, centerIndex: number) => { console.info('first' + firstIndex) console.info('last' + lastIndex) + console.info('center' + centerIndex) + }) + .onScroll((scrollOffset: number, scrollState: ScrollState) => { + console.info(`onScroll scrollState = ${ScrollState[scrollState]}, scrollOffset = ${[scrollOffset]}`) }) .width('90%') } @@ -230,6 +266,7 @@ struct ListLanesExample { } .height(300) .width("90%") + .friction(0.6) .border({ width: 3, color: Color.Red }) .lanes({ minLength: 40, maxLength: 40 }) .alignListItem(this.alignListItem) @@ -249,7 +286,7 @@ struct ListLanesExample { } ``` -![list](figures/list1.gif) +![list](figures/list-alignListItem.gif) ### Example 3 @@ -293,6 +330,7 @@ struct ListExample{ }, item => item) }.width('90%') .scrollBar(BarState.Off) + .friction(0.6) }.width('100%') Button('edit list') @@ -305,3 +343,50 @@ struct ListExample{ ``` ![list](figures/list3.gif) + +### Example 4 + +```ts +// xxx.ets +@Entry +@Component +struct ListExample { + private arr: number[] = Array.apply(this, {length: 20}).map((item, i) => i) + private scrollerForList: Scroller = new Scroller() + + build() { + Column() { + Row() { + List({ space: 20, initialIndex: 0, scroller: this.scrollerForList }) { + ForEach(this.arr, (item) => { + ListItem() { + Text('' + item) + .width('100%').height(100).fontSize(16) + .textAlign(TextAlign.Center) + } + .borderRadius(10).backgroundColor(0xFFFFFF) + .width('60%') + .height('80%') + }, item => item) + } + .chainAnimation(true) + .edgeEffect(EdgeEffect.Spring) + .listDirection(Axis.Horizontal) + .height('100%') + .width('100%') + .scrollSnapAlign(ScrollSnapAlign.CENTER) + .borderRadius(10) + .backgroundColor(0xDCDCDC) + .listDirection(Axis.Horizontal) + .width('100%') + } + .width('100%') + .height('100%') + .backgroundColor(0xDCDCDC) + .padding({ top: 10}) + } + } +} +``` + +![list](figures/list4.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-container-listitem.md b/en/application-dev/reference/arkui-ts/ts-container-listitem.md index cd8ef63993cdbfdc654453e9d647bd2fdb5ac7d1..86b924cdc24f71291ed592877833a14b6d5448b3 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-listitem.md +++ b/en/application-dev/reference/arkui-ts/ts-container-listitem.md @@ -76,12 +76,11 @@ For a list in horizontal layout, it refers to the delete item displayed below (o | Name | Type | Mandatory| Description | | -------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| deleteAreaDistance | [Length](ts-types.md#length) | No| Swipe distance threshold for deleting the list item.
Default value: **56vp**
**NOTE**
This parameter cannot be set in percentage.
If the value is greater than the list item width minus the width of **swipeAction**, or is less than or equal to 0, the delete area will not be set.| -| onDelete | () => void | No| Callback invoked when the list item is released while in the delete area.
**NOTE**
This callback is invoked only when the list item is released in a position that meets or goes beyond the specified swipe distance threshold (which must be valid) for deleting the list item.| -| onEntryDeleteArea | () => void | No| Callback invoked each time the list item enters the delete area.| -| onExitDeleteArea | () => void | No|Callback invoked each time the list item exits the delete area.| +| actionAreaDistance | [Length](ts-types.md#length) | No| Swipe distance threshold for deleting the list item.
Default value: **56vp**
**NOTE**
This parameter cannot be set in percentage.
If the value is greater than the list item width minus the width of **swipeAction**, or is less than or equal to 0, the delete area will not be set.| +| onAction | () => void | No| Callback invoked when the list item is released while in the delete area.
**NOTE**
This callback is invoked only when the list item is released in a position that meets or goes beyond the specified swipe distance threshold (which must be valid) for deleting the list item.| +| onEnterActionArea | () => void | No| Callback invoked each time the list item enters the delete area.| +| onExitActionArea | () => void | No|Callback invoked each time the list item exits the delete area.| | builder | CustomBuilder | No|Swipe action item displayed when the list item is swiped left or right (in vertical list layout) or up or down (in horizontal list layout).| -| useDefaultDeleteAnimation | boolean | No|Whether to use the default delete animation.
Default value: **true**| ## ListItemOptions10+ | Name | Type | Mandatory| Description | @@ -101,9 +100,10 @@ For a list in horizontal layout, it refers to the delete item displayed below (o | -------- | -------- | | onSelect(event: (isSelected: boolean) => void)8+ | Triggered when the selected state of the **\** changes.
**isSelected**: Returns **true** if the **\** is selected by mouse drag; returns **false** otherwise.| - ## Example +### Example 1 + ```ts // xxx.ets @Entry @@ -130,6 +130,8 @@ struct ListItemExample { ![en-us_image_0000001219864159](figures/en-us_image_0000001219864159.gif) +### Example 2 + ```ts // xxx.ets @@ -165,19 +167,18 @@ struct ListItemExample2 { .swipeAction({ end: { builder: this.itemEnd.bind(this, item), - useDefaultDeleteAnimation: true, - onDelete: () => { + onAction: () => { animateTo({ duration: 1000 }, () => { let index = this.arr.indexOf(item) this.arr.splice(index, 1) }) }, - deleteAreaDistance: 80, - onEnterDeleteArea: () => { + actionAreaDistance: 80, + onEnterActionArea: () => { this.enterEndDeleteAreaString = "enterEndDeleteArea" this.exitEndDeleteAreaString = "not exitEndDeleteArea" }, - onExitDeleteArea: () => { + onExitActionArea: () => { this.enterEndDeleteAreaString = "not enterEndDeleteArea" this.exitEndDeleteAreaString = "exitEndDeleteArea" } @@ -196,3 +197,43 @@ struct ListItemExample2 { } ``` ![deleteListItem](figures/deleteListItem.gif) + +### Example 3 + +```ts +// xxx.ets +@Entry +@Component +struct ListItemExample3 { + private arr: any = [ListItemStyle.CARD, ListItemStyle.CARD,ListItemStyle.NONE] + build() { + Column() { + List({ space: "4vp", initialIndex: 0 }) { + ListItemGroup({style:ListItemGroupStyle.CARD}){ + ForEach(this.arr, (itemStyle,index) => { + ListItem({style:itemStyle}) { + Text(""+index) + .width("100%") + .textAlign(TextAlign.Center) + } + }) + } + ForEach(this.arr, (itemStyle,index) => { + ListItem({style:itemStyle}) { + Text(""+index) + .width("100%") + .textAlign(TextAlign.Center) + } + }) + } + .width('100%') + .multiSelectable(true) + .backgroundColor(0xDCDCDC) // List in light blue + } + .width('100%') + .padding({ top: 5 }) + } +} + +``` +![ListItemStyle](figures/listItem3.jpeg) diff --git a/en/application-dev/reference/arkui-ts/ts-container-listitemgroup.md b/en/application-dev/reference/arkui-ts/ts-container-listitemgroup.md index 48ed2249eb25c786c2bcd5f8cb900bd4e4b1589a..9f3ff104bab488a2bcc3f4e02f3ddd572742ba34 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-listitemgroup.md +++ b/en/application-dev/reference/arkui-ts/ts-container-listitemgroup.md @@ -8,9 +8,9 @@ The **\** component is used to display list item groups. It must ## Usage Guidelines -If the **listDirection** attribute of the parent **\** component is set to **Axis.Vertical**, the **height** attribute of the **\** component cannot be set. The height of a **\** component is the sum of its header height, footer height, and total height of the list items. If the **listDirection** attribute of the parent **\** component is set to **Axis.Horizontal**, the **width** attribute of the **\** component cannot be set. The width of a **\** component is the sum of its header width, footer width, and total width of the list items. +If the **listDirection** attribute of the parent **\** component is set to **Axis.Vertical**, the **height** attribute of the **\** component is fixed at the sum of the component's header height, footer height, and total height of the list items. If the **listDirection** attribute of the parent **\** component is set to **Axis.Horizontal**, the **width** attribute of the **\** component is fixed at the sum of the component's header width, footer width, and total width of the list items. -The list items in the **\** component cannot be edited, selected, or dragged. That is, the **editable** and **selectable** attributes of these list items do not take effect. +The list items in the **\** component cannot be edited or dragged. That is, their **editable** attribute does not take effect. ## Child Components @@ -27,8 +27,8 @@ ListItemGroup(options?: {header?: CustomBuilder, footer?: CustomBuilder, space?: | ------------------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ | | header | [CustomBuilder](ts-types.md#custombuilder8) | No | Header of the list item group. | | footer | [CustomBuilder](ts-types.md#custombuilder8) | No | Footer of the list item group. | -| space | number \| string | No | Spacing between list items. This parameter is valid only between list items, but not between a header and list item or between a footer and list item.| -| style10+ | [ListItemGroupStyle](#listitemgroupstyle10) | No | Style of the list item group.
Default value: **ListItemGroupStyle.NONE**
If this parameter is set to **ListItemGroupStyle.NONE**, no style is applied.
If this parameter is set to **ListItemGroupStyle.CARD**, the default card style is applied, but only when **ListItemStyle.CARD** is set for [\](ts-container-listitem.md).
It can be in focus, hover, press, selected, or disable style depending on the state.
**NOTE**
In the default card style, the list has its **listDirection** attribute fixed at **Axis.Vertical** and **alignListItem** attribute at **ListItemAlign.Center**; the **header** and **footer** parameters cannot be set for the list item group. | +| space | number \| string | No | Spacing between list items. This parameter is valid only between list items, but not between the header and list item or between the footer and list item.| +| style10+ | [ListItemGroupStyle](#listitemgroupstyle10) | No | Style of the list item group.
Default value: **ListItemGroupStyle.NONE**
If this parameter is set to **ListItemGroupStyle.NONE**, no style is applied.
If this parameter is set to **ListItemGroupStyle.CARD**, the default card style is applied, but only when **ListItemStyle.CARD** is set for [\](ts-container-listitem.md).
In the default card style, list items can be in focus, hover, press, selected, or disable style depending on their state.
**NOTE**
In the default card style, the parent **\** component has its **listDirection** attribute fixed at **Axis.Vertical** and its **alignListItem** attribute defaulted at **ListItemAlign.Center**; the **header** and **footer** parameters cannot be set for the list item group. | ## Attributes @@ -45,7 +45,7 @@ ListItemGroup(options?: {header?: CustomBuilder, footer?: CustomBuilder, space?: > **NOTE** > -> The **\** component does not support the universal attribute **[aspectRatio](ts-universal-attributes-layout-constraints.md)**. +> The **\** component does not support the universal attribute [aspectRatio](ts-universal-attributes-layout-constraints.md). > > If the main axis of **\** runs in the vertical direction, the [height](ts-universal-attributes-size.md) setting does not take effect. > @@ -54,6 +54,8 @@ ListItemGroup(options?: {header?: CustomBuilder, footer?: CustomBuilder, space?: ## Example +### Example 1 + ```ts // xxx.ets @Entry @@ -119,3 +121,55 @@ struct ListItemGroupExample { ``` ![en-us_image_0000001219864159](figures/en-us_image_listitemgroup.gif) + +### Example 2 + +```ts +// xxx.ets +@Entry +@Component +struct ListItemGroupExample2 { + private arr: any = [ + { + style:ListItemGroupStyle.CARD, + itemStyles:[ListItemStyle.CARD, ListItemStyle.CARD, ListItemStyle.CARD] + }, + { + style:ListItemGroupStyle.CARD, + itemStyles:[ListItemStyle.CARD, ListItemStyle.CARD, ListItemStyle.NONE] + }, + { + style:ListItemGroupStyle.CARD, + itemStyles:[ListItemStyle.CARD, ListItemStyle.NONE, ListItemStyle.CARD] + }, + { + style:ListItemGroupStyle.NONE, + itemStyles:[ListItemStyle.CARD, ListItemStyle.CARD, ListItemStyle.NONE] + } + ] + build() { + Column() { + List({ space: "4vp", initialIndex: 0 }) { + ForEach(this.arr, (item,index) => { + ListItemGroup({ style:item.style }) { + ForEach(item.itemStyles, (itemStyle,itemIndex) => { + ListItem({style:itemStyle}) { + Text("Item "+(itemIndex+1)+" in group "+(index+1)) + .width("100%") + .textAlign(TextAlign.Center) + } + }, item => item) + } + }) + } + .width('100%') + .multiSelectable(true) + .backgroundColor(0xDCDCDC) // List in light blue + } + .width('100%') + .padding({ top: 5 }) + } +} + +``` +![ListItemGroupStyle](figures/listItemGroup2.jpeg) diff --git a/en/application-dev/reference/arkui-ts/ts-container-panel.md b/en/application-dev/reference/arkui-ts/ts-container-panel.md index bc38624a2bfaa00817283a74515a1ecfd647f2cd..b0359c645851f1e28e8f3ab8a3371d3f501df89d 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-panel.md +++ b/en/application-dev/reference/arkui-ts/ts-container-panel.md @@ -40,6 +40,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | miniHeight | string \| number | Panel height in the **PanelMode.Mini** mode.
Default value: **48**
Unit: vp
**NOTE**
This attribute cannot be set in percentage.| | show | boolean | Whether to show the panel.| | backgroundMask9+|[ResourceColor](ts-types.md#resourcecolor)|Background mask of the panel.| +| showCloseIcon10+ | boolean | Whether to display the close icon. The value **true** means to display the close icon, and **false** means the opposite.
Default value: **false**| ## PanelType @@ -93,6 +94,7 @@ struct PanelExample { .type(PanelType.Foldable).mode(PanelMode.Half) .dragBar(true) // The drag bar is enabled by default. .halfHeight(500) // The panel height is half of the screen height by default. + .showCloseIcon(true) // Display the close icon. .onChange((width: number, height: number, mode: PanelMode) => { console.info(`width:${width},height:${height},mode:${mode}`) }) @@ -101,4 +103,4 @@ struct PanelExample { } ``` -![en-us_image_0000001256978381](figures/en-us_image_0000001256978381.gif) +![en-us_image_0000001174422896](figures/en-us_image_0000001174422896.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-container-rowsplit.md b/en/application-dev/reference/arkui-ts/ts-container-rowsplit.md index 4a2fe8e741369350691f6f46ebeb929adbcc208c..6ad3efe53622d76410255e7896c3e273ecaca2d1 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-rowsplit.md +++ b/en/application-dev/reference/arkui-ts/ts-container-rowsplit.md @@ -1,6 +1,6 @@ # RowSplit -The **\** lays out child components horizontally and inserts a vertical divider between child components. +The **\** lays out child components horizontally and inserts a vertical divider between every two child components. > **NOTE** > @@ -19,15 +19,13 @@ RowSplit() | Name| Type| Description| | -------- | -------- | -------- | -| resizeable | boolean | Whether the divider can be dragged.
Default value: **false** | +| resizeable | boolean | Whether the divider can be dragged.
Default value: **false** | > **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. +> The divider of **\** can change the width of the left and right child components, but only to the extent that the resultant width falls within the maximum and minimum widths of the child components. > -> The universal attributes **clip** and **margin** are not supported. +> Universal attributes such as **clip** and **margin** are supported. If **clip** is not set, the default value **true** is used. ## Example @@ -54,4 +52,4 @@ struct RowSplitExample { } ``` -![en-us_image_0000001212058482](figures/en-us_image_0000001212058482.gif) +![en-us_image_0000001219982729](figures/en-us_image_0000001219982729.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-container-scroll.md b/en/application-dev/reference/arkui-ts/ts-container-scroll.md index 8fd15ac0a038142180ee2705ee4b6026ba6ac5e9..b6eda086a1bde6b6a2b6d3f0ab5ec3e2a752f1f5 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-scroll.md +++ b/en/application-dev/reference/arkui-ts/ts-container-scroll.md @@ -35,6 +35,9 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | scrollBarColor | string \| number \| [Color](ts-appendix-enums.md#color) | Color of the scrollbar.| | scrollBarWidth | string \| number | Width of the scrollbar. This attribute cannot be set in percentage.
Default value: **4**
Unit: vp
**NOTE**
If the width of the scrollbar exceeds its height, it will change to the default value.| | edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect. For details, see **EdgeEffect**.
Default value: **EdgeEffect.None**| +| enableScrollInteraction10+ | boolean | Whether to support scroll gestures. When this attribute is set to **false**, scrolling by finger or mouse is not supported, but the scrolling controller API is not affected.
Default value: **true** | +| nestedScroll10+ | [NestedScrollOptions](#nestedscrolloptions10) | Nested scrolling options. You can set the nested scrolling mode in the forward and backward directions to implement scrolling linkage with the parent component.| +| friction10+ | number \| [Resource](ts-types.md#resource) | Friction coefficient. It applies only to gestures in the scrolling area, and it affects only indirectly the scroll chaining during the inertial scrolling process.
Default value: **0.9** for wearable devices and **0.6** for non-wearable devices
**NOTE**
A value less than or equal to 0 evaluates to the default value.| ## ScrollDirection | Name | Description | @@ -42,18 +45,18 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Horizontal | Only horizontal scrolling is supported. | | Vertical | Only vertical scrolling is supported. | | None | Scrolling is disabled. | -| Free(deprecated) | Vertical or horizontal scrolling is supported.
This API is deprecated since API version 9. | +| Free(deprecated) | Vertical or horizontal scrolling is supported.
This API is deprecated since API version 9.| ## Events -| Name | Description | +| Name | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| onScrollFrameBegin9+(event: (offset: number, state: ScrollState) => { offsetRemain }) | Triggered when each frame scrolling starts. The input parameters indicate the amount by which the **\** component will scroll. The event handler then works out the amount by which the component needs to scroll based on the real-world situation and returns the result.
\- **offset**: amount to scroll by.
\- **state**: current scrolling status.
- **offsetRemain**: actual amount by which the component scrolls.
**NOTE**
1. This event is triggered when scrolling is started by the **\** component or other input settings, such as keyboard and mouse operations.
2. This event is not triggered when the controller API is called.
3. This event does not support the out-of-bounds bounce effect.
**NOTE**
The value of **offsetRemain** can be a negative value.
If the **onScrollFrameBegine** event and **scrollBy** method are used to implement nested scrolling, set the **edgeEffect** attribute of the scrollable child component to **None**. For example, if a **\** is nested in the **\** component, **edgeEffect** of the **\** must be set to **EdgeEffect.None**. | -| onScroll(event: (xOffset: number, yOffset: number) => void) | Triggered to return the horizontal and vertical offsets during scrolling when the specified scroll event occurs.
**NOTE**
1. This event is triggered when scrolling is started by the **\** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called.
3. This event supports the out-of-bounds bounce effect. | -| onScrollEdge(event: (side: Edge) => void) | Triggered when scrolling reaches the edge.
**NOTE**
1. This event is triggered when scrolling reaches the edge after being started by the **\** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called.
3. This event supports the out-of-bounds bounce effect. | -| onScrollEnd(deprecated) (event: () => void) | Triggered when scrolling stops.
This event is deprecated since API version 9. Use the **onScrollStop** event instead.
**NOTE**
1. This event is triggered when scrolling is stopped by the **\** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called, accompanied by a transition animation. | -| onScrollStart9+(event: () => void) | Triggered when scrolling starts and is initiated by the user's finger dragging the **\** component or its scrollbar. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](#scroller) starts.
**NOTE**
1. This event is triggered when scrolling is started by the **\** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called, accompanied by a transition animation. | -| onScrollStop9+(event: () => void) | Triggered when scrolling stops after the user's finger leaves the screen. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](#scroller) stops.
**NOTE**
1. This event is triggered when scrolling is stopped by the **\** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called, accompanied by a transition animation. | +| onScrollFrameBegin9+(event: (offset: number, state: ScrollState) => { offsetRemain }) | Triggered when each frame scrolling starts. The input parameters indicate the amount by which the **\** component will scroll. The event handler then works out the amount by which the component needs to scroll based on the real-world situation and returns the result.
\- **offset**: amount to scroll by.
\- **state**: current scrolling status.
- **offsetRemain**: actual amount by which the component scrolls.
**NOTE**
1. This event is triggered when scrolling is started by the **\** component or other input settings, such as keyboard and mouse operations.
2. This event is not triggered when the controller API is called.
3. This event does not support the out-of-bounds bounce effect.
**NOTE**
The value of **offsetRemain** can be a negative value.
If the **onScrollFrameBegine** event and **scrollBy** method are used to implement nested scrolling, set the **edgeEffect** attribute of the scrollable child component to **None**. For example, if a **\** is nested in the **\** component, **edgeEffect** of the **\** must be set to **EdgeEffect.None**.| +| onScroll(event: (xOffset: number, yOffset: number) => void) | Triggered to return the horizontal and vertical offsets during scrolling when the specified scroll event occurs.
**NOTE**
1. This event is triggered when scrolling is started by the **\** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called.
3. This event supports the out-of-bounds bounce effect.| +| onScrollEdge(event: (side: Edge) => void) | Triggered when scrolling reaches the edge.
**NOTE**
1. This event is triggered when scrolling reaches the edge after being started by the **\** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called.
3. This event supports the out-of-bounds bounce effect.| +| onScrollEnd(deprecated) (event: () => void) | Triggered when scrolling stops.
This event is deprecated since API version 9. Use the **onScrollStop** event instead.
**NOTE**
1. This event is triggered when scrolling is stopped by the **\** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called, accompanied by a transition animation.| +| onScrollStart9+(event: () => void) | Triggered when scrolling starts and is initiated by the user's finger dragging the **\** component or its scrollbar. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](#scroller) starts.
**NOTE**
1. This event is triggered when scrolling is started by the **\** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called, accompanied by a transition animation.| +| onScrollStop9+(event: () => void) | Triggered when scrolling stops after the user's finger leaves the screen. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](#scroller) stops.
**NOTE**
1. This event is triggered when scrolling is stopped by the **\** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called, accompanied by a transition animation.| > **NOTE** > @@ -73,7 +76,7 @@ scroller: Scroller = new Scroller() ### scrollTo -scrollTo(value: { xOffset: number | string, yOffset: number | string, animation?: { duration: number, curve: Curve } }): void +scrollTo(value: { xOffset: number | string, yOffset: number | string, animation?: { duration?: number, curve?: Curve | ICurve } | boolean }): void Scrolls to the specified position. @@ -82,9 +85,9 @@ Scrolls to the specified position. | Name | Type | Mandatory| Description | | --------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| xOffset | number \| string | Yes | Horizontal scrolling offset.
**NOTE**
This parameter cannot be set in percentage.
This parameter is valid only when the scroll axis is the x-axis.| -| yOffset | number \| string | Yes | Vertical scrolling offset.
**NOTE**
This parameter cannot be set in percentage.
This parameter is valid only when the scroll axis is the y-axis.| -| animation | {
duration: number,
curve: [Curve](ts-appendix-enums.md#curve)
} | No | Animation configuration, which includes the following:
- **duration**: scrolling duration.
- **curve**: scrolling curve.
Default value:
{
duration: 0,
curve: Curve.Ease
}
**NOTE**
A value less than 0 evaluates to the default value.| +| xOffset | number \| string | Yes | Horizontal scrolling offset.
**NOTE**
This parameter cannot be set in percentage.
If the value is less than 0, no operation is performed. That is, this parameter does not take effect.
This parameter is valid only when the scroll axis is the x-axis.| +| yOffset | number \| string | Yes | Vertical scrolling offset.
**NOTE**
This parameter cannot be set in percentage.
If the value is less than 0, no operation is performed. That is, this parameter does not take effect.
This parameter is valid only when the scroll axis is the y-axis.| +| animation | {duration?: number, curve?: [Curve](ts-appendix-enums.md#curve) \| [ICurve](../apis/js-apis-curve.md#icurve)10+ } \| boolean10+ | No | Animation configuration, which includes the following:
- **duration**: scrolling duration.
- **curve**: scrolling curve.
- **boolean**: whether to enable the default spring animation.
Default value:
{
duration: 1000,
curve: Curve.Ease
}
boolean: false
**NOTE**
A value less than 0 evaluates to the default value.
Currently, the **\**, **\**, **\**, and **\** support the **Boolean** type and **ICurve**.| ### scrollEdge @@ -112,7 +115,7 @@ Scrolls to the next or previous page. | Name | Type | Mandatory | Description | | --------- | ------- | ---- | ------------------------------ | | next | boolean | Yes | Whether to turn to the next page. The value **true** means to scroll to the next page, and **false** means to scroll to the previous page.| -| direction(deprecated) | [Axis](ts-appendix-enums.md#axis) | No | Scrolling direction: horizontal or vertical.
This API is deprecated since API version 9. | +| direction(deprecated) | [Axis](ts-appendix-enums.md#axis) | No | Scrolling direction: horizontal or vertical.
This API is deprecated since API version 9. | ### currentOffset @@ -146,7 +149,7 @@ When **smooth** is set to **true**, all passed items are loaded and counted in l | Name | Type| Mandatory| Description | | --------------------- | -------- | ---- | ------------------------------------------------------------ | -| value | number | Yes | Index of the item to be scrolled to in the list. | +| value | number | Yes | Index of the item to be scrolled to in the list.
**NOTE**
If the value set is a negative value or greater than the maximum index of the list items, the value is abnormal, and no scrolling will be performed. | | smooth10+ | boolean | No | Whether to enable the smooth animation for scrolling to the item with the specified index. The value **true** means to enable that the smooth animation, and **false** means the opposite.
Default value: **false**
**NOTE**
Currently, only the **\** component supports this parameter.| | align10+ | [ScrollAlign](#scrollalign10) | No | How the list item to scroll to is aligned with the list.
Default value: **ScrollAlign.START**
**NOTE**
Currently, only the **\** component supports this parameter.| @@ -169,6 +172,22 @@ Scrolls by the specified amount. | dx | Length | Yes | Amount to scroll by in the horizontal direction. The percentage format is not supported.| | dy | Length | Yes | Amount to scroll by in the vertical direction. The percentage format is not supported.| +### isAtEnd10+ + +isAtEnd(): boolean + +Checks whether the component has scrolled to the bottom. + +> **NOTE** +> +> This API is available for the **\**, **\**, **\**, and **\** components. + +**Return value** + +| Type | Description | +| ------- | -------- | +| boolean | The value **true** means that the component has scrolled to the bottom, and **false** means the opposite.| + ## ScrollAlign10+ | Name | Description | @@ -178,11 +197,27 @@ Scrolls by the specified amount. | END | The end edge of the list item is flush with the end edge of the list.| | AUTO | The list item is automatically aligned.
If the list item is fully contained within the display area, no adjustment is performed. Otherwise, the list item is aligned so that its start or end edge is flush with the start or end edge of the list, whichever requires a shorter scrolling distance.| +## NestedScrollOptions10+ +| Name | Type | Description | +| ----- | ------ | ----------------- | +| scrollForward | NestedScrollMode | Nested scrolling option when the component scrolls forward.| +| scrollBackward | NestedScrollMode | Nested scrolling option when the component scrolls backward.| + +## NestedScrollMode10+ +| Name | Description | +| ------ | ------------------------------ | +| SELF_ONLY | The scrolling is contained within the component, and no scroll chaining occurs, that is, the parent component does not scroll when the component scrolling reaches the boundary. | +| SELF_FIRST | The component scrolls first, and when it hits the boundary, the parent component scrolls. When the parent component hits the boundary, its edge effect is displayed. If no edge effect is specified for the parent component, the edge effect of the child component is displayed instead. | +| PARENT_FIRST | The parent component scrolls first, and when it hits the boundary, the component scrolls. When the component hits the boundary, its edge effect is displayed. If no edge effect is specified for the component, the edge effect of the parent component is displayed instead.| +| PARALLEL | The component and its parent component scroll at the same time. When both the component and its parent component hit the boundary, the edge effect of the component is displayed. If no edge effect is specified for the component, the edge effect of the parent component is displayed instead.| + ## Example ### Example 1 ```ts // xxx.ets +import Curves from '@ohos.curves' + @Entry @Component struct ScrollExample { @@ -209,6 +244,7 @@ struct ScrollExample { .scrollBar(BarState.On) // The scrollbar is always displayed. .scrollBarColor(Color.Gray) // Color of the scrollbar. .scrollBarWidth(10) // The scrollbar width is 10. + .friction(0.6) .edgeEffect(EdgeEffect.None) .onScroll((xOffset: number, yOffset: number) => { console.info(xOffset + ' ' + yOffset) @@ -223,7 +259,7 @@ struct ScrollExample { Button('scroll 150') .height('5%') .onClick(() => { // Click to scroll down to 150.0 vp. - this.scroller.scrollBy(0,150) + this.scroller.scrollBy(0, 150) }) .margin({ top: 10, left: 20 }) Button('scroll 100') @@ -232,24 +268,31 @@ struct ScrollExample { this.scroller.scrollTo({ xOffset: 0, yOffset: this.scroller.currentOffset().yOffset + 100 }) }) .margin({ top: 60, left: 20 }) + Button('scroll 100') + .height('5%') + .onClick(() => {// Click to scroll down by 100.0 vp. An animation is applied to the scrolling. + let curve = Curves.interpolatingSpring(100, 1, 228, 30) // Create a step curve. + this.scroller.scrollTo({ xOffset: 0, yOffset: this.scroller.currentOffset().yOffset + 100, animation: { duration: 1000, curve: curve }}) + }) + .margin({ top: 110, left: 20 }) Button('back top') .height('5%') .onClick(() => { // Click to go back to the top. this.scroller.scrollEdge(Edge.Top) }) - .margin({ top: 110, left: 20 }) + .margin({ top: 160, left: 20 }) Button('next page') .height('5%') .onClick(() => { // Click to go to the next page. this.scroller.scrollPage({ next: true }) }) - .margin({ top: 170, left: 20 }) + .margin({ top: 210, left: 20 }) }.width('100%').height('100%').backgroundColor(0xDCDCDC) } } ``` -![en-us_image_0000001256978363](figures/en-us_image_0000001256978363.gif) +![en-us_image_0000001174104386](figures/en-us_image_0000001174104386.gif) ### Example 2 ```ts @@ -284,6 +327,7 @@ struct NestedScroll { .width("100%") .height("50%") .edgeEffect(EdgeEffect.None) + .friction(0.6) .onReachStart(() => { this.listPosition = 0 }) @@ -311,3 +355,64 @@ struct NestedScroll { ``` ![NestedScroll](figures/NestedScroll.gif) + +### Example 3 +```ts +@Entry +@Component +struct StickyNestedScroll { + @State message: string = 'Hello World' + @State arr: number[] = [] + + @Styles listCard() { + .backgroundColor(Color.White) + .height(72) + .width("100%") + .borderRadius(12) + } + build() { + Scroll() { + Column() { + Text("Scroll Area") + .width("100%") + .height("40%") + .backgroundColor('#0080DC') + .textAlign(TextAlign.Center) + Tabs({barPosition:BarPosition.Start}) { + TabContent() { + List({space:10}) { + ForEach(this.arr, (item) => { + ListItem() { + Text("item" + item) + .fontSize(16) + }.listCard() + }, item => item) + }.width("100%") + .edgeEffect(EdgeEffect.Spring) + .nestedScroll({ + scrollForward:NestedScrollMode.PARENT_FIRST, + scrollBackward:NestedScrollMode.SELF_FIRST + }) + }.tabBar("Tab1") + TabContent() { + }.tabBar("Tab2") + } + .vertical(false) + .height("100%") + }.width("100%") + } + .edgeEffect(EdgeEffect.Spring) + .friction(0.6) + .backgroundColor('#DCDCDC') + .scrollBar(BarState.Off) + .width('100%') + .height('100%') + } + aboutToAppear() { + for (let i = 0; i < 30; i++) { + this.arr.push(i) + } + } +} +``` +![NestedScroll2](figures/NestedScroll2.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md b/en/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md index da83e2257a34430922c41df0ed57fc91aa8a137e..3735991eeea0045115f085c11f63f9452d861f18 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md +++ b/en/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md @@ -45,13 +45,13 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | showSideBar | boolean | Whether to display the sidebar.
Default value: **true**
Since API version 10, this attribute supports [$$](../../quick-start/arkts-two-way-sync.md) for two-way binding of variables.| | controlButton | [ButtonStyle](#buttonstyle) | Attributes of the sidebar control button.| | showControlButton | boolean | Whether to display the sidebar control button.
Default value: **true**| -| sideBarWidth | number \| [Length](ts-types.md#length)9+ | Width of the sidebar.
Default value: **240vp**
Unit: vp
**NOTE**
In API version 9 and earlier versions, the default value is **200vp**. In API version 10, the default value is **240vp**.
A value less than 0 evaluates to the default value.
The value must comply with the width constraints. If it is not within the valid range, the value closest to the set one is used.
The width of the sidebar, whether it is specified or kept at the default, takes precedence over that of the sidebar child components.| -| minSideBarWidth | number \| [Length](ts-types.md#length)9+ | Minimum width of the sidebar.
Default value: **240vp**
Unit: vp
**NOTE**
In API version 9 and earlier versions, the default value is **200vp**. In API version 10, the default value is **240vp**.
A value less than 0 evaluates to the default value.
The value cannot exceed the width of the sidebar container itself. Otherwise, the width of the sidebar container itself is used.
When set, the minimum width of the sidebar takes precedence over that of the sidebar child components. If it is not set, however, the minimum width of the sidebar child component takes precedence.| -| maxSideBarWidth | number \| [Length](ts-types.md#length)9+ | Maximum width of the sidebar.
Default value: **280vp**
Unit: vp
**NOTE**
A value less than 0 evaluates to the default value.
The value cannot exceed the width of the sidebar container itself. Otherwise, the width of the sidebar container itself is used.
When set, the maximum width of the sidebar takes precedence over that of the sidebar child components. If it is not set, however, the maximum width of the sidebar child component takes precedence.| +| sideBarWidth | number \| [Length](ts-types.md#length)9+ | Width of the sidebar.
Default value: **240vp**
Unit: vp
**NOTE**
In API version 9 and earlier versions, the default value is **200vp**. In API version 10, the default value is **240vp**.
A value less than 0 evaluates to the default value.
The value must comply with the width constraints. If it is not within the valid range, the value closest to the set one is used.
The width of the sidebar, whether it is specified or kept at the default value, takes precedence over that of the sidebar child components.| +| minSideBarWidth | number \| [Length](ts-types.md#length)9+ | Minimum width of the sidebar.
Default value: **240vp**
Unit: vp
**NOTE**
In API version 9 and earlier versions, the default value is **200vp**. In API version 10, the default value is **240vp**.
A value less than 0 evaluates to the default value.
The value cannot exceed the width of the sidebar container itself. Otherwise, the width of the sidebar container itself is used.
**minSideBarWidth**, whether it is specified or kept at the default value, takes precedence over **minWidth** of the sidebar child components.| +| maxSideBarWidth | number \| [Length](ts-types.md#length)9+ | Maximum width of the sidebar.
Default value: **280vp**
Unit: vp
**NOTE**
A value less than 0 evaluates to the default value.
The value cannot exceed the width of the sidebar container itself. Otherwise, the width of the sidebar container itself is used.
**maxSideBarWidth**, whether it is specified or kept at the default value, takes precedence over **maxWidth** of the sidebar child components.| | autoHide9+ | boolean | Whether to automatically hide the sidebar when it is dragged to be smaller than the minimum width.
Default value: **true**
**NOTE**
The value is subject to the **minSideBarWidth** attribute method. If it is not set in **minSideBarWidth**, the default value is used.
Whether the sidebar should be hidden is determined when it is being dragged. When its width is less than the minimum width, the damping effect is required to trigger hiding (a distance out of range).| | sideBarPosition9+ | [SideBarPosition](#sidebarposition9) | Position of the sidebar.
Default value: **SideBarPosition.Start**| | divider10+ | [DividerStyle](#dividerstyle10) \| null | Divider style.
- **DividerStyle** (default): The divider is displayed.
- **null**: The divider is not displayed.| -| minContentWidth10+ | [Dimension](ts-types.md#dimension10) | Minimum width of the content area of the sidebar container.
Default value: **360vp**
Unit: vp
**NOTE**
A value less than 0 evaluates to the default value.
In Embed mode, when the component size is increased, only the content area is enlarged; when the component size is decreased, the content area is shrunk until its width reaches the value defined by **minContentWidth**, and then the sidebar is shrunk until its width reaches the value defined by **minSideBarWidth**; if the component size is further decreased, while respecting the minimum width of the sidebar, the content area is further shrunk until it is 0 vp large.
minContentWidth takes precedence over maxSideBarWidth and sideBarWidth of the sidebar. If minContentWidth is not set, the priority of the default value is lower than that of minSideBarWidth and maxSideBarWidth.| +| minContentWidth10+ | [Dimension](ts-types.md#dimension10) | Minimum width of the content area of the sidebar container.
Default value: **360vp**
Unit: vp
**NOTE**
If this attribute is set to a value less than 0, the default value is used. If this attribute is not set, the value **0vp** is used.
In Embed mode, when the component size is increased, only the content area is enlarged; when the component size is decreased, the content area is shrunk until its width reaches the value defined by **minContentWidth**, and then the sidebar is shrunk until its width reaches the value defined by **minSideBarWidth**; if the component size is further decreased, while respecting the minimum width of the sidebar, the content area is further shrunk, with the content clipped, until it is 0 vp large.
**minContentWidth**, whether it is specified or kept at the default value, takes precedence over **minSideBarWidth** and **sideBarWidth** of the sidebar. | ## ButtonStyle @@ -83,7 +83,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the > The settings of the [universal size attributes](ts-universal-attributes-size.md) **width** and **height** do not take effect for the sidebar child component. > The settings do not take effect for the sidebar content area either. By default, the sidebar content area takes up the remaining space of the sidebar container. > -> If the attribute method is not used, the sidebar is displayed depending on the size. +> If the **showSideBar** attribute is not set, the sidebar's visibility is subject to its size. > > - If the size is less than 520 vp, the sidebar is not displayed by default. > - If the size is greater than or equal to 520 vp, the sidebar is displayed by default. @@ -127,8 +127,6 @@ struct SideBarContainerExample { }.width('100%') .justifyContent(FlexAlign.SpaceEvenly) .backgroundColor('#19000000') - - Column() { Text('SideBarContainer content text1').fontSize(25) Text('SideBarContainer content text2').fontSize(25) @@ -148,6 +146,7 @@ struct SideBarContainerExample { .onChange((value: boolean) => { console.info('status:' + value) }) + .divider({strokeWidth: '1vp', color: Color.Gray, startMargin: '4vp', endMargin: '4vp'}) } } ``` diff --git a/en/application-dev/reference/arkui-ts/ts-container-swiper.md b/en/application-dev/reference/arkui-ts/ts-container-swiper.md index 3ebb5c039cfcec05cbe209e7d58a5142a1169c95..0756ef290138140a62b2602cd7860d03da07929c 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-swiper.md +++ b/en/application-dev/reference/arkui-ts/ts-container-swiper.md @@ -50,7 +50,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | disableSwipe8+ | boolean | Whether to disable the swipe feature.
Default value: **false** | | curve8+ | [Curve](ts-appendix-enums.md#curve) \| string | Animation curve. The ease-in/ease-out curve is used by default. For details about common curves, see [Curve](ts-appendix-enums.md#curve). You can also create custom curves (interpolation curve objects) by using the API provided by the [interpolation calculation](../apis/js-apis-curve.md) module.
Default value: **Curve.Linear**| | indicatorStyle(deprecated) | {
left?: [Length](ts-types.md#length),
top?: [Length](ts-types.md#length),
right?: [Length](ts-types.md#length),
bottom?: [Length](ts-types.md#length),
size?: [Length](ts-types.md#length),
mask?: boolean,
color?: [ResourceColor](ts-types.md),
selectedColor?: [ResourceColor](ts-types.md)
} | Style of the navigation point indicator.
\- **left**: distance between the navigation point indicator and the left edge of the **\** component.
\- **top**: distance between the navigation point indicator and the top edge of the **\** component.
\- **right**: distance between the navigation point indicator and the right edge of the **\** component.
\- **bottom**: distance between the navigation point indicator and the bottom edge of the **\** component.
\- **size**: diameter of the navigation point indicator. The value cannot be in percentage. Default value: **6vp**
\- **mask**: whether to enable the mask for the navigation point indicator.
\- **color**: color of the navigation point indicator.
\- **selectedColor**: color of the selected navigation dot.
This API is supported since API version 8 and is deprecated since API version 10. You are advised to use [indicator](#indicator10) instead.| -| displayCount8+ | number \| string \|
[SwiperAutoFill](#swiperautofill10)10+ | Number of elements to display per page.
Default value: **1**
**NOTE**
If the value is of the string type, it can only be **'auto'**, whose display effect is the same as that of **SwiperDisplayMode.AutoLinear**.
If the value is set to a number less than or equal to 0, the default value **1** is used.
If the value is of the number type, child components stretch (shrink) on the main axis after the swiper width [deducting the result of itemSpace x (displayCount – 1)] is evenly distributed among them on the main axis.
If the value is of the SwiperAutoFill type, the system automatically calculates and changes the number of elements to display per page based on the **\** component width and the **minSize** settings for the child component. If **minSize** is left empty or set to a value less than or equal to 0, the **\** component displays one column.| +| displayCount8+ | number \| string \|
[SwiperAutoFill](#swiperautofill10)10+ | Number of elements to display per page.
Default value: **1**
**NOTE**
If the value is of the string type, it can only be **'auto'**, whose display effect is the same as that of **SwiperDisplayMode.AutoLinear**.
If the value is set to a number less than or equal to 0, the default value **1** is used.
If the value is of the number type, child components stretch (shrink) on the main axis after the swiper width [deducting the result of itemSpace x (displayCount - 1)] is evenly distributed among them on the main axis.
If the value is of the SwiperAutoFill type, the system automatically calculates and changes the number of elements to display per page based on the **\** component width and the **minSize** settings for the child component. If **minSize** is left empty or set to a value less than or equal to 0, the **\** component displays one column.| | effectMode8+ | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Swipe effect. For details, see **EdgeEffect**.
Default value: **EdgeEffect.Spring**
**NOTE**
The spring effect does not take effect when the controller API is called.| | displayArrow10+ | value:[ArrowStyle](#arrowstyle10) \| boolean,
isHoverShow?: boolean | Arrow style of the navigation point indicator.
- **value**: arrow and background to set. In abnormal scenarios, the default values in the **ArrowStyle** object are used.
\- **isHoverShow**: whether to show the arrow only when the mouse pointer hovers over the navigation point indicator.
Default value: **false**
**NOTE**
When **isHoverShow** is set to **false**, the arrow is always displayed and can be clicked to turn pages.
When **isHoverShow** is set to **true**, the arrow is displayed only when the mouse pointer hovers over the navigation point indicator, and it can be clicked to turn pages.| | nextMargin10+ |
[Length](ts-types.md#length)
| Next margin, used to reveal a small part of the next item.
Default value: **0**
**NOTE**
This attribute is available only when **SwiperDisplayMode** is set to **STRETCH**.
When the main axis runs horizontally and either the next margin or previous margin is greater than the calculated width of the child component, neither the next margin nor previous margin is displayed.
When the main axis runs vertically and either the next margin or previous margin is greater than the calculated height of the child component, neither the next margin nor previous margin is displayed.| @@ -112,8 +112,8 @@ Defines the navigation point indicator of the dot style, which inherits attribut | ------------------ | ---------------------------------------- | ---- | ---------------------------------------- | | itemWidth | [Length](ts-types.md#length) | No | Width of the navigation point indicator of the dot style.
Default value: **6**
Unit: vp| | itemHeight | [Length](ts-types.md#length) | No | Height of the navigation point indicator of the dot style.
Default value: **6**
Unit: vp| -| selectedItemWidth | [Length](ts-types.md#length) | No | Width of the selected indicator dot.
Default value: **6**
Unit: vp| -| selectedItemHeight | [Length](ts-types.md#length) | No | Height of the selected indicator dot.
Default value: **6**
Unit: vp| +| selectedItemWidth | [Length](ts-types.md#length) | No | Width of the selected navigation point indicator of the dot style.
Default value: **6**
Unit: vp| +| selectedItemHeight | [Length](ts-types.md#length) | No | Height of the selected navigation point indicator of the dot style.
Default value: **6**
Unit: vp| | mask | boolean | No | Whether to enable the mask for the navigation point indicator of the dot style.
Default value: **false**| | color | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the navigation point indicator of the dot style.
Default value: **'\#182431'** (10% opacity)| | selectedColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the selected indicator dot.
Default value: **'\#007DFF'**| @@ -125,21 +125,21 @@ Defines the navigation point indicator of the digit style, which inherits attrib | Name | Type | Mandatory. | Description | | ----------------- | ---------------------------------------- | ---- | ---------------------------------------- | | fontColor | [ResourceColor](ts-types.md#resourcecolor) | No | Font color of the navigation point indicator of the digit style.
Default value: **'\#ff182431'**| -| selectedFontColor | [ResourceColor](ts-types.md#resourcecolor) | No | Font color of the selected indicator digit.
Default value: **'\#ff182431'**| +| selectedFontColor | [ResourceColor](ts-types.md#resourcecolor) | No | Font color of the selected navigation point indicator of the digit style.
Default value: **'\#ff182431'**| | digitFont | {
size?:[Length](ts-types.md#length)
weight?:number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string
} | No | Font style of the navigation point indicator of the digit style.
\- **size**: font size.
Default value: **14vp**
\- **weight**: font weight.| -| selectedDigitFont | {
size?:[Length](ts-types.md#length)
weight?:number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string
} | No | Font style of the selected indicator digit.
\- **size**: font size.
Default value: **14vp**
\- **weight**: font weight.| +| selectedDigitFont | {
size?:[Length](ts-types.md#length)
weight?:number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string
} | No | Font style of the selected navigation point indicator of the digit style.
\- **size**: font size.
Default value: **14vp**
\- **weight**: font weight.| ## ArrowStyle10+ Describes the left and right arrow attributes. | Name | Type | Mandatory. | Description | | ---------------- | ---------------------------------------- | ---- | ---------------------------------------- | -| isShowBackground | boolean | No | Whether to show the background for the arrow.
Default value: **false** | +| showBackground | boolean | No | Whether to show the background for the arrow.
Default value: **false** | | isSidebarMiddle | boolean | No | Whether the arrow is shown on either side of the navigation point indicator.
Default value: **false** (the arrow is shown on either side of the navigation point indicator)| | backgroundSize | [Length](ts-types.md#length) | No | Size of the background.
On both sides of the navigation point indicator:
Default value: **24vp**
On both sides of the component:
Default value: **32vp**
This parameter cannot be set in percentage.| -| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the background.
On both sides of the navigation point indicator:
Default value: **'\#19182431'**
On both sides of the component:
Default value: **'\#00000000'**| -| arrowSize | [Length](ts-types.md#length) | No | Size of the arrow.
On both sides of the navigation point indicator:
Default value: **18vp**
On both sides of the component:
Default value: **24vp**
**NOTE**
If **isShowBackground** is set to **true**, the value of **arrowSize** is 3/4 of the value of **backgroundSize**.
This parameter cannot be set in percentage.| -| arrowColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the arrow.
Default value: **\#182431** | +| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the background.
On both sides of the navigation point indicator:
Default value: **'\#00000000'**
On both sides of the component:
Default value: **'\#19182431'**| +| arrowSize | [Length](ts-types.md#length) | No | Size of the arrow.
On both sides of the navigation point indicator:
Default value: **18vp**
On both sides of the component:
Default value: **24vp**
**NOTE**
If **showBackground** is set to **true**, the value of **arrowSize** is 3/4 of the value of **backgroundSize**.
This parameter cannot be set in percentage.| +| arrowColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the arrow.
Default value: **'\#182431'** | ## SwiperAutoFill10+ @@ -219,7 +219,7 @@ struct SwiperExample { .duration(1000) .itemSpace(0) .displayArrow({ - isShowBackground:true, + showBackground:true, isSidebarMiddle:true, backgroundSize:24, backgroundColor:Color.White, diff --git a/en/application-dev/reference/arkui-ts/ts-container-tabcontent.md b/en/application-dev/reference/arkui-ts/ts-container-tabcontent.md index eb02f7a2612744645c0b167eb4d6f128f6f425b5..cc44bf4a37191793ff3557fde6e0ccc4a17e53cf 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-tabcontent.md +++ b/en/application-dev/reference/arkui-ts/ts-container-tabcontent.md @@ -27,8 +27,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Description| | -------- | -------- | -------- | -| tabBar | string \| [Resource](ts-types.md#resource) \| {
icon?: string \| [Resource](ts-types.md#resource),
text?: string \| [Resource](ts-types.md#resource)
}
\| [CustomBuilder](ts-types.md)8+ | Content displayed on the tab bar.
**CustomBuilder**: builder, to which components can be passed (applicable to API version 8 and later versions).
**NOTE**
If an icon uses an SVG image, the width and height attributes of the SVG image must be deleted. Otherwise, the icon size will be determined by the width and height attributes of the SVG image.
If the content set exceeds the space provided by the tab bar, it will be clipped.| -| tabBar9+ | [SubTabBarStyle](#subtabbarstyle9) \| [BottomTabBarStyle](#bottomtabbarstyle9) | Content displayed on the tab bar.
**SubTabBarStyle**: subtab style. It takes text as its input parameter.
**BottomTabBarStyle**: bottom and side tab style. It takes text and images as its input parameters.
**NOTE**
The bottom tab style does not include an underline.
When an icon display error occurs, a gray blank block is displayed.| +| tabBar | string \| [Resource](ts-types.md#resource) \| {
icon?: string \| [Resource](ts-types.md#resource),
text?: string \| [Resource](ts-types.md#resource)
}
\| [CustomBuilder](ts-types.md)8+ | Content displayed on the tab bar.
**CustomBuilder**: builder, to which components can be passed (applicable to API version 8 and later versions).
**NOTE**
When using an SVG image for the icon, delete the width and height attributes of the image. Otherwise, the icon size will be determined by the width and height attributes of the SVG image.
If the content set exceeds the space provided by the tab bar, it will be clipped.| +| tabBar9+ | [SubTabBarStyle](#subtabbarstyle9) \| [BottomTabBarStyle](#bottomtabbarstyle9) | Content displayed on the tab bar.
**SubTabBarStyle**: subtab style. It takes text as its input parameter.
**BottomTabBarStyle**: bottom and side tab style. It takes text and images as its input parameters.
**NOTE**
The bottom tab style does not include an indicator.
When an icon display error occurs, a gray blank block is displayed.| > **NOTE** > @@ -71,7 +71,7 @@ The following attributes are supported. | Name | Type | Description | | ------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | -| indicator10+ | [IndicatorStyle](#indicatorstyle10)| Underline indicator style of the selected subtab. It is valid only in the horizontal layout.
| +| indicator10+ | [IndicatorStyle](#indicatorstyle10)| Indicator style of the selected subtab. It is valid only in the horizontal layout. | | selectedMode10+ | [SelectedMode](#selectedmode10) | Display mode of the selected subtab.
Default value: **SelectedMode.INDICATOR**| | board10+ | [BoardStyle](#boardstyle10) | Board style of the selected subtab.| | labelStyle10+ | [LabelStyle](#labelstyle10) | Label text and font of the subtab.| @@ -80,23 +80,23 @@ The following attributes are supported. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------------------------------- | -| color | [ResourceColor](ts-types.md#resourcecolor) | No| Underline indicator color and board color.
Default value: **#FF007DFF**| -| height | [Length](ts-types.md#length) | No| Height of the underline indicator. It cannot be set in percentage.
Default value: **2.0**
Unit: vp| -| width | [Length](ts-types.md#length) | No| Width of the underline indicator. It cannot be set in percentage.
Default value: **0.0**
Unit: vp
**NOTE**
If this parameter is set to **0**, the tab text width is used.| -| borderRadius | [Length](ts-types.md#length) | No| Radius of the rounded corner of the underline indicator. It cannot be set in percentage.
Default value: **0.0**
Unit: vp| -| marginTop | [Length](ts-types.md#length) | No| Spacing between the underline indicator and text. It cannot be set in percentage.
Default value: **8.0**
Unit: vp| +| color | [ResourceColor](ts-types.md#resourcecolor) | No| Color of the indicator and board.
Default value: **#FF007DFF** | +| height | [Length](ts-types.md#length) | No| Height of the indicator. It cannot be set in percentage.
Default value: **2.0**
Unit: vp| +| width | [Length](ts-types.md#length) | No| Width of the indicator. It cannot be set in percentage.
Default value: **0.0**
Unit: vp
**NOTE**
If this parameter is set to **0**, the tab text width will be used instead. | +| borderRadius | [Length](ts-types.md#length) | No| Rounded corner radius of the indicator. It cannot be set in percentage.
Default value: **0.0**
Unit: vp| +| marginTop | [Length](ts-types.md#length) | No| Spacing between the indicator and text. It cannot be set in percentage.
Default value: **8.0**
Unit: vp| ## SelectedMode10+ | Name | Description | | ---------- | ------------------------ | -| INDICATOR | Underline indicator mode. | +| INDICATOR | Indicator mode. | | BOARD | Board mode. | ## BoardStyle10+ | Name| Type| Mandatory| Description| | -------- | -------- | -------- | ------------------------------------ | -| borderRadius | [Length](ts-types.md#length) | No| Radius of the rounded corner of the board. It cannot be set in percentage.
Default value: **8.0**
Unit: vp| +| borderRadius | [Length](ts-types.md#length) | No| Rounded corner radius of the board. It cannot be set in percentage.
Default value: **8.0**
Unit: vp | ## LabelStyle10+ @@ -129,6 +129,7 @@ A constructor used to create a **BottomTabBarStyle** instance. ### of10+ static of(icon: ResourceStr, text: ResourceStr) + Static constructor used to create a **BottomTabBarStyle** instance. **Parameters** @@ -140,7 +141,7 @@ Static constructor used to create a **BottomTabBarStyle** instance. ## Example -Example 1: +### Example 1 ```ts // xxx.ets @@ -246,7 +247,7 @@ struct TabContentExample { ![tabContent](figures/tabContent1.gif) -Example 2: +### Example 2 ```ts // xxx.ets @@ -302,7 +303,7 @@ struct TabContentExample { ![tabContent](figures/tabContent2.gif) -Example 3: +### Example 3 ```ts // xxx.ets @@ -400,7 +401,7 @@ struct TabBarStyleExample { ![tabbarStyle](figures/TabBarStyle.jpeg) -Example 4 +### Example 4 ```ts // xxx.ets @@ -422,7 +423,7 @@ struct TabsAttr { private spaceFlag: boolean = true; build() { Column() { - Button ("Underline Indicator Color Change").width ('100%').margin ({bottom:'12vp'}) + Button ("Change Indicator Color").width ('100%').margin ({bottom:'12vp'}) .onClick((event: ClickEvent) => { // Animation configuration for the width and height attributes of the