diff --git a/CODEOWNERS b/CODEOWNERS index edd18e432e49611b156796afbc8ae80702c9ac17..2cc43b65e4e8ed2079838a54d1f7a375d9daec51 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -1,18 +1,19 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - + +- Copyright (c) 2021-2022 Huawei Device Co., Ltd. +- Licensed under the Apache License, Version 2.0 (the "License"); +- you may not use this file except in compliance with the License. +- You may obtain a copy of the License at +* +- http://www.apache.org/licenses/LICENSE-2.0 +* +- Unless required by applicable law or agreed to in writing, software +- distributed under the License is distributed on an "AS IS" BASIS, +- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +- See the License for the specific language governing permissions and +- limitations under the License. +*/ + zh-cn/device-dev/kernel/ @Austin23 zh-cn/device-dev/website.md @Austin23 zh-cn/device-dev/faqs/ @Austin23 @@ -132,7 +133,7 @@ zh-cn/device-dev/subsystems/subsys-xts-guide.md @Austin23 zh-cn/application-dev/ability/ @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen zh-cn/application-dev/IDL/ @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen zh-cn/application-dev/device-usage-statistics/ @RayShih @shuaytao @wangzhen107 @inter515 -zh-cn/application-dev/ui/ @HelloCrease @qieqiewl @tomatodevboy @niulihua +zh-cn/application-dev/ui/ @HelloCrease @huaweimaxuchu @tomatodevboy @niulihua zh-cn/application-dev/notification/ @RayShih @jayleehw @li-weifeng2 @currydavids zh-cn/application-dev/windowmanager/ @ge-yafang @zhangqiang183 @zhouyaoying @zxg-gitee zh-cn/application-dev/webgl/ @zengyawen @zhangqiang183 @wind_zj @zxg-gitee @@ -187,22 +188,22 @@ zh-cn/application-dev/key-features/multi-device-app-dev/ @lingminghw @crazyracin zh-cn/application-dev/database/ @ge-yafang @feng-aiwen @gong-a-shi @logic42 zh-cn/application-dev/napi/native-window-guidelines.md @ge-yafang @zhangqiang183 @zhouyaoying @zxg-gitee zh-cn/application-dev/napi/mindspore-lite-guidelines.md @ge-yafang @grbuzhidao @jianghui58 @auraxu -zh-cn/application-dev/napi/rawfile_guidelines.md @HelloCrease +zh-cn/application-dev/napi/rawfile_guidelines.md @ningningW zh-cn/application-dev/background-agent-scheduled-reminder/ @RayShih -zh-cn/application-dev/background-task-management/ @HelloCrease @wangwenli_wolf @tangtiantian2021 @nan-xiansen -zh-cn/application-dev/work-scheduler/ @HelloCrease -zh-cn/application-dev/internationalization/ @HelloCrease @Buda-Liu @budda-wang @yangqing3 +zh-cn/application-dev/background-task-management/ @ningningW @wangwenli_wolf @tangtiantian2021 @nan-xiansen +zh-cn/application-dev/work-scheduler/ @ningningW +zh-cn/application-dev/internationalization/ @ningningW @Buda-Liu @budda-wang @yangqing3 zh-cn/application-dev/device/usb-overview.md @ge-yafang @jasonyujia @andeszhang @liuhonggang123 zh-cn/application-dev/device/usb-guidelines.md @ge-yafang @jasonyujia @andeszhang @liuhonggang123 zh-cn/application-dev/device/device-location-overview.md @RayShih zh-cn/application-dev/device/device-location-info.md @RayShih zh-cn/application-dev/device/device-location-geocoding.md @RayShih -zh-cn/application-dev/device/sensor-overview.md @HelloCrease @hellohyh001 @butterls @star-wind-snow-and-rain -zh-cn/application-dev/device/sensor-guidelines.md @HelloCrease @hellohyh001 @butterls @star-wind-snow-and-rain -zh-cn/application-dev/device/vibrator-overview.md @HelloCrease @hellohyh001 @butterls @star-wind-snow-and-rain -zh-cn/application-dev/device/vibrator-guidelines.md @HelloCrease @hellohyh001 @butterls @star-wind-snow-and-rain -zh-cn/application-dev/device/sample-server-overview.md @HelloCrease @hughes802 @zhangzhengxue @mamba-ting -zh-cn/application-dev/device/sample-server-guidelines.md @HelloCrease @hughes802 @zhangzhengxue @mamba-ting +zh-cn/application-dev/device/sensor-overview.md @ningningW @hellohyh001 @butterls @star-wind-snow-and-rain +zh-cn/application-dev/device/sensor-guidelines.md @ningningW @hellohyh001 @butterls @star-wind-snow-and-rain +zh-cn/application-dev/device/vibrator-overview.md @ningningW @hellohyh001 @butterls @star-wind-snow-and-rain +zh-cn/application-dev/device/vibrator-guidelines.md @ningningW @hellohyh001 @butterls @star-wind-snow-and-rain +zh-cn/application-dev/device/sample-server-overview.md @ningningW @hughes802 @zhangzhengxue @mamba-ting +zh-cn/application-dev/device/sample-server-guidelines.md @ningningW @hughes802 @zhangzhengxue @mamba-ting zh-cn/application-dev/reference/arkui-js/ @HelloCrease @huaweimaxuchu @niulihua @tomatodevboy zh-cn/application-dev/reference/arkui-ts/ @HelloCrease @huaweimaxuchu @niulihua @tomatodevboy zh-cn/application-dev/reference/native-lib @zengyawen @gongjunsong @liwentao_uiw @BlackStone @@ -238,11 +239,11 @@ zh-cn/application-dev/quick-start/arkts-rendering-control.md @gaoyong @niejiteng zh-cn/application-dev/quick-start/arkts-restrictions-and-extensions.md @gaoyong @niejiteng @jumozhanjiang @HelloCrease zh-cn/application-dev/napi/napi-guidelines.md @RayShih @huaweimaxuchu @niulihua @tomatodevboy zh-cn/application-dev/napi/drawing-guidelines.md @zengyawen @zhangqiang183 @wind_zj @zxg-gitee -zh-cn/application-dev/napi/rawfile-guidelines.md @HelloCrease @Buda-Liu @budda-wang @yangqing3 +zh-cn/application-dev/napi/rawfile-guidelines.md @ningningW @Buda-Liu @budda-wang @yangqing3 zh-cn/application-dev/reference/js-service-widget-ui/ @HelloCrease zh-cn/application-dev/faqs/ @zengyawen zh-cn/application-dev/file-management/ @zengyawen -zh-cn/application-dev/application-test/ @HelloCrease +zh-cn/application-dev/application-test/ @ningningW zh-cn/application-dev/device-usage-statistics/ @RayShih @shuaytao @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-ability-context.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen @@ -277,7 +278,7 @@ zh-cn/application-dev/reference/apis/js-apis-application-WindowExtensionAbility. zh-cn/application-dev/reference/apis/js-apis-appmanager.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-arraylist.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-audio.md @liuyuehua1 @zengyawen @magekkkk @currydavids -zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md @wangwenli_wolf @HelloCrease @tangtiantian2021 @nan-xiansen +zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen 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 @@ -330,11 +331,11 @@ zh-cn/application-dev/reference/apis/js-apis-deviceUsageStatistics.md @shuaytao zh-cn/application-dev/reference/apis/js-apis-display.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-distributed-account.md @nianCode @zengyawen @JiDong-CS @murphy1984 zh-cn/application-dev/reference/apis/js-apis-distributed-data.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 -zh-cn/application-dev/reference/apis/js-apis-distributedMissionManager.md @wangwenli_wolf @HelloCrease @tangtiantian2021 @nan-xiansen +zh-cn/application-dev/reference/apis/js-apis-distributedMissionManager.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen zh-cn/application-dev/reference/apis/js-apis-document.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-effectKit.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-emitter.md @jayleehw @RayShih @li-weifeng2 @currydavids -zh-cn/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md @Buda-Liu @HelloCrease @budda-wang @yangqing3 +zh-cn/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md @Buda-Liu @ningningW @budda-wang @yangqing3 zh-cn/application-dev/reference/apis/js-apis-environment.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-errorManager.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-eventhub.md @jayleehw @RayShih @li-weifeng2 @currydavids @@ -362,30 +363,30 @@ zh-cn/application-dev/reference/apis/js-apis-hitracechain.md @stone2050 @zengyaw zh-cn/application-dev/reference/apis/js-apis-hitracemeter.md @stone2050 @zengyawen @stesen @elsen-liu zh-cn/application-dev/reference/apis/js-apis-http.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-huks.md @gaoyong @zengyawen @niejiteng @jumozhanjiang -zh-cn/application-dev/reference/apis/js-apis-i18n.md @Buda-Liu @HelloCrease @budda-wang @yangqing3 +zh-cn/application-dev/reference/apis/js-apis-i18n.md @Buda-Liu @ningningW @budda-wang @yangqing3 zh-cn/application-dev/reference/apis/js-apis-image.md @zhangqiang183 @zengyawen @chenyuheng @zxg-gitee -zh-cn/application-dev/reference/apis/js-apis-inputconsumer.md @mayunteng_1 @HelloCrease @cococoler @alien0208 -zh-cn/application-dev/reference/apis/js-apis-inputdevice.md @mayunteng_1 @HelloCrease @cococoler @alien0208 -zh-cn/application-dev/reference/apis/js-apis-inputevent.md @mayunteng_1 @HelloCrease @cococoler @alien0208 -zh-cn/application-dev/reference/apis/js-apis-inputeventclient.md @mayunteng_1 @HelloCrease @cococoler @alien0208 -zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md @feng-aiwen @ge-yafang @SuperShrimp @murphy1984 -zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-context.md @feng-aiwen @ge-yafang @SuperShrimp @murphy1984 -zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @feng-aiwen @ge-yafang @SuperShrimp @murphy1984 -zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @feng-aiwen @ge-yafang @SuperShrimp @murphy1984 -zh-cn/application-dev/reference/apis/js-apis-inputmonitor.md @mayunteng_1 @HelloCrease @cococoler @alien0208 -zh-cn/application-dev/reference/apis/js-apis-intl.md @Buda-Liu @HelloCrease @budda-wang @yangqing3 -zh-cn/application-dev/reference/apis/js-apis-keycode.md @mayunteng_1 @HelloCrease @cococoler @alien0208 -zh-cn/application-dev/reference/apis/js-apis-keyevent.md @mayunteng_1 @HelloCrease @cococoler @alien0208 +zh-cn/application-dev/reference/apis/js-apis-inputconsumer.md @mayunteng_1 @ningningW @cococoler @alien0208 +zh-cn/application-dev/reference/apis/js-apis-inputdevice.md @mayunteng_1 @ningningW @cococoler @alien0208 +zh-cn/application-dev/reference/apis/js-apis-inputevent.md @mayunteng_1 @ningningW @cococoler @alien0208 +zh-cn/application-dev/reference/apis/js-apis-inputeventclient.md @mayunteng_1 @ningningW @cococoler @alien0208 +zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md @feng-aiwen @ningningW @SuperShrimp @murphy1984 +zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-context.md @feng-aiwen @ningningW @SuperShrimp @murphy1984 +zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @feng-aiwen @ningningW @SuperShrimp @murphy1984 +zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @feng-aiwen @ningningW @SuperShrimp @murphy1984 +zh-cn/application-dev/reference/apis/js-apis-inputmonitor.md @mayunteng_1 @ningningW @cococoler @alien0208 +zh-cn/application-dev/reference/apis/js-apis-intl.md @Buda-Liu @ningningW @budda-wang @yangqing3 +zh-cn/application-dev/reference/apis/js-apis-keycode.md @mayunteng_1 @ningningW @cococoler @alien0208 +zh-cn/application-dev/reference/apis/js-apis-keyevent.md @mayunteng_1 @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 @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy +zh-cn/application-dev/reference/apis/js-apis-logs.md @huaweimaxuchu @ningningW @niulihua @tomatodevboy 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 @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-missionManager.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen -zh-cn/application-dev/reference/apis/js-apis-mouseevent.md @mayunteng_1 @HelloCrease @cococoler @alien0208 +zh-cn/application-dev/reference/apis/js-apis-mouseevent.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-net-connection.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-nfcController.md @cheng_guohong @RayShih @cheng_guohong @quanli125 zh-cn/application-dev/reference/apis/js-apis-nfcTag.md @cheng_guohong @RayShih @cheng_guohong @quanli125 @@ -396,7 +397,7 @@ zh-cn/application-dev/reference/apis/js-apis-particleAbility.md @littlejerry1 @R zh-cn/application-dev/reference/apis/js-apis-pasteboard.md @feng-aiwen @ge-yafang @gong-a-shi @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-pointer.md @mayunteng_1 @HelloCrease @cococoler @alien0208 +zh-cn/application-dev/reference/apis/js-apis-pointer.md @mayunteng_1 @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 @@ -406,16 +407,16 @@ zh-cn/application-dev/reference/apis/js-apis-prompt.md @huaweimaxuchu @HelloCrea zh-cn/application-dev/reference/apis/js-apis-queue.md @gongjunsong @ge-yafang @flyingwolf @BlackStone 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 @zengyawen @nagexiucai @murphy1984 -zh-cn/application-dev/reference/apis/js-apis-resource-manager.md @Buda-Liu @HelloCrease @budda-wang @yangqing3 +zh-cn/application-dev/reference/apis/js-apis-request.md @feng-aiwen @ningningW @nagexiucai @murphy1984 +zh-cn/application-dev/reference/apis/js-apis-resource-manager.md @Buda-Liu @ningningW @budda-wang @yangqing3 zh-cn/application-dev/reference/apis/js-apis-router.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-rpc.md @xuepianpian @RayShih @zhaopeng_gitee @vagrant_world zh-cn/application-dev/reference/apis/js-apis-runninglock.md @aqxyjay @zengyawen @aqxyjay @alien0208 -zh-cn/application-dev/reference/apis/js-apis-screen-lock.md @feng-aiwen @ge-yafang @wangzhangjun @murphy1984 +zh-cn/application-dev/reference/apis/js-apis-screen-lock.md @feng-aiwen @ningningW @wangzhangjun @murphy1984 zh-cn/application-dev/reference/apis/js-apis-screen.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-screenshot.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-securityLabel.md @panqinxu @zengyawen @bubble_mao @jinhaihw -zh-cn/application-dev/reference/apis/js-apis-sensor.md @hellohyh001 @HelloCrease @butterls @star-wind-snow-and-rain +zh-cn/application-dev/reference/apis/js-apis-sensor.md @hellohyh001 @ningningW @butterls @star-wind-snow-and-rain zh-cn/application-dev/reference/apis/js-apis-service-extension-ability.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-service-extension-context.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-settings.md @tetex @ge-yafang @cnzhaoxiaohu @anning7 @@ -430,7 +431,7 @@ zh-cn/application-dev/reference/apis/js-apis-system-battery.md @aqxyjay @zengyaw zh-cn/application-dev/reference/apis/js-apis-system-bluetooth.md @cheng_guohong @RayShih @cheng_guohong @quanli125 zh-cn/application-dev/reference/apis/js-apis-system-brightness.md @aqxyjay @zengyawen @aqxyjay @alien0208 zh-cn/application-dev/reference/apis/js-apis-system-cipher.md @gaoyong @zengyawen @niejiteng @jumozhanjiang -zh-cn/application-dev/reference/apis/js-apis-system-configuration.md @Buda-Liu @HelloCrease @budda-wang @tomatodevboy +zh-cn/application-dev/reference/apis/js-apis-system-configuration.md @Buda-Liu @ningningW @budda-wang @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-system-device.md @mupceet @zengyawen @handyohos @nan-xiansen zh-cn/application-dev/reference/apis/js-apis-system-fetch.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-system-file.md @panqinxu @zengyawen @bubble_mao @jinhaihw @@ -443,29 +444,29 @@ zh-cn/application-dev/reference/apis/js-apis-system-parameter.md @mupceet @zengy zh-cn/application-dev/reference/apis/js-apis-system-prompt.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-system-request.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-system-router.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy -zh-cn/application-dev/reference/apis/js-apis-system-sensor.md @hellohyh001 @HelloCrease @butterls @star-wind-snow-and-rain +zh-cn/application-dev/reference/apis/js-apis-system-sensor.md @hellohyh001 @ningningW @butterls @star-wind-snow-and-rain zh-cn/application-dev/reference/apis/js-apis-system-storage.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 -zh-cn/application-dev/reference/apis/js-apis-system-time.md @feng-aiwen @ge-yafang @illybyy @murphy1984 -zh-cn/application-dev/reference/apis/js-apis-system-timer.md @feng-aiwen @ge-yafang @illybyy @murphy1984 -zh-cn/application-dev/reference/apis/js-apis-system-vibrate.md @hellohyh001 @HelloCrease @butterls @star-wind-snow-and-rain +zh-cn/application-dev/reference/apis/js-apis-system-time.md @feng-aiwen @ningningW @illybyy @murphy1984 +zh-cn/application-dev/reference/apis/js-apis-system-timer.md @feng-aiwen @ningningW @illybyy @murphy1984 +zh-cn/application-dev/reference/apis/js-apis-system-vibrate.md @hellohyh001 @ningningW @butterls @star-wind-snow-and-rain 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 @HelloCrease @inter515 @jiyong +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 @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy -zh-cn/application-dev/reference/apis/js-apis-touchevent.md @mayunteng_1 @HelloCrease @cococoler @alien0208 +zh-cn/application-dev/reference/apis/js-apis-touchevent.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-treemap.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-treeset.md @gongjunsong @ge-yafang @flyingwolf @BlackStone -zh-cn/application-dev/reference/apis/js-apis-uitest.md @inter515 @HelloCrease @inter515 @jiyong -zh-cn/application-dev/reference/apis/js-apis-update.md @hughes802 @HelloCrease @zhangzhengxue @mamba-ting +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-usb.md @jasonyujia @ge-yafang @andeszhang @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-vibrator.md @hellohyh001 @HelloCrease @butterls @star-wind-snow-and-rain +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 @ge-yafang @wangzhangjun @murphy1984 +zh-cn/application-dev/reference/apis/js-apis-wallpaper.md @feng-aiwen @ningningW @wangzhangjun @murphy1984 zh-cn/application-dev/reference/apis/js-apis-wantAgent.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-webgl.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-webgl2.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee @@ -475,8 +476,8 @@ zh-cn/application-dev/reference/apis/js-apis-wifiext.md @cheng_guohong @RayShih zh-cn/application-dev/reference/apis/js-apis-window.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-windowAnimationManager.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-worker.md @gongjunsong @ge-yafang @flyingwolf @BlackStone -zh-cn/application-dev/reference/apis/js-apis-workScheduler.md @wangwenli_wolf @HelloCrease @tangtiantian2021 @nan-xiansen -zh-cn/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md @wangwenli_wolf @HelloCrease @tangtiantian2021 @nan-xiansen +zh-cn/application-dev/reference/apis/js-apis-workScheduler.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen +zh-cn/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen zh-cn/application-dev/reference/apis/js-apis-xml.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-zlib.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-webview.md @bigpumpkin @HelloCrease @litao33 @zhang-xinyue15 @@ -512,21 +513,21 @@ zh-cn/application-dev/reference/apis/js-apis-bundleManager.md @shuaytao @RayShih zh-cn/application-dev/reference/apis/js-apis-bundleMonitor.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-colorSpaceManager.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-commonEventManager.md @jayleehw @RayShih @li-weifeng2 @currydavids -zh-cn/application-dev/reference/apis/js-apis-configPolicy.md @Buda-Liu @HelloCrease @budda-wang @yangqing3 -zh-cn/application-dev/reference/apis/js-apis-cooperate.md @mayunteng_1 @HelloCrease @cococoler @alien0208 +zh-cn/application-dev/reference/apis/js-apis-configPolicy.md @Buda-Liu @ningningW @budda-wang @yangqing3 +zh-cn/application-dev/reference/apis/js-apis-cooperate.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-cryptoFramework.md @gaoyong @zengyawen @niejiteng @jumozhanjiang zh-cn/application-dev/reference/apis/js-apis-curve.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-defaultAppManager.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-distributedBundle.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-distributedKVStore.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 -zh-cn/application-dev/reference/apis/js-apis-enterprise-adminManager.md @Buda-Liu @HelloCrease @budda-wang @yangqing3 -zh-cn/application-dev/reference/apis/js-apis-enterprise-dateTimeManager.md @Buda-Liu @HelloCrease @budda-wang @yangqing3 +zh-cn/application-dev/reference/apis/js-apis-enterprise-adminManager.md @Buda-Liu @ningningW @budda-wang @yangqing3 +zh-cn/application-dev/reference/apis/js-apis-enterprise-dateTimeManager.md @Buda-Liu @ningningW @budda-wang @yangqing3 zh-cn/application-dev/reference/apis/js-apis-fileAccess.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-fileExtensionInfo.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-freeInstall.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-geoLocationManager.md @cheng_guohong @RayShih @cheng_guohong @xiangkejin123 zh-cn/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md @stone2050 @zengyawen @stesen @elsen-liu -zh-cn/application-dev/reference/apis/js-apis-inputmethod-subtype.md @feng-aiwen @ge-yafang @SuperShrimp @murphy1984 +zh-cn/application-dev/reference/apis/js-apis-inputmethod-subtype.md @feng-aiwen @ningningW @SuperShrimp @murphy1984 zh-cn/application-dev/reference/apis/js-apis-installer.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-launcherBundleManager.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-matrix4.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy @@ -534,11 +535,11 @@ zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md @zhang-hai-feng @ze zh-cn/application-dev/reference/apis/js-apis-net-sharing.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-nfctech.md @cheng_guohong @RayShih @cheng_guohong @quanli125 zh-cn/application-dev/reference/apis/js-apis-promptAction.md @cheng_guohong @RayShih @cheng_guohong @quanli125 -zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md @wangwenli_wolf @HelloCrease @tangtiantian2021 @nan-xiansen -zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @wangwenli_wolf @HelloCrease @tangtiantian2021 @nan-xiansen -zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md @wangwenli_wolf @HelloCrease @tangtiantian2021 @nan-xiansen -zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md @wangwenli_wolf @HelloCrease @tangtiantian2021 @nan-xiansen -zh-cn/application-dev/reference/apis/js-apis-stationary.md @mayunteng_1 @HelloCrease @cococoler @alien0208 +zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen +zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen +zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen +zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen +zh-cn/application-dev/reference/apis/js-apis-stationary.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-system-capability.md taiyipei taiyipei BlackStone zh-cn/application-dev/reference/apis/js-apis-system-parameterV9.md @mupceet @zengyawen @handyohos @nan-xiansen zh-cn/application-dev/reference/apis/js-apis-tagSession.md @cheng_guohong @RayShih @cheng_guohong @quanli125 @@ -546,7 +547,6 @@ zh-cn/application-dev/reference/apis/js-apis-usb-deprecated.md @cheng_guohong @R zh-cn/application-dev/reference/apis/js-apis-userFileManager.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-useriam-faceauth.md @gaoyong @zengyawen @niejiteng @jumozhanjiang - zh-cn/application-dev/reference/errorcodes/errorcode-ability.md @RayShih zh-cn/application-dev/reference/errorcodes/errorcode-access-token.md @zengyawen zh-cn/application-dev/reference/errorcodes/errorcode-accessibility.md @RayShih @@ -555,7 +555,7 @@ zh-cn/application-dev/reference/errorcodes/errorcode-animator.md @HelloCrease zh-cn/application-dev/reference/errorcodes/errorcode-app-account.md @zengyawen zh-cn/application-dev/reference/errorcodes/errorcode-audio.md @zengyawen zh-cn/application-dev/reference/errorcodes/errorcode-avsession.md @zengyawen -zh-cn/application-dev/reference/errorcodes/errorcode-backgroundTaskMgr.md @HelloCrease +zh-cn/application-dev/reference/errorcodes/errorcode-backgroundTaskMgr.md @ningningW zh-cn/application-dev/reference/errorcodes/errorcode-batteryStatistics.md @zengyawen zh-cn/application-dev/reference/errorcodes/errorcode-brightness.md @zengyawen zh-cn/application-dev/reference/errorcodes/errorcode-buffer.md @ge-yafang @@ -566,13 +566,13 @@ zh-cn/application-dev/reference/errorcodes/errorcode-containers.md @ge-yafang zh-cn/application-dev/reference/errorcodes/errorcode-data-rdb.md @ge-yafang zh-cn/application-dev/reference/errorcodes/errorcode-datashare.md @ge-yafang zh-cn/application-dev/reference/errorcodes/errorcode-device-manager.md @RayShih -zh-cn/application-dev/reference/errorcodes/errorcode-DeviceUsageStatistics.md @HelloCrease +zh-cn/application-dev/reference/errorcodes/errorcode-DeviceUsageStatistics.md @ningningW zh-cn/application-dev/reference/errorcodes/errorcode-display.md @ge-yafang zh-cn/application-dev/reference/errorcodes/errorcode-distributed-dataObject.md @ge-yafang zh-cn/application-dev/reference/errorcodes/errorcode-distributedKVStore.md @ge-yafang zh-cn/application-dev/reference/errorcodes/errorcode-DistributedNotificationService.md @RayShih zh-cn/application-dev/reference/errorcodes/errorcode-DistributedSchedule.md @RayShih -zh-cn/application-dev/reference/errorcodes/errorcode-enterpriseDeviceManager.md @HelloCrease +zh-cn/application-dev/reference/errorcodes/errorcode-enterpriseDeviceManager.md @ningningW zh-cn/application-dev/reference/errorcodes/errorcode-faultlogger.md @zengyawen zh-cn/application-dev/reference/errorcodes/errorcode-filemanagement.md @zengyawen zh-cn/application-dev/reference/errorcodes/errorcode-geoLocationManager.md @RayShih @@ -580,30 +580,30 @@ zh-cn/application-dev/reference/errorcodes/errorcode-hiappevent.md @zengyawen zh-cn/application-dev/reference/errorcodes/errorcode-hisysevent.md @zengyawen zh-cn/application-dev/reference/errorcodes/errorcode-hiviewdfx-hidebug.md @zengyawen zh-cn/application-dev/reference/errorcodes/errorcode-huks.md @zengyawen -zh-cn/application-dev/reference/errorcodes/errorcode-i18n.md @HelloCrease -zh-cn/application-dev/reference/errorcodes/errorcode-inputmethod-framework.md @ge-yafang -zh-cn/application-dev/reference/errorcodes/errorcode-multimodalinput.md @HelloCrease +zh-cn/application-dev/reference/errorcodes/errorcode-i18n.md @ningningW +zh-cn/application-dev/reference/errorcodes/errorcode-inputmethod-framework.md @ningningW +zh-cn/application-dev/reference/errorcodes/errorcode-multimodalinput.md @ningningW zh-cn/application-dev/reference/errorcodes/errorcode-nfc.md @RayShih zh-cn/application-dev/reference/errorcodes/errorcode-pasteboard.md @ge-yafang zh-cn/application-dev/reference/errorcodes/errorcode-power.md @zengyawen zh-cn/application-dev/reference/errorcodes/errorcode-preferences.md @ge-yafang zh-cn/application-dev/reference/errorcodes/errorcode-promptAction.md @HelloCrease -zh-cn/application-dev/reference/errorcodes/errorcode-reminderAgentManager.md @HelloCrease -zh-cn/application-dev/reference/errorcodes/errorcode-request.md @zengyawen -zh-cn/application-dev/reference/errorcodes/errorcode-resource-manager.md @HelloCrease +zh-cn/application-dev/reference/errorcodes/errorcode-reminderAgentManager.md @ningningW +zh-cn/application-dev/reference/errorcodes/errorcode-request.md @ningningW +zh-cn/application-dev/reference/errorcodes/errorcode-resource-manager.md @ningningW zh-cn/application-dev/reference/errorcodes/errorcode-router.md @HelloCrease zh-cn/application-dev/reference/errorcodes/errorcode-rpc.md @RayShih zh-cn/application-dev/reference/errorcodes/errorcode-runninglock.md @zengyawen -zh-cn/application-dev/reference/errorcodes/errorcode-sensor.md @HelloCrease +zh-cn/application-dev/reference/errorcodes/errorcode-sensor.md @ningningW zh-cn/application-dev/reference/errorcodes/errorcode-system-parameterV9.md @zengyawen zh-cn/application-dev/reference/errorcodes/errorcode-thermal.md @zengyawen -zh-cn/application-dev/reference/errorcodes/errorcode-uitest.md @HelloCrease +zh-cn/application-dev/reference/errorcodes/errorcode-uitest.md @ningningW zh-cn/application-dev/reference/errorcodes/errorcode-universal.md @RayShih -zh-cn/application-dev/reference/errorcodes/errorcode-update.md @HelloCrease +zh-cn/application-dev/reference/errorcodes/errorcode-update.md @ningningW zh-cn/application-dev/reference/errorcodes/errorcode-usb.md @ge-yafang zh-cn/application-dev/reference/errorcodes/errorcode-useriam.md @zengyawen -zh-cn/application-dev/reference/errorcodes/errorcode-vibrator.md @HelloCrease +zh-cn/application-dev/reference/errorcodes/errorcode-vibrator.md @ningningW 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 @HelloCrease +zh-cn/application-dev/reference/errorcodes/errorcode-workScheduler.md @ningningW zh-cn/application-dev/reference/errorcodes/errorcode-zlib.md @RayShih diff --git a/en/application-dev/IDL/figures/SDKpath.png b/en/application-dev/IDL/figures/SDKpath.png new file mode 100644 index 0000000000000000000000000000000000000000..aa7e33f0246e07fa9f6b8aeb0677c7159dfceb3d Binary files /dev/null and b/en/application-dev/IDL/figures/SDKpath.png differ diff --git a/en/application-dev/IDL/figures/SDKpath2.png b/en/application-dev/IDL/figures/SDKpath2.png new file mode 100644 index 0000000000000000000000000000000000000000..51ac48d2f04d876a204493415b79a5f12e183685 Binary files /dev/null and b/en/application-dev/IDL/figures/SDKpath2.png differ diff --git a/en/application-dev/IDL/idl-guidelines.md b/en/application-dev/IDL/idl-guidelines.md index 5b3a5d7990d4dfe55ddef2ad77ef7dab84033a2e..f165215bad4d663b794c249f8029d33aeeda5863 100644 --- a/en/application-dev/IDL/idl-guidelines.md +++ b/en/application-dev/IDL/idl-guidelines.md @@ -149,198 +149,53 @@ The value of <*formal_param_attr*> can be **in**, **out**, or **inout**, indicat ## How to Develop -### Development Using C++ +### Obtaining IDL +On DevEco Studio, choose **Tools > SDK Manager** to view the local installation path of the OpenHarmony SDK. The following figure uses DevEco Studio 3.0.0.993 as an example. +![SDKpath](./figures/SDKpath.png) +![SDKpath](./figures/SDKpath2.png) -#### Creating an IDL File - - You can use C++ to create IDL files. An example IDL file is as follows: +Go to the local installation path, choose **toolchains > 3.x.x.x** (the folder named after the version number), and check whether the executable file of IDL exists. -```cpp - interface OHOS.IIdlTestService { - int TestIntTransaction([in] int data); - void TestStringTransaction([in] String data); - } -``` +> **NOTE**: Use the SDK of the latest version. The use of an earlier version may cause errors in some statements. -You can run the **./idl -gen-cpp -d dir -c dir/iTest.idl** command (**-d** indicates the output directory) to generate the interface file, stub file, and proxy file in the **dir** directory in the execution environment. The names of the generated interface class files are the same as that of the IDL file, except that the file name extensions are **.h** and **.cpp**. For example, the files generated for **IIdlTestService.idl** are **i_idl_test_service.h**, **idl_test_service_proxy.h**, **idl_test_service_stub.h**, **idl_test_service_proxy.cpp**, and **idl_test_service_stub.cpp**. +If the executable file does not exist, download the SDK package from the mirror as instructed in the [Release Notes](../../release-notes). The following uses the [3.2 Beta3](../../release-notes/OpenHarmony-v3.2-beta3.md#acquiring-source-code-from-mirrors) as an example. -#### Exposing Interfaces on the Server +For details about how to replace the SDK package, see [Guide to Switching to Full SDK](../quick-start/full-sdk-switch-guide.md). -The stub class generated by IDL is an abstract implementation of the interface class and declares all methods in the IDL file. +After obtaining the executable file, perform subsequent development steps based on your scenario. -```cpp -#ifndef OHOS_IDLTESTSERVICESTUB_H -#define OHOS_IDLTESTSERVICESTUB_H -#include -#include "iidl_test_service.h" - -namespace OHOS { -class IdlTestServiceStub : public IRemoteStub { -public: - int OnRemoteRequest( - /* [in] */ uint32_t code, - /* [in] */ MessageParcel& data, - /* [out] */ MessageParcel& reply, - /* [in] */ MessageOption& option) override; - -private: - static constexpr int COMMAND_TEST_INT_TRANSACTION = MIN_TRANSACTION_ID + 0; - static constexpr int COMMAND_TEST_STRING_TRANSACTION = MIN_TRANSACTION_ID + 1; -}; -} // namespace OHOS -#endif // OHOS_IDLTESTSERVICESTUB_H -``` +### Development Using TS -You need to inherit the interface class defined in the IDL file and implement the methods in the class. In addition, you need to register the defined services with SAMGR during service initialization. In the following code snippet, **TestService** inherits the **IdlTestServiceStub** interface class and implements the **TestIntTransaction** and **TestStringTransaction** methods. +#### Creating an IDL File -```cpp -#ifndef OHOS_IPC_TEST_SERVICE_H -#define OHOS_IPC_TEST_SERVICE_H - -#include "hilog/log.h" -#include "log_tags.h" -#include "idl_test_service_stub.h" - -namespace OHOS { -class TestService : public IdlTestServiceStub { -public: - TestService(); - ~TestService(); - static int Instantiate(); - ErrCode TestIntTransaction(int data, int &rep) override; - ErrCode TestStringTransaction(const std::string& data) override; -private: - static constexpr HiviewDFX::HiLogLabel LABEL = { LOG_CORE, LOG_ID_IPC, "TestService" }; -}; -} // namespace OHOS -#endif // OHOS_IPC_TEST_SERVICE_H -``` +You can use TS to create IDL files. -The sample code for registering a service is as follows: + For example, create a file named **IIdlTestService.idl** with the following content: ```cpp -#include "test_service.h" - -#include - -#include "if_system_ability_manager.h" -#include "ipc_debug.h" -#include "ipc_skeleton.h" -#include "iservice_registry.h" -#include "system_ability_definition.h" - -namespace OHOS { -using namespace OHOS::HiviewDFX; - -int TestService::Instantiate() -{ - ZLOGI(LABEL, "%{public}s call in", __func__); - auto saMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (saMgr == nullptr) { - ZLOGE(LABEL, "%{public}s:fail to get Registry", __func__); - return -ENODEV; - } - - sptr newInstance = new TestService(); - int result = saMgr->AddSystemAbility(IPC_TEST_SERVICE, newInstance); - ZLOGI(LABEL, "%{public}s: IPC_TEST_SERVICE result = %{public}d", __func__, result); - return result; -} - -TestService::TestService() -{ -} - -TestService::~TestService() -{ -} - -ErrCode TestService::TestIntTransaction(int data, int &rep) -{ - ZLOGE(LABEL, " TestService:read from client data = %{public}d", data); - rep = data + data; - return ERR_NONE; -} - -ErrCode TestService::TestStringTransaction(const std::string &data) -{ - ZLOGE(LABEL, "TestService:read string from client data = %{public}s", data.c_str()); - return data.size(); -} -} // namespace OHOS + interface OHOS.IIdlTestService { + int TestIntTransaction([in] int data); + void TestStringTransaction([in] String data); + } ``` -#### Calling Methods from the Client for IPC - -The C++ client obtains the service proxy defined in the system through SAMGR and then invokes the interface provided by the proxy. The sample code is as follows: +Run the **idl -gen-ts -d *dir* -c dir/IIdlTestService.idl** command in the folder where the executable file is located. -```cpp -#include "test_client.h" - -#include "if_system_ability_manager.h" -#include "ipc_debug.h" -#include "ipc_skeleton.h" -#include "iservice_registry.h" -#include "system_ability_definition.h" - -namespace OHOS { -int TestClient::ConnectService() -{ - auto saMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (saMgr == nullptr) { - ZLOGE(LABEL, "get registry fail"); - return -1; - } +-*dir* next to **d** is the target output folder. For example, if the target output folder is **IIdlTestServiceTs**, run the **idl -gen-ts -d IIdlTestServiceTs -c IIdlTestServiceTs/IIdlTestService.idl** command in the folder where the executable file is located. The interface file, stub file, and proxy file are generated in the *dir* directory (**IIdlTestServiceTs** directory in this example) in the execution environment. - sptr object = saMgr->GetSystemAbility(IPC_TEST_SERVICE); - if (object != nullptr) { - ZLOGE(LABEL, "Got test Service object"); - testService_ = (new (std::nothrow) IdlTestServiceProxy(object)); - } +> **NOTE**: The generated interface class file name must be the same as that of the .idl file. Otherwise, an error occurs during code generation. - if (testService_ == nullptr) { - ZLOGE(LABEL, "Could not find Test Service!"); - return -1; - } - - return 0; -} +For example, for an .idl file named **IIdlTestService.idl** and target output directory named **IIdlTestServiceTs**, the directory structure is similar to the following: -void TestClient::StartIntTransaction() -{ - if (testService_ != nullptr) { - ZLOGE(LABEL, "StartIntTransaction"); - [[maybe_unused]] int result = 0; - testService_->TestIntTransaction(1234, result); // 1234 : test number - ZLOGE(LABEL, "Rec result from server %{public}d.", result); - } -} - -void TestClient::StartStringTransaction() -{ - if (testService_ != nullptr) { - ZLOGI(LABEL, "StartIntTransaction"); - testService_->TestStringTransaction("IDL Test"); - } -} -} // namespace OHOS ``` - -### Development Using TS - -#### Creating an IDL File - - You can use TS to create IDL files. An example IDL file is as follows: - -```ts - interface OHOS.IIdlTestService { - int TestIntTransaction([in] int data); - void TestStringTransaction([in] String data); - } +├── IIdlTestServiceTs # IDL code output folder +│ ├── i_idl_test_service.ts # File generated +│ ├── idl_test_service_proxy.ts # File generated +│ ├── idl_test_service_stub.ts # File generated +│ └── IIdlTestService.idl # Constructed .idl file +└── idl.exe # Executable file of IDL ``` -Run the **./idl -c IIdlTestService.idl -gen-ts -d /data/ts/** command (**-d** indicates the output directory) to generate the interface file, stub file, and proxy file in the **/data/ts** directory in the execution environment. The names of the generated interface class files are the same as that of the IDL file, except that the file name extension is **.ts**. For example, the files generated for the **IIdlTestService.idl** file are **i_idl_test_service.ts**, **idl_test_service_proxy.ts**, and **idl_test_service_stub.ts**. - #### Exposing Interfaces on the Server The stub class generated by IDL is an abstract implementation of the interface class and declares all methods in the IDL file. @@ -356,8 +211,8 @@ export default class IdlTestServiceStub extends rpc.RemoteObject implements IIdl super(des); } - onRemoteRequest(code: number, data, reply, option): boolean { - console.log("onRemoteRequest called, code = " + code); + async onRemoteRequestEx(code: number, data, reply, option): Promise { + console.log("onRemoteRequestEx called, code = " + code); switch(code) { case IdlTestServiceStub.COMMAND_TEST_INT_TRANSACTION: { let _data = data.readInt(); @@ -529,137 +384,3 @@ export default class MySequenceable { private str; } ``` - -## How to Develop for Interworking Between C++ and TS - -### TS Proxy and C++ Stub Development - -#### C++ Service Object - -1. Use C++ to construct an IDL file and run commands to generate interfaces, stub files, and proxy files. - -2. Create a service object, inherit the interface class defined in the C++ stub file, and implement the methods in the class. An example is as follows: - - ```cpp - class IdlTestServiceImpl : public IdlTestServiceStub { - public: - IdlTestServiceImpl() = default; - virtual ~IdlTestServiceImpl() = default; - - ErrCode TestIntTransaction(int _data, int& result) override - { - result = 256; - return ERR_OK; - } - - ErrCode TestStringTransaction(const std::string& _data) override - { - return ERR_OK; - } - }; - ``` - -#### Native APIs in C++ - -C++ provides C++ service objects to TS in the format of native APIs. For example, C++ provides a **GetNativeObject** method, which is used to create an **IdlTestServiceImpl** instance. Using the **NAPI_ohos_rpc_CreateJsRemoteObject** method, you can create a JS remote object for the TS application. - -```cpp -NativeValue* GetNativeObject(NativeEngine& engine, NativeCallbackInfo& info) -{ - sptr impl = new IdlTestServiceImpl(); - napi_value napiRemoteObject = NAPI_ohos_rpc_CreateJsRemoteObject(reinterpret_cast(&engine), impl); - NativeValue* nativeRemoteObject = reinterpret_cast(napiRemoteObject); - return nativeRemoteObject; -} -``` - -#### TS Proxy Object - -Use TS to construct an IDL file and run commands to generate interfaces, stub files, and proxy files. An example proxy file is as follows: - -```ts -import {testIntTransactionCallback} from "./i_idl_test_service"; -import {testStringTransactionCallback} from "./i_idl_test_service"; -import IIdlTestService from "./i_idl_test_service"; -import rpc from "@ohos.rpc"; - -export default class IdlTestServiceProxy implements IIdlTestService { - constructor(proxy) { - this.proxy = proxy; - } - - testIntTransaction(data: number, callback: testIntTransactionCallback): void - { - let _option = new rpc.MessageOption(); - let _data = new rpc.MessageParcel(); - let _reply = new rpc.MessageParcel(); - _data.writeInt(data); - this.proxy.sendRequest(IdlTestServiceProxy.COMMAND_TEST_INT_TRANSACTION, _data, _reply, _option).then(function(result) { - if (result.errCode == 0) { - let _errCode = result.reply.readInt(); - if (_errCode != 0) { - let _returnValue = undefined; - callback(_errCode, _returnValue); - return; - } - let _returnValue = result.reply.readInt(); - callback(_errCode, _returnValue); - } else { - console.log('sendRequest failed, errCode: ' + result.errCode); - } - }) - } - - testStringTransaction(data: string, callback: testStringTransactionCallback): void - { - let _option = new rpc.MessageOption(); - let _data = new rpc.MessageParcel(); - let _reply = new rpc.MessageParcel(); - _data.writeString(data); - this.proxy.sendRequest(IdlTestServiceProxy.COMMAND_TEST_STRING_TRANSACTION, _data, _reply, _option).then(function(result) { - if (result.errCode == 0) { - let _errCode = result.reply.readInt(); - callback(_errCode); - } else { - console.log('sendRequest failed, errCode: ' + result.errCode); - } - }) - } - - static readonly COMMAND_TEST_INT_TRANSACTION = 1; - static readonly COMMAND_TEST_STRING_TRANSACTION = 2; - private proxy -} -``` - -#### Interworking Between TS and C++ Applications - -1. The TS application invokes the native API to obtain the remote C++ service object. -2. Construct a TS proxy and transfers the remote C++ service object to it. -3. Use the TS proxy to call the method declared in the IDL file to implement the interworking between the TS proxy and C++ stub. The following is an example: - -```ts -import IdlTestServiceProxy from './idl_test_service_proxy' -import nativeMgr from 'nativeManager'; - -function testIntTransactionCallback(errCode: number, returnValue: number) -{ - console.log('errCode: ' + errCode + ' returnValue: ' + returnValue); -} - -function testStringTransactionCallback(errCode: number) -{ - console.log('errCode: ' + errCode); -} - -function jsProxyTriggerCppStub() -{ - let nativeObj = nativeMgr.GetNativeObject(); - let tsProxy = new IdlTestServiceProxy(nativeObj); - // Call testIntTransaction. - tsProxy.testIntTransaction(10, testIntTransactionCallback); - - // Call testStringTransaction. - tsProxy.testStringTransaction('test', testIntTransactionCallback); -} -``` diff --git a/en/application-dev/ability/Readme-EN.md b/en/application-dev/ability-deprecated/Readme-EN.md similarity index 88% rename from en/application-dev/ability/Readme-EN.md rename to en/application-dev/ability-deprecated/Readme-EN.md index 6a11f497d375874b96bfed77a77dce033821d6e3..5c803a47558bbd52765090debe162dbecd996ae6 100644 --- a/en/application-dev/ability/Readme-EN.md +++ b/en/application-dev/ability-deprecated/Readme-EN.md @@ -1,5 +1,8 @@ # Ability Development +> **NOTE**
+> This folder is deprecated. Read [Application Models](../application-models/Readme-EN.md) instead. + - [Ability Framework Overview](ability-brief.md) - [Context Usage](context-userguide.md) - FA Model diff --git a/en/application-dev/ability/ability-assistant-guidelines.md b/en/application-dev/ability-deprecated/ability-assistant-guidelines.md similarity index 90% rename from en/application-dev/ability/ability-assistant-guidelines.md rename to en/application-dev/ability-deprecated/ability-assistant-guidelines.md index 4d7b0edb2b91ca07123ad7495f4d64fc2f525e1d..d2e45f5d5492c23bcce0ec48674427df2cb2b765 100644 --- a/en/application-dev/ability/ability-assistant-guidelines.md +++ b/en/application-dev/ability-deprecated/ability-assistant-guidelines.md @@ -73,10 +73,10 @@ The ability assistant enables you to start applications, atomic services, and te | -a/--all | - | Prints ability information in all missions. | | -l/--mission-list | type (All logs are printed if this parameter is left unspecified.)| Prints mission stack information.
The following values are available for **type**:
- NORMAL
- DEFAULT_STANDARD
- DEFAULT_SINGLE
- LAUNCHER | | -e/--extension | elementName | Prints extended component information. | - | -u/--userId | UserId | Prints stack information of a specified user ID. This parameter must be used together with other parameters.
Example commands: aa **dump -a -u 100** and **aa dump -d -u 100**. | - | -d/--data | - | Prints Data ability information. | - | -i/--ability | AbilityRecord ID | Prints detailed information about a specified ability. | - | -c/--client | - | Prints detailed ability information. This parameter must be used together with other parameters.
Example commands: **aa dump -a -c** and **aa dump -i 21 -c**. | + | -u/--userId | UserId | Prints stack information of a specified user ID. This parameter must be used together with other parameters.
Example commands: aa **dump -a -u 100** and **aa dump -d -u 100**.| + | -d/--data | - | Prints Data ability information. | + | -i/--ability | AbilityRecord ID | Prints detailed information about a specified ability. | + | -c/--client | - | Prints detailed ability information. This parameter must be used together with other parameters.
Example commands: **aa dump -a -c** and **aa dump -i 21 -c**.| **Method** diff --git a/en/application-dev/ability/ability-brief.md b/en/application-dev/ability-deprecated/ability-brief.md similarity index 100% rename from en/application-dev/ability/ability-brief.md rename to en/application-dev/ability-deprecated/ability-brief.md diff --git a/en/application-dev/ability/ability-delegator.md b/en/application-dev/ability-deprecated/ability-delegator.md similarity index 96% rename from en/application-dev/ability/ability-delegator.md rename to en/application-dev/ability-deprecated/ability-delegator.md index 5fd0293efde6d6d264be28b6c30123e7697bee6b..b32d472176a5b6270fece94ae4bd8ae9a7bd73fa 100644 --- a/en/application-dev/ability/ability-delegator.md +++ b/en/application-dev/ability-deprecated/ability-delegator.md @@ -46,19 +46,19 @@ For details about how to use DevEco Studio to start the test framework, see [Ope ## Introduction to TestRunner -**TestRunner** is the entry class of the test framework test process. When the test process is started, the system calls related APIs in **TestRunner**. You need to inherit this class and override the **onPrepare** and **onRun** APIs. When creating an application template, DevEco Studio initializes the default **TestRunner** and starts the default **TestAbility** in the **onRun** API. You can modify the test code of **TestAbility** or override **onPrepare** and **onRun** in **TestRunner** to implement your own test code. For details, see [TestRunner](../reference/apis/js-apis-testRunner.md). +**TestRunner** is the entry class of the test framework test process. When the test process is started, the system calls related APIs in **TestRunner**. You need to inherit this class and override the **onPrepare** and **onRun** APIs. When creating an application template, DevEco Studio initializes the default **TestRunner** and starts the default **TestAbility** in the **onRun** API. You can modify the test code of **TestAbility** or override **onPrepare** and **onRun** in **TestRunner** to implement your own test code. For details, see [TestRunner](../reference/apis/js-apis-application-testRunner.md). ## Introduction to AbilityDelegatorRegistry -**AbilityDelegatorRegistry** is the **AbilityDelegator** repository class provided by the test framework. You can use **AbilityDelegatorRegistry** to obtain an **AbilityDelegator** instance and the input and generated parameters **AbilityDelegatorArgs** during the test. You can use **AbilityDelegator** to invoke the function set provided by the test framework for testing and verification. For details, see [AbilityDelegatorRegistry](../reference/apis/js-apis-abilityDelegatorRegistry.md). +**AbilityDelegatorRegistry** is the **AbilityDelegator** repository class provided by the test framework. You can use **AbilityDelegatorRegistry** to obtain an **AbilityDelegator** instance and the input and generated parameters **AbilityDelegatorArgs** during the test. You can use **AbilityDelegator** to invoke the function set provided by the test framework for testing and verification. For details, see [AbilityDelegatorRegistry](../reference/apis/js-apis-application-abilityDelegatorRegistry.md). ## Introduction to AbilityDelegatorArgs -**AbilityDelegatorArgs** is a test parameter class provided by the test framework. You can use **AbilityDelegatorArgs** to obtain the parameters passed and generated during the test. For details, see [AbilityDelegatorArgs](../reference/apis/js-apis-application-abilityDelegatorArgs.md). +**AbilityDelegatorArgs** is a test parameter class provided by the test framework. You can use **AbilityDelegatorArgs** to obtain the parameters passed and generated during the test. For details, see [AbilityDelegatorArgs](../reference/apis/js-apis-inner-application-abilityDelegatorArgs.md). ## Introduction to AbilityMonitor -**AbilityMonitor** is provided by the test framework for binding to and listening for abilities. You can use **AbilityMonitor** to bind to an **Ability** instance and add **AbilityMonitor** to the listening list. When **AbilityMonitor** is bound to an ability, the creation and lifecycle changes of the ability will trigger the related callback in **AbilityMonitor**. You can test and verify the ability in these callbacks. For details, see [AbilityMonitor](../reference/apis/js-apis-application-abilityMonitor.md). +**AbilityMonitor** is provided by the test framework for binding to and listening for abilities. You can use **AbilityMonitor** to bind to an **Ability** instance and add **AbilityMonitor** to the listening list. When **AbilityMonitor** is bound to an ability, the creation and lifecycle changes of the ability will trigger the related callback in **AbilityMonitor**. You can test and verify the ability in these callbacks. For details, see [AbilityMonitor](../reference/apis/js-apis-inner-application-abilityMonitor.md). **Example** @@ -131,7 +131,7 @@ abilityDelegator.startAbility(want, (err, data) => { ### Scheduling the Ability Lifecycle -**AbilityDelegator** provides APIs to display and schedule the ability lifecycle and supports the foreground and background. It works with **AbilityMonitor** to listen for the ability lifecycle. For details, see [AbilityDelegator](../reference/apis/js-apis-application-abilityDelegator.md). +**AbilityDelegator** provides APIs to display and schedule the ability lifecycle and supports the foreground and background. It works with **AbilityMonitor** to listen for the ability lifecycle. For details, see [AbilityDelegator](../reference/apis/js-apis-inner-application-abilityDelegator.md). ### Running a Shell Command diff --git a/en/application-dev/ability/context-userguide.md b/en/application-dev/ability-deprecated/context-userguide.md similarity index 94% rename from en/application-dev/ability/context-userguide.md rename to en/application-dev/ability-deprecated/context-userguide.md index 17fd6b5eb780f656ada33e94a6d1584ebbc55e5c..ac65d92cb9422d040ff16cab1640cd1f9bed5d5c 100644 --- a/en/application-dev/ability/context-userguide.md +++ b/en/application-dev/ability-deprecated/context-userguide.md @@ -4,12 +4,12 @@ **Context** provides the capability of obtaining contextual information of an application. -The OpenHarmony application framework has two models: Feature Ability (FA) model and stage model. Correspondingly, there are two sets of context mechanisms. **application/BaseContext** is a common context base class. It uses the **stageMode** attribute to specify whether the context is used for the stage model. - -- FA model - - Only the methods in **app/Context** can be used for the context in the FA model. Both the application-level context and ability-level context are instances of this type. If an ability-level method is invoked in the application-level context, an error occurs. Therefore, you must pay attention to the actual meaning of the **Context** instance. + The OpenHarmony application framework has two models: Feature Ability (FA) model and stage model. Correspondingly, there are two sets of context mechanisms. **application/BaseContext** is a common context base class. It uses the **stageMode** attribute to specify whether the context is used for the stage model. +- FA model + +Only the methods in **app/Context** can be used for the context in the FA model. Both the application-level context and ability-level context are instances of this type. If an ability-level method is invoked in the application-level context, an error occurs. Therefore, you must pay attention to the actual meaning of the **Context** instance. + - Stage model The stage model has the following types of contexts: **application/Context**, **application/ApplicationContext**, **application/AbilityStageContext**, **application/ExtensionContext**, **application/AbilityContext**, and **application/FormExtensionContext**. For details about these contexts and how to use them, see [Context in the Stage Model](#context-in-the-stage-model). @@ -239,7 +239,7 @@ export default class MainAbility extends Ability { ### application/FormExtensionContext -For details, see [FormExtensionContext](../reference/apis/js-apis-formextensioncontext.md). +For details, see [FormExtensionContext](../reference/apis/js-apis-inner-application-formExtensionContext.md). ### Obtaining the Context on an ArkTS Page diff --git a/en/application-dev/ability/continuationmanager.md b/en/application-dev/ability-deprecated/continuationmanager.md similarity index 99% rename from en/application-dev/ability/continuationmanager.md rename to en/application-dev/ability-deprecated/continuationmanager.md index 20c272e75a16c2bcf14d567c1cbc7afa28a3a69a..0ba79f95acf165d604d8f854832703d7fc4af3f8 100644 --- a/en/application-dev/ability/continuationmanager.md +++ b/en/application-dev/ability-deprecated/continuationmanager.md @@ -188,7 +188,7 @@ As the entry of the ability continuation capability, **continuationManager** is } ``` - The preceding multi-device collaboration operation is performed across devices in the stage model. For details about this operation in the FA model, see [Page Ability Development](https://gitee.com/openharmony/docs/blob/master/en/application-dev/ability/fa-pageability.md). + The preceding multi-device collaboration operation is performed across devices in the stage model. For details about this operation in the FA model, see [Page Ability Development](fa-pageability.md). You can also instruct the device selection module to update the device connection state. The sample code is as follows: diff --git a/en/application-dev/ability/fa-brief.md b/en/application-dev/ability-deprecated/fa-brief.md similarity index 96% rename from en/application-dev/ability/fa-brief.md rename to en/application-dev/ability-deprecated/fa-brief.md index 3788fe994f9f984449c28bdb6f15ff96adb29c21..5ad79cfe259f1fb9cf865b9d6f496c0f31c47ae0 100644 --- a/en/application-dev/ability/fa-brief.md +++ b/en/application-dev/ability-deprecated/fa-brief.md @@ -38,4 +38,6 @@ When an ability is started, an application process as well as a thread for this For details about the project directory structure of the FA model, see [OpenHarmony Project Overview](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-project-overview-0000001218440650#section4154183910141). -For details about how to configure the application package structure of the FA model, see [Application Package Structure Configuration File](../quick-start/package-structure.md). +For details about how to configure the application package structure of the FA model, see [Application Package Structure Configuration File](../quick-start/application-configuration-file-overview-fa.md). + + \ No newline at end of file diff --git a/en/application-dev/ability/fa-dataability.md b/en/application-dev/ability-deprecated/fa-dataability.md similarity index 99% rename from en/application-dev/ability/fa-dataability.md rename to en/application-dev/ability-deprecated/fa-dataability.md index e3fd895c2a3530aa0f8aa85919657a62f3f72c06..8d94e8f225a3966d676e6c7631968c25f5634531 100644 --- a/en/application-dev/ability/fa-dataability.md +++ b/en/application-dev/ability-deprecated/fa-dataability.md @@ -148,7 +148,7 @@ The basic dependency packages include: 1. Create a Data ability helper. - For details about the APIs provided by **DataAbilityHelper**, see [DataAbilityHelper Module](../reference/apis/js-apis-dataAbilityHelper.md). + For details about the APIs provided by **DataAbilityHelper**, see [DataAbilityHelper Module](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md). ```js // Different from the URI defined in the config.json file, the URI passed in the parameter has an extra slash (/), because there is a DeviceID parameter between the second and the third slash (/). import featureAbility from '@ohos.ability.featureAbility' diff --git a/en/application-dev/ability/fa-formability.md b/en/application-dev/ability-deprecated/fa-formability.md similarity index 99% rename from en/application-dev/ability/fa-formability.md rename to en/application-dev/ability-deprecated/fa-formability.md index 377d5e4b8faeda387f4eda5a6506d103c3d76395..a91ca4b9baf98f32bad7ea081024d74949baf726 100644 --- a/en/application-dev/ability/fa-formability.md +++ b/en/application-dev/ability-deprecated/fa-formability.md @@ -43,7 +43,7 @@ The table below describes the **LifecycleForm** APIs, which represent the lifecy | onDestroy(formId: string): void | Called to notify the widget provider that a widget has been destroyed. | | onAcquireFormState?(want: Want): formInfo.FormState | Called to instruct the widget provider to receive the status query result of a widget. | -The table below describes the **FormProvider** APIs. For details, see [FormProvider](../reference/apis/js-apis-formprovider.md). +The table below describes the **FormProvider** APIs. For details, see [FormProvider](../reference/apis/js-apis-application-formProvider.md). **Table 2** FormProvider APIs diff --git a/en/application-dev/ability/fa-pageability.md b/en/application-dev/ability-deprecated/fa-pageability.md similarity index 99% rename from en/application-dev/ability/fa-pageability.md rename to en/application-dev/ability-deprecated/fa-pageability.md index f6eb70595322d3f3308c00afcc9a5907ff87054f..2f4741b80ef771c9b478d32a7713b597fb65c2d4 100644 --- a/en/application-dev/ability/fa-pageability.md +++ b/en/application-dev/ability-deprecated/fa-pageability.md @@ -61,7 +61,7 @@ By default, **singleton** is used. | API | Description | | --------------------------------------------------- | --------------- | -| void startAbility(parameter: StartAbilityParameter) | Starts an ability. | +| void startAbility(parameter: StartAbilityParameter) | Starts an ability. | | Context getContext(): | Obtains the application context.| | void terminateSelf() | Terminates the ability. | | bool hasWindowFocus() | Checks whether the ability has focus. | diff --git a/en/application-dev/ability-deprecated/fa-serviceability.md b/en/application-dev/ability-deprecated/fa-serviceability.md new file mode 100644 index 0000000000000000000000000000000000000000..cf766f35f72c76eb738d3b168d39cbcba0f21da3 --- /dev/null +++ b/en/application-dev/ability-deprecated/fa-serviceability.md @@ -0,0 +1,335 @@ +# Service Ability Development + +## When to Use +A Service ability is used to run tasks in the background, such as playing music or downloading files. It does not provide a UI for user interaction. Service abilities can be started by other applications or abilities and can keep running in the background even after the user switches to another application. + +## Lifecycle APIs + +**Table 1** Service ability lifecycle APIs +|API|Description| +|:------|:------| +|onStart?(): void|Called to initialize a Service ability when the Service ability is being created. This callback is invoked only once in the entire lifecycle of a Service ability.| +|onCommand?(want: Want, startId: number): void|Called every time a Service ability is created on the client. You can collect calling statistics and perform initialization operations in this callback.| +|onConnect?(want: Want): rpc.RemoteObject|Called when another ability is connected to the Service ability.| +|onDisconnect?(want: Want): void|Called when another ability is disconnected from the Service ability.| +|onStop?(): void|Called when the Service ability is being destroyed. You should override this callback for your Service ability to clear its resources, such as threads and registered listeners.| + +The differences between **onCommand()** and **onConnect()** are as follows: + - The **onCommand()** callback is triggered each time the client starts the Service ability by calling **startAbility** or **startAbilityForResult**. + - The **onConnect()** callback is triggered each time the client establishes a new connection with the Service ability by calling **connectAbility**. + +## How to Develop + +### Creating and Registering a Service Ability + +1. Override the Service ability-related lifecycle callbacks to implement your own logic for processing interaction requests. + + + + ```ts + export default { + onStart() { + console.log('ServiceAbility onStart'); + }, + onCommand(want, startId) { + console.log('ServiceAbility onCommand'); + }, + onConnect(want) { + console.log('ServiceAbility OnConnect'); + // Below lists the implementation of ServiceAbilityStub. + return new ServiceAbilityStub('test'); + }, + onDisconnect(want) { + console.log('ServiceAbility OnDisConnect'); + }, + onStop() { + console.log('ServiceAbility onStop'); + } + } + ``` + +2. Register a Service ability. + + Declare the Service ability in the **config.json** file by setting its **type** attribute to **service**. + + ```json + { + "module": { + "abilities": [ + { + "name": ".ServiceAbility", + "type": "service", + "visible": true + ... + } + ] + ... + } + ... + } + ``` + + + +### Starting a Service Ability + +The **Ability** class provides the **startAbility()** API for you to start another Service ability by passing a **Want** object. + +To set information about the target Service ability, you can first construct a **Want** object with the **bundleName** and **abilityName** parameters specified. + +- **bundleName** specifies the bundle name of the target application. +- **abilityName** specifies the target ability name. + +The following code snippet shows how to start a Service ability running on the local device: + +```ts +import featureAbility from '@ohos.ability.featureAbility' + +featureAbility.startAbility( + { + want: + { + bundleName: "com.jstest.service", + abilityName: "com.jstest.service.ServiceAbility" + } + } +).then((err) => { + console.log("startService success"); +}).catch (err => { + console.log("startService FAILED"); +}); +``` + +In the preceding code, the **startAbility()** API is used to start the Service ability. +- If the Service ability is not running, the system initializes the Service ability, and calls **onStart()** and **onCommand()** on the Service ability in sequence. +- If the Service ability is running, the system directly calls **onCommand()** on the Service ability. + +The following code snippet shows how to start a Service ability running on the remote device. For details, see [Connecting to a Remote Service Ability](#connecting-to-a-remote-service-ability). + +```ts +import featureAbility from '@ohos.ability.featureAbility' + +featureAbility.startAbility( + { + want: + { + deviceId: remoteDeviceId, // Remote device ID. + bundleName: "com.jstest.service", + abilityName: "com.jstest.service.ServiceAbility" + } + } +).then((err) => { + console.log("startService success"); +}).catch (err => { + console.log("startService FAILED"); +}); +``` + + +### Stopping a Service Ability + + In normal cases, a Service ability can be stopped by itself or by the system. + - The Service ability can call **particleAbility.terminateSelf()** to stop itself. + - If the application process where the Service ability is located exits, the Service ability is reclaimed along with the process. + - If the Service ability is only accessed through **connectAbility()** (the **onCommand()** callback has never been triggered), the system stops the Service ability when the last connection to the Service ability is disconnected. + +### Connecting to a Local Service Ability + +If a Service ability wants to interact with a Page ability or a Service ability in another application, you must first create a connection. A Service ability allows other abilities to connect to it through **connectAbility()**. + + +You can use either of the following methods to connect to a Service ability: + +1. Using the IDL to automatically generate code + + Use OpenHarmony Interface Definition Language (IDL) to automatically generate the corresponding client, server, and **IRemoteObject** code. For details, see [Development Using TS](../IDL/idl-guidelines.md#development-using-ts). + +2. Writing code in the corresponding file + + When using **connectAbility()**, pass the **Want** and **ConnectOptions** objects of the target Service ability, where **ConnectOptions** encapsulates the following three callbacks that need to be implemented. + - **onConnect()**: callback used for processing when the Service ability is connected. + - **onDisconnect()**: callback used for processing when the Service ability is disconnected. + - **onFailed()**: callback used for processing when the connection to the Service ability fails. + + The following code snippet shows how to implement the callbacks: + + ```ts + import prompt from '@system.prompt' + + var option = { + onConnect: function onConnectCallback(element, proxy) { + console.log(`onConnectLocalService onConnectDone`); + if (proxy === null) { + prompt.showToast({ + message: "Connect service failed" + }); + return; + } + // After obtaining the proxy of the Service ability, the calling ability can communicate with the Service ability. + let data = rpc.MessageParcel.create(); + let reply = rpc.MessageParcel.create(); + let option = new rpc.MessageOption(); + data.writeString("InuptString"); + proxy.sendRequest(0, data, reply, option); + prompt.showToast({ + message: "Connect service success" + }); + }, + onDisconnect: function onDisconnectCallback(element) { + console.log(`onConnectLocalService onDisconnectDone element:${element}`); + prompt.showToast({ + message: "Disconnect service success" + }); + }, + onFailed: function onFailedCallback(code) { + console.log(`onConnectLocalService onFailed errCode:${code}`); + prompt.showToast({ + message: "Connect local service onFailed" + }); + } + }; + ``` + + The following code snippet shows how to connect to a local Service ability: + + ```ts + import featureAbility from '@ohos.ability.featureAbility' + + let want = { + bundleName: "com.jstest.service", + abilityName: "com.jstest.service.ServiceAbility" + }; + let connectId = featureAbility.connectAbility(want, option); + ``` + + When a Service ability is connected, the **onConnect()** callback is invoked and returns an **IRemoteObject** defining the proxy used for communicating with the Service ability. OpenHarmony provides the default implementation of **IRemoteObject**. You can inherit **rpc.RemoteObject** to create a custom implementation class for interaction with the Service ability. For details, see the [RPC API Reference](..\reference\apis\js-apis-rpc.md). + + The following code snippet shows how the Service ability returns itself to the calling ability: + + ```ts + import rpc from "@ohos.rpc" + + class ServiceAbilityStub extends rpc.RemoteObject { + constructor(des: any) { + if (typeof des === 'string') { + super(des); + } else { + console.log("Error, the input param is not string"); + return; + } + } + + onRemoteRequest(code: number, data: any, reply: any, option: any) { + console.log("onRemoteRequest called"); + // Execute the service logic. + if (code === 1) { + // Sort the input strings. + let string = data.readString(); + console.log(`Input string = ${string}`); + let result = Array.from(string).sort().join(''); + console.log(`Output result = ${result}`); + reply.writeString(result); + } else { + console.log(`Unknown request code`); + } + return true; + } + } + + export default { + onStart() { + console.log('ServiceAbility onStart'); + }, + onCommand(want, startId) { + console.log('ServiceAbility onCommand'); + }, + onConnect(want) { + console.log('ServiceAbility OnConnect'); + return new ServiceAbilityStub('ServiceAbilityRemoteObject'); + }, + onDisconnect(want) { + console.log('ServiceAbility OnDisConnect'); + }, + onStop() { + console.log('ServiceAbility onStop'); + } + } + ``` + +### Connecting to a Remote Service Ability + +This feature applies only to system applications. The method of creating a **ConnectOptions** object for connecting to a remote Service ability is similar to that for connecting to a local Service ability. The differences are as follows: + - The application must apply for the data synchronization permission from the user. + - **Want** of the target Service ability must contain the remote device ID. + +> **NOTE** +> +> The **getTrustedDeviceList** API of **DeviceManager** is open only to system applications. Currently, only system applications can connect to a remote Service ability. +> +> For details about the API definition, see [Device Management](..\reference\apis\js-apis-device-manager.md). + +The data synchronization permission is required in the cross-device scenario. Configure the permission in the **config.json** file. + +```json +{ + ... + "module": { + ... + "reqPermissions": [{ + "name": "ohos.permission.DISTRIBUTED_DATASYNC" + }] + } +} +``` + +The **DISTRIBUTED_DATASYNC** permission is user granted. Therefore, your application, when being started, must display a dialog box to request the permission. The sample code is as follows: + +```ts +import abilityAccessCtrl from "@ohos.abilityAccessCtrl" +import bundle from '@ohos.bundle' + +async function RequestPermission() { + console.info('RequestPermission begin'); + let array: Array = ["ohos.permission.DISTRIBUTED_DATASYNC"]; + let bundleFlag = 0; + let tokenID = undefined; + let userID = 100; + let appInfo = await bundle.getApplicationInfo('ohos.samples.etsDemo', bundleFlag, userID); + tokenID = appInfo.accessTokenId; + let atManager = abilityAccessCtrl.createAtManager(); + let requestPermissions: Array = []; + for (let i = 0;i < array.length; i++) { + let result = await atManager.verifyAccessToken(tokenID, array[i]); + console.info("verifyAccessToken result:" + JSON.stringify(result)); + if (result != abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) { + requestPermissions.push(array[i]); + } + } + console.info("requestPermissions:" + JSON.stringify(requestPermissions)); + if (requestPermissions.length == 0 || requestPermissions == []) { + return; + } + let context = featureAbility.getContext(); + context.requestPermissionsFromUser(requestPermissions, 1, (data)=>{ + console.info("data:" + JSON.stringify(data)); + }); + console.info('RequestPermission end'); +} +``` + +To obtain the device ID, import the **@ohos.distributedHardware.deviceManager** module, which provides **getTrustedDeviceList** to obtain the remote device ID. For details about how to use the API, see [Device Management](..\reference\apis\js-apis-device-manager.md). + +To connect to a remote Service ability, you only need to define **deviceId** in **Want**. The sample code is as follows: + +```ts +import featureAbility from '@ohos.ability.featureAbility' + +let want = { + deviceId: remoteDeviceId, + bundleName: "com.jstest.service", + abilityName: "com.jstest.service.ServiceAbility" +}; +let connectId = featureAbility.connectAbility(want, option); +``` + +The other implementations are the same as those for the connection to a local Service ability. For details, see the sample code provided under [Connecting to a Local Service Ability](#connecting-to-a-local-service-ability). diff --git a/en/application-dev/ability/figures/AbilityComponentInstanceMission.png b/en/application-dev/ability-deprecated/figures/AbilityComponentInstanceMission.png similarity index 100% rename from en/application-dev/ability/figures/AbilityComponentInstanceMission.png rename to en/application-dev/ability-deprecated/figures/AbilityComponentInstanceMission.png diff --git a/en/application-dev/ability/figures/ExtensionAbility.png b/en/application-dev/ability-deprecated/figures/ExtensionAbility.png similarity index 100% rename from en/application-dev/ability/figures/ExtensionAbility.png rename to en/application-dev/ability-deprecated/figures/ExtensionAbility.png diff --git a/en/application-dev/ability/figures/aa-dump-a.PNG b/en/application-dev/ability-deprecated/figures/aa-dump-a.PNG similarity index 100% rename from en/application-dev/ability/figures/aa-dump-a.PNG rename to en/application-dev/ability-deprecated/figures/aa-dump-a.PNG diff --git a/en/application-dev/ability/figures/aa-dump-i.PNG b/en/application-dev/ability-deprecated/figures/aa-dump-i.PNG similarity index 100% rename from en/application-dev/ability/figures/aa-dump-i.PNG rename to en/application-dev/ability-deprecated/figures/aa-dump-i.PNG diff --git a/en/application-dev/ability/figures/aa-dump-l.PNG b/en/application-dev/ability-deprecated/figures/aa-dump-l.PNG similarity index 100% rename from en/application-dev/ability/figures/aa-dump-l.PNG rename to en/application-dev/ability-deprecated/figures/aa-dump-l.PNG diff --git a/en/application-dev/ability/figures/contextIntroduction.png b/en/application-dev/ability-deprecated/figures/contextIntroduction.png similarity index 100% rename from en/application-dev/ability/figures/contextIntroduction.png rename to en/application-dev/ability-deprecated/figures/contextIntroduction.png diff --git a/en/application-dev/ability/figures/continuation-info.png b/en/application-dev/ability-deprecated/figures/continuation-info.png similarity index 100% rename from en/application-dev/ability/figures/continuation-info.png rename to en/application-dev/ability-deprecated/figures/continuation-info.png diff --git a/en/application-dev/ability/figures/continuationManager.png b/en/application-dev/ability-deprecated/figures/continuationManager.png similarity index 100% rename from en/application-dev/ability/figures/continuationManager.png rename to en/application-dev/ability-deprecated/figures/continuationManager.png diff --git a/en/application-dev/ability/figures/fa-dataability-uri.png b/en/application-dev/ability-deprecated/figures/fa-dataability-uri.png similarity index 100% rename from en/application-dev/ability/figures/fa-dataability-uri.png rename to en/application-dev/ability-deprecated/figures/fa-dataability-uri.png diff --git a/en/application-dev/ability/figures/fa-form-example.png b/en/application-dev/ability-deprecated/figures/fa-form-example.png similarity index 100% rename from en/application-dev/ability/figures/fa-form-example.png rename to en/application-dev/ability-deprecated/figures/fa-form-example.png diff --git a/en/application-dev/ability/figures/fa-pageAbility-lifecycle.png b/en/application-dev/ability-deprecated/figures/fa-pageAbility-lifecycle.png similarity index 100% rename from en/application-dev/ability/figures/fa-pageAbility-lifecycle.png rename to en/application-dev/ability-deprecated/figures/fa-pageAbility-lifecycle.png diff --git a/en/application-dev/ability/figures/fa-threading-model.png b/en/application-dev/ability-deprecated/figures/fa-threading-model.png similarity index 100% rename from en/application-dev/ability/figures/fa-threading-model.png rename to en/application-dev/ability-deprecated/figures/fa-threading-model.png diff --git a/en/application-dev/ability/figures/favsstage.png b/en/application-dev/ability-deprecated/figures/favsstage.png similarity index 100% rename from en/application-dev/ability/figures/favsstage.png rename to en/application-dev/ability-deprecated/figures/favsstage.png diff --git a/en/application-dev/ability/figures/lifecycle.png b/en/application-dev/ability-deprecated/figures/lifecycle.png similarity index 100% rename from en/application-dev/ability/figures/lifecycle.png rename to en/application-dev/ability-deprecated/figures/lifecycle.png diff --git a/en/application-dev/ability/figures/page-ability-lifecycle.png b/en/application-dev/ability-deprecated/figures/page-ability-lifecycle.png similarity index 100% rename from en/application-dev/ability/figures/page-ability-lifecycle.png rename to en/application-dev/ability-deprecated/figures/page-ability-lifecycle.png diff --git a/en/application-dev/ability/figures/stage-call.png b/en/application-dev/ability-deprecated/figures/stage-call.png similarity index 100% rename from en/application-dev/ability/figures/stage-call.png rename to en/application-dev/ability-deprecated/figures/stage-call.png diff --git a/en/application-dev/ability/figures/stageabilitylifecyclecallback.png b/en/application-dev/ability-deprecated/figures/stageabilitylifecyclecallback.png similarity index 100% rename from en/application-dev/ability/figures/stageabilitylifecyclecallback.png rename to en/application-dev/ability-deprecated/figures/stageabilitylifecyclecallback.png diff --git a/en/application-dev/ability/figures/stageconcept.png b/en/application-dev/ability-deprecated/figures/stageconcept.png similarity index 100% rename from en/application-dev/ability/figures/stageconcept.png rename to en/application-dev/ability-deprecated/figures/stageconcept.png diff --git a/en/application-dev/ability/figures/stagedesign.png b/en/application-dev/ability-deprecated/figures/stagedesign.png similarity index 100% rename from en/application-dev/ability/figures/stagedesign.png rename to en/application-dev/ability-deprecated/figures/stagedesign.png diff --git a/en/application-dev/ability/figures/stageprocessmodel.png b/en/application-dev/ability-deprecated/figures/stageprocessmodel.png similarity index 100% rename from en/application-dev/ability/figures/stageprocessmodel.png rename to en/application-dev/ability-deprecated/figures/stageprocessmodel.png diff --git a/en/application-dev/ability/public_sys-resources/icon-caution.gif b/en/application-dev/ability-deprecated/public_sys-resources/icon-caution.gif similarity index 100% rename from en/application-dev/ability/public_sys-resources/icon-caution.gif rename to en/application-dev/ability-deprecated/public_sys-resources/icon-caution.gif diff --git a/en/application-dev/ability/public_sys-resources/icon-danger.gif b/en/application-dev/ability-deprecated/public_sys-resources/icon-danger.gif similarity index 100% rename from en/application-dev/ability/public_sys-resources/icon-danger.gif rename to en/application-dev/ability-deprecated/public_sys-resources/icon-danger.gif diff --git a/en/application-dev/ability/public_sys-resources/icon-note.gif b/en/application-dev/ability-deprecated/public_sys-resources/icon-note.gif similarity index 100% rename from en/application-dev/ability/public_sys-resources/icon-note.gif rename to en/application-dev/ability-deprecated/public_sys-resources/icon-note.gif diff --git a/en/application-dev/ability/public_sys-resources/icon-notice.gif b/en/application-dev/ability-deprecated/public_sys-resources/icon-notice.gif similarity index 100% rename from en/application-dev/ability/public_sys-resources/icon-notice.gif rename to en/application-dev/ability-deprecated/public_sys-resources/icon-notice.gif diff --git a/en/application-dev/ability/public_sys-resources/icon-tip.gif b/en/application-dev/ability-deprecated/public_sys-resources/icon-tip.gif similarity index 100% rename from en/application-dev/ability/public_sys-resources/icon-tip.gif rename to en/application-dev/ability-deprecated/public_sys-resources/icon-tip.gif diff --git a/en/application-dev/ability/public_sys-resources/icon-warning.gif b/en/application-dev/ability-deprecated/public_sys-resources/icon-warning.gif similarity index 100% rename from en/application-dev/ability/public_sys-resources/icon-warning.gif rename to en/application-dev/ability-deprecated/public_sys-resources/icon-warning.gif diff --git a/en/application-dev/ability/stage-ability-continuation.md b/en/application-dev/ability-deprecated/stage-ability-continuation.md similarity index 98% rename from en/application-dev/ability/stage-ability-continuation.md rename to en/application-dev/ability-deprecated/stage-ability-continuation.md index 701b730a833a7b97f00398746cddae4d2856a248..7a11716f18f2c8b866e1fd11722ae0e07a32d4ce 100644 --- a/en/application-dev/ability/stage-ability-continuation.md +++ b/en/application-dev/ability-deprecated/stage-ability-continuation.md @@ -301,11 +301,13 @@ In the ability continuation scenario, the distributed data object is used to syn ### Restrictions -1. The continuation must be performed between the same ability, which means the same bundle name, module name, and ability name. For details, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). +1. The continuation must be performed between the same ability, which means the same bundle name, module name, and ability name. For details, see [Application Package Structure Configuration File](../quick-start/module-configuration-file.md). 2. Currently, the application can only implement the continuation capability. The continuation action must be initiated by the system. ### Best Practice - For better user experience, you are advised to use the **wantParam** parameter to transmit data smaller than 100 KB and use distributed objects to transmit data larger than 100 KB. +For better user experience, you are advised to use the **wantParam** parameter to transmit data smaller than 100 KB and use distributed objects to transmit data larger than 100 KB. + + \ No newline at end of file diff --git a/en/application-dev/ability/stage-ability.md b/en/application-dev/ability-deprecated/stage-ability.md similarity index 98% rename from en/application-dev/ability/stage-ability.md rename to en/application-dev/ability-deprecated/stage-ability.md index d09585b25531556cfbee2ab5cbd45c72191aa8a4..97ba5cff5cc083563f1d0f78c7b499bff2cd2050 100644 --- a/en/application-dev/ability/stage-ability.md +++ b/en/application-dev/ability-deprecated/stage-ability.md @@ -1,6 +1,6 @@ # Ability Development ## When to Use -Ability development in the [stage model](stage-brief.md) is significantly different from that in the FA model. The stage model requires you to declare the application package structure in the **module.json5** and **app.json5** files during application development. For details about the configuration file, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). To develop an ability based on the stage model, implement the following logic: +Ability development in the [stage model](stage-brief.md) is significantly different from that in the FA model. The stage model requires you to declare the application package structure in the **module.json5** and **app.json5** files during application development. For details about the configuration file, see [Application Package Structure Configuration File](../quick-start/application-package-structure-stage.md). To develop an ability based on the stage model, implement the following logic: - Create an ability that supports screen viewing and human-machine interaction. You must implement the following scenarios: ability lifecycle callbacks, obtaining ability configuration, requesting permissions, and notifying environment changes. - Start an ability. You need to implement ability startup on the same device, on a remote device, or with a specified UI page. - Call abilities. For details, see [Call Development](stage-call.md). @@ -30,7 +30,7 @@ By default, the singleton mode is used. The following is an example of the **mod ``` ## Creating an Ability ### Available APIs -The table below describes the APIs provided by the **AbilityStage** class, which has the **context** attribute. For details about the APIs, see [AbilityStage](../reference/apis/js-apis-application-abilitystage.md). +The table below describes the APIs provided by the **AbilityStage** class, which has the **context** attribute. For details about the APIs, see [AbilityStage](../reference/apis/js-apis-app-ability-abilityStage.md). **Table 1** AbilityStage APIs |API|Description| @@ -321,3 +321,5 @@ struct Index { } } ``` + + \ No newline at end of file diff --git a/en/application-dev/ability/stage-brief.md b/en/application-dev/ability-deprecated/stage-brief.md similarity index 85% rename from en/application-dev/ability/stage-brief.md rename to en/application-dev/ability-deprecated/stage-brief.md index 2cf186f82db342e02523ee4645521ea72fbd1f6f..2d5474e2c2f0e8328add287481b5ea47abcb2725 100644 --- a/en/application-dev/ability/stage-brief.md +++ b/en/application-dev/ability-deprecated/stage-brief.md @@ -12,15 +12,15 @@ The stage model is designed based on the following considerations: - Efficient management of application processes - As the device memory becomes larger, the number of processes concurrently running in the system increases. If the number of concurrent processes reaches several hundreds, the overall power consumption and performance of the system will be adversely affected without effective management measures. To restrict the behavior of background processes, the stage model uses four measures: transient task, continuous task, agent task, and Work Scheduler task. With these measures, foreground processes will obtain guaranteed resources, thereby delivering a better user experience. +As the device memory becomes larger, the number of processes concurrently running in the system increases. If the number of concurrent processes reaches several hundreds, the overall power consumption and performance of the system will be adversely affected without effective management measures. To restrict the behavior of background processes, the stage model uses four measures: transient task, continuous task, agent task, and Work Scheduler task. With these measures, foreground processes will obtain guaranteed resources, thereby delivering a better user experience. - Native support for cross-device migration and multi-device collaboration - OpenHarmony is a native distributed OS. Its application framework must be designed for easier component migration and collaboration across devices. The stage model achieves this design objective by providing features such as separation between ability and UI as well as integration of UI display and service capabilities. +OpenHarmony is a native distributed OS. Its application framework must be designed for easier component migration and collaboration across devices. The stage model achieves this design objective by providing features such as separation between ability and UI as well as integration of UI display and service capabilities. - Different window forms for various device types - The stage model redefines the ability lifecycle. In terms of architecture, the component manager and window manager are decoupled. This facilitates adaptation between window forms and device types. +The stage model redefines the ability lifecycle. In terms of architecture, the component manager and window manager are decoupled. This facilitates adaptation between window forms and device types. ## Basic Concepts @@ -103,8 +103,12 @@ The processes of an application can be classified into three types: ![stageprocessmodel](figures/stageprocessmodel.png) + + ## Application Package Structure For details about the project directory structure of the stage model, see [OpenHarmony Project Overview](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-project-overview-0000001218440650#section56487581904). -For details about how to configure the application package structure of the stage model, see [Application Package Structure Configuration File (Stage Model)](../quick-start/stage-structure.md). +For details about how to configure the application package structure of the stage model, see [Application Package Structure Configuration File](../quick-start/application-configuration-file-overview-stage.md). + + \ No newline at end of file diff --git a/en/application-dev/ability/stage-call.md b/en/application-dev/ability-deprecated/stage-call.md similarity index 99% rename from en/application-dev/ability/stage-call.md rename to en/application-dev/ability-deprecated/stage-call.md index 5c29001e5c62f4059121247e9a044474111527c3..e447dc4fd89f99948ebb379de7010c4db9486488 100644 --- a/en/application-dev/ability/stage-call.md +++ b/en/application-dev/ability-deprecated/stage-call.md @@ -34,7 +34,7 @@ The table below describes the ability call APIs. For details, see [Ability](../r **Table 2** Ability call APIs |API|Description| |:------|:------| -|startAbilityByCall(want: Want): Promise\|Starts an ability in the foreground (through the **want** configuration) or background (default) and obtains the **Caller** object for communication with the ability. For details, see [AbilityContext](../reference/apis/js-apis-ability-context.md#abilitycontextstartabilitybycall) or [ServiceExtensionContext](../reference/apis/js-apis-service-extension-context.md#serviceextensioncontextstartabilitybycall).| +|startAbilityByCall(want: Want): Promise\|Starts an ability in the foreground (through the **want** configuration) or background (default) and obtains the **Caller** object for communication with the ability. For details, see [AbilityContext](../reference/apis/js-apis-ability-context.md#abilitycontextstartabilitybycall) or [ServiceExtensionContext](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartabilitybycall).| |on(method: string, callback: CalleeCallBack): void|Callback invoked when the callee ability registers a method.| |off(method: string): void|Callback invoked when the callee ability deregisters a method.| |call(method: string, data: rpc.Sequenceable): Promise\|Sends agreed sequenceable data to the callee ability.| diff --git a/en/application-dev/ability/stage-formextension.md b/en/application-dev/ability-deprecated/stage-formextension.md similarity index 98% rename from en/application-dev/ability/stage-formextension.md rename to en/application-dev/ability-deprecated/stage-formextension.md index fa90f267c13c0fa002233f585ca7c6b3c9904637..c45b33732a4f902391eb153c9f5304b071bc4f34 100644 --- a/en/application-dev/ability/stage-formextension.md +++ b/en/application-dev/ability-deprecated/stage-formextension.md @@ -31,7 +31,7 @@ Stage widget development refers to the development conducted by the widget provi ## Available APIs -The **FormExtension** class has the following APIs. For details, see [FormExtension](../reference/apis/js-apis-formextension.md). +The **FormExtension** class has the following APIs. For details, see [FormExtension](../reference/apis/js-apis-app-form-formExtensionAbility.md). **Table 1** FormExtension APIs @@ -45,7 +45,7 @@ The **FormExtension** class has the following APIs. For details, see [FormExtens | onDestroy(formId: string): void | Called to notify the widget provider that a **Form** instance (widget) has been destroyed. | | onConfigurationUpdated(config: Configuration): void; | Called when the configuration of the environment where the widget is running is updated. | -The **FormExtension** class also has a member context, that is, the **FormExtensionContext** class. For details, see [FormExtensionContext](../reference/apis/js-apis-formextensioncontext.md). +The **FormExtension** class also has a member context, that is, the **FormExtensionContext** class. For details, see [FormExtensionContext](../reference/apis/js-apis-inner-application-formExtensionContext.md). **Table 2** FormExtensionContext APIs @@ -54,7 +54,7 @@ The **FormExtension** class also has a member context, that is, the **FormExtens | startAbility(want: Want, callback: AsyncCallback<void>): void | Starts an ability. This API uses an asynchronous callback to return the result. (This is a system API and cannot be called by third-party applications.)| | startAbility(want: Want): Promise<void> | Starts an ability. This API uses a promise to return the result. (This is a system API and cannot be called by third-party applications.)| -For details about the **FormProvider** APIs, see [FormProvider](../reference/apis/js-apis-formprovider.md). +For details, see [FormProvider](../reference/apis/js-apis-application-formProvider.md). **Table 3** FormProvider APIs @@ -412,4 +412,4 @@ The following is an example: } } } - ``` \ No newline at end of file + ``` diff --git a/en/application-dev/ability/stage-serviceextension.md b/en/application-dev/ability-deprecated/stage-serviceextension.md similarity index 99% rename from en/application-dev/ability/stage-serviceextension.md rename to en/application-dev/ability-deprecated/stage-serviceextension.md index 0d634ebe67ef9e332f658a0efb0f7ffdb0e1f2b7..98cae5914f7afa34c916c53f6bb423b590cf5070 100644 --- a/en/application-dev/ability/stage-serviceextension.md +++ b/en/application-dev/ability-deprecated/stage-serviceextension.md @@ -71,4 +71,5 @@ OpenHarmony does not support creation of a Service Extension ability for third-p console.log('onDestroy'); } } - ``` \ No newline at end of file + ``` + diff --git a/en/application-dev/ability/wantagent.md b/en/application-dev/ability-deprecated/wantagent.md similarity index 99% rename from en/application-dev/ability/wantagent.md rename to en/application-dev/ability-deprecated/wantagent.md index 5a85bab15b8422aaabb0a173ad888126e08fc038..4b1854d1a54a36f864b3dd4215040eb24db2e5f3 100644 --- a/en/application-dev/ability/wantagent.md +++ b/en/application-dev/ability-deprecated/wantagent.md @@ -2,8 +2,6 @@ ## When to Use The **WantAgent** class encapsulates want information that specifies a particular action, which can be starting an ability or publishing a common event. You can either call **wantAgent.trigger** to trigger a **WantAgent** directly or add a **WantAgent** to a notification so that it will be triggered when users tap the notification. - - ## Available APIs | API | Description| | ---------------------------------------------------------------------------------------------- | ----------- | diff --git a/en/application-dev/ability/fa-serviceability.md b/en/application-dev/ability/fa-serviceability.md deleted file mode 100644 index 3bafb0bc097f0277f88ff4489c2731afdad6569e..0000000000000000000000000000000000000000 --- a/en/application-dev/ability/fa-serviceability.md +++ /dev/null @@ -1,400 +0,0 @@ -# Service Ability Development - -## When to Use -A Service ability is used to run tasks in the background, such as playing music or downloading files. It does not provide a UI for user interaction. Service abilities can be started by other applications or abilities and can remain running in the background even after the user switches to another application. - -## Available APIs - -**Table 1** Service ability lifecycle APIs -|API|Description| -|:------|:------| -|onStart?(): void|Called to initialize a Service ability being created. This callback is invoked only once in the entire lifecycle of a Service ability. The **Want** object passed to this callback must be null.| -|onCommand?(want: Want, startId: number): void|Called every time a Service ability is created on a client. You can collect calling statistics and perform initialization operations in this callback.| -|onConnect?(want: Want): rpc.RemoteObject|Called when another ability is connected to the Service ability.| -|onDisconnect?(want: Want): void|Called when another ability is disconnected from the Service ability.| -|onStop?(): void|Called when the Service ability is being destroyed. You should override this callback for your Service ability to clear its resources, such as threads and registered listeners.| - -## How to Develop - -### Creating and Registering a Service Ability - -1. Override the Service ability-related lifecycle callbacks to implement your own logic for processing interaction requests. - - ```javascript - export default { - onStart() { - console.log('ServiceAbility onStart'); - }, - onCommand(want, startId) { - console.log('ServiceAbility onCommand'); - }, - onConnect(want) { - console.log('ServiceAbility OnConnect'); - return new FirstServiceAbilityStub('test'); - }, - onDisconnect(want) { - console.log('ServiceAbility OnDisConnect'); - }, - onStop() { - console.log('ServiceAbility onStop'); - }, - } - ``` - -2. Register a Service ability. - - Declare the Service ability in the **config.json** file by setting its **type** attribute to **service**. - - ```javascript - { - "module": { - "abilities": [ - { - "name": ".ServiceAbility", - "type": "service", - "visible": true - ... - } - ] - ... - } - ... - } - ``` - - - -### Starting a Service Ability - -The **Ability** class provides the **startAbility()** API for you to start another Service ability by passing a **Want** object. - -To set information about the target Service ability, you can first construct a **Want** object with the **bundleName** and **abilityName** parameters specified. The meanings of the parameters are as follows: - -- **bundleName** indicates the name of the bundle to which the target ability belongs. -- **abilityName** indicates the target ability name. - -The following code snippet shows how to start a Service ability running on the local device: - -```javascript -import featureAbility from '@ohos.ability.featureAbility'; -let promise = featureAbility.startAbility( - { - want: - { - bundleName: "com.jstest.service", - abilityName: "com.jstest.service.ServiceAbility", - }, - } -); -``` - -After the preceding code is executed, the **startAbility()** API is called to start the Service ability. -- If the Service ability is not running, the system calls **onStart()** to initialize the Service ability, and then calls **onCommand()** on the Service ability. -- If the Service ability is running, the system directly calls **onCommand()** on the Service ability. - -The following code snippet shows how to start a Service ability running on the remote device. For details about **getRemoteDeviceId()**, see [Connecting to a Remote Service Ability](#connecting-to-a-remote-service-ability). - -```javascript -import featureAbility from '@ohos.ability.featureAbility'; -let promise = featureAbility.startAbility( - { - want: - { - deviceId: getRemoteDeviceId(), // Remote device ID - bundleName: "com.jstest.service", - abilityName: "com.jstest.service.ServiceAbility", - }, - } -); -``` - - -### Stopping a Service Ability - -Once created, the Service ability keeps running in the background. The system does not stop or destroy it unless memory resources must be reclaimed. - -### Connecting to a Local Service Ability - -If you need to connect a Service ability to a Page ability or to a Service ability in another application, you must first implement the **IAbilityConnection** API for the connection. A Service ability allows other abilities to connect to it through **connectAbility()**. - - -You can use either of the following methods to connect to a Service ability: - -1. Using the IDL to automatically generate code - - Use OpenHarmony Interface Definition Language (IDL) to automatically generate the corresponding client, server, and **IRemoteObject** code. For details, see “Development Using TS" in [OpenHarmony IDL Specifications and User Guide](../IDL/idl-guidelines.md). - -2. Writing code in the corresponding file - - When calling **connectAbility()**, you should pass a **Want** object containing information about the target Service ability and an **IAbilityConnection** object to the API. **IAbilityConnection** provides the following callbacks that you should implement: **onConnect()**, **onDisconnect()**, and **onFailed()**. The **onConnect()** callback is invoked when a Service ability is connected, **onDisconnect()** is invoked when a Service ability is unexpectedly disconnected, and **onFailed()** is invoked when a connection to a Service ability fails. - - The following code snippet shows how to implement the callbacks: - - ```javascript - import prompt from '@system.prompt' - - var option = { - onConnect: function onConnectCallback(element, proxy) { - console.log(`onConnectLocalService onConnectDone`) - if (proxy === null) { - prompt.showToast({ - message: "Connect service failed" - }) - return - } - let data = rpc.MessageParcel.create() - let reply = rpc.MessageParcel.create() - let option = new rpc.MessageOption() - data.writeInterfaceToken("connect.test.token") - proxy.sendRequest(0, data, reply, option) - prompt.showToast({ - message: "Connect service success" - }) - }, - onDisconnect: function onDisconnectCallback(element) { - console.log(`onConnectLocalService onDisconnectDone element:${element}`) - prompt.showToast({ - message: "Disconnect service success" - }) - }, - onFailed: function onFailedCallback(code) { - console.log(`onConnectLocalService onFailed errCode:${code}`) - prompt.showToast({ - message: "Connect local service onFailed" - }) - } - } - ``` - - The following code snippet shows how to connect to a local Service ability: - - ```javascript - import featureAbility from '@ohos.ability.featureAbility'; - let connId = featureAbility.connectAbility( - { - bundleName: "com.jstest.service", - abilityName: "com.jstest.service.ServiceAbility", - }, - { - onConnect: onConnectCallback, - onDisconnect: onDisconnectCallback, - onFailed: onFailedCallback, - }, - ); - ``` - - When a Service ability is connected, the **onConnect()** callback is invoked and returns an **IRemoteObject** defining the proxy used for communicating with the Service ability. OpenHarmony provides a default implementation of **IRemoteObject**. You can extend **rpc.RemoteObject** to implement your own class of **IRemoteObject**. - - The following code snippet shows how the Service ability instance returns itself to the calling ability: - - ```javascript - import rpc from "@ohos.rpc"; - - class FirstServiceAbilityStub extends rpc.RemoteObject { - constructor(des: any) { - if (typeof des === 'string') { - super(des) - } else { - return - } - } - - onRemoteRequest(code: number, data: any, reply: any, option: any) { - console.log(printLog + ` onRemoteRequest called`) - if (code === 1) { - let string = data.readString() - console.log(printLog + ` string=${string}`) - let result = Array.from(string).sort().join('') - console.log(printLog + ` result=${result}`) - reply.writeString(result) - } else { - console.log(printLog + ` unknown request code`) - } - return true; - } - ``` - -### Connecting to a Remote Service Ability - ->**NOTE** -> ->This feature applies only to system applications, since the **getTrustedDeviceListSync** API of the **DeviceManager** class is open only to system applications. - -If you need to connect a Service ability to a Page ability or another Service ability on a remote device, you must first implement the **IAbilityConnection** interface for the connection. A Service ability allows abilities on another device to connect to it through **connectAbility()**. - -When calling **connectAbility()**, you should pass a **Want** object containing information about the target Service ability and an **IAbilityConnection** object to the API. **IAbilityConnection** provides the following callbacks that you should implement: **onConnect()**, **onDisconnect()**, and **onFailed()**. The **onConnect()** callback is invoked when a Service ability is connected, **onDisconnect()** is invoked when a Service ability is unexpectedly disconnected, and **onFailed()** is invoked when a connection to a Service ability fails. - -The following code snippet shows how to implement the callbacks: - -```ts -import prompt from '@system.prompt' - -var option = { - onConnect: function onConnectCallback(element, proxy) { - console.log(`onConnectRemoteService onConnectDone`) - if (proxy === null) { - prompt.showToast({ - message: "Connect service failed" - }) - return - } - let data = rpc.MessageParcel.create() - let reply = rpc.MessageParcel.create() - let option = new rpc.MessageOption() - data.writeInterfaceToken("connect.test.token") - proxy.sendRequest(0, data, reply, option) - prompt.showToast({ - message: "Connect service success" - }) - }, - onDisconnect: function onDisconnectCallback(element) { - console.log(`onConnectRemoteService onDisconnectDone element:${element}`) - prompt.showToast({ - message: "Disconnect service success" - }) - }, - onFailed: function onFailedCallback(code) { - console.log(`onConnectRemoteService onFailed errCode:${code}`) - prompt.showToast({ - message: "Connect local service onFailed" - }) - } -} -``` - -The **Want** of the target Service ability must contain the remote **deviceId**, which can be obtained from **DeviceManager**. The sample code is as follows: - -```ts -import deviceManager from '@ohos.distributedHardware.deviceManager'; - -// For details about the implementation of dmClass, see the implementation in Distributed Demo in Samples. -let dmClass; - -function getRemoteDeviceId() { - if (typeof dmClass === 'object' && dmClass != null) { - let list = dmClass.getTrustedDeviceListSync(); - if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') { - console.log("MainAbility onButtonClick getRemoteDeviceId err: list is null"); - return; - } - console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); - return list[0].deviceId; - } else { - console.log("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null"); - } -} -``` - -The following code snippet shows how to connect to a remote Service ability: - -```ts -import featureAbility from '@ohos.ability.featureAbility'; -let connId = featureAbility.connectAbility( - { - deviceId: getRemoteDeviceId(), - bundleName: "ohos.samples.etsDemo", - abilityName: "ohos.samples.etsDemo.ServiceAbility", - }, - { - onConnect: onConnectCallback, - onDisconnect: onDisconnectCallback, - onFailed: onFailedCallback, - }, -); -``` -In the cross-device scenario, the application must also apply for the data synchronization permission from end users. The sample code is as follows: - -```ts -import abilityAccessCtrl from "@ohos.abilityAccessCtrl"; -import bundle from '@ohos.bundle'; -async function RequestPermission() { - console.info('RequestPermission begin'); - let array: Array = ["ohos.permission.DISTRIBUTED_DATASYNC"]; - let bundleFlag = 0; - let tokenID = undefined; - let userID = 100; - let appInfo = await bundle.getApplicationInfo('ohos.samples.etsDemo', bundleFlag, userID); - tokenID = appInfo.accessTokenId; - let atManager = abilityAccessCtrl.createAtManager(); - let requestPermissions: Array = []; - for (let i = 0;i < array.length; i++) { - let result = await atManager.verifyAccessToken(tokenID, array[i]); - console.info("verifyAccessToken result:" + JSON.stringify(result)); - if (result == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) { - } else { - requestPermissions.push(array[i]); - } - } - console.info("requestPermissions:" + JSON.stringify(requestPermissions)); - if (requestPermissions.length == 0 || requestPermissions == []) { - return; - } - let context = featureAbility.getContext(); - context.requestPermissionsFromUser(requestPermissions, 1, (data)=>{ - console.info("data:" + JSON.stringify(data)); - }); - console.info('RequestPermission end'); -} -``` - -When a Service ability is connected, the **onConnect()** callback is invoked and returns an **IRemoteObject** defining the proxy used for communicating with the Service ability. OpenHarmony provides a default implementation of **IRemoteObject**. You can extend **rpc.RemoteObject** to implement your own class of **IRemoteObject**. - -The following code snippet shows how the Service ability instance returns itself to the calling ability: - -```ts -import rpc from "@ohos.rpc"; - -class FirstServiceAbilityStub extends rpc.RemoteObject { - constructor(des: any) { - if (typeof des === 'string') { - super(des) - } else { - return - } - } - - onRemoteRequest(code: number, data: any, reply: any, option: any) { - console.log(printLog + ` onRemoteRequest called`) - if (code === 1) { - let string = data.readString() - console.log(printLog + ` string=${string}`) - let result = Array.from(string).sort().join('') - console.log(printLog + ` result=${result}`) - reply.writeString(result) - } else { - console.log(printLog + ` unknown request code`) - } - return true; - } -} - -export default { - onStart() { - console.info('ServiceAbility onStart'); - }, - onStop() { - console.info('ServiceAbility onStop'); - }, - onConnect(want) { - console.log("ServiceAbility onConnect"); - try { - let value = JSON.stringify(want); - console.log("ServiceAbility want:" + value); - } catch(error) { - console.log("ServiceAbility error:" + error); - } - return new FirstServiceAbilityStub("first ts service stub"); - }, - onDisconnect(want) { - console.log("ServiceAbility onDisconnect"); - let value = JSON.stringify(want); - console.log("ServiceAbility want:" + value); - }, - onCommand(want, startId) { - console.info('ServiceAbility onCommand'); - let value = JSON.stringify(want); - console.log("ServiceAbility want:" + value); - console.log("ServiceAbility startId:" + startId); - } -}; -``` diff --git a/en/application-dev/application-models/Readme-EN.md b/en/application-dev/application-models/Readme-EN.md new file mode 100644 index 0000000000000000000000000000000000000000..a9473b7f6c2d0fb75e160cafdd1fb94b43633fa7 --- /dev/null +++ b/en/application-dev/application-models/Readme-EN.md @@ -0,0 +1,2 @@ +# Application Models + diff --git a/en/application-dev/device/sample-server-guidelines.md b/en/application-dev/device/sample-server-guidelines.md index faf07d1e82bed9aa679901add578df1aae2444fc..369fb8cc31d3c86e96c42bb38aef2f67761eb9e4 100644 --- a/en/application-dev/device/sample-server-guidelines.md +++ b/en/application-dev/device/sample-server-guidelines.md @@ -14,6 +14,8 @@ The sample server provides a package search server for checking update packages openssl req -newkey rsa:2048 -nodes -keyout serverKey.pem -x509 -days 365 -out serverCert.cer -subj "/C=CN/ST=GD/L=GZ/O=abc/OU=defg/CN=hijk/emailAddress=test.com" ``` + + 2. Modify the **bundle.json** file. Add **sub_component** to the **build** field. @@ -173,7 +175,7 @@ The sample server provides a package search server for checking update packages "\"descriptPackageId\": \"abcdefg1234567ABCDEFG\"," "}]," "\"descriptInfo\": [{" - "\"descriptPackageId\": \"abcdefg1234567ABCDEFG\"," + "\"descriptionType\": 0," "\"content\": \"This package message is used for sampleContent\"" "}]" "}"; diff --git a/en/application-dev/device/sample-server-overview.md b/en/application-dev/device/sample-server-overview.md index 6924f8d7f2256dff9ec828cc5fb62248f68599f1..9e31fe0b50a7d7641fde28ca16c252a97aa2d646 100644 --- a/en/application-dev/device/sample-server-overview.md +++ b/en/application-dev/device/sample-server-overview.md @@ -30,7 +30,7 @@ The following is an example of the JSON response returned by the server. Note th "descriptPackageId": "abcdefg1234567ABCDEFG" }], "descriptInfo": [{ - "descriptPackageId": "abcdefg1234567ABCDEFG", + "descriptionType": 0, "content": "This package is used for update." }] } diff --git a/en/application-dev/faqs/Readme-EN.md b/en/application-dev/faqs/Readme-EN.md index 37baff507755e5862045dfb3247324c6e80dcfdf..0f2738b7160dcc599c54ecbe1875d279d6f3661c 100644 --- a/en/application-dev/faqs/Readme-EN.md +++ b/en/application-dev/faqs/Readme-EN.md @@ -10,8 +10,10 @@ - [Network and Connection Development](faqs-connectivity.md) - [Data Management Development](faqs-data-management.md) - [Device Management Development](faqs-device-management.md) +- [DFX Development](faqs-dfx.md) +- [Intl Development](faqs-international.md) - [Native API Usage](faqs-native.md) - [Usage of Third- and Fourth-Party Libraries](faqs-third-party-library.md) -- [hdc_std Command Usage](faqs-ide.md) -- [IDE Usage](faqs-hdc-std.md) -- [Development Board](faqs-development-board.md) +- [IDE Usage](faqs-ide.md) +- [hdc_std Command Usage](faqs-hdc-std.md) +- [Development Board](faqs-development-board.md) \ No newline at end of file diff --git a/en/application-dev/faqs/faqs-connectivity.md b/en/application-dev/faqs/faqs-connectivity.md index e3b02269e2de947fb4ab4069f1d7ba4812825ddc..31e1db2e15e82875427d52a92dd26bcfeb69c34e 100644 --- a/en/application-dev/faqs/faqs-connectivity.md +++ b/en/application-dev/faqs/faqs-connectivity.md @@ -21,7 +21,7 @@ Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9 Error code 28 refers to **CURLE_OPERATION_TIMEDOUT**, which means a cURL operation timeout. For details, see any HTTP status code description available. -Reference: [Development Guide](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-http.md#httpresponse) and [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html) +Reference: [Response Codes](../reference/apis/js-apis-http.md#responsecode) and [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html) ## What does error code 6 mean for the response of \@ohos.net.http.d.ts? @@ -30,4 +30,4 @@ Applicable to: OpenHarmony SDK 3.2.3.5 Error code 6 indicates a failure to resolve the host in the address. You can ping the URL carried in the request to check whether the host is accessible. -Reference: [Development Guide](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-http.md#httpresponse) and [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html) +Reference: [Response Codes](../reference/apis/js-apis-http.md#responsecode) and [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html) diff --git a/en/application-dev/faqs/faqs-data-management.md b/en/application-dev/faqs/faqs-data-management.md index a35f335d1db6f89033e4deb839cf9b7af0f544a2..47f0b7ce20cd54a1cee4eb521801d4e7ca94e04b 100644 --- a/en/application-dev/faqs/faqs-data-management.md +++ b/en/application-dev/faqs/faqs-data-management.md @@ -1,12 +1,10 @@ # Data Management Development - - -## How Do I Save PixelMap data to a database? +## How Do I Save PixelMap Data to a Database? Applicable to: OpenHarmony SDK 3.2.3.5 -You can convert a **PixelMap** into a **ArrayBuffer** and save the **ArrayBuffer** to your database. +You can convert a **PixelMap** into an **ArrayBuffer** and save the **ArrayBuffer** to your database. Reference: [readPixelsToBuffer](../reference/apis/js-apis-image.md#readpixelstobuffer7-1) @@ -14,11 +12,65 @@ Reference: [readPixelsToBuffer](../reference/apis/js-apis-image.md#readpixelstob Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 -Run the hdc_std command to copy the .db, .db-shm, and .db-wal files from **/data/app/el2/100/database/Bundle name/entry/db/**, and then use the SQLite tool to open the files. +Run the hdc_std command to copy the .db, .db-shm, and .db-wal files in **/data/app/el2/100/database/*bundleName*/entry/db/**, and then use the SQLite tool to open the files. Example: - ``` hdc_std file recv /data/app/el2/100/database/com.xxxx.xxxx/entry/db/test.db ./test.db ``` + +## Does the Database Has a Lock Mechanism? + +Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 + +The distributed data service (DDS), relational database (RDB) store, and preferences provided OpenHarmony have a lock mechanism. You do not need to bother with the lock mechanism during the development. + +## What Is a Transaction in an RDB Store? + +Applicable to: all versions + +When a large number of operations are performed in an RDB store, an unexpected exception may cause a failure of some data operations and loss of certain data. As a result, the application may become abnormal or even crash. + +A transaction is a group of tasks serving as a single logical unit. It eliminates the failure of some of the operations and loss of associated data. + +## What Data Types Does an RDB Store Support? + +Applicable to: OpenHarmony SDK 3.0 or later, stage model of API version 9 + +An RDB store supports data of the number, string, and Boolean types. The number array supports data of the Double, Long, Float, Int, or Int64 type, with a maximum precision of 17 decimal digits. + +## How Do I View Database db Files? + +Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9 + +1. Run the **hdc_std shell** command. + +2. Obtain the absolute path or sandbox path of the database. + +The absolute path is **/data/app/el2//database/**. The default **** is **100**. + +To obtain the sandbox path, run the **ps -ef | grep hapName** command to obtain the process ID of the application. + +The database sandbox path is **/proc//root/data/storage/el2/database/**. + +3. Run the **find ./ -name "\*.db"** command in the absolute path or sandbox path of the database. + +## How Do I Store Long Text Data? + +Applicable to: OpenHarmony SDK 3.2.5.5, API version 9 + +- Preferences support a string of up to 8192 bytes. + +- The KV store supports a value of up to 4 MB. + +Reference: [Preference Overview](../database/database-preference-overview.md) and [Distributed Data Service Overview](../database/database-mdds-overview.md) + +## How Do I Develop DataShare on the Stage Model + +Applicable to: OpenHarmony SDK 3.2.5.5, API version 9 + +The DataShare on the stage model cannot be used with the **DataAbility** for the FA model. The connected server application must be implemented by using **DataShareExtensionAbility**. + +Reference: [DataShare Development](../database/database-datashare-guidelines.md) + diff --git a/en/application-dev/faqs/faqs-dfx.md b/en/application-dev/faqs/faqs-dfx.md new file mode 100644 index 0000000000000000000000000000000000000000..ec1c8dbfedd5fa3c087c96d54c9c2aab73d75e8a --- /dev/null +++ b/en/application-dev/faqs/faqs-dfx.md @@ -0,0 +1,54 @@ +# DFX Development + +## How do I locate the fault when the application crashes? + +Applicable to: OpenHarmony SDK 3.2.5.5 + +1. Locate the crash-related code based on the service log. + +2. View the error information in the crash file. The crash file is located at **/data/log/faultlog/faultlogger/**. + +## Why cannot access controls in the UiTest test framework? + +Applicable to: OpenHarmony SDK 3.2.5.5 + +Check whether **persist.ace.testmode.enabled** is turned on. + +Run **hdc\_std shell param get persist.ace.testmode.enabled**. + +If the value is **0**, run the **hdc\_std shell param set persist.ace.testmode.enabled 1** to enable the test mode. + + +## Why is private displayed in logs when the format parameter type of HiLog in C++ code is %d or %s? + +When format parameters such as **%d** and **%s** are directly used, the standard system uses **private** to replace the actual data for printing by default to prevent data leakage. To print the actual data, replace **%d** with **%{public}d** or replace **%s** with **%{public}s**. + +## What should I do if the hilog.debug log cannot be printed? + +Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 + +Run **hdc_std shell hilog -b D** to turn on the debugging switch. + +## Is HiLog or console recommended for log printing? How do I set the domain if HiLog is used? + +Applicable to: OpenHarmony SDK 3.2.2.5 + +You are advised to use the [HiLog](../reference/apis/js-apis-hilog.md) for log printing. For details about how to set the **domain** parameter, see the [Development Guide](../reference/apis/js-apis-hilog.md#hilogisloggable). + +## What is the maximum length of a log record when HiLog is used? Is it configurable? + +Applicable to: OpenHarmony SDK 3.2.2.5 + +The maximum length of a log record is 1,024 characters, and it is not changeable. + +## Can I separate multiple strings by spaces in the tag parameter of the HiLog API? + +Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9 + +No. Separating multiple strings by spaces is not allowed. + +## How do I print real data if HiLog does not contain data labeled by {public}? + +Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9 + +Run **hdc\_std shell hilog -p off** to disable logging of data labeled by {public}. diff --git a/en/application-dev/faqs/faqs-file-management.md b/en/application-dev/faqs/faqs-file-management.md index 1e3740047768d5d5fefa1420659c64da403ad587..adac2f5a6739a85c04005ef8068369776e90581c 100644 --- a/en/application-dev/faqs/faqs-file-management.md +++ b/en/application-dev/faqs/faqs-file-management.md @@ -1,15 +1,65 @@ # File Management Development +## Does fileio.rmdir Delete Files Recursively? +Applicable to: OpenHarmony SDK 3.2.6.3, stage model of API version 9 -## What If There is No Return Value or Error Captured After getAlbums Is Called? +Yes. **fileio.rmdir** deletes files recursively. + +## How Do I Create a File That Does Not Exist? + +Applicable to: OpenHarmony SDK 3.2.6.3, stage model of API version 9 + +You can use **fileio.open(filePath, 0o100, 0o666)**. The second parameter **0o100** means to create a file if it does not exist. The third parameter **mode** must also be specified. + +## What If "call fail callback fail, code: 202, data: json arguments illegal" Is Displayed? + +Applicable to: OpenHarmony SDK 3.2.6.3, stage model of API version 9 + +When the **fileio** module is used to copy files, the file path cannot start with "file:///". + +## How Do I Read Files Outside the App Sandbox? + +Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9 + +If the input parameter of the **fileio** API is **path**, only the sandbox directory of the current app obtained from the context can be accessed. To access data in other directories such as the user data, images, and videos, open the file as the data owner and operate with the file descriptor (FD) returned. + +For example, to read or write a file in Media Library, perform the following steps: + +1. Use **getFileAssets()** to obtain the **fileAsset** object. + +2. Use **fileAsset.open()** to obtain the FD. + +3. Use the obtained FD as the **fileIo** API parameter to read and write the file. + +## What If the File Contains Garbled Characters? + +Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 + +Read the file content from the buffer, and decode the file content using **util.TextDecoder**. + +Example: + +``` +import util from '@ohos.util' +async function readFile(path) { + let stream = fileio.createStreamSync(path, "r+"); + let readOut = await stream.read(new ArrayBuffer(4096)); + let textDecoder = new util.TextDecoder("utf-8", { ignoreBOM: true }); + let buffer = new Uint8Array(readOut.buffer) + let readString = textDecoder.decode(buffer, { stream: false }); + console.log ("[Demo] File content read: "+ readString); +} +``` + +## What Should I Do If There Is No Return Value or Error Captured After getAlbums Is Called? Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 -The **ohos.permission.READ_MEDIA** permission is required for calling **getAlbums**, and this permission needs user authorization. For details, see OpenHarmony [Application Permission List](../security/permission-list.md). +The **ohos.permission.READ_MEDIA** is required for using **getAlbums()**. In addition, this permission needs user authorization. For details, see [OpenHarmony Permission List](../security/permission-list.md). 1. Configure the required permission in the **module.json5** file. - + ``` "requestPermissions": [ { @@ -19,7 +69,7 @@ The **ohos.permission.READ_MEDIA** permission is required for calling **getAlbum ``` 2. Add the code for user authorization before the **MainAbility.ts -> onWindowStageCreate** page is loaded. - + ``` private requestPermissions() { let permissionList: Array = [ @@ -34,3 +84,21 @@ The **ohos.permission.READ_MEDIA** permission is required for calling **getAlbum }) } ``` + +## What Do I Do If the App Crashes When FetchFileResult() Is Called Multiple Times? + +Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 + +Each time after the **FetchFileResult** object is called, call **FetchFileResult.close()** to release and invalidate the **FetchFileResult** object . + +## What If An Error Is Reported by IDE When mediaLibrary.getMediaLibrary() Is Called in the Stage Model? + +Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 + +In the stage model, use **mediaLibrary.getMediaLibrary(context: Context)** to obtain the media library instance. + +## How Do I Sort the Data Returned by mediaLibrary.getFileAssets()? + +Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 + +Use the **order** attribute in **[MediaFetchOptions](../reference/apis/js-apis-medialibrary.md#mediafetchoptions7)** to sort the data returned. diff --git a/en/application-dev/faqs/faqs-hdc-std.md b/en/application-dev/faqs/faqs-hdc-std.md index 04c0a202a57b702164b8bcb7a32299d3abd5d75c..60f93da61d7d78a4e148b65c0e30d379b1e1206d 100644 --- a/en/application-dev/faqs/faqs-hdc-std.md +++ b/en/application-dev/faqs/faqs-hdc-std.md @@ -1,17 +1,14 @@ # hdc_std Command Usage - - -## What are the commands commonly used for log management? +## Common Log Commands Applicable to: OpenHarmony SDK 3.2.2.5 -- Clearing logs: hdc_std shell hilog -r +Clearing logs: hdc_std shell hilog -r -- Increasing the buffer size to 20 MB: hdc_std shell hilog -G 20M - -- Capturing logs: hdc_std shell hilog > log.txt +Increasing the buffer size to 20 MB: hdc_std shell hilog -G 20M +Capturing logs: hdc_std shell hilog > log.txt ## What should I do to avoid log flow control? @@ -27,43 +24,64 @@ Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 After performing the preceding operations, restart the DevEco Studio. +## What should I do if the HAP installed on the development board through the IDE cannot be opened? -## Is HiLog or Console recommended for log printing? How do I set the domain if HiLog is used? +Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 -Applicable to: OpenHarmony SDK 3.2.2.5 +Check whether the SDK version is consistent with the system version on the development board. You are advised to use the SDK version and system version that are released on the same day. -[HiLog](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-hilog.md) is recommended for an application to print logs. For details about domain setting, see [Development Guide](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-hilog.md#hilogisloggable). +## How do I upload files using the hdc command? +Applicable to: OpenHarmony SDK 3.2.2.5 -## What is the maximum length of a log record when HiLog is used? Is it configurable? +Run the **hdc_std file send** command. -Applicable to: OpenHarmony SDK 3.2.2.5 +## How do I prevent the screen of the RK3568 development board from turning off? -The maximum length of a log record is 1,024 characters, and it is not changeable. +Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 +Run the **hdc_std shell "power-shell setmode 602"** command. -## What should I do if a HAP package cannot be opened after being installed on the development board using the IDE? +## How do I start an ability using the hdc command? Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 -Check whether the SDK version is consistent with the system version on the development board. You are advised to use the SDK version and system version that are released on the same day. +Run the **hdc\_std shell aa start -a AbilityName -b bundleName -m moduleName** command. +## How do I change the read and write permissions on a file directory on the development board? -## How do I upload files using an hdc command? +Applicable to: OpenHarmony SDK 3.2.5.6, stage model of API version 9 + +Run the **hdc\_std shell mount -o remount,rw /** command. + +## What should I do if the error message "Unknown file option -r" is displayed when hdc_std file recv is run? + +Applicable to: OpenHarmony SDK 3.2.5.6, stage model of API version 9 + +1. Use the the hdc tool in the device image or SDK of the same version. + +2. Remove any Chinese characters or spaces from the directory specified for the hdc tool. + +## How do I uninstall an application using the hdc command? Applicable to: OpenHarmony SDK 3.2.2.5 -Run the **hdc_std file send** command. +Run the **hdc\_std uninstall [-k] [package_name]** command. -## How do I prevent the screen of the RK3568 development board from turning off? +## How do I check whether the system is 32-bit or 64-bit? -Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 +Applicable to: OpenHarmony SDK 3.2.5.5 -Run the **hdc_std shell "power-shell setmode 602"** command. +Run the **hdc\_std shell getconf LONG_BIT** command. +If **64** is returned, the system is a 64-bit one. Otherwise, the system is a 32-bit one. -## How do I start an ability using an hdc command? +## How do I view the component tree structure? -Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 +Applicable to: OpenHarmony SDK 3.2.5.5 + +1. Run the **hdc\_std shell** command to launch the CLI. + +2. Run the **aa dump -a** command to find **abilityID**. -Run the **hdc_std shell aa start -a AbilityName -b bundleName -m moduleName** command. +3. Run the **aa dump -i [abilityID] -c -render** command to view the component tree. diff --git a/en/application-dev/faqs/faqs-international.md b/en/application-dev/faqs/faqs-international.md new file mode 100644 index 0000000000000000000000000000000000000000..546402921ce3a2cd9f9972721727a84d9a31295a --- /dev/null +++ b/en/application-dev/faqs/faqs-international.md @@ -0,0 +1,19 @@ +# Intl Development + +## How resources in AppScope, such as images and text, are referenced? + +Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 + +Resources are referenced in the **$r('app.type.name')** format. Where, **type** indicates the resource type, such as color, string, and media, and **name** indicates the resource name. + +## How do I convert the resource type to string? + +Applicable to: OpenHarmony SDK3.0, stage model of API version 9 + +If the resource type is set to **string**, the qualifier directory can be set as **this.context.resourceManager.getStringSync(\\$r('app.string.test').id)** and can be converted synchronously. The **\$r('app.string.test', 2)** mode is not supported. For more usage methods, see [Resource Manager](../reference/apis/js-apis-resource-manager.md#getstringsync9). + +## Why should I do if the constants referenced by $ in the form_config.json file does not take effect? + +Applicable to: OpenHarmony SDK 3.2.6.5, API9 Stage model + +In the **form\_config.json** file, **$** cannot be used to reference constants. diff --git a/en/application-dev/media/audio-playback.md b/en/application-dev/media/audio-playback.md index 92aa1cd4fc35a4b64ad9b1044c1a7bd59f24453d..bbdb993ecdb9a1289a939af43db0e670ec10f98f 100644 --- a/en/application-dev/media/audio-playback.md +++ b/en/application-dev/media/audio-playback.md @@ -2,11 +2,11 @@ ## Introduction -You can use audio playback APIs to convert audio data into audible analog signals and play the signals using output devices. You can also manage playback tasks. For example, you can start, suspend, stop playback, release resources, set the volume, seek to a playback position, and obtain track information. +You can use audio playback APIs to convert audio data into audible analog signals and play the signals using output devices. You can also manage playback tasks. For example, you can control the playback and volume, obtain track information, and release resources. ## Working Principles -The following figures show the audio playback status changes and the interaction with external modules for audio playback. +The following figures show the audio playback state transition and the interaction with external modules for audio playback. **Figure 1** Audio playback state transition @@ -28,7 +28,7 @@ For details about the APIs, see [AudioPlayer in the Media API](../reference/apis > **NOTE** > -> The method for obtaining the path in the FA model is different from that in the stage model. **pathDir** used in the sample code below is an example. You need to obtain the path based on project requirements. For details about how to obtain the path, see [Application Sandbox Path Guidelines](../reference/apis/js-apis-fileio.md#guidelines). +> The method for obtaining the path in the FA model is different from that in the stage model. For details about how to obtain the path, see [Application Sandbox Path Guidelines](../reference/apis/js-apis-fileio.md#guidelines). ### Full-Process Scenario @@ -109,7 +109,7 @@ async function audioPlayerDemo() { setCallBack(audioPlayer); // Set the event callbacks. // 2. Set the URI of the audio file. let fdPath = 'fd://' - let pathDir = "/data/storage/el2/base/haps/entry/files" // The method for obtaining pathDir in the FA model is different from that in the stage model. For details, see NOTE just below How to Develop. You need to obtain pathDir based on project requirements. + let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command. let path = pathDir + '/01.mp3' await fileIO.open(path).then((fdNumber) => { @@ -151,7 +151,7 @@ export class AudioDemo { let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. this.setCallBack(audioPlayer); // Set the event callbacks. let fdPath = 'fd://' - let pathDir = "/data/storage/el2/base/haps/entry/files" // The method for obtaining pathDir in the FA model is different from that in the stage model. For details, see NOTE just below How to Develop. You need to obtain pathDir based on project requirements. + let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command. let path = pathDir + '/01.mp3' await fileIO.open(path).then((fdNumber) => { @@ -199,7 +199,7 @@ export class AudioDemo { async nextMusic(audioPlayer) { this.isNextMusic = true; let nextFdPath = 'fd://' - let pathDir = "/data/storage/el2/base/haps/entry/files" // The method for obtaining pathDir in the FA model is different from that in the stage model. For details, see NOTE just below How to Develop. You need to obtain pathDir based on project requirements. + let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\02.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command. let nextpath = pathDir + '/02.mp3' await fileIO.open(nextpath).then((fdNumber) => { @@ -217,7 +217,7 @@ export class AudioDemo { let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. this.setCallBack(audioPlayer); // Set the event callbacks. let fdPath = 'fd://' - let pathDir = "/data/storage/el2/base/haps/entry/files" // The method for obtaining pathDir in the FA model is different from that in the stage model. For details, see NOTE just below How to Develop. You need to obtain pathDir based on project requirements. + let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command. let path = pathDir + '/01.mp3' await fileIO.open(path).then((fdNumber) => { @@ -256,7 +256,7 @@ export class AudioDemo { let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. this.setCallBack(audioPlayer); // Set the event callbacks. let fdPath = 'fd://' - let pathDir = "/data/storage/el2/base/haps/entry/files" // The method for obtaining pathDir in the FA model is different from that in the stage model. For details, see NOTE just below How to Develop. You need to obtain pathDir based on project requirements. + let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command. let path = pathDir + '/01.mp3' await fileIO.open(path).then((fdNumber) => { diff --git a/en/application-dev/media/camera.md b/en/application-dev/media/camera.md index 25e5e573057661487895bc003c143393287b4829..8032348105eb70a3b5dbfd431de3632d6d04cb8a 100644 --- a/en/application-dev/media/camera.md +++ b/en/application-dev/media/camera.md @@ -81,6 +81,9 @@ for (let index = 0; index < cameraArray.length; index++) { // Create a camera input stream. let cameraInput = await cameraManager.createCameraInput(cameraArray[0]) +// Open camera +await cameraInput.open(); + // Obtain the output stream capabilities supported by the camera. let cameraOutputCap = await cameraManager.getSupportedOutputCapability(cameraArray[0]); if (!cameraOutputCap) { diff --git a/en/application-dev/napi/mindspore-lite-guidelines.md b/en/application-dev/napi/mindspore-lite-guidelines.md index 47ede475575484d60317e9ed7e2afe586fb12524..420d09121f86b7a4612c2e7ad6fe5f29831be80b 100644 --- a/en/application-dev/napi/mindspore-lite-guidelines.md +++ b/en/application-dev/napi/mindspore-lite-guidelines.md @@ -24,7 +24,7 @@ APIs involved in MindSpore Lite model inference are categorized into context API | ------------------ | ----------------- | |OH_AI_ContextHandle OH_AI_ContextCreate()|Creates a context object.| |void OH_AI_ContextSetThreadNum(OH_AI_ContextHandle context, int32_t thread_num)|Sets the number of runtime threads.| -| void OH_AI_ContextSetThreadAffinityMode(OH_AI_ContextHandle context, int mode)|Sets the affinity mode for binding runtime threads to CPU cores, which are categorized into little cores and big cores depending on the CPU frequency.| +| void OH_AI_ContextSetThreadAffinityMode(OH_AI_ContextHandle context, int mode)|Sets the affinity mode for binding runtime threads to CPU cores, which are classified into large, medium, and small cores based on the CPU frequency. You only need to bind the large or medium cores, but not small cores.| |OH_AI_DeviceInfoHandle OH_AI_DeviceInfoCreate(OH_AI_DeviceType device_type)|Creates a runtime device information object.| |void OH_AI_ContextDestroy(OH_AI_ContextHandle *context)|Destroys a context object.| |void OH_AI_DeviceInfoSetEnableFP16(OH_AI_DeviceInfoHandle device_info, bool is_fp16)|Sets whether to enable float16 inference. This function is available only for CPU and GPU devices.| diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index feb018281da35356278e1e16bddbc8638a323a47..76d12ed38f81bdf496fd228f9cbea11eb8422510 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -1,64 +1,133 @@ # APIs - [API Reference Document Description](development-intro.md) + - Ability Framework - - FA Model - - [@ohos.ability.featureAbility](js-apis-featureAbility.md) - - [@ohos.ability.particleAbility](js-apis-particleAbility.md) - - ability/[dataAbilityHelper](js-apis-dataAbilityHelper.md) - - app/[context](js-apis-Context.md) - - Stage Model - - [@ohos.application.Ability](js-apis-application-ability.md) - - [@ohos.application.AbilityConstant](js-apis-application-abilityConstant.md) - - [@ohos.application.AbilityStage](js-apis-application-abilitystage.md) - - [@ohos.application.abilityLifecycleCallback](js-apis-application-abilityLifecycleCallback.md) + - Stage Model (Recommended) + - [@ohos.app.ability.Ability](js-apis-app-ability-ability.md) + - [@ohos.app.ability.AbilityConstant](js-apis-app-ability-abilityConstant.md) + - [@ohos.app.ability.abilityLifecycleCallback](js-apis-app-ability-abilityLifecycleCallback.md) + - [@ohos.app.ability.AbilityStage](js-apis-app-ability-abilityStage.md) + - [@ohos.app.ability.common](js-apis-app-ability-common.md) + - [@ohos.app.ability.contextConstant](js-apis-app-ability-contextConstant.md) + - [@ohos.app.ability.EnvironmentCallback](js-apis-app-ability-environmentCallback.md) + - [@ohos.app.ability.ExtensionAbility](js-apis-app-ability-extensionAbility.md) + - [@ohos.app.ability.ServiceExtensionAbility](js-apis-app-ability-serviceExtensionAbility.md) + - [@ohos.app.ability.StartOptions](js-apis-app-ability-startOptions.md) + - [@ohos.app.ability.UIAbility](js-apis-app-ability-uiAbility.md) + - [@ohos.app.form.FormExtensionAbility](js-apis-app-form-formExtensionAbility.md) - [@ohos.application.DataShareExtensionAbility](js-apis-application-DataShareExtensionAbility.md) - - [@ohos.application.EnvironmentCallback](js-apis-application-EnvironmentCallback.md) - - [@ohos.application.FormExtension](js-apis-formextension.md) - - [@ohos.application.ServiceExtensionAbility](js-apis-service-extension-ability.md) - - [@ohos.application.StartOptions](js-apis-application-StartOptions.md) - [@ohos.application.StaticSubscriberExtensionAbility](js-apis-application-staticSubscriberExtensionAbility.md) - - [@ohos.application.WindowExtensionAbility](js-apis-application-windowExtensionAbility.md) - - application/[AbilityContext](js-apis-ability-context.md) - - application/[ApplicationContext](js-apis-application-applicationContext.md) - - application/[AbilityStageContext](js-apis-abilitystagecontext.md) - - application/[Context](js-apis-application-context.md) - - application/[ExtensionContext](js-apis-extension-context.md) - - application/[FormExtensionContext](js-apis-formextensioncontext.md) - - application/[PermissionRequestResult](js-apis-permissionrequestresult.md) - - application/[ServiceExtensionContext](js-apis-service-extension-context.md) - - FA and Stage Models - - [@ohos.ability.dataUriUtils](js-apis-DataUriUtils.md) + - Stage Model (To Be Deprecated Soon) + - [@ohos.application.Ability](js-apis-application-ability.md) + - [@ohos.application.AbilityConstant](js-apis-application-abilityConstant.md) + - [@ohos.application.AbilityLifecycleCallback](js-apis-application-abilityLifecycleCallback.md) + - [@ohos.application.AbilityStage](js-apis-application-abilityStage.md) + - [@ohos.application.context](js-apis-application-context.md) + - [@ohos.application.EnvironmentCallback](js-apis-application-environmentCallback.md) + - [@ohos.application.ExtensionAbility](js-apis-application-extensionAbility.md) + - [@ohos.application.FormExtension](js-apis-application-formExtension.md) + - [@ohos.application.ServiceExtensionAbility](js-apis-application-serviceExtensionAbility.md) + - [@ohos.application.StartOptions](js-apis-application-startOptions.md) + - FA Model + - [@ohos.ability.ability](js-apis-ability-ability.md) + - [@ohos.ability.featureAbility](js-apis-ability-featureAbility.md) + - [@ohos.ability.particleAbility](js-apis-ability-particleAbility.md) + - Both Models (Recommended) + - [@ohos.app.ability.abilityDelegatorRegistry](js-apis-app-ability-abilityDelegatorRegistry.md) + - [@ohos.app.ability.abilityManager](js-apis-app-ability-abilityManager.md) + - [@ohos.app.ability.appManager](js-apis-app-ability-appManager.md) + - [@ohos.app.ability.appRecovery](js-apis-app-ability-appRecovery.md) + - [@ohos.app.ability.Configuration](js-apis-app-ability-configuration.md) + - [@ohos.app.ability.ConfigurationConstant](js-apis-app-ability-configurationConstant.md) + - [@ohos.app.ability.dataUriUtils](js-apis-app-ability-dataUriUtils.md) + - [@ohos.app.ability.errorManager](js-apis-app-ability-errorManager.md) + - [@ohos.app.ability.missionManager](js-apis-app-ability-missionManager.md) + - [@ohos.app.ability.quickFixManager](js-apis-app-ability-quickFixManager.md) + - [@ohos.app.ability.Want](js-apis-app-ability-want.md) + - [@ohos.app.ability.wantAgent](js-apis-app-ability-wantAgent.md) + - [@ohos.app.ability.wantConstant](js-apis-app-ability-wantConstant.md) + - [@ohos.app.form.formBindingData](js-apis-app-form-formBindingData.md) + - [@ohos.app.form.formHost](js-apis-app-form-formHost.md) + - [@ohos.app.form.formInfo](js-apis-app-form-formInfo.md) + - [@ohos.app.form.formProvider](js-apis-app-form-formProvider.md) + - Both Models (To Be Deprecated Soon) + - [@ohos.ability.dataUriUtils](js-apis-ability-dataUriUtils.md) - [@ohos.ability.errorCode](js-apis-ability-errorCode.md) - [@ohos.ability.wantConstant](js-apis-ability-wantConstant.md) - - [@ohos.application.abilityDelegatorRegistry](js-apis-abilityDelegatorRegistry.md) + - [@ohos.application.abilityDelegatorRegistry](js-apis-application-abilityDelegatorRegistry.md) - [@ohos.application.abilityManager](js-apis-application-abilityManager.md) - - [@ohos.application.appManager](js-apis-appmanager.md) - - [@ohos.application.errorManager](js-apis-errorManager.md) - - [@ohos.application.formBindingData](js-apis-formbindingdata.md) - - [@ohos.application.formError](js-apis-formerror.md) - - [@ohos.application.formHost](js-apis-formhost.md) - - [@ohos.application.formInfo](js-apis-formInfo.md) - - [@ohos.application.formProvider](js-apis-formprovider.md) - - [@ohos.application.missionManager](js-apis-missionManager.md) - - [@ohos.application.quickFixManager](js-apis-application-quickFixManager.md) - - [@ohos.application.Want](js-apis-application-Want.md) - - [@ohos.continuation.continuationManager](js-apis-continuation-continuationManager.md) + - [@ohos.application.appManager](js-apis-application-appManager.md) + - [@ohos.application.Configuration](js-apis-application-configuration.md) + - [@ohos.application.ConfigurationConstant](js-apis-application-configurationConstant.md) + - [@ohos.application.errorManager)](js-apis-application-errorManager.md) + - [@ohos.application.formBindingData](js-apis-application-formBindingData.md) + - [@ohos.application.formError](js-apis-application-formError.md) + - [@ohos.application.formHost](js-apis-application-formHost.md) + - [@ohos.application.formInfo](js-apis-application-formInfo.md) + - [@ohos.application.formProvider](js-apis-application-formProvider.md) + - [@ohos.application.missionManager](js-apis-application-missionManager.md) + - [@ohos.application.Want](js-apis-application-want.md) - [@ohos.wantAgent](js-apis-wantAgent.md) - - application/[abilityDelegator](js-apis-application-abilityDelegator.md) - - application/[abilityDelegatorArgs](js-apis-application-abilityDelegatorArgs.md) - - application/[abilityMonitor](js-apis-application-abilityMonitor.md) - - application/[AbilityRunningInfo](js-apis-abilityrunninginfo.md) - - application/[ExtensionRunningInfo](js-apis-extensionrunninginfo.md) - - application/[MissionSnapshot](js-apis-application-MissionSnapshot.md) - - application/[ProcessRunningInformation](js-apis-processrunninginformation.md) - - application/[shellCmdResult](js-apis-application-shellCmdResult.md) - - continuation/[continuationExtraParams](js-apis-continuation-continuationExtraParams.md) - - continuation/[ContinuationResult](js-apis-continuation-continuationResult.md) + - Dependent Elements and Definitions + - ability + - [abilityResult](js-apis-inner-ability-abilityResult.md) + - [connectOptions](js-apis-inner-ability-connectOptions.md) + - [dataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) + - [dataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md) + - [dataAbilityResult](js-apis-inner-ability-dataAbilityResult.md) + - [startAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) + - [want](js-apis-inner-ability-want.md) + - app + - [appVersionInfo](js-apis-inner-app-appVersionInfo.md) + - [context](js-apis-inner-app-context.md) + - [processInfo](js-apis-inner-app-processInfo.md) + - application + - [AbilityContext](js-apis-ability-context.md) + - [abilityDelegator](js-apis-inner-application-abilityDelegator.md) + - [abilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md) + - [abilityMonitor](js-apis-inner-application-abilityMonitor.md) + - [AbilityRunningInfo](js-apis-inner-application-abilityRunningInfo.md) + - [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) + - [AbilityStateData](js-apis-inner-application-abilityStateData.md) + - [abilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) + - [ApplicationContext](js-apis-inner-application-applicationContext.md) + - [ApplicationStateObserver](js-apis-inner-application-applicationStateObserver.md) + - [AppStateData](js-apis-inner-application-appStateData.md) + - [BaseContext](js-apis-inner-application-baseContext.md) + - [Context](js-apis-inner-application-context.md) + - [ContinueCallback](js-apis-inner-application-continueCallback.md) + - [ContinueDeviceInfo](js-apis-inner-application-continueDeviceInfo.md) + - [ErrorObserver](js-apis-inner-application-errorObserver.md) + - [ExtensionContext](js-apis-inner-application-extensionContext.md) + - [ExtensionRunningInfo](js-apis-inner-application-extensionRunningInfo.md) + - [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) + - [MissionCallbacks](js-apis-inner-application-missionCallbacks.md) + - [MissionDeviceInfo](js-apis-inner-application-missionDeviceInfo.md) + - [MissionInfo](js-apis-inner-application-missionInfo.md) + - [MissionListener](js-apis-inner-application-missionListener.md) + - [MissionParameter](js-apis-inner-application-missionParameter.md) + - [MissionSnapshot](js-apis-inner-application-missionSnapshot.md) + - [PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md) + - [ProcessData](js-apis-inner-application-processData.md) + - [ProcessRunningInfo](js-apis-inner-application-processRunningInfo.md) + - [ProcessRunningInformation](js-apis-inner-application-processRunningInformation.md) + - [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) + - [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) + - [shellCmdResult](js-apis-inner-application-shellCmdResult.md) + - wantAgent + - [triggerInfo](js-apis-inner-wantAgent-triggerInfo.md) + - [wantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md) + - Continuation + - [@ohos.continuation.continuationManager (continuationManager)](js-apis-continuation-continuationManager.md) + - continuation + - [continuationExtraParams](js-apis-continuation-continuationExtraParams.md) + - [continuationResult](js-apis-continuation-continuationResult.md) + - Common Event and Notification - [@ohos.events.emitter](js-apis-emitter.md) - [@ohos.notification](js-apis-notification.md) - - application/[EventHub](js-apis-eventhub.md) + - application/[EventHub](js-apis-inner-application-eventHub.md) - Bundle Management - [@ohos.bundle.appControl](js-apis-appControl.md) - [@ohos.bundle.bundleManager](js-apis-bundleManager.md) @@ -69,19 +138,20 @@ - [@ohos.bundle.installer](js-apis-installer.md) - [@ohos.bundle.launcherBundleManager](js-apis-launcherBundleManager.md) - [@ohos.zlib](js-apis-zlib.md) - - bundleManager/[abilityInfo](js-apis-bundleManager-abilityInfo.md) - - bundleManager/[applicationInfo](js-apis-bundleManager-applicationInfo.md) - - bundleManager/[bundleInfo](js-apis-bundleManager-bundleInfo.md) - - bundleManager/[dispatchInfo](js-apis-bundleManager-dispatchInfo.md) - - bundleManager/[elementName](js-apis-bundleManager-elementName.md) - - bundleManager/[extensionAbilityInfo](js-apis-bundleManager-extensionAbilityInfo.md) - - bundleManager/[hapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) - - bundleManager/[launcherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md) - - bundleManager/[metadata](js-apis-bundleManager-metadata.md) - - bundleManager/[packInfo](js-apis-bundleManager-packInfo.md) - - bundleManager/[permissionDef](js-apis-bundleManager-permissionDef.md) - - bundleManager/[remoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md) - - bundleManager/[shortcutInfo](js-apis-bundleManager-shortcutInfo.md) + - bundleManager + - [abilityInfo](js-apis-bundleManager-abilityInfo.md) + - [applicationInfo](js-apis-bundleManager-applicationInfo.md) + - [bundleInfo](js-apis-bundleManager-bundleInfo.md) + - [dispatchInfo](js-apis-bundleManager-dispatchInfo.md) + - [elementName](js-apis-bundleManager-elementName.md) + - [extensionAbilityInfo](js-apis-bundleManager-extensionAbilityInfo.md) + - [hapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) + - [launcherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md) + - [metadata](js-apis-bundleManager-metadata.md) + - [packInfo](js-apis-bundleManager-packInfo.md) + - [permissionDef](js-apis-bundleManager-permissionDef.md) + - [remoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md) + - [shortcutInfo](js-apis-bundleManager-shortcutInfo.md) - UI Page - [@ohos.animator](js-apis-animator.md) - [@ohos.mediaquery](js-apis-mediaquery.md) @@ -89,16 +159,19 @@ - [@ohos.router](js-apis-router.md) - Graphics - [@ohos.animation.windowAnimationManager](js-apis-windowAnimationManager.md) + - [@ohos.application.WindowExtensionAbility](js-apis-application-windowExtensionAbility.md) - [@ohos.display ](js-apis-display.md) - [@ohos.effectKit](js-apis-effectKit.md) - [@ohos.graphics.colorSpaceManager](js-apis-colorSpaceManager.md) - [@ohos.screen](js-apis-screen.md) - [@ohos.screenshot](js-apis-screenshot.md) - [@ohos.window](js-apis-window.md) - - [webgl](js-apis-webgl.md) - - [webgl2](js-apis-webgl2.md) + - webgl + - [webgl](js-apis-webgl.md) + - [webgl2](js-apis-webgl2.md) - Media - [@ohos.multimedia.audio](js-apis-audio.md) + - [@ohos.multimedia.avsession](js-apis-avsession.md) - [@ohos.multimedia.camera](js-apis-camera.md) - [@ohos.multimedia.image](js-apis-image.md) - [@ohos.multimedia.media](js-apis-media.md) @@ -130,15 +203,16 @@ - [@ohos.data.distributedKVStore](js-apis-distributedKVStore.md) - [@ohos.data.preferences](js-apis-data-preferences.md) - [@ohos.data.rdb](js-apis-data-rdb.md) - - [@ohos.data.ValuesBucket](js-apis-data-ValuesBucket.md) - - data/rdb/[resultSet](js-apis-data-resultset.md) + - [@ohos.data.ValuesBucket](js-apis-data-valuesBucket.md) + - data/rdb + - [resultSet](js-apis-data-resultset.md) - File Management - [@ohos.document](js-apis-document.md) - [@ohos.environment](js-apis-environment.md) - [@ohos.data.fileAccess](js-apis-fileAccess.md) - [@ohos.fileExtensionInfo](js-apis-fileExtensionInfo.md) - [@ohos.fileio](js-apis-fileio.md) - - [@ohos.filemanagement.userfile_manager](js-apis-userfilemanager.md) + - [@ohos.filemanagement.userFileManager](js-apis-userfilemanager.md) - [@ohos.multimedia.medialibrary](js-apis-medialibrary.md) - [@ohos.securityLabel](js-apis-securityLabel.md) - [@ohos.statfs](js-apis-statfs.md) @@ -167,10 +241,13 @@ - [@ohos.nfc.controller](js-apis-nfcController.md) - [@ohos.nfc.tag](js-apis-nfcTag.md) - [@ohos.rpc](js-apis-rpc.md) + - [@ohos.wifiManager (WLAN)](js-apis-wifiManager.md) + - [@ohos.wifiManagerExt](js-apis-wifiManagerExt.md) - [@ohos.wifi](js-apis-wifi.md) - [@ohos.wifiext](js-apis-wifiext.md) - - tag/[nfctech](js-apis-nfctech.md) - - tag/[tagSession](js-apis-tagSession.md) + - tag + - [nfctech](js-apis-nfctech.md) + - [tagSession](js-apis-tagSession.md) - Basic Features - [@ohos.accessibility](js-apis-accessibility.md) - [@ohos.accessibility.config](js-apis-accessibility-config.md) @@ -182,8 +259,9 @@ - [@ohos.hiSysEvent](js-apis-hisysevent.md) - [@ohos.hiTraceChain](js-apis-hitracechain.md) - [@ohos.hiTraceMeter](js-apis-hitracemeter.md) - - [@ohos.inputmethod](js-apis-inputmethod.md) - - [@ohos.inputmethodengine](js-apis-inputmethodengine.md) + - [@ohos.hiviewdfx.hiAppEvent](js-apis-hiviewdfx-hiappevent.md) + - [@ohos.inputMethod](js-apis-inputmethod.md) + - [@ohos.inputMethodEngine](js-apis-inputmethodengine.md) - [@ohos.inputmethodextensionability](js-apis-inputmethod-extension-ability.md) - [@ohos.inputmethodextensioncontext](js-apis-inputmethod-extension-context.md) - [@ohos.pasteboard](js-apis-pasteboard.md) @@ -191,6 +269,7 @@ - [@ohos.systemTime](js-apis-system-time.md) - [@ohos.systemTimer](js-apis-system-timer.md) - [@ohos.wallpaper](js-apis-wallpaper.md) + - [@ohos.web.webview](js-apis-webview.md) - [console](js-apis-logs.md) - [Timer](js-apis-timer.md) - application/[AccessibilityExtensionContext](js-apis-accessibility-extension-context.md) @@ -214,6 +293,7 @@ - [@ohos.runningLock](js-apis-runninglock.md) - [@ohos.sensor](js-apis-sensor.md) - [@ohos.settings](js-apis-settings.md) + - [@ohos.stationary](js-apis-stationary.md) - [@ohos.systemParameterV9](js-apis-system-parameterV9.md) - [@ohos.thermal](js-apis-thermal.md) - [@ohos.update](js-apis-update.md) @@ -225,7 +305,7 @@ - [@ohos.account.osAccount](js-apis-osAccount.md) - Custom Management - [@ohos.configPolicy](js-apis-configPolicy.md) - - [@ohos.enterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md) + - [@ohos.EnterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md) - Language Base Class Library - [@ohos.buffer](js-apis-buffer.md) - [@ohos.convertxml](js-apis-convertxml.md) @@ -250,15 +330,14 @@ - [@ohos.worker](js-apis-worker.md) - [@ohos.xml](js-apis-xml.md) - Test - - [@ohos.application.testRunner](js-apis-testRunner.md) + - [@ohos.application.testRunner](js-apis-application-testRunner.md) - [@ohos.uitest](js-apis-uitest.md) -- APIs No Longer Maintained +- APIs No Longer Maintained - [@ohos.backgroundTaskManager](js-apis-backgroundTaskManager.md) - [@ohos.bundle](js-apis-Bundle.md) - [@ohos.bundle.innerBundleManager](js-apis-Bundle-InnerBundleManager.md) - [@ohos.bundleState](js-apis-deviceUsageStatistics.md) - [@ohos.bytrace](js-apis-bytrace.md) - - [@ohos.commonEvent](js-apis-commonEvent.md) - [@ohos.data.storage](js-apis-data-storage.md) - [@ohos.data.distributedData](js-apis-distributed-data.md) - [@ohos.distributedBundle](js-apis-Bundle-distributedBundle.md) @@ -268,7 +347,7 @@ - [@ohos.prompt](js-apis-prompt.md) - [@ohos.reminderAgent](js-apis-reminderAgent.md) - [@ohos.systemParameter](js-apis-system-parameter.md) - - [@ohos.workScheduler](js-apis-workScheduler.md) + - [@ohos.usb](js-apis-usb-deprecated.md) - [@system.app](js-apis-system-app.md) - [@system.battery](js-apis-system-battery.md) - [@system.bluetooth](js-apis-system-bluetooth.md) @@ -288,17 +367,17 @@ - [@system.sensor](js-apis-system-sensor.md) - [@system.storage](js-apis-system-storage.md) - [@system.vibrator](js-apis-system-vibrate.md) - - application/[ProcessRunningInfo](js-apis-processrunninginfo.md) - - bundle/[abilityInfo](js-apis-bundle-AbilityInfo.md) - - bundle/[applicationInfo](js-apis-bundle-ApplicationInfo.md) - - bundle/[bundleInfo](js-apis-bundle-BundleInfo.md) - - bundle/[bundleInstaller](js-apis-bundle-BundleInstaller.md) - - bundle/[bundleStatusCallback](js-apis-Bundle-BundleStatusCallback.md) - - bundle/[customizeData](js-apis-bundle-CustomizeData.md) - - bundle/[elementName](js-apis-bundle-ElementName.md) - - bundle/[hapModuleInfo](js-apis-bundle-HapModuleInfo.md) - - bundle/[launcherAbilityInfo](js-apis-bundle-LauncherAbilityInfo.md) - - bundle/[moduleInfo](js-apis-bundle-ModuleInfo.md) - - bundle/[PermissionDef](js-apis-bundle-PermissionDef.md) - - bundle/[remoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md) - - bundle/[shortcutInfo](js-apis-bundle-ShortcutInfo.md) + - bundle + - [abilityInfo](js-apis-bundle-AbilityInfo.md) + - [applicationInfo](js-apis-bundle-ApplicationInfo.md) + - [bundleInfo](js-apis-bundle-BundleInfo.md) + - [bundleInstaller](js-apis-bundle-BundleInstaller.md) + - [bundleStatusCallback](js-apis-Bundle-BundleStatusCallback.md) + - [customizeData](js-apis-bundle-CustomizeData.md) + - [elementName](js-apis-bundle-ElementName.md) + - [hapModuleInfo](js-apis-bundle-HapModuleInfo.md) + - [launcherAbilityInfo](js-apis-bundle-LauncherAbilityInfo.md) + - [moduleInfo](js-apis-bundle-ModuleInfo.md) + - [PermissionDef](js-apis-bundle-PermissionDef.md) + - [remoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md) + - [shortcutInfo](js-apis-bundle-ShortcutInfo.md) diff --git a/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md b/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md index 9d023410fff66869318fca78d3cae361ff71217b..40725aefbf65838c8da46d75a13368c68118df0d 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md +++ b/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md @@ -1,8 +1,8 @@ -# innerBundleManager(deprecated) +# @ohos.bundle.innerBundleManager The **innerBundleManager** module provides APIs for the **Home Screen** application. -> +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > This module is deprecated since API version 9. You are advised to use [launcherBundleManager](js-apis-launcherBundleManager.md) and [bundleMonitor](js-apis-bundleMonitor.md) instead. @@ -41,7 +41,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- | | bundleName | string | Yes | Bundle name of an application. | -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| userId | number | Yes | User ID. The value must be greater than or equal to 0.| | callback | AsyncCallback\> | Yes | Callback used to return an array of the launcher ability information. | @@ -69,7 +69,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | ------ | ---- | ----------------------------------------------------- | | bundleName | string | Yes | Bundle name of an application. | -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| userId | number | Yes | User ID. The value must be greater than or equal to 0.| **Return value** @@ -216,7 +216,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- | -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| userId | number | Yes | User ID. The value must be greater than or equal to 0.| | callback | AsyncCallback\> | Yes | Callback used to return an array of the launcher ability information. | ## innerBundleManager.getAllLauncherAbilityInfos(deprecated) @@ -242,7 +242,7 @@ This is a system API and cannot be called by third-party applications. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ----------------------------------------------------- | -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| userId | number | Yes | User ID. The value must be greater than or equal to 0.| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-Bundle.md b/en/application-dev/reference/apis/js-apis-Bundle.md index 52a10b74d2346bc15d2fc17ce196b190bfbfa521..83cf9c77d2899e1c0c0969be8199c602e4374816 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle.md +++ b/en/application-dev/reference/apis/js-apis-Bundle.md @@ -1,24 +1,24 @@ -# Bundle +# @ohos.bundle -The **Bundle** module provides APIs for querying the information about bundles, applications, abilities, Extension abilities, and application states. +The **bundle** module provides APIs for obtaining information about an application, including [bundle information](js-apis-bundle-BundleInfo.md), [application information](js-apis-bundle-ApplicationInfo.md), and [ability information](js-apis-bundle-AbilityInfo.md). It also provides APIs to obtain and set the application disabling state. > **NOTE** > > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -```js +```ts import bundle from '@ohos.bundle'; ``` ## Required Permissions -| Required Permissions | Permission Level | Description | -| ------------------------------------------ | ------------ | ------------------ | -| ohos.permission.GET_BUNDLE_INFO | normal | Permission to query information about a specified application. | -| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED| system_basic | Permission to query information about all applications.| -| ohos.permission.INSTALL_BUNDLE | system_core | Permission to install or uninstall applications. | -| ohos.permission.MANAGE_DISPOSED_APP_STATUS | system_core | Permission to set and query the application disposal status. | +| Required Permissions | Permission Level | Description | +|--------------------------------------------|--------------|---------------| +| ohos.permission.GET_BUNDLE_INFO | normal | Permission to query information about a specified bundle. | +| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED| system_basic | Permission to query information about all bundles. | +| ohos.permission.INSTALL_BUNDLE | system_core | Permission to install or uninstall bundles. | +| ohos.permission.MANAGE_DISPOSED_APP_STATUS | system_core | Permission to set and query the application disposal status.| For details, see [Permission Levels](../../security/accesstoken-overview.md#permission-levels). @@ -30,6 +30,8 @@ getApplicationInfo(bundleName: string, bundleFlags: number, userId?: number): Pr Obtains the application information based on a given bundle name. This API uses a promise to return the result. +No permission is required for obtaining the caller's own information. + **Required permissions** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -42,8 +44,8 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name of an application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| bundleName | string | Yes | Bundle name of the application. | +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflagdeprecated).| | userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** @@ -54,7 +56,7 @@ SystemCapability.BundleManager.BundleFramework **Example** -```js +```ts let bundleName = "com.example.myapplication"; let bundleFlags = 0; let userId = 100; @@ -74,6 +76,8 @@ getApplicationInfo(bundleName: string, bundleFlags: number, userId: number, call Obtains the application information of the specified user based on a given bundle name. This API uses an asynchronous callback to return the result. +No permission is required for obtaining the caller's own information. + **Required permissions** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -86,14 +90,14 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name of an application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| bundleName | string | Yes | Bundle name of the application. | +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| userId | number | Yes | User ID. The value must be greater than or equal to 0. | | callback | AsyncCallback\<[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)> | Yes | Callback used to return the application information. | **Example** -```js +```ts let bundleName = "com.example.myapplication"; let bundleFlags = 0; let userId = 100; @@ -115,6 +119,8 @@ getApplicationInfo(bundleName: string, bundleFlags: number, callback: AsyncCallb Obtains the application information based on a given bundle name. This API uses an asynchronous callback to return the result. +No permission is required for obtaining the caller's own information. + **Required permissions** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -127,13 +133,13 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name of an application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| bundleName | string | Yes | Bundle name of the application. | +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| | callback | AsyncCallback\<[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)> | Yes | Callback used to return the application information. | **Example** -```js +```ts let bundleName = "com.example.myapplication"; let bundleFlags = 0; bundle.getApplicationInfo(bundleName, bundleFlags, (err, data) => { @@ -152,7 +158,7 @@ bundle.getApplicationInfo(bundleName, bundleFlags, (err, data) => { getAllBundleInfo(bundleFlag: BundleFlag, userId?: number): Promise> -Obtains the information of all available bundles of the specified user in the system. This API uses a promise to return the result. +Obtains the information of all bundles of the specified user. This API uses a promise to return the result. **Required permissions** @@ -166,7 +172,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | ---------- | ---- | ------------------------------------------------------------ | -| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| bundleFlag | BundleFlag | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| | userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** @@ -177,7 +183,7 @@ SystemCapability.BundleManager.BundleFramework **Example** -```js +```ts let bundleFlag = 0; let userId = 100; bundle.getAllBundleInfo(bundleFlag, userId) @@ -195,7 +201,7 @@ bundle.getAllBundleInfo(bundleFlag, userId) getAllBundleInfo(bundleFlag: BundleFlag, callback: AsyncCallback>): void -Obtains the information of all available bundles in the system. This API uses an asynchronous callback to return the result. +Obtains the information of all bundles of the current user. This API uses an asynchronous callback to return the result. **Required permissions** @@ -209,12 +215,12 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| -| callback | AsyncCallback> | Yes | Callback used to return the information of all available bundles. | +| bundleFlag | BundleFlag | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| callback | AsyncCallback> | Yes | Callback used to return the information of all bundles. | **Example** -```js +```ts let bundleFlag = 0; bundle.getAllBundleInfo(bundleFlag, (err, data) => { if (err) { @@ -232,7 +238,7 @@ bundle.getAllBundleInfo(bundleFlag, (err, data) => { getAllBundleInfo(bundleFlag: BundleFlag, userId: number, callback: AsyncCallback>): void -Obtains the information of all available bundles of the specified user in the system. This API uses an asynchronous callback to return the result. +Obtains the information of all bundles of the specified user. This API uses an asynchronous callback to return the result. **Required permissions** @@ -244,15 +250,16 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | -| callback | AsyncCallback> | Yes | Callback used to return the information of all available bundles. | +| Name | Type | Mandatory | Description | +|------------|-------------------------------------------------------------------|-----|---------------------------------------------------------------------| +| bundleFlag | BundleFlag | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| callback | AsyncCallback> | Yes | Callback used to return the information of all bundles. | +| **Example** -```js +```ts let bundleFlag = 0; let userId = 100; bundle.getAllBundleInfo(bundleFlag, userId, (err, data) => { @@ -273,6 +280,8 @@ getBundleInfo(bundleName: string, bundleFlags: number, options?: BundleOptions): Obtains the bundle information based on a given bundle name. This API uses a promise to return the result. +No permission is required for obtaining the caller's own information. + **Required permissions** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -283,11 +292,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------------- | ---- | --------------------------------------- | -| bundleName | string | Yes | Bundle name of an application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| -| options | [BundleOptions](#bundleoptions) | No | Includes **userId**. | +| Name | Type | Mandatory | Description | +| ----------- | ------------- | ---- |---------------------------------------------------------------------| +| bundleName | string | Yes | Bundle name of the application. | +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| options | [BundleOptions](#bundleoptions) | No | Options that contain the user ID. | **Return value** @@ -297,7 +306,7 @@ SystemCapability.BundleManager.BundleFramework **Example** -```js +```ts let bundleName = "com.example.myapplication"; let bundleFlags = 1; let options = { @@ -319,6 +328,8 @@ getBundleInfo(bundleName: string, bundleFlags: number, callback: AsyncCallback\< Obtains the bundle information based on a given bundle name. This API uses an asynchronous callback to return the result. +No permission is required for obtaining the caller's own information. + **Required permissions** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -329,15 +340,15 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ---------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name of an application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| -| callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the bundle information. | +| Name | Type | Mandatory| Description | +| ----------- | ---------------------------------------------------------- | ---- |---------------------------------------------------------------------| +| bundleName | string | Yes | Bundle name of the application. | +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the bundle information. | **Example** -```js +```ts let bundleName = "com.example.myapplication"; let bundleFlags = 1; bundle.getBundleInfo(bundleName, bundleFlags, (err, data) => { @@ -358,6 +369,8 @@ getBundleInfo(bundleName: string, bundleFlags: number, options: BundleOptions, c Obtains the bundle information based on a given bundle name and bundle options. This API uses an asynchronous callback to return the result. +No permission is required for obtaining the caller's own information. + **Required permissions** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -370,14 +383,14 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ---------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name of an application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| bundleName | string | Yes | Bundle name of the application. | +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| | options | [BundleOptions](#bundleoptions) | Yes | Includes **userId**. | | callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the bundle information. | **Example** -```js +```ts let bundleName = "com.example.myapplication"; let bundleFlags = 1; let options = { @@ -400,7 +413,7 @@ bundle.getBundleInfo(bundleName, bundleFlags, options, (err, data) => { getBundleInstaller(): Promise<BundleInstaller>; -Obtains the installation package information. This API uses a promise to return the result. +Obtains the installation package. This API uses a promise to return the result. **Required permissions** @@ -418,7 +431,17 @@ This is a system API and cannot be called by third-party applications. | Type | Description | | ------------------------------------------------------------ | -------------------------------------------- | -| Promise<[BundleInstaller](js-apis-bundle-BundleInstaller.md)> | Promise used to return the installation package information.| +| Promise<[BundleInstaller](js-apis-bundle-BundleInstaller.md)> | Promise used to return the installation package.| + +**Example** + +```ts +bundle.getBundleInstaller().then((data) => { + console.info('getBundleInstaller successfully.'); +}).catch((error) => { + console.error('getBundleInstaller failed.'); +}); +``` ## bundle.getBundleInstallerdeprecated @@ -426,7 +449,7 @@ This is a system API and cannot be called by third-party applications. getBundleInstaller(callback: AsyncCallback<BundleInstaller>): void; -Obtains the installation package information. This API uses an asynchronous callback to return the result. +Obtains the installation package. This API uses an asynchronous callback to return the result. **Required permissions** @@ -444,8 +467,19 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ---------------- | -| callback | AsyncCallback<[BundleInstaller](js-apis-bundle-BundleInstaller.md)> | Yes | Callback used to return the installation package information.| +| callback | AsyncCallback<[BundleInstaller](js-apis-bundle-BundleInstaller.md)> | Yes | Callback used to return the installation package.| + +**Example** +```ts +bundle.getBundleInstaller((err, data) => { + if (err.code == 0) { + console.error('getBundleInstaller failed.'); + } else { + console.info('getBundleInstaller successfully'); + } +}); +``` ## bundle.cleanBundleCacheFiles8+ deprecated > This API is deprecated since API version 9. You are advised to use [bundleManager.cleanBundleCacheFiles](js-apis-bundleManager.md#bundlemanagercleanbundlecachefiles) instead. @@ -470,9 +504,23 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | ------------------- | ---- | ------------------------------------- | -| bundleName | string | Yes | Bundle name of an application.| +| bundleName | string | Yes | Bundle name of the application.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Example** + +```ts +let bundleName = "com.example.myapplication"; + +bundle.cleanBundleCacheFiles(bundleName, err => { + if (err) { + console.error('cleanBundleCacheFiles failed.'); + } else { + console.info('cleanBundleCacheFiles successfully.'); + } +}); +``` + ## bundle.cleanBundleCacheFiles8+ deprecated > This API is deprecated since API version 9. You are advised to use [bundleManager.cleanBundleCacheFiles](js-apis-bundleManager.md#bundlemanagercleanbundlecachefiles) instead. @@ -497,7 +545,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | ------ | ---- | ------------------------------------- | -| bundleName | string | Yes | Bundle name of an application.| +| bundleName | string | Yes | Bundle name of the application.| **Return value** @@ -505,6 +553,18 @@ This is a system API and cannot be called by third-party applications. | ------------- | ------------------------------------ | | Promise\ | Promise that returns no value.| +**Example** + +```ts +let bundleName = "com.example.myapplication"; + +bundle.cleanBundleCacheFiles(bundleName).then(()=> { + console.info('cleanBundleCacheFiles successfully.'); +}).catch(err=> { + console.error('cleanBundleCacheFiles failed.'); +}); +``` + ## bundle.setApplicationEnabled8+ deprecated > This API is deprecated since API version 9. You are advised to use [bundleManager.setApplicationEnabled](js-apis-bundleManager.md#bundlemanagersetapplicationenabled) instead. @@ -527,11 +587,25 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------- | ---- | ----------------------------------------------- | -| bundleName | string | Yes | Bundle name of an application. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------- | ---- |--------------------------------| +| bundleName | string | Yes | Bundle name of the application. | | isEnable | boolean | Yes | Whether to enable the application. The value **true** means to enable the application, and **false** means the opposite.| -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```ts +let bundleName = "com.example.myapplication"; + +bundle.setApplicationEnabled(bundleName, false, err => { + if (err) { + console.error('setApplicationEnabled failed.'); + } else { + console.info('setApplicationEnabled successfully.'); + } +}); +``` ## bundle.setApplicationEnabled8+ deprecated @@ -555,9 +629,9 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------- | ---- | ----------------------------------------------- | -| bundleName | string | Yes | Bundle name of an application. | +| Name | Type | Mandatory| Description | +| ---------- | ------- | ---- |------------------------------| +| bundleName | string | Yes | Bundle name of the application. | | isEnable | boolean | Yes | Whether to enable the application. The value **true** means to enable the application, and **false** means the opposite.| **Return value** @@ -566,6 +640,18 @@ This is a system API and cannot be called by third-party applications. | ------------- | ------------------------------------ | | Promise\ | Promise that returns no value.| +**Example** + +```ts +let bundleName = "com.example.myapplication"; + +bundleManager.setApplicationEnabled(bundleName, false).then(()=> { + console.info('setApplicationEnabled successfully.'); +}).catch(err=> { + console.error('setApplicationEnabled failed.'); +}); +``` + ## bundle.setAbilityEnabled8+ deprecated > This API is deprecated since API version 9. You are advised to use [bundleManager.setAbilityEnabled](js-apis-bundleManager.md#bundlemanagersetabilityenabled) instead. @@ -627,6 +713,28 @@ This is a system API and cannot be called by third-party applications. | ------------- | ------------------------------------ | | Promise\ | Promise that returns no value.| +**Example** + +```ts +let flag = bundle.BundleFlag.GET_ABILITY_INFO_WITH_PERMISSION; +let userId = 100; +let want = { + bundleName : "com.example.myapplication", + abilityName : "com.example.myapplication.MainAbility" +}; + +bundle.getAbilityInfo(want, flag, userId).then((abilityInfo) => { + console.info('getAbilityInfo successfully. Data: ' + JSON.stringify(abilityInfo)); + + bundle.setAbilityEnabled(abilityInfo, false).then(data => { + console.info('setAbilityEnabled successfully.'); + }).catch(err => { + console.error('setAbilityEnabled failed:' + JSON.stringify(err)); + }) +}).catch(error => { + console.error('getAbilityInfo failed. Cause: ' + JSON.stringify(error)); +}); +``` ## bundle.getPermissionDef8+ deprecated > This API is deprecated since API version 9. You are advised to use [bundleManager.getPermissionDef](js-apis-bundleManager.md#bundlemanagergetpermissiondef) instead. @@ -654,6 +762,19 @@ This is a system API and cannot be called by third-party applications. | permissionName | string | Yes | Name of the permission. | | callback | AsyncCallback<[PermissionDef](js-apis-bundle-PermissionDef)> | Yes | Callback used to return the permission details.| +**Example** + +```ts +let permission = "ohos.permission.GET_BUNDLE_INFO"; +bundleManager.getPermissionDef(permission, (err, data) => { + if (err) { + console.error('getPermissionDef failed:' + err.message); + } else { + console.info('getPermissionDef successfully:' + JSON.stringify(data)); + } +}); +``` + ## bundle.getPermissionDef8+ deprecated > This API is deprecated since API version 9. You are advised to use [bundleManager.getPermissionDef](js-apis-bundleManager.md#bundlemanagergetpermissiondef) instead. @@ -686,6 +807,16 @@ This is a system API and cannot be called by third-party applications. | ------------------------------------------------------ | ------------------------------------------------------ | | Promise<[PermissionDef](js-apis-bundle-PermissionDef)> | Promise used to return the permission details.| +**Example** + +```ts +let permissionName = "ohos.permission.GET_BUNDLE_INFO"; +bundle.getPermissionDef(permissionName).then((data) => { + console.info('getPermissionDef successfully. Data: ' + JSON.stringify(data)); +}).catch(error => { + console.error('getPermissionDef failed. Cause: ' + error.message); +}); +``` ## bundle.getAllApplicationInfodeprecated @@ -707,8 +838,8 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ------------------------------------------------------------ | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** @@ -718,7 +849,7 @@ SystemCapability.BundleManager.BundleFramework **Example** -```js +```ts let bundleFlags = 8; let userId = 100; bundle.getAllApplicationInfo(bundleFlags, userId) @@ -735,7 +866,7 @@ bundle.getAllApplicationInfo(bundleFlags, userId) getAllApplicationInfo(bundleFlags: number, userId: number, callback: AsyncCallback>): void -Obtains the information about all applications of the specified user. This API uses an asynchronous callback to return the result. +Obtains the information about all applications. This API uses an asynchronous callback to return the result. **Required permissions** @@ -749,14 +880,14 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| | userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | | callback | AsyncCallback> | Yes | Callback used to return the application information. | **Example** -```js -let bundleFlags = 8; +```ts +let bundleFlags = bundle.BundleFlag.GET_APPLICATION_INFO_WITH_PERMISSION; let userId = 100; bundle.getAllApplicationInfo(bundleFlags, userId, (err, data) => { if (err) { @@ -774,7 +905,7 @@ bundle.getAllApplicationInfo(bundleFlags, userId, (err, data) => { getAllApplicationInfo(bundleFlags: number, callback: AsyncCallback>) : void; -Obtains the information about all applications. This API uses an asynchronous callback to return the result. +Obtains the information about all applications of the current user. This API uses an asynchronous callback to return the result. **Required permissions** @@ -788,13 +919,13 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| | callback | AsyncCallback> | Yes | Callback used to return the application information. | **Example** -```js -let bundleFlags = 8; +```ts +let bundleFlags = bundle.BundleFlag.GET_APPLICATION_INFO_WITH_PERMISSION; bundle.getAllApplicationInfo(bundleFlags, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); @@ -820,8 +951,8 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ------------ | -| hapFilePath | string | Yes | Path where the HAP file is stored. The path should point to the relative directory of the current application's data directory.| -| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| hapFilePath | string | Yes | Path where the HAP file is stored. The absolute path of the application and the data directory sandbox path are supported.| +| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| **Return value** | Type | Description | @@ -830,8 +961,8 @@ SystemCapability.BundleManager.BundleFramework **Example** -```js -let hapFilePath = "/data/xxx/test.hap"; +```ts +let hapFilePath = "/data/storage/el2/base/test.hap"; let bundleFlags = 0; bundle.getBundleArchiveInfo(hapFilePath, bundleFlags) .then((data) => { @@ -857,14 +988,14 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ------------ | -| hapFilePath | string | Yes | Path where the HAP file is stored. The path should point to the relative directory of the current application's data directory.| -| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| hapFilePath | string | Yes | Path where the HAP file is stored.. The absolute path of the application and the data directory sandbox path are supported.| +| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| | callback| AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the information about the bundles.| **Example** -```js -let hapFilePath = "/data/xxx/test.hap"; +```ts +let hapFilePath = "/data/storage/el2/base/test.hap"; let bundleFlags = 0; bundle.getBundleArchiveInfo(hapFilePath, bundleFlags, (err, data) => { if (err) { @@ -884,6 +1015,8 @@ getAbilityInfo(bundleName: string, abilityName: string): Promise\ Obtains the ability information based on a given bundle name and ability name. This API uses a promise to return the result. +No permission is required for obtaining the caller's own information. + **Required permissions** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -894,9 +1027,9 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------ | ---- | ---------------- | -| bundleName | string | Yes | Bundle name of an application. | +| Name | Type | Mandatory | Description | +| ----------- | ------ | ---- |------------| +| bundleName | string | Yes | Bundle name of the application. | | abilityName | string | Yes | Ability name.| **Return value** @@ -907,7 +1040,7 @@ SystemCapability.BundleManager.BundleFramework **Example** -```js +```ts let bundleName = "com.example.myapplication"; let abilityName = "com.example.myapplication.MainAbility"; bundle.getAbilityInfo(bundleName, abilityName) @@ -926,6 +1059,8 @@ getAbilityInfo(bundleName: string, abilityName: string, callback: AsyncCallback\ Obtains the ability information based on a given bundle name and ability name. This API uses an asynchronous callback to return the result. +No permission is required for obtaining the caller's own information. + **Required permissions** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -936,15 +1071,15 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------------ | ---- | ---------------- | -| bundleName | string | Yes | Bundle name of an application. | -| abilityName | string | Yes | Ability name.| +| Name | Type | Mandatory | Description | +| ----------- | ------------ | ---- |----------------------------| +| bundleName | string | Yes | Bundle name of the application. | +| abilityName | string | Yes | Ability name. | | callback | AsyncCallback\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | Callback used to return the ability information.| **Example** -```js +```ts let bundleName = "com.example.myapplication"; let abilityName = "com.example.myapplication.MainAbility"; bundle.getAbilityInfo(bundleName, abilityName, (err, data) => { @@ -964,6 +1099,8 @@ getAbilityLabel(bundleName: string, abilityName: string): Promise\ Obtains the application name based on a given bundle name and ability name. This API uses a promise to return the result. +No permission is required for obtaining the caller's own information. + **Required permissions** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -974,10 +1111,10 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------ | ---- | ---------------- | -| bundleName | string | Yes | Bundle name of an application. | -| abilityName | string | Yes | Ability name.| +| Name | Type | Mandatory | Description | +|-------------|--------|-----|------------| +| bundleName | string | Yes | Bundle name of the application. | +| abilityName | string | Yes | Ability name.| **Return value** @@ -987,7 +1124,7 @@ SystemCapability.BundleManager.BundleFramework **Example** -```js +```ts let bundleName = "com.example.myapplication"; let abilityName = "com.example.myapplication.MainAbility"; bundle.getAbilityLabel(bundleName, abilityName) @@ -1006,6 +1143,8 @@ getAbilityLabel(bundleName: string, abilityName: string, callback : AsyncCallbac Obtains the application name based on a given bundle name and ability name. This API uses an asynchronous callback to return the result. +No permission is required for obtaining the caller's own information. + **Required permissions** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -1016,15 +1155,15 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ---------------------- | ---- | ---------------- | -| bundleName | string | Yes | Bundle name of an application. | -| abilityName | string | Yes | Ability name.| -| callback | AsyncCallback\ | Yes | Callback used to return the application name. | +| Name | Type | Mandatory | Description | +|-------------|------------------------|-----|-------------------------| +| bundleName | string | Yes | Bundle name of the application. | +| abilityName | string | Yes | Ability name. | +| callback | AsyncCallback\ | Yes | Callback used to return the application name.| **Example** -```js +```ts let bundleName = "com.example.myapplication"; let abilityName = "com.example.myapplication.MainAbility"; bundle.getAbilityLabel(bundleName, abilityName, (err, data) => { @@ -1062,7 +1201,7 @@ SystemCapability.BundleManager.BundleFramework **Example** -```js +```ts let bundleName = "com.example.myapplication"; let abilityName = "com.example.myapplication.MainAbility"; bundle.getAbilityInfo(bundleName, abilityName).then((abilityInfo)=>{ @@ -1095,7 +1234,7 @@ SystemCapability.BundleManager.BundleFramework **Example** -```js +```ts let bundleName = "com.example.myapplication"; let abilityName = "com.example.myapplication.MainAbility"; bundle.getAbilityInfo(bundleName, abilityName).then((abilityInfo)=>{ @@ -1125,17 +1264,17 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | ------ | ---- | ------------------------ | -| bundleName | string | Yes | Bundle name of an application.| +| bundleName | string | Yes | Bundle name of the application.| **Return value** | Type | Description | | ----------------- | ------------------------- | -| Promise\ | Promise used to return whether the ability is enabled. If the ability is enabled, **true** will be returned; otherwise, **false** will be returned.| +| Promise\ | Promise used to return whether the application is enabled. If the application is enabled, **true** will be returned; otherwise, **false** will be returned.| **Example** -```js +```ts let bundleName = "com.example.myapplication"; bundle.isApplicationEnabled(bundleName) .then((data) => { @@ -1161,12 +1300,12 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | ----------------------- | ---- | ------------------------ | -| bundleName | string | Yes | Bundle name of an application.| -| callback | AsyncCallback\ | Yes | Callback used to return whether the ability is enabled. If the ability is enabled, **true** will be returned; otherwise, **false** will be returned. | +| bundleName | string | Yes | Bundle name of the application.| +| callback | AsyncCallback\ | Yes | Callback used to return whether the application is enabled. If the application is enabled, **true** will be returned; otherwise, **false** will be returned. | **Example** -```js +```ts let bundleName = "com.example.myapplication"; bundle.isApplicationEnabled(bundleName, (err, data) => { if (err) { @@ -1185,6 +1324,8 @@ queryAbilityByWant(want: Want, bundleFlags: number, userId?: number): Promise> | Yes | Callback used to return the ability information. | +| Name | Type | Mandatory | Description | +|-------------|---------------------------------------------------------------------|-----|-------------------------------------------------------------------------| +| want | [Want](js-apis-application-want.md) | Yes | Want that contains the bundle name. | +| bundleFlags | number | Yes | Ability information to be returned. For details about the available enumerated values, see the ability information flags in [BundleFlag](#bundleflag).| +| userId | number | Yes | User ID. The value must be greater than or equal to 0. | +| callback | AsyncCallback> | Yes | Callback used to return the ability information. | **Example** -```js +```ts let bundleFlags = 0; let userId = 100; let want = { @@ -1277,6 +1420,8 @@ queryAbilityByWant(want: Want, bundleFlags: number, callback: AsyncCallback> | Yes | Callback used to return the ability information. | +| Name | Type | Mandatory | Description | +|-------------|---------------------------------------------------------------------|-----|-------------------------------------------------------------------------| +| want | [Want](js-apis-application-want.md) | Yes | Want that contains the bundle name. | +| bundleFlags | number | Yes | Ability information to be returned. For details about the available enumerated values, see the ability information flags in [BundleFlag](#bundleflag).| +| callback | AsyncCallback> | Yes | Callback used to return the ability information. | **Example** -```js +```ts let bundleFlags = 0; let want = { bundleName : "com.example.myapplication", @@ -1332,16 +1477,16 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | ------ | ---- | ------------------------ | -| bundleName | string | Yes | Bundle name of an application.| +| bundleName | string | Yes | Bundle name of the application.| **Return value** | Type | Description | | -------------- | -------------------------------------- | -| Promise\<[Want](js-apis-application-Want.md)> | Promise used to return the **Want** object.| +| Promise\<[Want](js-apis-application-want.md)> | Promise used to return the **Want** object.| **Example** -```js +```ts let bundleName = "com.example.myapplication"; bundle.getLaunchWantForBundle(bundleName) .then((data) => { @@ -1371,12 +1516,12 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | --------------------------------------------------- | ---- | -------------------------------------------------------- | -| bundleName | string | Yes | Bundle name of an application. | -| callback | AsyncCallback\<[Want](js-apis-application-Want.md)> | Yes | Callback used to return the **Want** object.| +| bundleName | string | Yes | Bundle name of the application. | +| callback | AsyncCallback\<[Want](js-apis-application-want.md)> | Yes | Callback used to return the **Want** object.| **Example** -```js +```ts let bundleName = "com.example.myapplication"; bundle.getLaunchWantForBundle(bundleName, (err, data) => { if (err) { @@ -1413,7 +1558,7 @@ SystemCapability.BundleManager.BundleFramework **Example** -```js +```ts let uid = 20010005; bundle.getNameForUid(uid) .then((data) => { @@ -1437,14 +1582,14 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ----------------------------------------------- | -| uid | number | Yes | UID based on which the bundle name is to obtain. | +| Name | Type | Mandatory | Description | +|----------|------------------------|-----|----------------------------| +| uid | number | Yes | UID based on which the bundle name is to obtain. | | callback | AsyncCallback\ | Yes | Callback used to return the bundle name.| **Example** -```js +```ts let uid = 20010005; bundle.getNameForUid(uid, (err, data) => { if (err) { @@ -1464,6 +1609,8 @@ getAbilityIcon(bundleName: string, abilityName: string): Promise\ | Yes | Callback used to return the [pixel map](js-apis-image.md).| **Example** -```js +```ts let bundleName = "com.example.myapplication"; let abilityName = "com.example.myapplication.MainAbility"; bundle.getAbilityIcon(bundleName, abilityName, (err, data) => { @@ -1536,7 +1686,7 @@ bundle.getAbilityIcon(bundleName, abilityName, (err, data) => { ``` ## InstallErrorCodedeprecated -> This API is deprecated since API version 9. You are not advised to use it anymore. +> This API is deprecated since API version 9. You are not advised using it anymore. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -1567,7 +1717,11 @@ bundle.getAbilityIcon(bundleName, abilityName, (err, data) => { > This API is deprecated since API version 9. You are advised to use [bundleManager.BundleFlag](js-apis-bundleManager.md#bundleflag) instead. -Enumerates bundle flags. +Enumerates the bundle flags, which indicate the type of bundle information to obtain. + +If an API does not match the flag, the flag is ignored. For example, using **GET_ABILITY_INFO_WITH_PERMISSION** to obtain the application information does not affect the result. + +Flags can be used together. For example, you can use the combination of **GET_APPLICATION_INFO_WITH_PERMISSION** and **GET_APPLICATION_INFO_WITH_DISABLE** to obtain the result that contains both application permission information and disabled application information. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -1587,9 +1741,9 @@ Enumerates bundle flags. | GET_ALL_APPLICATION_INFO | 0xFFFF0000 | Obtains all application information. | ## BundleOptionsdeprecated -> This API is deprecated since API version 9. You are not advised to use it anymore. +> This API is deprecated since API version 9. You are not advised using it anymore. -Describes the bundle options. +Options that contain the user ID. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -1601,7 +1755,7 @@ Describes the bundle options. > This API is deprecated since API version 9. You are advised to use [bundleManager.AbilityType](js-apis-bundleManager.md#abilitytype) instead. -Enumerates ability types. +Enumerates the ability types. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -1630,7 +1784,7 @@ Enumerates display orientations. > This API is deprecated since API version 9. You are advised to use [bundleManager.LaunchType](js-apis-bundleManager.md#launchtype) instead. -Enumerates launch modes. +Enumerates the ability launch modes. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -1640,9 +1794,9 @@ Enumerates launch modes. | STANDARD | 1 | The ability can have multiple instances. | ## AbilitySubTypedeprecated -> This API is deprecated since API version 9. You are not advised to use it anymore. +> This API is deprecated since API version 9. You are not advised using it anymore. -Enumerates ability subtypes. +Enumerates the ability subtypes. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -1652,9 +1806,9 @@ Enumerates ability subtypes. | CA | 1 | Ability that has a UI.| ## ColorModedeprecated -> This API is deprecated since API version 9. You are not advised to use it anymore. +> This API is deprecated since API version 9. You are not advised using it anymore. -Enumerates color modes. +Enumerates the color modes of applications and widgets. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -1669,7 +1823,7 @@ Enumerates color modes. > This API is deprecated since API version 9. You are advised to use [bundleManager.PermissionGrantState](js-apis-bundleManager.md#permissiongrantstate) instead. -Enumerates permission grant states. +Enumerates the permission grant states. **System capability**: SystemCapability.BundleManager.BundleFramework diff --git a/en/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md b/en/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md index ee930acfff5313490039b5a6fe2f75d132e04234..c9cc2b79ba9aed4400fdc52bd938c5e3db711b6b 100644 --- a/en/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md @@ -1,4 +1,4 @@ -# EnterpriseAdminExtensionAbility +# @ohos.enterprise.EnterpriseAdminExtensionAbility The **EnterpriseAdminExtensionAbility** module provides Extension abilities for enterprise administrators. diff --git a/en/application-dev/reference/apis/js-apis-ability-ability.md b/en/application-dev/reference/apis/js-apis-ability-ability.md index 97294e5a37ae6213e594027721fababee9896b47..84033dd0a9d22eba5ffe275c38f078bfb0649b83 100644 --- a/en/application-dev/reference/apis/js-apis-ability-ability.md +++ b/en/application-dev/reference/apis/js-apis-ability-ability.md @@ -1,4 +1,4 @@ -# Ability +# @ohos.ability.ability The **Ability** module provides all level-2 module APIs for developers to export. @@ -37,5 +37,3 @@ let abilityResult: ability.AbilityResult; let connectOptions: ability.ConnectOptions; let startAbilityParameter: ability.StartAbilityParameter; ``` - - \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-ability-context.md b/en/application-dev/reference/apis/js-apis-ability-context.md index 40110bb6f928b5d76a9f916340cc7fce07975152..f77fd415a1bb7dd8a7d8968f96dce2718f2873ed 100644 --- a/en/application-dev/reference/apis/js-apis-ability-context.md +++ b/en/application-dev/reference/apis/js-apis-ability-context.md @@ -32,7 +32,7 @@ class MainAbility extends Ability { | -------- | -------- | -------- | -------- | -------- | | abilityInfo | AbilityInfo | Yes| No| Ability information.| | currentHapModuleInfo | HapModuleInfo | Yes| No| Information about the current HAP.| -| config | [Configuration](js-apis-configuration.md) | Yes| No| Configuration information.| +| config | [Configuration](js-apis-application-configuration.md) | Yes| No| Configuration information.| ## AbilityContext.startAbility @@ -46,15 +46,15 @@ Starts an ability. This API uses an asynchronous callback to return the result. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -95,16 +95,16 @@ Starts an ability with the start options specified. This API uses an asynchronou | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| -| options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Parameters used for starting the ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| options | [StartOptions](js-apis-application-startOptions.md) | Yes| Parameters used for starting the ability.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -148,8 +148,8 @@ Starts an ability. This API uses a promise to return the result. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| -| options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| options | [StartOptions](js-apis-application-startOptions.md) | No| Parameters used for starting the ability.| **Return value** @@ -161,8 +161,8 @@ Starts an ability. This API uses a promise to return the result. | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -206,15 +206,15 @@ Starts an ability. This API uses an asynchronous callback to return the result w | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want |[Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| -| callback | AsyncCallback<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | Yes| Callback used to return the result.| +| want |[Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| callback | AsyncCallback<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Yes| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -248,7 +248,7 @@ Starts an ability. This API uses an asynchronous callback to return the result w startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback<AbilityResult>): void; -Starts an ability with start options specified. This API uses an asynchronous callback to return the result when the ability is terminated. +Starts an ability with the start options specified. This API uses an asynchronous callback to return the result when the ability is terminated. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -256,16 +256,16 @@ Starts an ability with start options specified. This API uses an asynchronous ca | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want |[Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| -| options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Parameters used for starting the ability.| -| callback | AsyncCallback<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | Yes| Callback used to return the result.| +| want |[Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| options | [StartOptions](js-apis-application-startOptions.md) | Yes| Parameters used for starting the ability.| +| callback | AsyncCallback<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Yes| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -311,22 +311,22 @@ Starts an ability. This API uses a promise to return the result when the ability | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| -| options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| options | [StartOptions](js-apis-application-startOptions.md) | No| Parameters used for starting the ability.| **Return value** | Type| Description| | -------- | -------- | -| Promise<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | Promise used to return the result.| +| Promise<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Promise used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -373,7 +373,7 @@ Starts an ability. This API uses an asynchronous callback to return the result w | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | callback | AsyncCallback\ | Yes| Callback used to return the result.| @@ -381,8 +381,8 @@ Starts an ability. This API uses an asynchronous callback to return the result w | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -418,7 +418,7 @@ Starts an ability. This API uses an asynchronous callback to return the result w startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\): void; -Starts an ability with start options specified. This API uses an asynchronous callback to return the result when the account of the ability is destroyed. +Starts an ability with the start options specified. This API uses an asynchronous callback to return the result when the account of the ability is destroyed. **Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS @@ -430,17 +430,17 @@ Starts an ability with start options specified. This API uses an asynchronous ca | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Parameters used for starting the ability.| +| options | [StartOptions](js-apis-application-startOptions.md) | Yes| Parameters used for starting the ability.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -479,7 +479,7 @@ Starts an ability with start options specified. This API uses an asynchronous ca startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\; -Starts an ability with start options specified. This API uses a promise to return the result when the account of the ability is destroyed. +Starts an ability with the start options specified. This API uses a promise to return the result when the account of the ability is destroyed. **Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS @@ -491,9 +491,9 @@ Starts an ability with start options specified. This API uses a promise to retur | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.| +| options | [StartOptions](js-apis-application-startOptions.md) | No| Parameters used for starting the ability.| **Return value** @@ -505,8 +505,8 @@ Starts an ability with start options specified. This API uses a promise to retur | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -553,15 +553,15 @@ Starts a new Service Extension ability. This API uses an asynchronous callback t | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -604,14 +604,14 @@ Starts a new Service Extension ability. This API uses a promise to return the re | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -656,7 +656,7 @@ Starts a new Service Extension ability with the account ID specified. This API u | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | callback | AsyncCallback\ | Yes| Callback used to return the result.| @@ -664,8 +664,8 @@ Starts a new Service Extension ability with the account ID specified. This API u | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -711,15 +711,15 @@ Starts a new Service Extension ability with the account ID specified. This API u | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -762,15 +762,15 @@ Stops a Service Extension ability in the same application. This API uses an asyn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -813,14 +813,14 @@ Stops a Service Extension ability in the same application. This API uses a promi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -865,7 +865,7 @@ Stops a Service Extension ability in the same application with the account ID sp | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | callback | AsyncCallback\ | Yes| Callback used to return the result.| @@ -873,8 +873,8 @@ Stops a Service Extension ability in the same application with the account ID sp | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -920,15 +920,15 @@ Stops a Service Extension ability in the same application with the account ID sp | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -976,8 +976,8 @@ Terminates this ability. This API uses an asynchronous callback to return the re | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -1013,8 +1013,8 @@ Terminates this ability. This API uses a promise to return the result. | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -1042,15 +1042,15 @@ Terminates this ability. This API uses an asynchronous callback to return the ab | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| parameter | [AbilityResult](js-apis-featureAbility.md#abilityresult) | Yes| Information returned to the caller.| +| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes| Information returned to the caller.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -1097,7 +1097,7 @@ Terminates this ability. This API uses a promise to return the ability result in | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| parameter | [AbilityResult](js-apis-featureAbility.md#abilityresult) | Yes| Information returned to the caller.| +| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes| Information returned to the caller.| **Return value** @@ -1109,8 +1109,8 @@ Terminates this ability. This API uses a promise to return the ability result in | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -1153,12 +1153,14 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| -| options | [ConnectOptions](js-apis-featureAbility.md#connectoptions) | Yes| Parameters for the connection.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes| Parameters for the connection.| **Return value** @@ -1170,8 +1172,8 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -1214,9 +1216,9 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| options | [ConnectOptions](js-apis-featureAbility.md#connectoptions) | Yes| Parameters for the connection.| +| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes| Parameters for the connection.| **Return value** @@ -1228,8 +1230,8 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -1280,13 +1282,13 @@ Disconnects a connection. This API uses a promise to return the result. | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts - // connection is the return value of connectAbility. + // connection is the return value of connectServiceExtensionAbility. var connection = 1; try { @@ -1326,8 +1328,8 @@ Disconnects a connection. This API uses an asynchronous callback to return the r | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -1367,7 +1369,7 @@ Starts an ability in the foreground or background and obtains the caller object | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the ability to start, including **abilityName**, **moduleName**, **bundleName**, **deviceId** (optional), and **parameters** (optional). If **deviceId** is left blank or null, the local ability is started. If **parameters** is left blank or null, the ability is started in the background.| +| want | [Want](js-apis-application-want.md) | Yes| Information about the ability to start, including **abilityName**, **moduleName**, **bundleName**, **deviceId** (optional), and **parameters** (optional). If **deviceId** is left blank or null, the local ability is started. If **parameters** is left blank or null, the ability is started in the background.| **Return value** @@ -1458,7 +1460,7 @@ Starts an ability with the account ID specified. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | callback | AsyncCallback\ | Yes| Callback used to return the result.| @@ -1466,8 +1468,8 @@ Starts an ability with the account ID specified. This API uses an asynchronous c | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -1514,17 +1516,17 @@ Starts an ability with the account ID and start options specified. This API uses | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Parameters used for starting the ability.| +| options | [StartOptions](js-apis-application-startOptions.md) | Yes| Parameters used for starting the ability.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -1574,16 +1576,16 @@ Starts an ability with the account ID specified. This API uses a promise to retu | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Parameters used for starting the ability.| +| options | [StartOptions](js-apis-application-startOptions.md) | No| Parameters used for starting the ability.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -1629,7 +1631,7 @@ Requests permissions from the user by displaying a dialog box. This API uses an | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | permissions | Array<string> | Yes| Permissions to request.| -| callback | AsyncCallback<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Yes| Callback used to return the result.| +| callback | AsyncCallback<[PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md)> | Yes| Callback used to return the result.| **Example** @@ -1660,7 +1662,7 @@ Requests permissions from the user by displaying a dialog box. This API uses a p | Type| Description| | -------- | -------- | -| Promise<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Promise used to return the result.| +| Promise<[PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md)> | Promise used to return the result.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-DataUriUtils.md b/en/application-dev/reference/apis/js-apis-ability-dataUriUtils.md similarity index 90% rename from en/application-dev/reference/apis/js-apis-DataUriUtils.md rename to en/application-dev/reference/apis/js-apis-ability-dataUriUtils.md index 18cfa0cdc0c54ea8e8aa85fc43fcf61b3d63fc7a..108345299ae8e55e185b6d33df259400afe2dada 100644 --- a/en/application-dev/reference/apis/js-apis-DataUriUtils.md +++ b/en/application-dev/reference/apis/js-apis-ability-dataUriUtils.md @@ -1,6 +1,6 @@ -# DataUriUtils +# @ohos.ability.dataUriUtils -The **DataUriUtils** module provides APIs to handle utility classes for objects using the **DataAbilityHelper** schema. You can use the APIs to attach an ID to the end of a given URI and obtain, delete, or update the ID attached to the end of a given URI. +The **DataUriUtils** module provides APIs to handle utility classes for objects using the **DataAbilityHelper** schema. You can use the APIs to attach an ID to the end of a given URI and obtain, delete, or update the ID attached to the end of a given URI. This module will be replaced by the **app.ability.dataUriUtils** module in the near future. You are advised to use the **[@ohos.app.ability.dataUriUtils](js-apis-app-ability-dataUriUtils.md)** module. > **NOTE** > @@ -8,7 +8,7 @@ The **DataUriUtils** module provides APIs to handle utility classes for objects ## Modules to Import -```js +```ts import dataUriUtils from '@ohos.ability.dataUriUtils'; ``` @@ -34,7 +34,7 @@ Obtains the ID attached to the end of a given URI. **Example** -```js +```ts dataUriUtils.getId("com.example.dataUriUtils/1221") ``` @@ -63,7 +63,7 @@ Attaches an ID to the end of a given URI. **Example** -```js +```ts var idint = 1122; dataUriUtils.attachId( "com.example.dataUriUtils", @@ -95,12 +95,10 @@ Deletes the ID from the end of a given URI. **Example** -```js +```ts dataUriUtils.deleteId("com.example.dataUriUtils/1221") ``` - - ## dataUriUtils.updateId updateId(uri: string, id: number): string @@ -124,7 +122,7 @@ Updates the ID in a given URI. **Example** -```js +```ts var idint = 1122; dataUriUtils.updateId( "com.example.dataUriUtils", diff --git a/en/application-dev/reference/apis/js-apis-ability-errorCode.md b/en/application-dev/reference/apis/js-apis-ability-errorCode.md index 6a131521d3c447cfb2df65b53a592c5be89678be..c6e16f3f0cbe2bd0dd18dd5ea7fd72c8a0f44fb7 100644 --- a/en/application-dev/reference/apis/js-apis-ability-errorCode.md +++ b/en/application-dev/reference/apis/js-apis-ability-errorCode.md @@ -1,14 +1,14 @@ -# ErrorCode +# @ohos.ability.errorCode -The **ErrorCode** module defines the error codes that can be used when the ability is started. +The **ErrorCode** module defines the error codes that can be used when the ability is started. + + **NOTE** -> **NOTE** -> > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -``` +```ts import errorCode from '@ohos.ability.errorCode' ``` diff --git a/en/application-dev/reference/apis/js-apis-featureAbility.md b/en/application-dev/reference/apis/js-apis-ability-featureAbility.md similarity index 79% rename from en/application-dev/reference/apis/js-apis-featureAbility.md rename to en/application-dev/reference/apis/js-apis-ability-featureAbility.md index 66999a98279dc43aa0fee542883a6ed70ad5ee8d..2f1b927b6191b6b87b649f1b4a85067deb705541 100644 --- a/en/application-dev/reference/apis/js-apis-featureAbility.md +++ b/en/application-dev/reference/apis/js-apis-ability-featureAbility.md @@ -1,4 +1,4 @@ -# FeatureAbility +# @ohos.ability.featureAbility The **FeatureAbility** module provides a UI for interacting with users. You can use APIs of this module to start a new ability, obtain the **dataAbilityHelper**, set a Page ability, obtain the window corresponding to this ability, and connect to a Service ability. @@ -13,7 +13,7 @@ APIs of the **FeatureAbility** module can be called only by Page abilities. ## Modules to Import -``` +```ts import featureAbility from '@ohos.ability.featureAbility'; ``` @@ -29,12 +29,12 @@ Starts an ability. This API uses an asynchronous callback to return the result. | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------------- | -| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| +| parameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | Yes | Ability to start.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** -```javascript +```ts import featureAbility from '@ohos.ability.featureAbility'; import wantConstant from '@ohos.ability.wantConstant'; featureAbility.startAbility( @@ -72,11 +72,11 @@ Starts an ability. This API uses a promise to return the result. | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------------- | -| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| +| parameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | Yes | Ability to start.| **Example** -```javascript +```ts import featureAbility from '@ohos.ability.featureAbility'; import wantConstant from '@ohos.ability.wantConstant'; featureAbility.startAbility( @@ -121,7 +121,7 @@ Obtains a **dataAbilityHelper** object. **Example** -```javascript +```ts import featureAbility from '@ohos.ability.featureAbility'; var dataAbilityHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" @@ -140,12 +140,12 @@ Starts an ability. This API uses an asynchronous callback to return the executio | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------------- | -| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| -| callback | AsyncCallback\<[AbilityResult](#abilityresult)> | Yes | Callback used to return the result. | +| parameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | Yes | Ability to start.| +| callback | AsyncCallback\<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Yes | Callback used to return the result. | **Example** -```javascript +```ts import featureAbility from '@ohos.ability.featureAbility'; import wantConstant from '@ohos.ability.wantConstant'; featureAbility.startAbilityForResult( @@ -181,17 +181,17 @@ Starts an ability. This API uses a promise to return the execution result when t | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | ------------- | -| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| +| parameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | Yes | Ability to start.| **Return value** | Type | Description | | ---------------------------------------- | ------- | -| Promise\<[AbilityResult](#abilityresult)> | Promised returned with the execution result.| +| Promise\<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Promised returned with the execution result.| **Example** -```javascript +```ts import featureAbility from '@ohos.ability.featureAbility'; import wantConstant from '@ohos.ability.wantConstant'; featureAbility.startAbilityForResult( @@ -237,12 +237,12 @@ Destroys this Page ability, with the result code and data sent to the caller. Th | Name | Type | Mandatory | Description | | --------- | ------------------------------- | ---- | -------------- | -| parameter | [AbilityResult](#abilityresult) | Yes | Ability to destroy.| +| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes | Ability to start.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** -```javascript +```ts import featureAbility from '@ohos.ability.featureAbility'; import wantConstant from '@ohos.ability.wantConstant'; featureAbility.terminateSelfWithResult( @@ -289,7 +289,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th | Name | Type | Mandatory | Description | | --------- | ------------------------------- | ---- | ------------- | -| parameter | [AbilityResult](#abilityresult) | Yes | Ability to destroy.| +| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes | Ability to start.| **Return value** @@ -299,7 +299,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th **Example** -```javascript +```ts import featureAbility from '@ohos.ability.featureAbility'; import wantConstant from '@ohos.ability.wantConstant'; featureAbility.terminateSelfWithResult( @@ -349,7 +349,7 @@ Checks whether the main window of this ability has the focus. This API uses an a **Example** -```javascript +```ts import featureAbility from '@ohos.ability.featureAbility'; featureAbility.hasWindowFocus((err, data) => { console.info("hasWindowFocus err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); @@ -372,7 +372,7 @@ Checks whether the main window of this ability has the focus. This API uses a pr **Example** -```javascript +```ts import featureAbility from '@ohos.ability.featureAbility'; featureAbility.hasWindowFocus().then((data) => { console.info("hasWindowFocus data: " + JSON.stringify(data)); @@ -391,11 +391,11 @@ Obtains the **Want** object sent from this ability. This API uses an asynchronou | Name | Type | Mandatory | Description | | -------- | ----------------------------- | ---- | --------- | -| callback | AsyncCallback\<[Want](js-apis-application-Want.md)> | Yes | Callback used to return the result.| +| callback | AsyncCallback\<[Want](js-apis-application-want.md)> | Yes | Callback used to return the result.| **Example** -```javascript +```ts import featureAbility from '@ohos.ability.featureAbility'; featureAbility.getWant((err, data) => { console.info("getWant err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); @@ -414,11 +414,11 @@ Obtains the **Want** object sent from this ability. This API uses a promise to r | Type | Description | | ----------------------- | ---------------- | -| Promise\<[Want](js-apis-application-Want.md)> | Promise used to return the result.| +| Promise\<[Want](js-apis-application-want.md)> | Promise used to return the result.| **Example** -```javascript +```ts import featureAbility from '@ohos.ability.featureAbility'; featureAbility.getWant().then((data) => { console.info("getWant data: " + JSON.stringify(data)); @@ -441,7 +441,7 @@ Obtains the application context. **Example** -```javascript +```ts import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext() context.getBundleName((err, data) => { @@ -465,7 +465,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th **Example** -```javascript +```ts import featureAbility from '@ohos.ability.featureAbility'; featureAbility.terminateSelf( (err) => { @@ -490,7 +490,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th **Example** -```javascript +```ts import featureAbility from '@ohos.ability.featureAbility'; featureAbility.terminateSelf().then((data) => { console.info("==========================>terminateSelf=======================>"); @@ -509,20 +509,8 @@ Connects this ability to a specific Service ability. This API uses an asynchrono | Name | Type | Mandatory | Description | | ------- | -------------- | ---- | --------------------- | -| request | [Want](js-apis-application-Want.md) | Yes | Service ability to connect.| -| options | [ConnectOptions](#connectoptions) | Yes | Callback used to return the result. | - -## ConnectOptions - -Describes the connection options. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name | Readable|Writable| Type | Mandatory | Description | -| ------------ | -- | -- | -------- | ---- | ------------------------- | -| onConnect7+ | Yes|No | function | Yes | Callback invoked when the connection is successful. | -| onDisconnect7+ | Yes|No | function | Yes | Callback invoked when the connection fails. | -| onFailed7+ | Yes|No | function | Yes | Callback invoked when **connectAbility** fails to be called.| +| request | [Want](js-apis-application-want.md) | Yes | Service ability to connect.| +| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes | Callback used to return the result. | **Return value** @@ -532,7 +520,7 @@ Describes the connection options. **Example** -```javascript +```ts import rpc from '@ohos.rpc'; import featureAbility from '@ohos.ability.featureAbility'; function onConnectCallback(element, remote){ @@ -575,7 +563,7 @@ Disconnects this ability from a specific Service ability. This API uses an async **Example** -```javascript +```ts import rpc from '@ohos.rpc'; import featureAbility from '@ohos.ability.featureAbility'; function onConnectCallback(element, remote){ @@ -627,7 +615,7 @@ Disconnects this ability from a specific Service ability. This API uses a promis **Example** -```javascript +```ts import rpc from '@ohos.rpc'; import featureAbility from '@ohos.ability.featureAbility'; function onConnectCallback(element, remote){ @@ -675,7 +663,7 @@ Obtains the window corresponding to this ability. This API uses an asynchronous **Example** -```javascript +```ts featureAbility.getWindow((err, data) => { console.info("getWindow err: " + JSON.stringify(err) + "data: " + typeof(data)); }); @@ -697,143 +685,12 @@ Obtains the window corresponding to this ability. This API uses a promise to ret **Example** -```javascript +```ts featureAbility.getWindow().then((data) => { console.info("getWindow data: " + typeof(data)); }); ``` -## ConnectOptions.onConnect7+ - -onConnect(elementName: ElementName, remote: rpc.IRemoteObject): void; - -Callback invoked when the connection is successful. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ----------- | ----------------- | ---- | -------- | -| elementName | ElementName | Yes | Element name. | -| remote | rpc.IRemoteObject | Yes | RPC remote object.| - -**Example** - -```javascript -import rpc from '@ohos.rpc'; -import featureAbility from '@ohos.ability.featureAbility'; -function onConnectCallback(element, remote){ - console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); -} -function onDisconnectCallback(element){ - console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) -} -function onFailedCallback(code){ - console.log('featureAbilityTest ConnectAbility onFailed errCode : ' + code) -} -var connectId = featureAbility.connectAbility( - { - deviceId: "", - bundleName: "com.ix.ServiceAbility", - abilityName: "ServiceAbilityA", - }, - { - onConnect: onConnectCallback, - onDisconnect: onDisconnectCallback, - onFailed: onFailedCallback, - }, -); -``` - -## ConnectOptions.onDisconnect7+ - -onDisconnect(elementName: ElementName): void; - -Callback invoked when the connection fails. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ----------- | ----------- | ---- | ---- | -| elementName | ElementName | Yes | Element name.| - -**Example** - -```javascript -import rpc from '@ohos.rpc'; -import featureAbility from '@ohos.ability.featureAbility'; -function onConnectCallback(element, remote){ - console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); -} -function onDisconnectCallback(element){ - console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) -} -function onFailedCallback(code){ - console.log('featureAbilityTest ConnectAbility onFailed errCode : ' + code) -} -var connectId = featureAbility.connectAbility( - { - deviceId: "", - bundleName: "com.ix.ServiceAbility", - abilityName: "ServiceAbilityA", - }, - { - onConnect: onConnectCallback, - onDisconnect: onDisconnectCallback, - onFailed: onFailedCallback, - }, -); -``` - -## ConnectOptions.onFailed7+ - -onFailed(code: number): void; - -Callback invoked when **connectAbility** fails to be called. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | --------- | -| code | number | Yes | Number type.| - -**Example** - -```javascript -import rpc from '@ohos.rpc'; -import featureAbility from '@ohos.ability.featureAbility'; -function onConnectCallback(element, remote){ - console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); -} -function onDisconnectCallback(element){ - console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) -} -function onFailedCallback(code){ - console.log('featureAbilityTest ConnectAbility onFailed errCode : ' + code) -} -var connectId = featureAbility.connectAbility( - { - deviceId: "", - bundleName: "com.ix.ServiceAbility", - abilityName: "ServiceAbilityA", - }, - { - onConnect: onConnectCallback, - onDisconnect: onDisconnectCallback, - onFailed: onFailedCallback, - }, -); -``` - - - - - ## AbilityWindowConfiguration The value is obtained through the **featureAbility.AbilityWindowConfiguration** API. @@ -902,26 +759,6 @@ Enumerates operation types of the Data ability. | TYPE_DELETE7+ | 3 | Deletion operation.| | TYPE_ASSERT7+ | 4 | Assert operation.| - - -## AbilityResult - -**System capability**: SystemCapability.Ability.AbilityBase - -| Name | Type | Readable| Writable | Mandatory | Description | -| --------------- |-------- | ------ | ------------- | ---- | ------------------------------------- | -| resultCode7+| number| Yes | No | Yes | Result code returned after the ability is destroyed. The feature for defining error-specific result codes is coming soon.| -| want7+ | [Want](js-apis-application-Want.md)| Yes | No| No | Data returned after the ability is destroyed. You can define the data to be returned. This parameter can be **null**. | - -## StartAbilityParameter - -**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel - -| Name | Type | Readable| Writable | Mandatory | Description | -| ------------------- | -------- | -------------------- | ---- | -------------------------------------- | -| want | [Want](js-apis-application-Want.md)| Yes | No | Yes | Information about the ability to start. | -| abilityStartSetting | {[key: string]: any} | Yes |No | No | Special attribute of the ability to start. This attribute can be passed in the method call.| - ## flags **System capability**: SystemCapability.Ability.AbilityBase diff --git a/en/application-dev/reference/apis/js-apis-particleAbility.md b/en/application-dev/reference/apis/js-apis-ability-particleAbility.md similarity index 75% rename from en/application-dev/reference/apis/js-apis-particleAbility.md rename to en/application-dev/reference/apis/js-apis-ability-particleAbility.md index 75b6378962fb1f3c25bcf7e12a0a2df20a151628..46355b926228755520d3d215d4275af03ecd88bc 100644 --- a/en/application-dev/reference/apis/js-apis-particleAbility.md +++ b/en/application-dev/reference/apis/js-apis-ability-particleAbility.md @@ -1,4 +1,4 @@ -# particleAbility +# @ohos.ability.particleAbility The **particleAbility** module provides APIs for Service abilities. You can use the APIs to start and terminate a Particle ability, obtain a **dataAbilityHelper** object, connect the current ability to a specific Service ability, and disconnect the current ability from a specific Service ability. @@ -13,7 +13,7 @@ The ParticleAbility module is used to perform operations on abilities of the Dat ## Modules to Import -```js +```ts import particleAbility from '@ohos.ability.particleAbility' ``` @@ -27,19 +27,19 @@ Starts a Particle ability. This API uses an asynchronous callback to return the **Parameters** - | Name | Type | Mandatory| Description | | --------- | ----------------------------------------------- | ---- | ----------------- | -| parameter | [StartAbilityParameter](js-apis-featureAbility.md#startabilityparameter) | Yes | Ability to start.| +| parameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | Yes | Ability to start.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** -```js +```ts import particleAbility from '@ohos.ability.particleAbility' import wantConstant from '@ohos.ability.wantConstant' + particleAbility.startAbility( - { + { want: { action: "action.system.home", @@ -49,17 +49,15 @@ particleAbility.startAbility( deviceId: "", bundleName: "com.example.Data", abilityName: "com.example.Data.MainAbility", - uri:"" + uri: "" }, }, (error, result) => { - console.log('particleAbility startAbility errCode:' + error + 'result:' + result) + console.log('particleAbility startAbility errCode:' + error + 'result:' + result) }, ) ``` - - ## particleAbility.startAbility startAbility(parameter: StartAbilityParameter): Promise\; @@ -70,10 +68,9 @@ Starts a Particle ability. This API uses a promise to return the result. **Parameters** - | Name | Type | Mandatory| Description | | --------- | ----------------------------------------------- | ---- | ----------------- | -| parameter | [StartAbilityParameter](js-apis-featureAbility.md#startabilityparameter) | Yes | Ability to start.| +| parameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | Yes | Ability to start.| **Return value** @@ -83,11 +80,12 @@ Starts a Particle ability. This API uses a promise to return the result. **Example** -```js +```ts import particleAbility from '@ohos.ability.particleAbility' import wantConstant from '@ohos.ability.wantConstant' + particleAbility.startAbility( - { + { want: { action: "action.system.home", @@ -97,7 +95,7 @@ particleAbility.startAbility( deviceId: "", bundleName: "com.example.Data", abilityName: "com.example. Data.MainAbility", - uri:"" + uri: "" }, }, ).then((data) => { @@ -105,8 +103,6 @@ particleAbility.startAbility( }); ``` - - ## particleAbility.terminateSelf terminateSelf(callback: AsyncCallback\): void @@ -123,17 +119,16 @@ Terminates this Particle ability. This API uses an asynchronous callback to retu **Example** -```js +```ts import particleAbility from '@ohos.ability.particleAbility' + particleAbility.terminateSelf( (error, result) => { - console.log('particleAbility terminateSelf errCode:' + error + 'result:' + result) + console.log('particleAbility terminateSelf errCode:' + error + 'result:' + result) } ) ``` - - ## particleAbility.terminateSelf terminateSelf(): Promise\ @@ -150,8 +145,9 @@ Terminates this Particle ability. This API uses a promise to return the result. **Example** -```js +```ts import particleAbility from '@ohos.ability.particleAbility' + particleAbility.terminateSelf().then((data) => { console.info("particleAbility terminateSelf"); }); @@ -181,8 +177,9 @@ Obtains a **dataAbilityHelper** object. **Example** -```js -import particleAbility from '@ohos.ability.particleAbility' +```ts +import particleAbility from '@ohos.ability.particleAbility' + var uri = ""; particleAbility.acquireDataAbilityHelper(uri) ``` @@ -208,7 +205,7 @@ Requests a continuous task from the system. This API uses an asynchronous callba **Example** -```js +```ts import notification from '@ohos.notification'; import particleAbility from '@ohos.ability.particleAbility'; import wantAgent from '@ohos.wantAgent'; @@ -277,7 +274,7 @@ Requests a continuous task from the system. This API uses a promise to return th **Example** -```js +```ts import notification from '@ohos.notification'; import particleAbility from '@ohos.ability.particleAbility'; import wantAgent from '@ohos.wantAgent'; @@ -333,7 +330,7 @@ Requests to cancel a continuous task from the system. This API uses an asynchron **Example** -```js +```ts import particleAbility from '@ohos.ability.particleAbility'; function callback(err, data) { @@ -364,7 +361,7 @@ Requests a continuous task from the system. This API uses a promise to return th **Example** -```js +```ts import particleAbility from '@ohos.ability.particleAbility'; particleAbility.cancelBackgroundRunning().then(() => { @@ -375,7 +372,6 @@ particleAbility.cancelBackgroundRunning().then(() => { ``` - ## particleAbility.connectAbility connectAbility(request: Want, options:ConnectOptions): number @@ -388,7 +384,7 @@ Connects this ability to a specific Service ability. This API uses a callback to | Name | Type | Mandatory| Description | | ------- | -------------- | ---- | ---------------------------- | -| request | [Want](js-apis-application-Want.md) | Yes | Service ability to connect.| +| request | [Want](js-apis-application-want.md) | Yes | Service ability to connect.| | options | ConnectOptions | Yes | Callback used to return the result. | @@ -396,46 +392,48 @@ ConnectOptions **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name | Readable/Writable| Type | Mandatory | Description | -| ------------ | ---- | -------- | ---- | ------------------------- | -| onConnect | Read only | function | Yes | Callback invoked when the connection is successful. | -| onDisconnect | Read only | function | Yes | Callback invoked when the connection fails. | -| onFailed | Read only | function | Yes | Callback invoked when **connectAbility** fails to be called.| +| Name | Type | Mandatory | Description | +| ------------ | -------- | ---- | ------------------------- | +| onConnect | function | Yes | Callback invoked when the connection is successful. | +| onDisconnect | function | Yes | Callback invoked when the connection fails. | +| onFailed | function | Yes | Callback invoked when **connectAbility** fails to be called.| **Example** -```js - import rpc from '@ohos.rpc' - function onConnectCallback(element, remote){ - console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); - } - function onDisconnectCallback(element){ - console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) - } - function onFailedCallback(code){ - console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code) - } - var connId = particleAbility.connectAbility( - { - bundleName: "com.ix.ServiceAbility", - abilityName: "ServiceAbilityA", - }, - { - onConnect: onConnectCallback, - onDisconnect: onDisconnectCallback, - onFailed: onFailedCallback, - }, - ); - - particleAbility.disconnectAbility(connId).then((data)=>{ - console.log( " data: " + data); - }).catch((error)=>{ - console.log('particleAbilityTest result errCode : ' + error.code ) - }); - +```ts +import rpc from '@ohos.rpc' -``` +function onConnectCallback(element, remote) { + console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); +} + +function onDisconnectCallback(element) { + console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) +} + +function onFailedCallback(code) { + console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code) +} + +var connId = particleAbility.connectAbility( + { + bundleName: "com.ix.ServiceAbility", + abilityName: "ServiceAbilityA", + }, + { + onConnect: onConnectCallback, + onDisconnect: onDisconnectCallback, + onFailed: onFailedCallback, + }, +); +particleAbility.disconnectAbility(connId).then((data) => { + console.log(" data: " + data); +}).catch((error) => { + console.log('particleAbilityTest result errCode : ' + error.code) +}); + +``` ## particleAbility.disconnectAbility @@ -453,34 +451,37 @@ Disconnects this ability from the Service ability. This API uses a callback to r **Example** -```js +```ts import rpc from '@ohos.rpc' - function onConnectCallback(element, remote){ - console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); - } - function onDisconnectCallback(element){ - console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) - } - function onFailedCallback(code){ - console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code) - } - var connId = particleAbility.connectAbility( - { - bundleName: "com.ix.ServiceAbility", - abilityName: "ServiceAbilityA", - }, - { - onConnect: onConnectCallback, - onDisconnect: onDisconnectCallback, - onFailed: onFailedCallback, - }, - ); - var result = particleAbility.disconnectAbility(connId).then((data)=>{ - console.log( " data: " + data); - }).catch((error)=>{ - console.log('particleAbilityTest result errCode : ' + error.code ) - }); +function onConnectCallback(element, remote) { + console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); +} + +function onDisconnectCallback(element) { + console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) +} + +function onFailedCallback(code) { + console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code) +} + +var connId = particleAbility.connectAbility( + { + bundleName: "com.ix.ServiceAbility", + abilityName: "ServiceAbilityA", + }, + { + onConnect: onConnectCallback, + onDisconnect: onDisconnectCallback, + onFailed: onFailedCallback, + }, +); +var result = particleAbility.disconnectAbility(connId).then((data) => { + console.log(" data: " + data); +}).catch((error) => { + console.log('particleAbilityTest result errCode : ' + error.code) +}); ``` @@ -500,34 +501,38 @@ Disconnects this ability from the Service ability. This API uses a promise to re **Example** -```js +```ts import rpc from '@ohos.rpc' -function onConnectCallback(element, remote){ - console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); - } - function onDisconnectCallback(element){ - console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) - } - function onFailedCallback(code){ - console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code) - } - var connId = particleAbility.connectAbility( - { - bundleName: "com.ix.ServiceAbility", - abilityName: "ServiceAbilityA", - }, - { - onConnect: onConnectCallback, - onDisconnect: onDisconnectCallback, - onFailed: onFailedCallback, - }, - ); - - particleAbility.disconnectAbility(connId).then((data)=>{ - console.log( " data: " + data); - }).catch((error)=>{ - console.log('particleAbilityTest result errCode : ' + error.code ) - }); + +function onConnectCallback(element, remote) { + console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); +} + +function onDisconnectCallback(element) { + console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) +} + +function onFailedCallback(code) { + console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code) +} + +var connId = particleAbility.connectAbility( + { + bundleName: "com.ix.ServiceAbility", + abilityName: "ServiceAbilityA", + }, + { + onConnect: onConnectCallback, + onDisconnect: onDisconnectCallback, + onFailed: onFailedCallback, + }, +); + +particleAbility.disconnectAbility(connId).then((data) => { + console.log(" data: " + data); +}).catch((error) => { + console.log('particleAbilityTest result errCode : ' + error.code) +}); ``` diff --git a/en/application-dev/reference/apis/js-apis-ability-wantConstant.md b/en/application-dev/reference/apis/js-apis-ability-wantConstant.md index 4b1a66f071f464d6662d8429606c48aa025e8ef6..30fb8b3b970b22513f2dd520d43a11b76f66e47d 100644 --- a/en/application-dev/reference/apis/js-apis-ability-wantConstant.md +++ b/en/application-dev/reference/apis/js-apis-ability-wantConstant.md @@ -1,14 +1,14 @@ -# wantConstant +# @ohos.ability.wantConstant The **wantConstant** module provides the actions, entities, and flags used in **Want** objects. > **NOTE** > -> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported since API version 6 and deprecated since API version 9. You are advised to use [@ohos.app.ability.wantConstant](js-apis-app-ability-wantConstant.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -```js +```ts import wantConstant from '@ohos.ability.wantConstant'; ``` @@ -46,6 +46,7 @@ Enumerates the action constants of the **Want** object. | ACTION_FILE_SELECT7+ | ohos.action.fileSelect | Action of selecting a file. | | PARAMS_STREAM7+ | ability.params.stream | URI of the data stream associated with the target when the data is sent. | | ACTION_APP_ACCOUNT_OAUTH 8+ | ohos.account.appAccount.action.oauth | Action of providing the OAuth service. | +| ACTION_APP_ACCOUNT_AUTH 9+ | account.appAccount.action.auth | Action of providing the authentication service. | | ACTION_MARKET_DOWNLOAD 9+ | ohos.want.action.marketDownload | Action of downloading an application from the application market.
**System API**: This is a system API and cannot be called by third-party applications. | | ACTION_MARKET_CROWDTEST 9+ | ohos.want.action.marketCrowdTest | Action of crowdtesting an application from the application market.
**System API**: This is a system API and cannot be called by third-party applications. | | DLP_PARAMS_SANDBOX9+ |ohos.dlp.params.sandbox | Action of obtaining the sandbox flag.
**System API**: This is a system API and cannot be called by third-party applications. | diff --git a/en/application-dev/reference/apis/js-apis-accessibility-GesturePath.md b/en/application-dev/reference/apis/js-apis-accessibility-GesturePath.md new file mode 100644 index 0000000000000000000000000000000000000000..34d4df8dd99bb528ae79d8d13de74f491f75f3db --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-accessibility-GesturePath.md @@ -0,0 +1,46 @@ +# @ohos.accessibility.GesturePath + + The **GesturePath** module provides APIs for creating gesture path information required for an accessibility application to inject gestures. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```ts +import GesturePath from '@ohos.accessibility.GesturePath'; +``` + +## GesturePath + +Defines a gesture path. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +### Attributes + +| Name | Type | Readable | Writable | Description | +| ------------ | ---------------------------------------- | ---- | ---- | ------ | +| points | Array<[GesturePoint](js-apis-accessibility-GesturePoint.md#gesturepoint)> | Yes | Yes | Gesture touch point. | +| durationTime | number | Yes | Yes | Total gesture duration, in milliseconds.| + +### constructor + +constructor(durationTime: number); + +Constructor used to create a **GesturePath** object. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| durationTime | number | Yes| Total gesture duration, in milliseconds.| + +**Example** + +```ts +let gesturePath = new GesturePath.GesturePath(20); +``` diff --git a/en/application-dev/reference/apis/js-apis-accessibility-GesturePoint.md b/en/application-dev/reference/apis/js-apis-accessibility-GesturePoint.md new file mode 100644 index 0000000000000000000000000000000000000000..5792c44cd9fc89cf495e943a4e40463ce89281c4 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-accessibility-GesturePoint.md @@ -0,0 +1,47 @@ +# @ohos.accessibility.GesturePoint + + The **GesturePoint** module provides APIs for creating gesture touch point information required for an accessibility application to inject gestures. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```ts +import GesturePoint from '@ohos.accessibility.GesturePoint'; +``` + +## GesturePoint + +Defines a gesture touch point. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +### Attributes + +| Name | Type | Readable | Writable | Description | +| --------- | ------ | ---- | ---- | ------- | +| positionX | number | Yes | Yes | X coordinate of the touch point.| +| positionY | number | Yes | Yes | Y coordinate of the touch point.| + +### constructor + +constructor(positionX: number, positionY: number); + +Constructor used to create a **GesturePoint** object. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| positionX | number | Yes| X coordinate of the touch point.| +| positionY | number | Yes | Y coordinate of the touch point.| + +**Example** + +```ts +let gesturePoint = new GesturePoint.GesturePoint(1, 2); +``` diff --git a/en/application-dev/reference/apis/js-apis-accessibility-config.md b/en/application-dev/reference/apis/js-apis-accessibility-config.md index c33230f7181ce92a50cee6c1417eb5d71a124f68..33b6f586279309125be085e8a28d5423b271fae3 100644 --- a/en/application-dev/reference/apis/js-apis-accessibility-config.md +++ b/en/application-dev/reference/apis/js-apis-accessibility-config.md @@ -1,17 +1,16 @@ -# System Accessibility Configuration +# @ohos.accessibility.config -The **config** module allows you to configure system accessibility features, including accessibility extension, high-contrast text, mouse buttons, and captions. +The System Accessibility Configuration module allows you to configure system accessibility features, including accessibility extension, high-contrast text, mouse buttons, and captions. > **NOTE** > -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> -> The APIs provided by this module are system APIs. +> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs provided by this module are system APIs. ## Modules to Import -```typescript -import config from "@ohos.accessibility.config"; +```ts +import config from '@ohos.accessibility.config'; ``` ## Attributes @@ -22,20 +21,20 @@ import config from "@ohos.accessibility.config"; | -------- | -------- | -------- | -------- | -------- | | highContrastText | [Config](#config)\| Yes| Yes| Whether to enable high-contrast text.| | invertColor | [Config](#config)\| Yes| Yes| Whether to enable color inversion.| -| daltonizationColorFilter | [Config](#config)\<[DaltonizationColorFilter](#daltonizationcolorfilter)>| Yes| Yes| Daltonization filter. | +| daltonizationColorFilter | [Config](#config)<[DaltonizationColorFilter](#daltonizationcolorfilter)>| Yes| Yes| Configuration of the daltonization filter.| | contentTimeout | [Config](#config)\| Yes| Yes| Recommended duration for content display. The value ranges from 0 to 5000, in milliseconds.| -| animationOff | [Config](#config)\| Yes| Yes| Whether to enable animation.| +| animationOff | [Config](#config)\| Yes| Yes| Whether to disable animation.| | brightnessDiscount | [Config](#config)\| Yes| Yes| Brightness discount. The value ranges from 0 to 1.0.| | mouseKey | [Config](#config)\| Yes| Yes| Whether to enable the mouse button feature.| -| mouseAutoClick | [Config](#config)\| Yes| Yes| Interval for the automatic mouse clicks. The value ranges from 0 to 5000, in milliseconds.| +| mouseAutoClick | [Config](#config)\| Yes| Yes| Interval for automatic mouse clicks. The value ranges from 0 to 5000, in milliseconds.| | shortkey | [Config](#config)\| Yes| Yes| Whether to enable the accessibility extension shortcut key.| -| shortkeyTarget | [Config](#config)\| Yes| Yes| Target application for the accessibility extension shortcut key. The value format is bundleName/abilityName.| +| shortkeyTarget | [Config](#config)\| Yes| Yes| Target application for the accessibility extension shortcut key. The value format is 'bundleName/abilityName'.| | captions | [Config](#config)\| Yes| Yes| Whether to enable captions.| -| captionsStyle | [Config](#config)\<[accessibility.CaptionsStyle](./js-apis-accessibility.md#captionsstyle8)>| Yes| Yes| Captions style.| +| captionsStyle | [Config](#config)\<[accessibility.CaptionsStyle](js-apis-accessibility.md#captionsstyle8)>| Yes| Yes| Captions style.| ## enableAbility -enableAbility(name: string, capability: Array<[accessibility.Capability](./js-apis-accessibility.md#capability)>): Promise<void>; +enableAbility(name: string, capability: Array<accessibility.Capability>): Promise<void>; Enables an accessibility extension ability. This API uses a promise to return the result. @@ -45,29 +44,44 @@ Enables an accessibility extension ability. This API uses a promise to return th | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes| Name of the accessibility extension ability. The format is bundleName/abilityName.| -| capability | Array<[accessibility.Capability](./js-apis-accessibility.md#capability)>) | Yes| Capability of the accessibility extension ability.| +| name | string | Yes| Name of the accessibility extension ability. The format is 'bundleName/abilityName'.| +| capability | Array<[accessibility.Capability](js-apis-accessibility.md#capability)> | Yes| Capability of the accessibility extension ability.| **Return value** | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the execution result.| +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300001 | Invalid bundle name or ability name. | +| 9300002 | Target ability already enabled. | **Example** - ```typescript - config.enableAbility("com.ohos.example/axExtension", ['retrieve']) - .then(() => { - console.info('enable succeed'); - }).catch((error) => { - console.error('enable failed'); - }); - ``` +```ts +import accessibility from '@ohos.accessibility'; +let name = 'com.ohos.example/axExtension'; +let capability : accessibility.Capability[] = ['retrieve']; +try { + config.enableAbility(name, capability).then(() => { + console.info('enable ability succeed'); + }).catch((err) => { + console.error('failed to enable ability, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to enable ability, because ' + JSON.stringify(exception)); +}; +``` ## enableAbility -enableAbility(name: string, capability: Array<[accessibility.Capability](./js-apis-accessibility.md#capability)>, callback: AsyncCallback<void>): void; +enableAbility(name: string, capability: Array<accessibility.Capability>, callback: AsyncCallback<void>): void; Enables an accessibility extension ability. This API uses an asynchronous callback to return the result. @@ -77,21 +91,37 @@ Enables an accessibility extension ability. This API uses an asynchronous callba | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes| Name of the accessibility extension ability. The format is bundleName/abilityName.| -| capability | Array<[accessibility.Capability](./js-apis-accessibility.md#capability)> | Yes| Capability of the accessibility extension ability.| -| callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| +| name | string | Yes| Name of the accessibility extension ability. The format is 'bundleName/abilityName'.| +| capability | Array<[accessibility.Capability](js-apis-accessibility.md#capability)> | Yes| Capability of the accessibility extension ability.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300001 | Invalid bundle name or ability name. | +| 9300002 | Target ability already enabled. | **Example** - ```typescript - config.enableAbility("com.ohos.example/axExtension", ['retrieve'], (err, data) => { - if (err) { - console.error('enable failed'); - return; - } - console.info('enable succeed'); - }) - ``` +```ts +import accessibility from '@ohos.accessibility'; +let name = 'com.ohos.example/axExtension'; +let capability : accessibility.Capability[] = ['retrieve']; +try { + config.enableAbility(name, capability, (err) => { + if (err) { + console.error('failed to enable ability, because ' + JSON.stringify(err)); + return; + } + console.info('enable ability succeed'); + }); +} catch (exception) { + console.error('failed to enable ability, because ' + JSON.stringify(exception)); +}; +``` ## disableAbility @@ -105,24 +135,36 @@ Disables an accessibility extension ability. This API uses a promise to return t | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes| Name of the accessibility extension ability. The format is bundleName/abilityName.| +| name | string | Yes| Name of the accessibility extension ability. The format is 'bundleName/abilityName'.| **Return value** | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the execution result.| +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300001 | Invalid bundle name or ability name. | **Example** - ```typescript - config.disableAbility("com.ohos.example/axExtension") - .then(() => { - console.info('disable succeed'); - }).catch((error) => { - console.error('disable failed'); - }); - ``` +```ts +let name = 'com.ohos.example/axExtension'; +try { + config.disableAbility(name).then(() => { + console.info('disable ability succeed'); + }).catch((err) => { + console.error('failed to disable ability, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to disable ability, because ' + JSON.stringify(exception)); +}; +``` ## disableAbility @@ -136,26 +178,39 @@ Disables an accessibility extension ability. This API uses an asynchronous callb | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes| Name of the accessibility extension ability. The format is bundleName/abilityName.| -| callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| +| name | string | Yes| Name of the accessibility extension ability. The format is 'bundleName/abilityName'.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300001 | Invalid bundle name or ability name. | **Example** - ```typescript - config.disableAbility("com.ohos.example/axExtension", (err, data) => { - if (err) { - console.error('disable failed'); - return; - } - console.info('disable succeed'); - }) - ``` +```ts +let name = 'com.ohos.example/axExtension'; +try { + config.disableAbility(name, (err, data) => { + if (err) { + console.error('failed to enable ability, because ' + JSON.stringify(err)); + return; + } + console.info('disable succeed'); + }); +} catch (exception) { + console.error('failed to enable ability, because ' + JSON.stringify(exception)); +}; +``` -## on('enableAbilityListsStateChanged') +## on('enabledAccessibilityExtensionListChange') -on(type: 'enableAbilityListsStateChanged', callback: Callback<void>): void; +on(type: 'enabledAccessibilityExtensionListChange', callback: Callback<void>): void; -Adds a listener for changes in the list of enabled accessibility extension abilities. +Adds a listener for changes in the list of enabled accessibility extension abilities. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -163,22 +218,27 @@ Adds a listener for changes in the list of enabled accessibility extension abili | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Listening type. The value is fixed at **'enableAbilityListsStateChanged'**, indicating the changes in the list of enabled accessibility extension abilities. | +| type | string | Yes| Listening type. The value is fixed at **'enabledAccessibilityExtensionListChange'**, indicating listening for changes in the list of enabled accessibility extension abilities.| | callback | Callback<void> | Yes| Callback invoked when the list of enabled accessibility extension abilities changes.| **Example** - ```typescript - config.on('enableAbilityListsStateChanged',() => { - console.info('ax extension ability enable list changed'); - }); - ``` +```ts +try { + config.on('enabledAccessibilityExtensionListChange', () => { + console.info('subscribe enabled accessibility extension list change state success'); + }); +} catch (exception) { + console.error('failed to subscribe enabled accessibility extension list change state, because ' + + JSON.stringify(exception)); +}; +``` -## off('enableAbilityListsStateChanged') +## off('enabledAccessibilityExtensionListChange') -off(type: 'enableAbilityListsStateChanged', callback?: Callback<void>): void; +off(type: 'enabledAccessibilityExtensionListChange', callback?: Callback<void>): void; -Cancels the listener for changes in the list of enabled accessibility extension abilities. +Cancels the listener for changes in the list of enabled accessibility extension abilities. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -186,14 +246,21 @@ Cancels the listener for changes in the list of enabled accessibility extension | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | No| Listening type. The value is fixed at **'enableAbilityListsStateChanged'**, indicating the changes in the list of enabled accessibility extension abilities. | +| type | string | Yes| Listening type. The value is fixed at **'enabledAccessibilityExtensionListChange'**, indicating listening for changes in the list of enabled accessibility extension abilities.| | callback | Callback<void> | No| Callback invoked when the list of enabled accessibility extension abilities changes.| **Example** - ```typescript - config.off('enableAbilityListsStateChanged'); - ``` +```ts +try { + config.off('enabledAccessibilityExtensionListChange', () => { + console.info('Unsubscribe enabled accessibility extension list change state success'); + }); +} catch (exception) { + console.error('failed to Unsubscribe enabled accessibility extension list change state, because ' + + JSON.stringify(exception)); +}; +``` ## Config @@ -203,7 +270,7 @@ Implements configuration, acquisition, and listening for attributes. set(value: T): Promise<void>; -Sets this attribute. This API uses a promise to return the result. +Sets the attribute value. This API uses a promise to return the result. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -217,24 +284,28 @@ Sets this attribute. This API uses a promise to return the result. | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the execution result.| +| Promise<void> | Promise that returns no value.| **Example** - ```typescript - config.highContrastText.set(true) - .then(() => { - console.info('highContrastText set succeed'); - }).catch((error) => { - console.error('highContrastText set failed'); - }); - ``` +```ts +let value = true; +try { + config.highContrastText.set(value).then(() => { + console.info('set highContrastText succeed'); + }).catch((err) => { + console.error('failed to set highContrastText, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to set config, because ' + JSON.stringify(exception)); +}; +``` ### set set(value: T, callback: AsyncCallback<void>): void; -Sets this attribute. This API uses an asynchronous callback to return the result. +Sets the attribute value. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -243,25 +314,30 @@ Sets this attribute. This API uses an asynchronous callback to return the result | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | T | Yes| Attribute value to set.| -| callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** - ```typescript - config.highContrastText.set(true, (err, data) => { - if (err) { - console.error('highContrastText set failed'); - return; - } - console.info('highContrastText set succeed'); - }) - ``` +```ts +let value = true; +try { + config.highContrastText.set(value, (err, data) => { + if (err) { + console.error('failed to set highContrastText, because ' + JSON.stringify(err)); + return; + } + console.info('set highContrastText succeed'); + }); +} catch (exception) { + console.error('failed to set config, because ' + JSON.stringify(exception)); +}; +``` ### get get(): Promise<T>; -Obtains the value of this attribute. This API uses a promise to return the result. +Obtains the attribute value. This API uses a promise to return the result. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -269,24 +345,25 @@ Obtains the value of this attribute. This API uses a promise to return the resul | Type| Description| | -------- | -------- | -| Promise<T> | Promise used to return the attribute value.| +| Promise<T> | Promise used to return the value obtained.| **Example** - ```typescript - config.highContrastText.get() - .then((value) => { - console.info('highContrastText get succeed'); - }).catch((error) => { - console.error('highContrastText get failed'); - }); - ``` +```ts +let value; +config.highContrastText.get().then((data) => { + value = data; + console.info('get highContrastText success'); +}).catch((err) => { + console.error('failed to get highContrastText, because ' + JSON.stringify(err)); +}); +``` ### get get(callback: AsyncCallback<T>): void; -Obtains the value of this attribute. This API uses an asynchronous callback to return the result. +Obtains the attribute value. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -294,25 +371,27 @@ Obtains the value of this attribute. This API uses an asynchronous callback to r | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<void> | Yes| Callback used to return the attribute value.| +| callback | AsyncCallback<T> | Yes| Callback used to return the attribute value.| **Example** - ```typescript - config.highContrastText.get((err, data) => { - if (err) { - console.error('highContrastText get failed'); - return; - } - console.info('highContrastText get succeed'); - }) - ``` +```ts +let value; +config.highContrastText.get((err, data) => { + if (err) { + console.error('failed to get highContrastText, because ' + JSON.stringify(err)); + return; + } + value = data; + console.info('get highContrastText success'); +}); +``` ### on on(callback: Callback<T>): void; -Adds a listener for attribute changes. +Adds a listener for attribute changes. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -324,17 +403,21 @@ Adds a listener for attribute changes. **Example** - ```typescript - config.highContrastText.on(() => { - console.info('highContrastText changed'); - }); - ``` +```ts +try { + config.highContrastText.on((data) => { + console.info('subscribe highContrastText success, result: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('failed subscribe highContrastText, because ' + JSON.stringify(exception)); +} +``` ### off off(callback?: Callback<T>): void; -Cancels the listener for attribute changes. +Cancels the listener for attribute changes. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -342,13 +425,15 @@ Cancels the listener for attribute changes. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | Callback<T> | No| Callback invoked when the attribute changes.| +| callback | Callback<T> | No| Callback invoked when the list of enabled accessibility extension abilities changes.| **Example** - ```typescript - config.highContrastText.off(); - ``` +```ts +config.highContrastText.off((data) => { + console.info('Unsubscribe highContrastText success, result: ' + JSON.stringify(data)); +}); +``` ## DaltonizationColorFilter diff --git a/en/application-dev/reference/apis/js-apis-accessibility.md b/en/application-dev/reference/apis/js-apis-accessibility.md index 6d318b4ade570aea27b58ca93d37ef0a3992d3bc..cf4443c60f4b58a17986bdb7ae5160fd6a95347c 100644 --- a/en/application-dev/reference/apis/js-apis-accessibility.md +++ b/en/application-dev/reference/apis/js-apis-accessibility.md @@ -1,4 +1,4 @@ -# Accessibility +# @ohos.accessibility The **Accessibility** module implements the accessibility functions, including obtaining the accessibility application list, accessibility application enabled status, and captions configuration. @@ -8,7 +8,7 @@ The **Accessibility** module implements the accessibility functions, including o ## Modules to Import -```typescript +```ts import accessibility from '@ohos.accessibility'; ``` @@ -49,7 +49,7 @@ Provides information about an accessibility application. | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| id | number | Yes| No| Ability ID.| +| id | string | Yes| No| Ability ID.| | name | string | Yes| No| Ability name.| | bundleName | string | Yes| No| Bundle name.| | targetBundleNames9+ | Array<string> | Yes| No| Name of the target bundle.| @@ -85,7 +85,7 @@ Describes the target action supported by an accessibility application. ## Capability -Enumerates the capabilities of an auxiliary application. +Enumerates the capabilities of an accessibility application. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -145,7 +145,7 @@ Describes the style of captions. ## CaptionsManager8+ -Implements configuration management for captions. +Implements configuration management for captions. Before calling any API of **CaptionsManager**, you must use the [accessibility.getCaptionsManager()](#accessibilitygetcaptionsmanager8) API to obtain a **CaptionsManager** instance. **System capability**: SystemCapability.BarrierFree.Accessibility.Hearing @@ -156,87 +156,113 @@ Implements configuration management for captions. | enabled | boolean | Yes| No| Whether to enable captions configuration.| | style | [CaptionsStyle](#captionsstyle8) | Yes| No| Style of captions.| -In the following API examples, you must first use the [accessibility.getCaptionsManager()](#accessibilitygetcaptionsmanager8) API to obtain a **captionsManager** instance, and then call the methods using the obtained instance. - ### on('enableChange') on(type: 'enableChange', callback: Callback<boolean>): void; -Enables listening for the enabled status changes of captions configuration. +Enables listening for the enabled status changes of captions configuration. This API uses an asynchronous callback to return the result. -- **Parameters** +**Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to listen for, which is set to **enableChange** in this API.| - | callback | Callback<boolean> | Yes| Callback invoked when the enabled status of captions configuration changes.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to listen for, which is set to **'enableChange'** in this API.| +| callback | Callback<boolean> | Yes| Callback invoked when the enabled status of captions configuration changes.| -- **Example** +**Example** - ```typescript - captionsManager.on('enableChange',(data) => { - console.info('success data:subscribeStateObserver : ' + JSON.stringify(data)) - }) - ``` +```ts +let captionsManager = accessibility.getCaptionsManager(); +try { + captionsManager.on('enableChange', (data) => { + console.info('subscribe caption manager enable state change, result: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('failed to subscribe caption manager enable state change, because ' + JSON.stringify(exception)); +} +``` ### on('styleChange') on(type: 'styleChange', callback: Callback<CaptionsStyle>): void; -Enables listening for captions style changes. +Enables listening for captions style changes. This API uses an asynchronous callback to return the result. -- **Parameters** +**Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to listen for, which is set to **styleChange** in this API.| - | callback | Callback<[CaptionsStyle](#captionsstyle8)> | Yes| Callback invoked when the style of captions changes.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to listen for, which is set to **'styleChange'** in this API.| +| callback | Callback<[CaptionsStyle](#captionsstyle8)> | Yes| Callback invoked when the style of captions changes.| -- **Example** +**Example** + +```ts +let captionStyle; +let captionsManager = accessibility.getCaptionsManager(); +try { + captionsManager.on('styleChange', (data) => { + captionStyle = data; + console.info('subscribe caption manager style state change, result: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('failed to subscribe caption manager style state change, because ' + JSON.stringify(exception)); +} +``` - ```typescript - captionsManager.on('styleChange',(data) => { - console.info('success data:subscribeStateObserver : ' + JSON.stringify(data)) - }) - ``` - ### off('enableChange') off(type: 'enableChange', callback?: Callback<boolean>): void; -Disables listening for the enabled status changes of captions configuration. +Disables listening for the enabled status changes of captions configuration. This API uses an asynchronous callback to return the result. -- **Parameters** +**Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to listen for, which is set to **enableChange** in this API.| - | callback | Callback<boolean> | No| Callback invoked when the enabled status of captions configuration changes.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to listen for, which is set to **'enableChange'** in this API.| +| callback | Callback<boolean> | No| Callback invoked when the enabled status of captions configuration changes.| -- **Example** +**Example** - ```typescript - captionsManager.off('enableChange') - ``` +```ts +let captionsManager = accessibility.getCaptionsManager(); +try { + captionsManager.off('enableChange', (data) => { + console.info('Unsubscribe caption manager enable state change, result: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('failed to Unsubscribe caption manager enable state change, because ' + JSON.stringify(exception)); +} +``` ### off('styleChange') off(type: 'styleChange', callback?: Callback<CaptionsStyle>): void; -Disables listening for captions style changes. +Disables listening for captions style changes. This API uses an asynchronous callback to return the result. -- **Parameters** +**Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to listen for, which is set to **styleChange** in this API.| - | callback | Callback<[CaptionsStyle](#captionsstyle8)> | No| Callback invoked when the style of captions changes.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to listen for, which is set to **'styleChange'** in this API.| +| callback | Callback<[CaptionsStyle](#captionsstyle8)> | No| Callback invoked when the style of captions changes.| -- **Example** +**Example** - ```typescript - captionsManager.off('styleChange') - ``` +```ts +let captionStyle; +let captionsManager = accessibility.getCaptionsManager(); +try { + captionsManager.off('styleChange', (data) => { + captionStyle = data; + console.info('Unsubscribe caption manager style state change, result: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('failed to Unsubscribe caption manager style state change, because ' + JSON.stringify(exception)); +} +``` ## EventInfo @@ -271,16 +297,20 @@ Implements a constructor. **System capability**: SystemCapability.BarrierFree.Accessibility.Core -- **Parameters** +**Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | jsonObject | string | Yes| JSON string required for creating an object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| jsonObject | string | Yes| JSON string required for creating an object.| -- **Example** +**Example** - ```typescript - let eventInfo = new accessibility.EventInfo({"type":"click","bundleName":"com.example.MyApplication","triggerAction":"click"}) + ```ts + let eventInfo = new accessibility.EventInfo({ + 'type':'click', + 'bundleName':'com.example.MyApplication', + 'triggerAction':'click' + }); ``` ## EventType @@ -331,153 +361,319 @@ Enumerates window update types. | active | Window activity change.| | focus | Window focus change.| -## accessibility.getAbilityLists +## accessibility.getAbilityLists(deprecated) getAbilityLists(abilityType: AbilityType, stateType: AbilityState): Promise<Array<AccessibilityAbilityInfo>> Obtains the accessibility application list. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. +> You are advised to use[getAccessibilityExtensionList()](#accessibilitygetaccessibilityextensionlist9). + **System capability**: SystemCapability.BarrierFree.Accessibility.Core -- **Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | abilityType | [AbilityType](#abilitytype) | Yes| Accessibility application type.| - | stateType | [AbilityState](#abilitystate) | Yes| Accessibility application status.| - -- **Return value** - - | Type| Description| - | -------- | -------- | - | Promise<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Promise used to return the accessibility application list.| - -- **Example** - - ```typescript - accessibility.getAbilityLists("spoken", "enable") - .then((data) => { - console.info('success data:getAbilityList1 : ' + JSON.stringify(data)); - for (let item of data) { - console.info(item.id); - console.info(item.name); - console.info(item.description); - console.info(item.abilityTypes); - console.info(item.eventTypes); - console.info(item.capabilities); - console.info(item.packageName); - console.info(item.filterBundleNames); - console.info(item.bundleName); - } - }).catch((error) => { - console.error('failed to getAbilityList1 because ' + JSON.stringify(error)); - }) - ``` +**Parameters** -## accessibility.getAbilityLists +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| abilityType | [AbilityType](#abilitytype) | Yes| Accessibility application type.| +| stateType | [AbilityState](#abilitystate) | Yes| Accessibility application status.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Promise used to return the accessibility application list.| + +**Example** + +```ts +let abilityType = 'spoken'; +let abilityState = 'enable'; +let abilityList: accessibility.AccessibilityInfo[]; +try { + accessibility.getAbilityLists(abilityType, abilityState).then((data) => { + for (let item of data) { + console.info(item.id); + console.info(item.name); + console.info(item.description); + console.info(item.bundleName); + extensionList.push(item); + } + console.info('get accessibility extension list success'); + }).catch((err) => { + console.error('failed to get accessibility extension list because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to get accessibility extension list because ' + JSON.stringify(exception)); +} +``` + +## accessibility.getAbilityLists(deprecated) getAbilityLists(abilityType: AbilityType, stateType: AbilityState,callback: AsyncCallback<Array<AccessibilityAbilityInfo>>): void Obtains the accessibility application list. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. +> You are advised to use [getAccessibilityExtensionList()](#accessibilitygetaccessibilityextensionlist9-1). + **System capability**: SystemCapability.BarrierFree.Accessibility.Core -- **Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | abilityType | [AbilityType](#abilitytype) | Yes| Accessibility application type.| - | stateType | [AbilityState](#abilitystate) | Yes| Accessibility application status.| - | callback | AsyncCallback<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Yes| Callback used to return the accessibility application list.| - -- **Example** - - ```typescript - accessibility.getAbilityLists("visual", "enable", (err, data) => { - if (err) { - console.error('failed to getAbilityList2 because ' + JSON.stringify(err)); - return; - } - console.info('success data:getAbilityList2 : ' + JSON.stringify(data)); - for (let item of data) { - console.info(item.id); - console.info(item.name); - console.info(item.description); - console.info(item.abilityTypes); - console.info(item.eventTypes); - console.info(item.capabilities); - console.info(item.packageName); - console.info(item.filterBundleNames); - console.info(item.bundleName); - } - }) - ``` +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| abilityType | [AbilityType](#abilitytype) | Yes| Accessibility application type.| +| stateType | [AbilityState](#abilitystate) | Yes| Accessibility application status.| +| callback | AsyncCallback<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Yes| Callback used to return the accessibility application list.| + +**Example** + +```ts +let abilityType = 'spoken'; +let abilityState = 'enable'; +let abilityList: accessibility.AccessibilityInfo[]; +try { + accessibility.getAbilityLists(abilityType, abilityState, (err, data) => { + if (err) { + console.error('failed to get accessibility extension list because ' + JSON.stringify(err)); + return; + } + for (let item of data) { + console.info(item.id); + console.info(item.name); + console.info(item.description); + console.info(item.bundleName); + abilityList.push(item); + } + console.info('get accessibility extension list success'); + }).catch((err) => { + console.error('failed to get accessibility extension list because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to get accessibility extension list because ' + JSON.stringify(exception)); +} +``` + +## accessibility.getAccessibilityExtensionList9+ + +getAccessibilityExtensionList(abilityType: AbilityType, stateType: AbilityState): Promise<Array<AccessibilityAbilityInfo>> + +Obtains the accessibility application list. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| abilityType | [AbilityType](#abilitytype) | Yes| Accessibility application type.| +| stateType | [AbilityState](#abilitystate) | Yes| Accessibility application status.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Promise used to return the accessibility application list.| + +**Example** + +```ts +let abilityType : accessibility.AbilityType = 'spoken'; +let abilityState : accessibility.AbilityState = 'enable'; +let extensionList: accessibility.AccessibilityAbilityInfo[] = []; +try { + accessibility.getAccessibilityExtensionList(abilityType, abilityState).then((data) => { + for (let item of data) { + console.info(item.id); + console.info(item.name); + console.info(item.description); + console.info(item.bundleName); + extensionList.push(item); + } + console.info('get accessibility extension list success'); + }).catch((err) => { + console.error('failed to get accessibility extension list because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to get accessibility extension list because ' + JSON.stringify(exception)); +} +``` + +## accessibility.getAccessibilityExtensionList9+ + +getAccessibilityExtensionList(abilityType: AbilityType, stateType: AbilityState, callback: AsyncCallback<Array<AccessibilityAbilityInfo>>): void + +Obtains the accessibility application list. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| abilityType | [AbilityType](#abilitytype) | Yes| Accessibility application type.| +| stateType | [AbilityState](#abilitystate) | Yes| Accessibility application status.| +| callback | AsyncCallback<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Yes| Callback used to return the accessibility application list.| + +**Example** + +```ts +let abilityType : accessibility.AbilityType = 'spoken'; +let abilityState : accessibility.AbilityState = 'enable'; +let extensionList: accessibility.AccessibilityAbilityInfo[] = []; +try { + accessibility.getAccessibilityExtensionList(abilityType, abilityState, (err, data) => { + if (err) { + console.error('failed to get accessibility extension list because ' + JSON.stringify(err)); + return; + } + for (let item of data) { + console.info(item.id); + console.info(item.name); + console.info(item.description); + console.info(item.bundleName); + extensionList.push(item); + } + console.info('get accessibility extension list success'); + }); +} catch (exception) { + console.error('failed to get accessibility extension list because ' + JSON.stringify(exception)); +} +``` ## accessibility.getCaptionsManager8+ getCaptionsManager(): CaptionsManager -Obtains the captions configuration. +Obtains a **CaptionsManager** instance. **System capability**: SystemCapability.BarrierFree.Accessibility.Hearing -- **Return value** +**Return value** - | Type| Description| - | -------- | -------- | - | [CaptionsManager](#captionsmanager8) | Captions configuration.| +| Type| Description| +| -------- | -------- | +| [CaptionsManager](#captionsmanager8) | Captions configuration.| -- **Example** +**Example** - ```typescript - captionsManager = accessibility.getCaptionsManager() - ``` +```ts +let captionsManager = accessibility.getCaptionsManager(); +``` -## accessibility.on('accessibilityStateChange' | 'touchGuideStateChange') +## accessibility.on('accessibilityStateChange') -on(type: 'accessibilityStateChange' | 'touchGuideStateChange', callback: Callback<boolean>): void +on(type: 'accessibilityStateChange', callback: Callback<boolean>): void -Enables listening for the enabled status changes of the accessibility application or touch guide mode. +Enables listening for the enabled status changes of the accessibility application. This API uses an asynchronous callback to return the result. -- **Parameters** +**Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to listen for.
- **'accessibilityStateChange'** means to listen for the enabled status changes of the accessibility application.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
- **'touchGuideStateChange'** means to listen for the enabled status changes of the touch guide mode.
**System capability**: SystemCapability.BarrierFree.Accessibility.Vision| - | callback | Callback\ | Yes| Callback invoked when the enabled status of captions configuration changes.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to listen for, which is set to **'accessibilityStateChange'** in this API.| +| callback | Callback<boolean> | Yes| Callback used to return the result.| -- **Example** +**Example** - ```typescript - accessibility.on('accessibilityStateChange',(data) => { - console.info('success data:subscribeStateObserver : ' + JSON.stringify(data)) - }) - ``` +```ts +try { + accessibility.on('accessibilityStateChange', (data) => { + console.info('subscribe accessibility state change, result: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('failed to subscribe accessibility state change, because ' + JSON.stringify(exception)); +} +``` -## accessibility.off('accessibilityStateChange' | 'touchGuideStateChange') +## accessibility.on('touchGuideStateChange') -off(type: 'accessibilityStateChange ' | 'touchGuideStateChange', callback?: Callback<boolean>): void +on(type: 'touchGuideStateChange', callback: Callback<boolean>): void -Disables listening for the enabled status changes of the accessibility application or touch guide mode. +Enables listening for the enabled status changes of the touch guide mode. This API uses an asynchronous callback to return the result. -- **Parameters** +**Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | No| Type of the event to listen for.
- **'accessibilityStateChange'** means to listen for the enabled status changes of the accessibility application.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
- **'touchGuideStateChange'** means to listen for the enabled status changes of the touch guide mode.
**System capability**: SystemCapability.BarrierFree.Accessibility.Vision| - | callback | Callback<boolean> | No| Callback invoked when the enabled status changes.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to listen for, which is set to **'touchGuideStateChange'** in this API.| +| callback | Callback<boolean> | Yes| Callback used to return the result.| -- **Example** +**Example** - ```typescript - accessibility.off('accessibilityStateChange',(data) => { - console.info('success data:unSubscribeStateObserver : ' + JSON.stringify(data)) - }) - ``` +```ts +try { + accessibility.on('touchGuideStateChange', (data) => { + console.info('subscribe touch guide state change, result: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('failed to subscribe touch guide state change, because ' + JSON.stringify(exception)); +} +``` + +## accessibility.off('accessibilityStateChange') + +off(type: 'accessibilityStateChange', callback?: Callback<boolean>): void + +Disables listening for the enabled status changes of the accessibility application. This API uses an asynchronous callback to return the result. + + + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | No| Type of the event to listen for, which is set to **'accessibilityStateChange'** in this API.| +| callback | Callback<boolean> | No| Callback used to return the result.| + +**Example** + +```ts +try { + accessibility.off('accessibilityStateChange', (data) => { + console.info('Unsubscribe accessibility state change, result: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('failed to Unsubscribe accessibility state change, because ' + JSON.stringify(exception)); +} +``` + +## accessibility.off('touchGuideStateChange') + +off(type: 'touchGuideStateChange', callback?: Callback<boolean>): void + +Disables listening for the enabled status changes of the touch guide mode. This API uses an asynchronous callback to return the result. + + + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | No| Type of the event to listen for, which is set to **'touchGuideStateChange'** in this API.| +| callback | Callback<boolean> | No| Callback used to return the result.| + +**Example** + +```ts +try { + accessibility.off('touchGuideStateChange', (data) => { + console.info('Unsubscribe touch guide state change, result: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('failed to Unsubscribe touch guide state change, because ' + JSON.stringify(exception)); +} +``` ## accessibility.isOpenAccessibility @@ -487,22 +683,21 @@ Checks whether accessibility is enabled. This API uses a promise to return the r **System capability**: SystemCapability.BarrierFree.Accessibility.Core -- **Return value** +**Return value** - | Type| Description| - | -------- | -------- | - | Promise<boolean> | Returns **true** if accessibility is enabled; returns **false** otherwise.| +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the result. Returns **true** if accessibility is enabled; returns **false** otherwise.| -- **Example** +**Example** - ```typescript - accessibility.isOpenAccessibility() - .then((data) => { - console.info('success data:isOpenAccessibility : ' + JSON.stringify(data)) - }).catch((error) => { - console.error('failed to isOpenAccessibility because ' + JSON.stringify(error)); - }) - ``` +```ts +accessibility.isOpenAccessibility().then((data) => { + console.info('success data:isOpenAccessibility : ' + JSON.stringify(data)) +}).catch((err) => { + console.error('failed to isOpenAccessibility because ' + JSON.stringify(err)); +}); +``` ## accessibility.isOpenAccessibility @@ -512,23 +707,23 @@ Checks whether accessibility is enabled. This API uses an asynchronous callback **System capability**: SystemCapability.BarrierFree.Accessibility.Core -- **Parameters** +**Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes| Callback used to return the result. Returns **true** if accessibility is enabled; returns **false** otherwise.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. Returns **true** if accessibility is enabled; returns **false** otherwise.| -- **Example** +**Example** - ```typescript - accessibility.isOpenAccessibility((err, data) => { - if (err) { - console.error('failed to isOpenAccessibility because ' + JSON.stringify(err)); - return; - } - console.info('success data:isOpenAccessibility : ' + JSON.stringify(data)) - }) - ``` +```ts +accessibility.isOpenAccessibility((err, data) => { + if (err) { + console.error('failed to isOpenAccessibility because ' + JSON.stringify(err)); + return; + } + console.info('success data:isOpenAccessibility : ' + JSON.stringify(data)) +}); +``` ## accessibility.isOpenTouchGuide @@ -538,22 +733,21 @@ Checks whether touch guide mode is enabled. This API uses a promise to return th **System capability**: SystemCapability.BarrierFree.Accessibility.Vision -- **Return value** +**Return value** - | Type| Description| - | -------- | -------- | - | Promise<boolean> | Returns **true** if touch guide mode is enabled; returns **false** otherwise.| +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the result. Returns **true** if touch guide mode is enabled; returns **false** otherwise.| -- **Example** +**Example** - ```typescript - accessibility.isOpenTouchGuide() - .then((data) => { - console.info('success data:isOpenTouchGuide : ' + JSON.stringify(data)) - }).catch((error) => { - console.error('failed to isOpenTouchGuide because ' + JSON.stringify(error)); - }) - ``` +```ts +accessibility.isOpenTouchGuide().then((data) => { + console.info('success data:isOpenTouchGuide : ' + JSON.stringify(data)) +}).catch((err) => { + console.error('failed to isOpenTouchGuide because ' + JSON.stringify(err)); +}); +``` ## accessibility.isOpenTouchGuide @@ -563,78 +757,172 @@ Checks whether touch guide mode is enabled. This API uses an asynchronous callba **System capability**: SystemCapability.BarrierFree.Accessibility.Vision -- **Parameters** +**Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes| Callback used to return the result. Returns **true** if touch guide mode is enabled; returns **false** otherwise.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. Returns **true** if touch guide mode is enabled; returns **false** otherwise.| -- **Example** +**Example** - ```typescript - accessibility.isOpenTouchGuide((err, data) => { - if (err) { - console.error('failed to isOpenTouchGuide because ' + JSON.stringify(err)); - return; - } - console.info('success data:isOpenTouchGuide : ' + JSON.stringify(data)) - }) - ``` +```ts +accessibility.isOpenTouchGuide((err, data) => { + if (err) { + console.error('failed to isOpenTouchGuide because ' + JSON.stringify(err)); + return; + } + console.info('success data:isOpenTouchGuide : ' + JSON.stringify(data)) +}); +``` -## accessibility.sendEvent +## accessibility.sendEvent(deprecated) sendEvent(event: EventInfo): Promise<void> Sends an accessibility event. This API uses a promise to return the result. -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -- **Parameters** +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. +> You are advised to use **[sendAccessibilityEvent()](#accessibilitysendaccessibilityevent9)**. - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | event | [EventInfo](#eventinfo) | Yes| Accessibility event.| +**System capability**: SystemCapability.BarrierFree.Accessibility.Core -- **Return value** +**Parameters** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result. Returns data if the accessibility event is sent successfully; returns an error otherwise.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | [EventInfo](#eventinfo) | Yes| Accessibility event.| -- **Example** +**Return value** - ```typescript - accessibility.sendEvent(this.eventInfo) - .then((data) => { - console.info('success data:sendEvent : ' + JSON.stringify(data)) - }).catch((error) => { - console.error('failed to sendEvent because ' + JSON.stringify(error)); - }) - ``` +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +let eventInfo = new accessibility.EventInfo({ + 'type':'click', + 'bundleName':'com.example.MyApplication', + 'triggerAction':'click' +}); +accessibility.sendEvent(eventInfo).then(() => { + console.info('send event success'); +}).catch((err) => { + console.error('failed to sendEvent because ' + JSON.stringify(err)); +}); +``` -## accessibility.sendEvent +## accessibility.sendEvent(deprecated) sendEvent(event: EventInfo, callback: AsyncCallback<void>): void Sends an accessibility event. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. +> You are advised to use **[sendAccessibilityEvent()](#accessibilitysendaccessibilityevent9-1)**. + **System capability**: SystemCapability.BarrierFree.Accessibility.Core -- **Parameters** +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | [EventInfo](#eventinfo) | Yes| Accessibility event.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation fails, **error** that contains data is returned. | + +**Example** + +```ts +let eventInfo = new accessibility.EventInfo({ + 'type':'click', + 'bundleName':'com.example.MyApplication', + 'triggerAction':'click' +}); +accessibility.sendEvent(eventInfo, (err, data) => { + if (err) { + console.error('failed to sendEvent because ' + JSON.stringify(err)); + return; + } + console.info('sendEvent success'); +}); +``` - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | event | [EventInfo](#eventinfo) | Yes| Accessibility event.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result. Returns data if the accessibility event is sent successfully; returns an error otherwise.| +## accessibility.sendAccessibilityEvent9+ -- **Example** +sendAccessibilityEvent(event: EventInfo): Promise<void> - ```typescript - accessibility.sendEvent(this.eventInfo,(err, data) => { - if (err) { - console.error('failed to sendEvent because ' + JSON.stringify(err)); - return; - } - console.info('success data:sendEvent : ' + JSON.stringify(data)) - }) - ``` +Sends an accessibility event. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | [EventInfo](#eventinfo) | Yes| Accessibility event.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +let eventInfo = new accessibility.EventInfo({ + 'type':'click', + 'bundleName':'com.example.MyApplication', + 'triggerAction':'click' +}); +try { + accessibility.sendAccessibilityEvent(eventInfo).then(() => { + console.info('send event success'); + }).catch((err) => { + console.error('failed to send event because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to send event because ' + JSON.stringify(exception)); +} +``` + +## accessibility.sendAccessibilityEvent9+ + +sendAccessibilityEvent(event: EventInfo, callback: AsyncCallback<void>): void + +Sends an accessibility event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | [EventInfo](#eventinfo) | Yes| Accessibility event.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation fails, **error** that contains data is returned. | + +**Example** + +```ts +let eventInfo = new accessibility.EventInfo({ + 'type':'click', + 'bundleName':'com.example.MyApplication', + 'triggerAction':'click' +}); +try { + accessibility.sendEvent(eventInfo, (err, data) => { + if (err) { + console.error('failed to send event because ' + JSON.stringify(err)); + return; + } + console.info('send event success'); + }); +} catch (exception) { + console.error('failed to send event because ' + JSON.stringify(exception)); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-ability.md b/en/application-dev/reference/apis/js-apis-app-ability-ability.md new file mode 100644 index 0000000000000000000000000000000000000000..59e1e229f2e8396ae11584dee80a439ea74fdf6b --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-ability.md @@ -0,0 +1,62 @@ +# @ohos.app.ability.Ability + +The **Ability** module manages the ability lifecycle and context, such as creating and destroying an ability, and dumping client information. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the stage model. + +## Modules to Import + +```ts +import Ability from '@ohos.app.ability.Ability'; +``` + +## Ability.onConfigurationUpdate + +onConfigurationUpdate(newConfig: Configuration): void; + +Called when the configuration of the environment where the ability is running is updated. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | newConfig | [Configuration](js-apis-app-ability-configuration.md) | Yes| New configuration.| + +**Example** + + ```ts + class myAbility extends Ability { + onConfigurationUpdate(config) { + console.log('onConfigurationUpdate, config:' + JSON.stringify(config)); + } + } + ``` + +## Ability.onMemoryLevel + +onMemoryLevel(level: AbilityConstant.MemoryLevel): void; + +Called when the system has decided to adjust the memory level. For example, this API can be used when there is not enough memory to run as many background processes as possible. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | level | [AbilityConstant.MemoryLevel](js-apis-app-ability-abilityConstant.md#abilityconstantmemorylevel) | Yes| Memory level that indicates the memory usage status. When the specified memory level is reached, a callback will be invoked and the system will start adjustment.| + +**Example** + + ```ts + class myAbility extends Ability { + onMemoryLevel(level) { + console.log('onMemoryLevel, level:' + JSON.stringify(level)); + } + } + ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md new file mode 100644 index 0000000000000000000000000000000000000000..5d6c93e6e2b45b33ca9cb7ec9976435c17fd2a56 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md @@ -0,0 +1,117 @@ +# @ohos.app.ability.AbilityConstant + +The **AbilityConstant** module provides ability launch parameters. + +The parameters include the initial launch reasons, reasons for the last exit, and ability continuation results. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the stage model. + +## Modules to Import + +```ts +import AbilityConstant from '@ohos.app.ability.AbilityConstant'; +``` + +## Attributes + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| launchReason | LaunchReason| Yes| Yes| Ability launch reason.| +| lastExitReason | LastExitReason | Yes| Yes| Reason for the last exit.| + +## AbilityConstant.LaunchReason + +Enumerates the ability launch reasons. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ----------------------------- | ---- | ------------------------------------------------------------ | +| UNKNOWN | 0 | Unknown reason.| +| START_ABILITY | 1 | Ability startup.| +| CALL | 2 | Call.| +| CONTINUATION | 3 | Ability continuation.| +| APP_RECOVERY | 4 | Application recovery.| + + +## AbilityConstant.LastExitReason + +Enumerates reasons for the last exit. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ----------------------------- | ---- | ------------------------------------------------------------ | +| UNKNOWN | 0 | Unknown reason.| +| ABILITY_NOT_RESPONDING | 1 | The ability does not respond.| +| NORMAL | 2 | Normal status.| + + +## AbilityConstant.OnContinueResult + +Enumerates ability continuation results. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ----------------------------- | ---- | ------------------------------------------------------------ | +| AGREE | 0 | Continuation agreed.| +| REJECT | 1 | Continuation denied.| +| MISMATCH | 2 | Mismatch.| + +## AbilityConstant.WindowMode + +Enumerates the window modes in which an ability can be displayed at startup. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value| Description | +| --- | --- | --- | +| WINDOW_MODE_UNDEFINED | 0 | Undefined window mode. | +| WINDOW_MODE_FULLSCREEN | 1 | The ability is displayed in full screen. | +| WINDOW_MODE_SPLIT_PRIMARY | 100 | The ability is displayed in the primary window in split-screen mode. | +| WINDOW_MODE_SPLIT_SECONDARY | 101 | The ability is displayed in the secondary window in split-screen mode. | +| WINDOW_MODE_FLOATING | 102 | The ability is displayed in a floating window.| + +## AbilityConstant.MemoryLevel + +Enumerates the memory levels. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value| Description | +| --- | --- | --- | +| MEMORY_LEVEL_MODERATE | 0 | Moderate memory usage. | +| MEMORY_LEVEL_LOW | 1 | Low memory usage. | +| MEMORY_LEVEL_CRITICAL | 2 | High memory usage. | + +## AbilityConstant.OnSaveResult + +Enumerates the result types for the operation of saving application data. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ----------------------------- | ---- | ------------------------------------------------------------ | +| ALL_AGREE | 0 | Agreed to save the status.| +| CONTINUATION_REJECT | 1 | Rejected to save the status in continuation.| +| CONTINUATION_MISMATCH | 2 | Continuation mismatch.| +| RECOVERY_AGREE | 3 | Agreed to restore the saved status.| +| RECOVERY_REJECT | 4 | Rejected to restore the saved state.| +| ALL_REJECT | 5 | Rejected to save the status.| + +## AbilityConstant.StateType + +Enumerates the scenarios for saving application data. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ----------------------------- | ---- | ------------------------------------------------------------ | +| CONTINUATION | 0 | Saving the status in continuation.| +| APP_RECOVERY | 1 | Saving the status in application recovery.| diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md new file mode 100644 index 0000000000000000000000000000000000000000..78fb6181c03380c6d69eb31318d1d459dec307fe --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md @@ -0,0 +1,71 @@ +# @ohos.app.ability.abilityDelegatorRegistry + +The **AbilityDelegatorRegistry** module provides APIs for storing the global registers of the registered **AbilityDelegator** and **AbilityDelegatorArgs** objects. You can use the APIs to obtain the **AbilityDelegator** and **AbilityDelegatorArgs** objects of an application. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```ts +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry' +``` + +## AbilityLifecycleState + +Enumerates the ability lifecycle states. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ------------- | ---- | --------------------------- | +| UNINITIALIZED | 0 | The ability is in an invalid state. | +| CREATE | 1 | The ability is created.| +| FOREGROUND | 2 | The ability is running in the foreground. | +| BACKGROUND | 3 | The ability is running in the background. | +| DESTROY | 4 | The ability is destroyed.| + +## AbilityDelegatorRegistry.getAbilityDelegator + +getAbilityDelegator(): AbilityDelegator + +Obtains the **AbilityDelegator** object of the application. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| [AbilityDelegator](js-apis-inner-application-abilityDelegator.md#AbilityDelegator) | [AbilityDelegator](js-apis-inner-application-abilityDelegator.md#AbilityDelegator) object, which can be used to schedule functions related to the test framework.| + +**Example** + +```ts +var abilityDelegator; +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +``` + +## AbilityDelegatorRegistry.getArguments + +getArguments(): AbilityDelegatorArgs + +Obtains the **AbilityDelegatorArgs** object of the application. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| [AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md) | [AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md) object, which can be used to obtain test parameters.| + +**Example** + +```ts +var args = AbilityDelegatorRegistry.getArguments(); +console.info("getArguments bundleName:" + args.bundleName); +console.info("getArguments testCaseNames:" + args.testCaseNames); +console.info("getArguments testRunnerClassName:" + args.testRunnerClassName); +``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityLifecycleCallback.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityLifecycleCallback.md new file mode 100644 index 0000000000000000000000000000000000000000..f3e6e08396d0b819efd6acda39218af497e83ef9 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityLifecycleCallback.md @@ -0,0 +1,211 @@ +# @ohos.app.ability.abilityLifecycleCallback + +The **AbilityLifecycleCallback** module provides callbacks, such as **onAbilityCreate**, **onWindowStageCreate**, and **onWindowStageDestroy**, to receive lifecycle state changes in the application context. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the stage model. + + +## Modules to Import + +```ts +import AbilityLifecycleCallback from "@ohos.app.ability.AbilityLifecycleCallback"; +``` + + +## AbilityLifecycleCallback.onAbilityCreate + +onAbilityCreate(ability: UIAbility): void; + +Called when an ability is created. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| + + +## AbilityLifecycleCallback.onWindowStageCreate + +onWindowStageCreate(ability: UIAbility, windowStage: window.WindowStage): void; + +Called when the window stage of an ability is created. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| + | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| + + +## AbilityLifecycleCallback.onWindowStageActive + +onWindowStageActive(ability: UIAbility, windowStage: window.WindowStage): void; + +Called when the window stage of an ability gains focus. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| + | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| + + +## AbilityLifecycleCallback.onWindowStageInactive + +onWindowStageInactive(ability: UIAbility, windowStage: window.WindowStage): void; + +Called when the window stage of an ability loses focus. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| + | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| + + +## AbilityLifecycleCallback.onWindowStageDestroy + +onWindowStageDestroy(ability: UIAbility, windowStage: window.WindowStage): void; + +Called when the window stage of an ability is destroyed. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| + | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| + + +## AbilityLifecycleCallback.onAbilityDestroy + +onAbilityDestroy(ability: UIAbility): void; + +Called when an ability is destroyed. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| + + +## AbilityLifecycleCallback.onAbilityForeground + +onAbilityForeground(ability: UIAbility): void; + +Called when an ability is switched from the background to the foreground. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| + + +## AbilityLifecycleCallback.onAbilityBackground + +onAbilityBackground(ability: UIAbility): void; + +Called when an ability is switched from the foreground to the background. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| + + +## AbilityLifecycleCallback.onAbilityContinue + +onAbilityContinue(ability: UIAbility): void; + +Called when an ability is continued on another device. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| + +**Example** + + + ```ts + import UIAbility from "@ohos.app.ability.UIAbility"; + + export default class MyAbility extends UIAbility { + onCreate() { + console.log("MyAbility onCreate") + let AbilityLifecycleCallback = { + onAbilityCreate(ability){ + console.log("AbilityLifecycleCallback onAbilityCreate ability:" + JSON.stringify(ability)); + }, + onWindowStageCreate(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageCreate ability:" + JSON.stringify(ability)); + console.log("AbilityLifecycleCallback onWindowStageCreate windowStage:" + JSON.stringify(windowStage)); + }, + onWindowStageActive(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageActive ability:" + JSON.stringify(ability)); + console.log("AbilityLifecycleCallback onWindowStageActive windowStage:" + JSON.stringify(windowStage)); + }, + onWindowStageInactive(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageInactive ability:" + JSON.stringify(ability)); + console.log("AbilityLifecycleCallback onWindowStageInactive windowStage:" + JSON.stringify(windowStage)); + }, + onWindowStageDestroy(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageDestroy ability:" + JSON.stringify(ability)); + console.log("AbilityLifecycleCallback onWindowStageDestroy windowStage:" + JSON.stringify(windowStage)); + }, + onAbilityDestroy(ability){ + console.log("AbilityLifecycleCallback onAbilityDestroy ability:" + JSON.stringify(ability)); + }, + onAbilityForeground(ability){ + console.log("AbilityLifecycleCallback onAbilityForeground ability:" + JSON.stringify(ability)); + }, + onAbilityBackground(ability){ + console.log("AbilityLifecycleCallback onAbilityBackground ability:" + JSON.stringify(ability)); + }, + onAbilityContinue(ability){ + console.log("AbilityLifecycleCallback onAbilityContinue ability:" + JSON.stringify(ability)); + } + } + // 1. Obtain applicationContext through the context attribute. + let applicationContext = this.context.getApplicationContext(); + // 2. Use applicationContext to register a listener for the ability lifecycle in the application. + let lifecycleid = applicationContext.on("abilityLifecycle", AbilityLifecycleCallback); + console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleid)); + }, + onDestroy() { + let applicationContext = this.context.getApplicationContext(); + applicationContext.off("abilityLifecycle", lifecycleid, (error, data) => { + console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error)); + }); + } + } + ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityManager.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityManager.md new file mode 100644 index 0000000000000000000000000000000000000000..0a191c0038f3a5811018346ffe779dc558b3ad20 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityManager.md @@ -0,0 +1,308 @@ +# @ohos.app.ability.abilityManager + +The **AbilityManager** module provides APIs for obtaining, adding, and modifying ability running information and state information. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are system APIs and cannot be called by third-party applications. + +## Modules to Import + +```ts +import AbilityManager from '@ohos.app.ability.abilityManager' +``` + +## AbilityState + +Enumerates the ability states. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name| Value| Description| +| -------- | -------- | -------- | +| INITIAL | 0 | The ability is in the initial state.| +| FOREGROUND | 9 | The ability is in the foreground state. | +| BACKGROUND | 10 | The ability is in the background state. | +| FOREGROUNDING | 11 | The ability is in the foregrounding state. | +| BACKGROUNDING | 12 | The ability is in the backgrounding state. | + +## updateConfiguration + +updateConfiguration(config: Configuration, callback: AsyncCallback\): void + +Updates the configuration. This API uses an asynchronous callback to return the result. + +**Permission required**: ohos.permission.UPDATE_CONFIGURATION + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| config | [Configuration](js-apis-app-ability-configuration.md) | Yes | New configuration.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```ts +import abilitymanager from '@ohos.app.ability.abilityManager'; + +var config = { + language: 'chinese' +} + +try { + abilitymanager.updateConfiguration(config, () => { + console.log('------------ updateConfiguration -----------'); + }) +} catch (paramError) { + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); +} +``` + +## updateConfiguration + +updateConfiguration(config: Configuration): Promise\ + +Updates the configuration. This API uses a promise to return the result. + +**Permission required**: ohos.permission.UPDATE_CONFIGURATION + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| config | [Configuration](js-apis-app-ability-configuration.md) | Yes | New configuration.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```ts +import abilitymanager from '@ohos.app.ability.abilityManager'; + +var config = { + language: 'chinese' +} + +try { + abilitymanager.updateConfiguration(config).then(() => { + console.log('updateConfiguration success'); + }).catch((err) => { + console.log('updateConfiguration fail'); + }) +} catch (paramError) { + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); +} +``` + +## getAbilityRunningInfos + +getAbilityRunningInfos(callback: AsyncCallback\>): void + +Obtains the ability running information. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| callback | AsyncCallback\> | Yes | Callback used to return the result. | + +**Example** + +```ts +import abilitymanager from '@ohos.app.ability.abilityManager'; + +try { + abilitymanager.getAbilityRunningInfos((err,data) => { + console.log("getAbilityRunningInfos err: " + err + " data: " + JSON.stringify(data)); + }); +} catch (paramError) { + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); +} +``` + +## getAbilityRunningInfos + +getAbilityRunningInfos(): Promise\> + +Obtains the ability running information. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------- | +| Promise\> | Promise used to return the result.| + +**Example** + +```ts +import abilitymanager from '@ohos.app.ability.abilityManager'; + +try { + abilitymanager.getAbilityRunningInfos().then((data) => { + console.log("getAbilityRunningInfos data: " + JSON.stringify(data)) + }).catch((err) => { + console.log("getAbilityRunningInfos err: " + err) + }); +} catch (paramError) { + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); +} +``` + +## getExtensionRunningInfos + +getExtensionRunningInfos(upperLimit: number, callback: AsyncCallback\>): void + +Obtains the extension running information. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| upperLimit | number | Yes| Maximum number of messages that can be obtained.| +| callback | AsyncCallback\> | Yes | Callback used to return the result. | + +**Example** + +```ts +import abilitymanager from '@ohos.app.ability.abilityManager'; + +var upperLimit = 0; + +try { + abilitymanager.getExtensionRunningInfos(upperLimit, (err,data) => { + console.log("getExtensionRunningInfos err: " + err + " data: " + JSON.stringify(data)); + }); +} catch (paramError) { + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); +} +``` + +## getExtensionRunningInfos + +getExtensionRunningInfos(upperLimit: number): Promise\> + +Obtains the extension running information. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| upperLimit | number | Yes| Maximum number of messages that can be obtained.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------- | +| Promise\> | Promise used to return the result.| + +**Example** + +```ts +import abilitymanager from '@ohos.app.ability.abilityManager'; + +var upperLimit = 0; + +try { + abilitymanager.getExtensionRunningInfos(upperLimit).then((data) => { + console.log("getAbilityRunningInfos data: " + JSON.stringify(data)); + }).catch((err) => { + console.log("getAbilityRunningInfos err: " + err); + }) +} catch (paramError) { + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); +} +``` + +## getTopAbility9+ + +getTopAbility(callback: AsyncCallback\): void; + +Obtains the top ability, which is the ability that has the window focus. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```ts +import abilitymanager from '@ohos.app.ability.abilityManager'; + +try { + abilitymanager.getTopAbility((err,data) => { + console.log("getTopAbility err: " + err + " data: " + JSON.stringify(data)); + }); +} catch (paramError) { + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); +} +``` + +## getTopAbility + +getTopAbility(): Promise\; + +Obtains the top ability, which is the ability that has the window focus. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------- | +| Promise\| Promise used to return the result.| + +**Example** + +```ts +import abilitymanager from '@ohos.app.ability.abilityManager'; + +try { + abilitymanager.getTopAbility().then((data) => { + console.log("getTopAbility data: " + JSON.stringify(data)); + }).catch((err) => { + console.log("getTopAbility err: " + err); + }) +} catch (paramError) { + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityStage.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityStage.md new file mode 100644 index 0000000000000000000000000000000000000000..b1226842409c7d03c82d25d33319042a716b9d86 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityStage.md @@ -0,0 +1,127 @@ +# @ohos.app.ability.AbilityStage + +**AbilityStage** is a runtime class for HAP files. + +**AbilityStage** notifies you of when you can perform HAP initialization such as resource pre-loading and thread creation during the HAP loading. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the stage model. + +## Modules to Import + +```ts +import AbilityStage from '@ohos.app.ability.AbilityStage'; +``` + +## AbilityStage.onCreate + +onCreate(): void + +Called when the application is created. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Example** + + ```ts + class MyAbilityStage extends AbilityStage { + onCreate() { + console.log("MyAbilityStage.onCreate is called") + } + } + ``` + + +## AbilityStage.onAcceptWant + +onAcceptWant(want: Want): string; + +Called when a specified ability is started. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-app-ability-want.md) | Yes| Information about the ability to start, such as the ability name and bundle name.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | string | Returns an ability ID. If this ability has been started, no new instance is created and the ability is placed at the top of the stack. Otherwise, a new instance is created and started.| + +**Example** + + ```ts + class MyAbilityStage extends AbilityStage { + onAcceptWant(want) { + console.log("MyAbilityStage.onAcceptWant called"); + return "com.example.test"; + } + } + ``` + + +## AbilityStage.onConfigurationUpdate + +onConfigurationUpdate(newConfig: Configuration): void; + +Called when the global configuration is updated. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | newConfig | [Configuration](js-apis-app-ability-configuration.md) | Yes| Callback invoked when the global configuration is updated. The global configuration indicates the configuration of the environment where the application is running and includes the language and color mode.| + +**Example** + + ```ts + class MyAbilityStage extends AbilityStage { + onConfigurationUpdate(config) { + console.log('onConfigurationUpdate, language:' + config.language); + } + } + ``` + +## AbilityStage.onMemoryLevel + +onMemoryLevel(level: AbilityConstant.MemoryLevel): void; + +Called when the system has decided to adjust the memory level. For example, this API can be used when there is not enough memory to run as many background processes as possible. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | level | [AbilityConstant.MemoryLevel](js-apis-app-ability-abilityConstant.md#abilityconstantmemorylevel) | Yes| Memory level that indicates the memory usage status. When the specified memory level is reached, a callback will be invoked and the system will start adjustment.| + +**Example** + + ```ts + class MyAbilityStage extends AbilityStage { + onMemoryLevel(level) { + console.log('onMemoryLevel, level:' + JSON.stringify(level)); + } + } + ``` + +## AbilityStage.context + +context: AbilityStageContext; + +Describes the configuration information about the context. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Type | Description | +| ----------- | --------------------------- | ------------------------------------------------------------ | +| context | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | Called when initialization is performed during ability startup.| diff --git a/en/application-dev/reference/apis/js-apis-app-ability-appManager.md b/en/application-dev/reference/apis/js-apis-app-ability-appManager.md new file mode 100644 index 0000000000000000000000000000000000000000..b6fae35d6d03575442b1223c63cbcd4150773bb9 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-appManager.md @@ -0,0 +1,753 @@ +# @ohos.app.ability.appManager + +The **appManager** module implements application management. You can use the APIs of this module to query whether the application is undergoing a stability test, whether the application is running on a RAM constrained device, the memory size of the application, and information about the running process. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```ts +import appManager from '@ohos.app.ability.appManager'; +``` + +## appManager.isRunningInStabilityTest9+ + +static isRunningInStabilityTest(callback: AsyncCallback<boolean>): void + +Checks whether this application is undergoing a stability test. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<boolean> | Yes| Callback used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| + +**Example** + + ```ts + import app from '@ohos.application.appManager'; + app.isRunningInStabilityTest((err, flag) => { + console.log('startAbility result:' + JSON.stringify(err)); + }) + ``` + + +## appManager.isRunningInStabilityTest9+ + +static isRunningInStabilityTest(): Promise<boolean> + +Checks whether this application is undergoing a stability test. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<boolean> | Promise used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| + +**Example** + + ```ts + import app from '@ohos.application.appManager'; + app.isRunningInStabilityTest().then((flag) => { + console.log('success:' + JSON.stringify(flag)); + }).catch((error) => { + console.log('failed:' + JSON.stringify(error)); + }); + ``` + + +## appManager.isRamConstrainedDevice + +isRamConstrainedDevice(): Promise\; + +Checks whether this application is running on a RAM constrained device. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<boolean> | Promise used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| + +**Example** + + ```ts + app.isRamConstrainedDevice().then((data) => { + console.log('success:' + JSON.stringify(data)); + }).catch((error) => { + console.log('failed:' + JSON.stringify(error)); + }); + ``` + +## appManager.isRamConstrainedDevice + +isRamConstrainedDevice(callback: AsyncCallback\): void; + +Checks whether this application is running on a RAM constrained device. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<boolean> | Yes| Callback used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| + +**Example** + + ```ts + app.isRamConstrainedDevice((err, data) => { + console.log('startAbility result failed:' + JSON.stringify(err)); + console.log('startAbility result success:' + JSON.stringify(data)); + }) + ``` + +## appManager.getAppMemorySize + +getAppMemorySize(): Promise\; + +Obtains the memory size of this application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<number> | Size of the application memory.| + +**Example** + + ```ts + app.getAppMemorySize().then((data) => { + console.log('success:' + JSON.stringify(data)); + }).catch((error) => { + console.log('failed:' + JSON.stringify(error)); + }); + ``` + +## appManager.getAppMemorySize + +getAppMemorySize(callback: AsyncCallback\): void; + +Obtains the memory size of this application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<number> | Yes| Size of the application memory.| + +**Example** + + ```ts + app.getAppMemorySize((err, data) => { + console.log('startAbility result failed :' + JSON.stringify(err)); + console.log('startAbility result success:' + JSON.stringify(data)); + }) + ``` + +## appManager.getProcessRunningInformation9+ + +getProcessRunningInformation(): Promise\>; + +Obtains information about the running processes. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\> | Promise used to return the process information.| + +**Example** + + ```ts + app.getProcessRunningInformation().then((data) => { + console.log('success:' + JSON.stringify(data)); + }).catch((error) => { + console.log('failed:' + JSON.stringify(error)); + }); + ``` + +## appManager.getProcessRunningInformation9+ + +getProcessRunningInformation(callback: AsyncCallback\>): void; + +Obtains information about the running processes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback\> | Yes| Callback used to return the process information.| + +**Example** + + ```ts + app.getProcessRunningInformation((err, data) => { + console.log('startAbility result failed :' + JSON.stringify(err)); + console.log('startAbility result success:' + JSON.stringify(data)); + }) + ``` + +## appManager.on + +on(type: "applicationState", observer: ApplicationStateObserver): number; + +Registers an observer to listen for the state changes of all applications. + +**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the API to call.| +| observer | [ApplicationStateObserver](./js-apis-inner-application-applicationStateObserver.md) | Yes| Numeric code of the observer.| + +**Example** + + ```js + var applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log('------------ onForegroundApplicationChanged -----------', appStateData); + }, + onAbilityStateChanged(abilityStateData) { + console.log('------------ onAbilityStateChanged -----------', abilityStateData); + }, + onProcessCreated(processData) { + console.log('------------ onProcessCreated -----------', processData); + }, + onProcessDied(processData) { + console.log('------------ onProcessDied -----------', processData); + }, + onProcessStateChanged(processData) { + console.log('------------ onProcessStateChanged -----------', processData); + } + } + try { + const observerCode = app.on(applicationStateObserver); + console.log('-------- observerCode: ---------', observerCode); + } catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); + } + + ``` + +## appManager.on + +on(type: "applicationState", observer: ApplicationStateObserver, bundleNameList: Array\): number; + +Registers an observer to listen for the state changes of a specified application. + +**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the API to call.| +| observer | [ApplicationStateObserver](./js-apis-inner-application-applicationStateObserver.md) | Yes| Numeric code of the observer.| +| bundleNameList | Array | Yes| **bundleName** array of the application. A maximum of 128 bundle names can be passed.| + +**Example** + + ```js + var applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log('------------ onForegroundApplicationChanged -----------', appStateData); + }, + onAbilityStateChanged(abilityStateData) { + console.log('------------ onAbilityStateChanged -----------', abilityStateData); + }, + onProcessCreated(processData) { + console.log('------------ onProcessCreated -----------', processData); + }, + onProcessDied(processData) { + console.log('------------ onProcessDied -----------', processData); + }, + onProcessStateChanged(processData) { + console.log('------------ onProcessStateChanged -----------', processData); + } + } + var bundleNameList = ['bundleName1', 'bundleName2']; + try { + const observerCode = app.on("applicationState", applicationStateObserver, bundleNameList); + console.log('-------- observerCode: ---------', observerCode); + } catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); + } + + ``` +## appManager.off + +off(type: "applicationState", observerId: number, callback: AsyncCallback\): void; + +Deregisters the application state observer. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the API to call.| +| observerId | number | Yes| Numeric code of the observer.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```js + var observerId = 100; + + function unregisterApplicationStateObserverCallback(err) { + if (err) { + console.log('------------ unregisterApplicationStateObserverCallback ------------', err); + } + } + try { + app.off(observerId, unregisterApplicationStateObserverCallback); + } catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); + } + ``` + +## appManager.off + +off(type: "applicationState", observerId: number): Promise\; + +Deregisters the application state observer. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the API to call.| +| observerId | number | Yes| Numeric code of the observer.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\ | Promise used to return the result.| + +**Example** + + ```js + var observerId = 100; + + try { + app.off(observerId) + .then((data) => { + console.log('----------- unregisterApplicationStateObserver success ----------', data); + }) + .catch((err) => { + console.log('----------- unregisterApplicationStateObserver fail ----------', err); + }) + } catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); + } + ``` + +## appManager.getForegroundApplications + +getForegroundApplications(callback: AsyncCallback\>): void; + +Obtains applications that are running in the foreground. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback\> | Yes| Callback used to return the application state data.| + +**Example** + + ```js + function getForegroundApplicationsCallback(err, data) { + if (err) { + console.log('--------- getForegroundApplicationsCallback fail ---------', err.code + ': ' + err.message); + } else { + console.log('--------- getForegroundApplicationsCallback success ---------', data) + } + } + app.getForegroundApplications(getForegroundApplicationsCallback); + ``` + +unregisterApplicationStateObserver(observerId: number): Promise\; + +Deregisters the application state observer. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| observerId | number | Yes| Numeric code of the observer.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\ | Promise used to return the result.| + +**Example** + + ```ts + var observerId = 100; + app.unregisterApplicationStateObserver(observerId) + .then((data) => { + console.log('----------- unregisterApplicationStateObserver success ----------', data); + }) + .catch((err) => { + console.log('----------- unregisterApplicationStateObserver fail ----------', err); + }) + ``` + +## appManager.getForegroundApplications9+ + +getForegroundApplications(callback: AsyncCallback\>): void; + +Obtains applications that are running in the foreground. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback\> | Yes| Callback used to return the application state data.| + +**Example** + + ```ts + function getForegroundApplicationsCallback(err, data) { + if (err) { + console.log('--------- getForegroundApplicationsCallback fail ---------', err); + } else { + console.log('--------- getForegroundApplicationsCallback success ---------', data) + } + } + app.getForegroundApplications(getForegroundApplicationsCallback); + ``` + +## appManager.getForegroundApplications9+ + +getForegroundApplications(): Promise\>; + +Obtains applications that are running in the foreground. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\> | Promise used to return the application state data.| + +**Example** + + ```ts + app.getForegroundApplications() + .then((data) => { + console.log('--------- getForegroundApplications success -------', data); + }) + .catch((err) => { + console.log('--------- getForegroundApplications fail -------', err); + }) + ``` + +## appManager.killProcessWithAccount9+ + +killProcessWithAccount(bundleName: string, accountId: number): Promise\ + +Kills a process by bundle name and account ID. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS and ohos.permission.CLEAN_BACKGROUND_PROCESSES + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | bundleName | string | Yes| Bundle name of an application.| + | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| + +**Example** + +```ts +var bundleName = 'bundleName'; +var accountId = 0; +app.killProcessWithAccount(bundleName, accountId) + .then((data) => { + console.log('------------ killProcessWithAccount success ------------', data); + }) + .catch((err) => { + console.log('------------ killProcessWithAccount fail ------------', err); + }) +``` + + +## appManager.killProcessWithAccount9+ + +killProcessWithAccount(bundleName: string, accountId: number, callback: AsyncCallback\): void + +Kills a process by bundle name and account ID. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS and ohos.permission.CLEAN_BACKGROUND_PROCESSES + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | bundleName | string | Yes| Bundle name of an application.| + | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| + | callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + +```ts +var bundleName = 'bundleName'; +var accountId = 0; +function killProcessWithAccountCallback(err, data) { + if (err) { + console.log('------------- killProcessWithAccountCallback fail, err: --------------', err); + } else { + console.log('------------- killProcessWithAccountCallback success, data: --------------', data); + } +} +app.killProcessWithAccount(bundleName, accountId, killProcessWithAccountCallback); +``` + +## appManager.killProcessesByBundleName9+ + +killProcessesByBundleName(bundleName: string, callback: AsyncCallback\); + +Kills a process by bundle name. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CLEAN_BACKGROUND_PROCESSES + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name of an application.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```ts + var bundleName = 'bundleName'; + function killProcessesByBundleNameCallback(err, data) { + if (err) { + console.log('------------- killProcessesByBundleNameCallback fail, err: --------------', err); + } else { + console.log('------------- killProcessesByBundleNameCallback success, data: --------------', data); + } + } + app.killProcessesByBundleName(bundleName, killProcessesByBundleNameCallback); + ``` + +## appManager.killProcessesByBundleName9+ + +killProcessesByBundleName(bundleName: string): Promise\; + +Kills a process by bundle name. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CLEAN_BACKGROUND_PROCESSES + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name of an application.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\ | Promise used to return the result.| + +**Example** + + ```ts +var bundleName = 'bundleName'; +app.killProcessesByBundleName(bundleName) + .then((data) => { + console.log('------------ killProcessesByBundleName success ------------', data); + }) + .catch((err) => { + console.log('------------ killProcessesByBundleName fail ------------', err); + }) + ``` + +## appManager.clearUpApplicationData9+ + +clearUpApplicationData(bundleName: string, callback: AsyncCallback\); + +Clears application data by bundle name. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CLEAN_APPLICATION_DATA + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name of an application.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```ts + var bundleName = 'bundleName'; + function clearUpApplicationDataCallback(err, data) { + if (err) { + console.log('------------- clearUpApplicationDataCallback fail, err: --------------', err); + } else { + console.log('------------- clearUpApplicationDataCallback success, data: --------------', data); + } + } + app.clearUpApplicationData(bundleName, clearUpApplicationDataCallback); + ``` + +## appManager.clearUpApplicationData9+ + +clearUpApplicationData(bundleName: string): Promise\; + +Clears application data by bundle name. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CLEAN_APPLICATION_DATA + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name of an application.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\ | Promise used to return the result.| + +**Example** + + ```ts + var bundleName = 'bundleName'; + app.clearUpApplicationData(bundleName) + .then((data) => { + console.log('------------ clearUpApplicationData success ------------', data); + }) + .catch((err) => { + console.log('------------ clearUpApplicationData fail ------------', err); + }) + ``` + +## ApplicationState9+ + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Value | Description | +| -------------------- | --- | --------------------------------- | +| STATE_CREATE | 1 | State indicating that the application is being created. | +| STATE_FOREGROUND | 2 | State indicating that the application is running in the foreground. | +| STATE_ACTIVE | 3 | State indicating that the application is active. | +| STATE_BACKGROUND | 4 | State indicating that the application is running in the background. | +| STATE_DESTROY | 5 | State indicating that the application is destroyed. | + +## ProcessState9+ + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Value | Description | +| -------------------- | --- | --------------------------------- | +| STATE_CREATE | 1 | State indicating that the process is being created. | +| STATE_FOREGROUND | 2 | State indicating that the process is running in the foreground. | +| STATE_ACTIVE | 3 | State indicating that the process is active. | +| STATE_BACKGROUND | 4 | State indicating that the process is running in the background. | +| STATE_DESTROY | 5 | State indicating that the process is destroyed. | diff --git a/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md b/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md new file mode 100644 index 0000000000000000000000000000000000000000..80c507b83ab0012aafbdc9745810730a54997293 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md @@ -0,0 +1,121 @@ +# @ohos.app.ability.appRecovery + +The **appRecovery** module provides APIs for recovering faulty applications. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. In the current version, only applications with a single ability in a single process can be recovered. + +## Modules to Import +```ts +import appRecovery from '@ohos.app.ability.appRecovery' +``` + + +## appRecovery.RestartFlag + +Enumerates the application restart options used in [enableAppRecovery](#apprecoveryenableapprecovery). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ----------------------------- | ---- | ------------------------------------------------------------ | +| ALWAYS_RESTART | 0 | The application is restarted in all cases.| +| CPP_CRASH_NO_RESTART | 0x0001 | The application is not restarted in the case of CPP_CRASH.| +| JS_CRASH_NO_RESTART | 0x0002 | The application is not restarted in the case of JS_CRASH.| +| APP_FREEZE_NO_RESTART | 0x0004 | The application is not restarted in the case of APP_FREEZE.| +| NO_RESTART | 0xFFFF | The application is not restarted in any case.| + +## appRecovery.SaveOccasionFlag + +Enumerates the scenarios for saving the application state, which is used in [enableAppRecovery](#apprecoveryenableapprecovery). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ----------------------------- | ---- | ------------------------------------------------------------ | +| SAVE_WHEN_ERROR | 0x0001 | Saving the application state when an application fault occurs.| +| SAVE_WHEN_BACKGROUND | 0x0002 | Saving the application state when the application is switched to the background.| + +## appRecovery.SaveModeFlag + +Enumerates the application state saving modes used in [enableAppRecovery](#apprecoveryenableapprecovery). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ----------------------------- | ---- | ------------------------------------------------------------ | +| SAVE_WITH_FILE | 0x0001 | The application state is saved and written to the local file cache.| +| SAVE_WITH_SHARED_MEMORY | 0x0002 | The application state is saved in the memory. When the application exits due to a fault, it is written to the local file cache.| + +## appRecovery.enableAppRecovery + +enableAppRecovery(restart?: RestartFlag, saveOccasion?: SaveOccasionFlag, saveMode?: SaveModeFlag) : void; + +Enables application recovery. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| restart | [RestartFlag](#apprecoveryrestartflag) | No| Whether the application is restarted upon a fault. By default, the application is not restarted.| +| saveOccasion | [SaveOccasionFlag](#apprecoverysaveoccasionflag) | No| Scenario for saving the application state. By default, the state is saved when a fault occurs.| +| saveMode | [SaveModeFlag](#apprecoverysavemodeflag) | No| Application state saving mode. By default, the application state is written to the local file cache.| + +**Example** + +```ts +export default class MyAbilityStage extends AbilityStage { + onCreate() { + appRecovery.enableAppRecovery(RestartFlag::ALWAYS_RESTART, SaveOccasionFlag::SAVE_WHEN_ERROR, SaveModeFlag::SAVE_WITH_FILE); + } +} +``` + +## appRecovery.restartApp + +restartApp(): void; + +Restarts the application. This API can be used together with APIs of [errorManager](js-apis-app-ability-errorManager.md). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + + +**Example** + +```ts +var observer = { + onUnhandledException(errorMsg) { + console.log('onUnhandledException, errorMsg: ', errorMsg) + appRecovery.restartApp(); + } +} + +``` + +## appRecovery.saveAppState + +saveAppState(): boolean; + +Saves the application state. This API can be used together with APIs of [errorManager](js-apis-app-ability-errorManager.md). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Whether the saving is successful.| + +**Example** + +```ts +var observer = { + onUnhandledException(errorMsg) { + console.log('onUnhandledException, errorMsg: ', errorMsg) + appRecovery.saveAppState(); + } +} +``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-common.md b/en/application-dev/reference/apis/js-apis-app-ability-common.md new file mode 100644 index 0000000000000000000000000000000000000000..23184c6036f12bd3c914d7b500fece72afafc538 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-common.md @@ -0,0 +1,62 @@ +# @ohos.app.ability.common + +The **Common** module provides all level-2 module APIs for developers to export. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the stage model. + +## Modules to Import + +```ts +import common from '@ohos.app.ability.common' +``` + +**System capability**: SystemCapability.Ability.AbilityBase + +| Name | Type | Mandatory| Description | +| ----------- | -------------------- | ---- | ------------------------------------------------------------ | +| UIAbilityContext | [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) | No | Level-2 module **UIAbilityContext**. | +| AbilityStageContext | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | No | Level-2 module **AbilityStageContext**.| +| ApplicationContext | [ApplicationContext](js-apis-inner-application-applicationContext.md) | No | Level-2 module **ApplicationContext**.| +| BaseContext | [BaseContext](js-apis-inner-application-baseContext.md) | No | Level-2 module **BaseContext**.| +| Context | [Context](js-apis-inner-application-context.md) | No | Level-2 module **Context**.| +| ExtensionContext | [ExtensionContext](js-apis-inner-application-extensionContext.md) | No | Level-2 module **ExtensionContext**.| +| FormExtensionContext | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | No | Level-2 module **FormExtensionContext**.| +| AreaMode | [AreaMode](#areamode) | No | Enumerated values of **AreaMode**.| +| EventHub | [EventHub](js-apis-inner-application-eventHub.md) | No | Level-2 module **EventHub**.| +| PermissionRequestResult | [PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md) | No | Level-2 module **PermissionRequestResult**.| +| PacMap | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#PacMap) | No | Level-2 module **PacMap**.| +| AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | No | Level-2 module **AbilityResult**.| +| ConnectOptions | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | No | Level-2 module **ConnectOptions**.| + +**Example** +```ts +import common from '@ohos.app.ability.common' + +let uiAbilityContext: common.UIAbilityContext; +let abilityStageContext: common.AbilityStageContext; +let applicationContext: common.ApplicationContext; +let baseContext: common.BaseContext; +let context: common.Context; +let extensionContext: common.ExtensionContext; +let formExtensionContext: common.FormExtensionContext; +let areaMode: common.AreaMode; +let eventHub: common.EventHub; +let permissionRequestResult: common.PermissionRequestResult; +let pacMap: common.PacMap; +let abilityResult: common.AbilityResult; +let connectOptions: common.ConnectOptions; +``` + +## AreaMode + +Defines the area where the file to be access is located. Each area has its own content. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| --------------- | ---- | --------------- | +| EL1 | 0 | Device-level encryption area. | +| EL2 | 1 | User credential encryption area. The default value is **EL2**.| diff --git a/en/application-dev/reference/apis/js-apis-app-ability-configuration.md b/en/application-dev/reference/apis/js-apis-app-ability-configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..90075377af701150b8de77600ed3ae3808b50d41 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-configuration.md @@ -0,0 +1,47 @@ +# @ohos.app.ability.Configuration + +The **Configuration** module defines environment change information. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```ts +import Configuration from '@ohos.app.ability.Configuration' +``` + +**System capability**: SystemCapability.Ability.AbilityBase + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| language | string | Yes| Yes| Language of the application.| +| colorMode | [ColorMode](js-apis-app-ability-configurationConstant.md#configurationconstantcolormode) | Yes| Yes| Color mode, which can be **COLOR_MODE_LIGHT** or **COLOR_MODE_DARK**. The default value is **COLOR_MODE_LIGHT**.| +| direction | Direction | Yes| No| Screen orientation, which can be **DIRECTION_HORIZONTAL** or **DIRECTION_VERTICAL**.| +| screenDensity | ScreenDensity | Yes| No| Screen resolution, which can be **SCREEN_DENSITY_SDPI** (120), **SCREEN_DENSITY_MDPI** (160), **SCREEN_DENSITY_LDPI** (240), **SCREEN_DENSITY_XLDPI** (320), **SCREEN_DENSITY_XXLDPI** (480), or **SCREEN_DENSITY_XXXLDPI** (640).| +| displayId | number | Yes| No| ID of the display where the application is located.| +| hasPointerDevice | boolean | Yes| No| Whether a pointer device, such as a keyboard, mouse, or touchpad, is connected.| + +For details about the fields, see the **ohos.app.ability.Configuration.d.ts** file. + +**Example** + + ```ts + let envCallback = { + onConfigurationUpdated(config) { + console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`) + let language = config.language; + let colorMode = config.colorMode; + let direction = config.direction; + let screenDensity = config.screenDensity; + let displayId = config.displayId; + let hasPointerDevice = config.hasPointerDevice; + } + }; + try { + var callbackId = applicationContext.on("environment", envCallback); + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + ``` diff --git a/en/application-dev/reference/apis/js-apis-configurationconstant.md b/en/application-dev/reference/apis/js-apis-app-ability-configurationConstant.md similarity index 82% rename from en/application-dev/reference/apis/js-apis-configurationconstant.md rename to en/application-dev/reference/apis/js-apis-app-ability-configurationConstant.md index 70d527483a15d7f676402ad406964740a5686a6b..24b6b4745b1ba606cdb40c741fa2fcf10376cc06 100644 --- a/en/application-dev/reference/apis/js-apis-configurationconstant.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-configurationConstant.md @@ -1,28 +1,21 @@ -# ConfigurationConstant +# @ohos.app.ability.ConfigurationConstant The **ConfigurationConstant** module provides the enumerated values of the environment configuration information. > **NOTE** > -> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import - -```js -import ConfigurationConstant from '@ohos.application.ConfigurationConstant'; +```ts +import ConfigurationConstant from '@ohos.app.ability.ConfigurationConstant'; ``` ## ConfigurationConstant.ColorMode You can obtain the value of this constant by calling the **ConfigurationConstant.ColorMode** API. -**Example** - -``` -ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT -``` - **System capability**: SystemCapability.Ability.AbilityBase | Name| Value| Description| @@ -36,12 +29,6 @@ ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT You can obtain the value of this constant by calling the **ConfigurationConstant.Direction** API. -**Example** - -``` -ConfigurationConstant.Direction.DIRECTION_VERTICAL -``` - **System capability**: SystemCapability.Ability.AbilityBase | Name| Value| Description| @@ -55,12 +42,6 @@ ConfigurationConstant.Direction.DIRECTION_VERTICAL You can obtain the value of this constant by calling the **ConfigurationConstant.ScreenDensity** API. -**Example** - -``` -ConfigurationConstant.ScreenDensity.SCREEN_DENSITY_NOT_SET -``` - **System capability**: SystemCapability.Ability.AbilityBase | Name| Value| Description| diff --git a/en/application-dev/reference/apis/js-apis-app-ability-contextConstant.md b/en/application-dev/reference/apis/js-apis-app-ability-contextConstant.md new file mode 100644 index 0000000000000000000000000000000000000000..dc1b5a1430c8c063de23cc87126ff891d5363b80 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-contextConstant.md @@ -0,0 +1,25 @@ +# @ohos.app.ability.contextConstant + +The **ContextConstant** module defines data encryption levels. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the stage model. + +## Modules to Import + +```ts +import contextConstant from '@ohos.app.ability.contextConstant'; +``` + +## ContextConstant.AreaMode + +You can obtain the value of this constant by calling the **ContextConstant.AreaMode** API. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name| Value| Description| +| -------- | -------- | -------- | +| EL1 | 0 | Device-level encryption area.| +| EL2 | 1 | User credential encryption area.| diff --git a/en/application-dev/reference/apis/js-apis-app-ability-dataUriUtils.md b/en/application-dev/reference/apis/js-apis-app-ability-dataUriUtils.md new file mode 100644 index 0000000000000000000000000000000000000000..a13e0f73daea27a21a57b6af321dcc9ee8afa038 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-dataUriUtils.md @@ -0,0 +1,155 @@ +# ohos.app.ability.dataUriUtils + +The **DataUriUtils** module provides APIs to handle utility classes for objects using the **DataAbilityHelper** schema. You can use the APIs to attach an ID to the end of a given URI and obtain, delete, or update the ID attached to the end of a given URI. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```ts +import dataUriUtils from '@ohos.app.ability.dataUriUtils'; +``` + +## dataUriUtils.getId + +getId(uri: string): number + +Obtains the ID attached to the end of a given URI. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ---- | ------ | ---- | --------------------------- | +| uri | string | Yes | URI object from which the ID is to be obtained.| + +**Return value** + +| Type | Description | +| ------ | ------------------------ | +| number | ID obtained from the URI object.| + +**Example** + +```ts +try { + var id = dataUriUtils.getId("com.example.dataUriUtils/1221") + console.info('get id: ' + id) +} catch(err) { + console.error('get id err ,check the uri' + err) +} +``` + + + +## dataUriUtils.attachId + +attachId(uri: string, id: number): string + +Attaches an ID to the end of a given URI. It can be used to generate a new URI. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ---- | ------ | ---- | --------------------------- | +| uri | string | Yes | URI object to which an ID is to be attached.| +| id | number | Yes | ID to be attached. | + +**Return value** + +| Type | Description | +| ------ | --------------------- | +| string | URI object with the ID attached.| + +**Example** + +```ts +var idint = 1122; +try { + var uri = dataUriUtils.attachId( + "com.example.dataUriUtils", + idint, + ) + console.info('attachId the uri is: ' + uri) +} catch (err) { + console.error('get id err ,check the uri' + err) +} + +``` + + + +## dataUriUtils.deleteId + +deleteId(uri: string): string + +Deletes the ID from the end of a given URI. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ---- | ------ | ---- | --------------------------- | +| uri | string | Yes | URI object from which the ID is to be deleted.| + +**Return value** + +| Type | Description | +| ------ | ------------------- | +| string | URI object with the ID deleted.| + +**Example** + +```ts +try { + var uri = dataUriUtils.deleteId("com.example.dataUriUtils/1221") + console.info('delete id with the uri is: ' + uri) +} catch(err) { + console.error('delete uri err, check the input uri' + err) +} + +``` + + + +## dataUriUtils.updateId + +updateId(uri: string, id: number): string + +Updates the ID in a given URI. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ---- | ------ | ---- | ------------------- | +| uri | string | Yes | URI object to be updated.| +| id | number | Yes | New ID. | + +**Return value** + +| Type | Description | +| ------ | --------------- | +| string | URI object with the new ID.| + +**Example** + +```ts + +try { + var idint = 1122; + var uri = dataUriUtils.updateId( + "com.example.dataUriUtils", + idint + ) +} catch (err) { + console.error('delete uri err, check the input uri' + err) +} +``` diff --git a/en/application-dev/reference/apis/js-apis-application-EnvironmentCallback.md b/en/application-dev/reference/apis/js-apis-app-ability-environmentCallback.md similarity index 82% rename from en/application-dev/reference/apis/js-apis-application-EnvironmentCallback.md rename to en/application-dev/reference/apis/js-apis-app-ability-environmentCallback.md index f0d75fc57deed25160bbb080ef1565a45a94679d..1208aeb8dabdbc09b77a9395e0ad313b1bf7e8cd 100644 --- a/en/application-dev/reference/apis/js-apis-application-EnvironmentCallback.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-environmentCallback.md @@ -1,4 +1,4 @@ -# EnvironmentCallback +# @ohos.app.ability.EnvironmentCallback The **EnvironmentCallback** module provides the **onConfigurationUpdated** API for the application context to listen for system environment changes. @@ -10,8 +10,8 @@ The **EnvironmentCallback** module provides the **onConfigurationUpdated** API f ## Modules to Import -```js -import EnvironmentCallback from "@ohos.application.EnvironmentCallback"; +```ts +import EnvironmentCallback from "@ohos.app.ability.EnvironmentCallback"; ``` @@ -27,19 +27,19 @@ Called when the system environment changes. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | config | [Configuration](js-apis-configuration.md) | Yes| **Configuration** object after the change.| + | config | [Configuration](js-apis-app-ability-configuration.md) | Yes| **Configuration** object after the change.| **Example** - ```js -import AbilityStage from "@ohos.application.AbilityStage"; + ```ts +import Ability from "@ohos.application.Ability"; var callbackId; -export default class MyAbilityStage extends AbilityStage { +export default class MyAbility extends Ability { onCreate() { - console.log("MyAbilityStage onCreate") + console.log("MyAbility onCreate") globalThis.applicationContext = this.context.getApplicationContext(); let EnvironmentCallback = { onConfigurationUpdated(config){ diff --git a/en/application-dev/reference/apis/js-apis-app-ability-errorManager.md b/en/application-dev/reference/apis/js-apis-app-ability-errorManager.md new file mode 100644 index 0000000000000000000000000000000000000000..3fb88a2b8ad93d3dbb5adf627f105d117ca86fda --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-errorManager.md @@ -0,0 +1,114 @@ +# @ohos.app.ability.errorManager + +The **ErrorManager** module provides APIs for registering and deregistering error observers. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import +``` +import errorManager from '@ohos.app.ability.errorManager' +``` + +## ErrorManager.on + +on(type: "error", observer: ErrorObserver): number; + +Registers an error observer. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the API to call.| +| observer | [ErrorObserver](./js-apis-inner-application-errorObserver.md) | Yes| Numeric code of the observer.| + +**Example** + +```js +var observer = { + onUnhandledException(errorMsg) { + console.log('onUnhandledException, errorMsg: ', errorMsg) + } +} +try { + errorManager.on("error", observer); +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} +``` + +## ErrorManager.off + +off(type: "error", observerId: number, callback: AsyncCallback\): void; + +Deregisters an error observer. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the API to call.| +| observerId | number | Yes| Numeric code of the observer.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + +```js +var observerId = 100; + +function unregisterErrorObserverCallback(err) { + if (err) { + console.log('------------ unregisterErrorObserverCallback ------------', err); + } +} +try { + errorManager.off("error", observerId, unregisterErrorObserverCallback); +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} +``` + +## ErrorManager.off + +off(type: "error", observerId: number): Promise\; + +Deregisters an error observer. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the API to call.| +| observerId | number | Yes| Numeric code of the observer.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +var observerId = 100; +try { + errorManager.off("error", observerId) + .then((data) => { + console.log('----------- unregisterErrorObserver success ----------', data); + }) + .catch((err) => { + console.log('----------- unregisterErrorObserver fail ----------', err); + }) +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} + +``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-extensionAbility.md b/en/application-dev/reference/apis/js-apis-app-ability-extensionAbility.md new file mode 100644 index 0000000000000000000000000000000000000000..b53881f7fdb5df90cf0a1783c04554ce93240b04 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-extensionAbility.md @@ -0,0 +1,30 @@ +# @ohos.app.ability.ExtensionAbility + +The **ExtensionAbility** module manages the Extension ability lifecycle and context, such as creating and destroying an Extension ability, and dumping client information. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the stage model. + +## Modules to Import + +```ts +import ExtensionAbility from '@ohos.app.ability.ExtensionAbility'; +``` + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Example** + + ```ts + class MyExtensionAbility extends ExtensionAbility { + onConfigurationUpdated(config) { + console.log('onConfigurationUpdated, config:' + JSON.stringify(config)); + } + + onMemoryLevel(level) { + console.log('onMemoryLevel, level:' + JSON.stringify(level)); + } + } + ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-missionManager.md b/en/application-dev/reference/apis/js-apis-app-ability-missionManager.md new file mode 100644 index 0000000000000000000000000000000000000000..4f989652d549a118d01097b3a8ec2f5084ec0031 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-missionManager.md @@ -0,0 +1,1058 @@ +# @ohos.app.ability.missionManager + +The **missionManager** module provides APIs to lock, unlock, and clear missions, and switch a mission to the foreground. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```ts +import missionManager from '@ohos.app.ability.missionManager' +``` + +## Required Permissions + +ohos.permission.MANAGE_MISSIONS + +## missionManager.on + +on(type:"mission", listener: MissionListener): number; + +Registers a listener to observe the mission status. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | listener | MissionListener | Yes| Listener to register.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | number | Returns the unique index of the mission status listener, which is created by the system and allocated when the listener is registered.| + +**Example** + +```ts +import Ability from '@ohos.application.Ability' +import missionManager from '@ohos.app.ability.missionManager'; + +var listener = { + onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, + onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, + onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, + onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, + onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, + onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")} +}; + +var listenerId = -1; + +export default class MainAbility extends Ability { + onCreate(want, launchParam) { + console.log("[Demo] MainAbility onCreate") + globalThis.abilityWant = want; + globalThis.context = this.context; + } + + onDestroy() { + try { + if (listenerId != -1) { + missionManager.off("mission", listenerId).catch(function (err) { + console.log(err); + }); + } + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + console.log("[Demo] MainAbility onDestroy") + } + + onWindowStageCreate(windowStage) { + // The main window is created. Set a main page for this ability. + console.log("[Demo] MainAbility onWindowStageCreate") + try { + listenerId = missionManager.on("mission", listener); + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + + windowStage.loadContent("pages/index", (err, data) => { + if (err.code) { + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)) + }); + + if (globalThis.flag) { + return; + } + } +}; +``` + + +## missionManager.off + +off(type: "mission", listenerId: number, callback: AsyncCallback<void>): void; + +Deregisters a mission status listener. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | listenerId | number | Yes| Unique index of the mission status listener to unregister. It is returned by **registerMissionListener**.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + +```ts +import Ability from '@ohos.application.Ability' +import missionManager from '@ohos.app.ability.missionManager'; + +var listener = { + onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, + onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, + onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, + onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, + onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, + onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")} +}; + +var listenerId = -1; + +export default class MainAbility extends Ability { + onCreate(want, launchParam) { + console.log("[Demo] MainAbility onCreate") + globalThis.abilityWant = want; + globalThis.context = this.context; + } + + onDestroy() { + try { + if (listenerId != -1) { + missionManager.off("mission", listenerId, (err) => { + console.log(err); + }); + } + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + console.log("[Demo] MainAbility onDestroy") + } + + onWindowStageCreate(windowStage) { + // The main window is created. Set a main page for this ability. + console.log("[Demo] MainAbility onWindowStageCreate") + try { + listenerId = missionManager.on("mission", listener); + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + + windowStage.loadContent("pages/index", (err, data) => { + if (err.code) { + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)) + }); + + if (globalThis.flag) { + return; + } + } +}; +``` + + +## missionManager.off + +off(type: "mission", listenerId: number): Promise<void>; + +Deregisters a mission status listener. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | listenerId | number | Yes| Unique index of the mission status listener to unregister. It is returned by **registerMissionListener**.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + +**Example** + +```ts +import Ability from '@ohos.application.Ability' +import missionManager from '@ohos.app.ability.missionManager'; + +var listener = { + onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, + onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, + onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, + onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, + onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, + onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")} +}; + +var listenerId = -1; + +export default class MainAbility extends Ability { + onCreate(want, launchParam) { + console.log("[Demo] MainAbility onCreate") + globalThis.abilityWant = want; + globalThis.context = this.context; + } + + onDestroy() { + try { + if (listenerId != -1) { + missionManager.off("mission", listenerId).catch(function (err) { + console.log(err); + }); + } + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + console.log("[Demo] MainAbility onDestroy") + } + + onWindowStageCreate(windowStage) { + // The main window is created. Set a main page for this ability. + console.log("[Demo] MainAbility onWindowStageCreate") + try { + listenerId = missionManager.on("mission", listener); + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + + windowStage.loadContent("pages/index", (err, data) => { + if (err.code) { + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)) + }); + + if (globalThis.flag) { + return; + } + } +}; +``` + + +## missionManager.getMissionInfo + +getMissionInfo(deviceId: string, missionId: number, callback: AsyncCallback<MissionInfo>): void; + +Obtains the information about a given mission. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| + | missionId | number | Yes| Mission ID.| + | callback | AsyncCallback<[MissionInfo](./js-apis-inner-application-missionInfo.md))> | Yes| Callback used to return the mission information obtained.| + +**Example** + + ```ts + import missionManager from '@ohos.app.ability.missionManager' + + try { + var allMissions=missionManager.getMissionInfos("",10).catch(function(err){console.log(err);}); + missionManager.getMissionInfo("", allMissions[0].missionId, (error, mission) => { + console.log("getMissionInfo is called, error.code = " + error.code) + console.log("mission.missionId = " + mission.missionId); + console.log("mission.runningState = " + mission.runningState); + console.log("mission.lockedState = " + mission.lockedState); + console.log("mission.timestamp = " + mission.timestamp); + console.log("mission.label = " + mission.label); + console.log("mission.iconPath = " + mission.iconPath); + }); + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + ``` + + +## missionManager.getMissionInfo + +getMissionInfo(deviceId: string, missionId: number): Promise<MissionInfo>; + +Obtains the information about a given mission. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| + | missionId | number | Yes| Mission ID.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[MissionInfo](./js-apis-inner-application-missionInfo.md)> | Promise used to return the mission information obtained.| + +**Example** + + ```ts + import missionManager from '@ohos.app.ability.missionManager' + + try { + var mission = missionManager.getMissionInfo("", 10).catch(function (err){ + console.log(err); + }); + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + ``` + + +## missionManager.getMissionInfos + +getMissionInfos(deviceId: string, numMax: number, callback: AsyncCallback<Array<MissionInfo>>): void; + +Obtains information about all missions. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| + | numMax | number | Yes| Maximum number of missions whose information can be obtained.| + | callback | AsyncCallback<Array<[MissionInfo](./js-apis-inner-application-missionInfo.md)>> | Yes| Callback used to return the array of mission information obtained.| + +**Example** + + ```ts + import missionManager from '@ohos.app.ability.missionManager' + + try { + missionManager.getMissionInfos("", 10, (error, missions) => { + console.log("getMissionInfos is called, error.code = " + error.code); + console.log("size = " + missions.length); + console.log("missions = " + JSON.stringify(missions)); + }) + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + ``` + + +## missionManager.getMissionInfos + +getMissionInfos(deviceId: string, numMax: number): Promise<Array<MissionInfo>>; + +Obtains information about all missions. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| + | numMax | number | Yes| Maximum number of missions whose information can be obtained.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<Array<[MissionInfo](./js-apis-inner-application-missionInfo.md)>> | Promise used to return the array of mission information obtained.| + +**Example** + + ```ts + import missionManager from '@ohos.app.ability.missionManager' + + try { + var allMissions = missionManager.getMissionInfos("", 10).catch(function (err){ + console.log(err); + }); + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + ``` + + +## missionManager.getMissionSnapShot + +getMissionSnapShot(deviceId: string, missionId: number, callback: AsyncCallback<MissionSnapshot>): void; + +Obtains the snapshot of a given mission. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| + | missionId | number | Yes| Mission ID.| + | callback | AsyncCallback<[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)> | Yes| Callback used to return the snapshot information obtained.| + +**Example** + + ```ts + import missionManager from '@ohos.app.ability.missionManager' + + try { + missionManager.getMissionInfos("", 10, (error, missions) => { + console.log("getMissionInfos is called, error.code = " + error.code); + console.log("size = " + missions.length); + console.log("missions = " + JSON.stringify(missions)); + var id = missions[0].missionId; + + missionManager.getMissionSnapShot("", id, (error, snapshot) => { + console.log("getMissionSnapShot is called, error.code = " + error.code); + console.log("bundleName = " + snapshot.ability.bundleName); + }) + }) + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + ``` + + +## missionManager.getMissionSnapShot + +getMissionSnapShot(deviceId: string, missionId: number): Promise<MissionSnapshot>; + +Obtains the snapshot of a given mission. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| + | missionId | number | Yes| Mission ID.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)> | Promise used to return the snapshot information obtained.| + +**Example** + + ```ts + import missionManager from '@ohos.app.ability.missionManager' + + try { + var allMissions; + missionManager.getMissionInfos("",10).then(function(res){ + allMissions=res; + }).catch(function(err){console.log(err);}); + console.log("size = " + allMissions.length); + console.log("missions = " + JSON.stringify(allMissions)); + var id = allMissions[0].missionId; + + var snapshot = missionManager.getMissionSnapShot("", id).catch(function (err){ + console.log(err); + }); + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + ``` + +## missionManager.getLowResolutionMissionSnapShot + +getLowResolutionMissionSnapShot(deviceId: string, missionId: number, callback: AsyncCallback\): void; + +Obtains the low-resolution snapshot of a given mission. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| + | missionId | number | Yes| Mission ID.| + | callback | AsyncCallback<[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)> | Yes| Callback used to return the snapshot information obtained.| + +**Example** + + ```ts + import missionManager from '@ohos.app.ability.missionManager' + + try { + missionManager.getMissionInfos("", 10, (error, missions) => { + console.log("getMissionInfos is called, error.code = " + error.code); + console.log("size = " + missions.length); + console.log("missions = " + JSON.stringify(missions)); + var id = missions[0].missionId; + + missionManager.getLowResolutionMissionSnapShot("", id, (error, snapshot) => { + console.log("getLowResolutionMissionSnapShot is called, error.code = " + error.code); + console.log("bundleName = " + snapshot.ability.bundleName); + }) + }) + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + ``` + + +## missionManager.getLowResolutionMissionSnapShot + +getLowResolutionMissionSnapShot(deviceId: string, missionId: number): Promise\; + +Obtains the low-resolution snapshot of a given mission. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| + | missionId | number | Yes| Mission ID.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)> | Promise used to return the snapshot information obtained.| + +**Example** + + ```ts + import missionManager from '@ohos.app.ability.missionManager' + + try { + var allMissions; + missionManager.getMissionInfos("",10).then(function(res){ + allMissions=res; + }).catch(function(err){console.log(err);}); + console.log("size = " + allMissions.length); + console.log("missions = " + JSON.stringify(allMissions)); + var id = allMissions[0].missionId; + + var snapshot = missionManager.getLowResolutionMissionSnapShot("", id).catch(function (err){ + console.log(err); + }); + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + ``` + + +## missionManager.lockMission + +lockMission(missionId: number, callback: AsyncCallback<void>): void; + +Locks a given mission. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | missionId | number | Yes| Mission ID.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```ts + import missionManager from '@ohos.app.ability.missionManager' + + try { + missionManager.getMissionInfos("", 10, (error, missions) => { + console.log("getMissionInfos is called, error.code = " + error.code); + console.log("size = " + missions.length); + console.log("missions = " + JSON.stringify(missions)); + var id = missions[0].missionId; + + missionManager.lockMission(id).then(() => { + console.log("lockMission is called "); + }); + }); + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + ``` + + +## missionManager.lockMission + +lockMission(missionId: number): Promise<void>; + +Locks a given mission. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | missionId | number | Yes| Mission ID.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + +**Example** + + ```ts + import missionManager from '@ohos.app.ability.missionManager' + + try { + var allMissions; + missionManager.getMissionInfos("",10).then(function(res){ + allMissions=res; + }).catch(function(err){console.log(err);}); + console.log("size = " + allMissions.length); + console.log("missions = " + JSON.stringify(allMissions)); + var id = allMissions[0].missionId; + + missionManager.lockMission(id).catch(function (err){ + console.log(err); + }); + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + ``` + + +## missionManager.unlockMission + +unlockMission(missionId: number, callback: AsyncCallback<void>): void; + +Unlocks a given mission. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| missionId | number | Yes| Mission ID.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```ts + import missionManager from '@ohos.app.ability.missionManager' + + try { + missionManager.getMissionInfos("", 10, (error, missions) => { + console.log("getMissionInfos is called, error.code = " + error.code); + console.log("size = " + missions.length); + console.log("missions = " + JSON.stringify(missions)); + var id = missions[0].missionId; + + missionManager.unlockMission(id).then(() => { + console.log("unlockMission is called "); + }); + }); + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + ``` + + +## missionManager.unlockMission + +unlockMission(missionId: number): Promise<void>; + +Unlocks a given mission. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | missionId | number | Yes| Mission ID.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + +**Example** + + ```ts + import missionManager from '@ohos.app.ability.missionManager' + + try { + var allMissions; + missionManager.getMissionInfos("",10).then(function(res){ + allMissions=res; + }).catch(function(err){console.log(err);}); + console.log("size = " + allMissions.length); + console.log("missions = " + JSON.stringify(allMissions)); + var id = allMissions[0].missionId; + + missionManager.lockMission(id).catch(function (err){ + console.log(err); + }); + missionManager.unlockMission(id).catch(function (err){ + console.log(err); + }); + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + ``` + + +## missionManager.clearMission + +clearMission(missionId: number, callback: AsyncCallback<void>): void; + +Clears a given mission, regardless of whether it is locked. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | missionId | number | Yes| Mission ID.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```ts + import missionManager from '@ohos.app.ability.missionManager' + + try { + missionManager.getMissionInfos("", 10, (error, missions) => { + console.log("getMissionInfos is called, error.code = " + error.code); + console.log("size = " + missions.length); + console.log("missions = " + JSON.stringify(missions)); + var id = missions[0].missionId; + + missionManager.clearMission(id).then(() => { + console.log("clearMission is called "); + }); + }); + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + ``` + + +## missionManager.clearMission + +clearMission(missionId: number): Promise<void>; + +Clears a given mission, regardless of whether it is locked. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | missionId | number | Yes| Mission ID.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + +**Example** + + ```ts + import missionManager from '@ohos.app.ability.missionManager' + + try { + var allMissions; + missionManager.getMissionInfos("",10).then(function(res){ + allMissions=res; + }).catch(function(err){console.log(err);}); + console.log("size = " + allMissions.length); + console.log("missions = " + JSON.stringify(allMissions)); + var id = allMissions[0].missionId; + + missionManager.clearMission(id).catch(function (err){ + console.log(err); + }); + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + ``` + + +## missionManager.clearAllMissions + +clearAllMissions(callback: AsyncCallback<void>): void; + +Clears all unlocked missions. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Example** + + ```ts + import missionManager from '@ohos.app.ability.missionManager' + + missionManager.clearAllMissions().then(() => { + console.log("clearAllMissions is called "); + }); + ``` + + +## missionManager.clearAllMissions + +clearAllMissions(): Promise<void>; + +Clears all unlocked missions. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + +**Example** + + ```ts + import missionManager from '@ohos.app.ability.missionManager' + missionManager.clearAllMissions().catch(function (err){ + console.log(err); + }); + ``` + + +## missionManager.moveMissionToFront + +moveMissionToFront(missionId: number, callback: AsyncCallback<void>): void; + +Switches a given mission to the foreground. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | missionId | number | Yes| Mission ID.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```ts + import missionManager from '@ohos.app.ability.missionManager' + + try { + missionManager.getMissionInfos("", 10, (error, missions) => { + console.log("getMissionInfos is called, error.code = " + error.code); + console.log("size = " + missions.length); + console.log("missions = " + JSON.stringify(missions)); + var id = missions[0].missionId; + + missionManager.moveMissionToFront(id).then(() => { + console.log("moveMissionToFront is called "); + }); + }); + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + ``` + + +## missionManager.moveMissionToFront + +moveMissionToFront(missionId: number, options: StartOptions, callback: AsyncCallback<void>): void; + +Switches a given mission to the foreground, with the startup parameters for the switching specified. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | missionId | number | Yes| Mission ID.| + | options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```ts + import missionManager from '@ohos.app.ability.missionManager' + + try { + missionManager.getMissionInfos("", 10, (error, missions) => { + console.log("getMissionInfos is called, error.code = " + error.code); + console.log("size = " + missions.length); + console.log("missions = " + JSON.stringify(missions)); + var id = missions[0].missionId; + + missionManager.moveMissionToFront(id,{windowMode : 101}).then(() => { + console.log("moveMissionToFront is called "); + }); + }); + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + ``` + + +## missionManager.moveMissionToFront + +moveMissionToFront(missionId: number, options?: StartOptions): Promise<void>; + +Switches a given mission to the foreground, with the startup parameters for the switching specified. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | missionId | number | Yes| Mission ID.| + | options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + +**Example** + + ```ts + import missionManager from '@ohos.app.ability.missionManager' + + try { + var allMissions; + missionManager.getMissionInfos("",10).then(function(res){ + allMissions=res; + }).catch(function(err){console.log(err);}); + console.log("size = " + allMissions.length); + console.log("missions = " + JSON.stringify(allMissions)); + var id = allMissions[0].missionId; + + missionManager.moveMissionToFront(id).catch(function (err){ + console.log(err); + }); + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + ``` diff --git a/en/application-dev/reference/apis/js-apis-application-quickFixManager.md b/en/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md similarity index 50% rename from en/application-dev/reference/apis/js-apis-application-quickFixManager.md rename to en/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md index 5abe8c19658d484fb335efc0d3fe8e2aa49bdc48..c703726492eb8bc4ddd1211f97d95a3490a8938a 100644 --- a/en/application-dev/reference/apis/js-apis-application-quickFixManager.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md @@ -1,4 +1,4 @@ -# quickFixManager +# @ohos.app.ability.quickFixManager The **quickFixManager** module provides APIs for quick fix. With quick fix, you can fix bugs in your application by applying patches, which is more efficient than by updating the entire application. @@ -8,8 +8,8 @@ The **quickFixManager** module provides APIs for quick fix. With quick fix, you ## Modules to Import -``` -import quickFixManager from '@ohos.application.quickFixManager'; +```ts +import quickFixManager from '@ohos.app.ability.quickFixManager'; ``` ## HapModuleQuickFixInfo @@ -20,11 +20,11 @@ Defines the quick fix information at the HAP file level. **System API**: This is a system API and cannot be called by third-party applications. -| Name | Readable/Writable| Type | Mandatory| Description | -| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | -| moduleName | Read only | string | Yes | Name of the HAP file. | -| originHapHash | Read only | string | Yes | Hash value of the HAP file. | -| quickFixFilePath | Read only | string | Yes | Installation path of the quick fix file. | +| Name | Type | Mandatory| Description | +| ----------- | -------------------- | ---- | ------------------------------------------------------------ | +| moduleName | string | Yes | Name of the HAP file. | +| originHapHash | string | Yes | Hash value of the HAP file. | +| quickFixFilePath | string | Yes | Installation path of the quick fix file. | ## ApplicationQuickFixInfo @@ -34,14 +34,14 @@ Defines the quick fix information at the application level. **System API**: This is a system API and cannot be called by third-party applications. -| Name | Readable/Writable| Type | Mandatory| Description | -| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | -| bundleName | Read only | string | Yes | Bundle name of the application. | -| bundleVersionCode | Read only | number | Yes | Internal version number of the application. | -| bundleVersionName | Read only | string | Yes | Version number of the application that is shown to users. | -| quickFixVersionCode | Read only | number | Yes | Version code of the quick fix patch package. | -| quickFixVersionName | Read only | string | Yes | Text description of the version number of the quick fix patch package. | -| hapModuleQuickFixInfo | Read only | Array\<[HapModuleQuickFixInfo](#hapmodulequickfixinfo)> | Yes | Quick fix information at the HAP file level. | +| Name | Type | Mandatory| Description | +| ----------- | -------------------- | ---- | ------------------------------------------------------------ | +| bundleName | string | Yes | Bundle name of the application. | +| bundleVersionCode | number | Yes | Internal version number of the application. | +| bundleVersionName | string | Yes | Version number of the application that is shown to users. | +| quickFixVersionCode | number | Yes | Version code of the quick fix patch package. | +| quickFixVersionName | string | Yes | Text description of the version number of the quick fix patch package. | +| hapModuleQuickFixInfo | Array\<[HapModuleQuickFixInfo](#hapmodulequickfixinfo)> | Yes | Quick fix information at the HAP file level. | ## quickFixManager.applyQuickFix @@ -59,22 +59,26 @@ Applies a quick fix patch. This API uses an asynchronous callback to return the | Parameter| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | hapModuleQuickFixFiles | Array\ | No| Quick fix files, each of which must contain a valid file path.| - | callback | AsyncCallback\ | No| Callback used to return the result.| + | hapModuleQuickFixFiles | Array\ | Yes| Quick fix files, each of which must contain a valid file path.| + | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** -```js - import quickFixManager from '@ohos.application.quickFixManager' +```ts + import quickFixManager from '@ohos.app.ability.quickFixManager' - let hapModuleQuickFixFiles = ["/data/storage/el2/base/entry.hqf"] - quickFixManager.applyQuickFix(hapModuleQuickFixFiles, (error) => { + try { + let hapModuleQuickFixFiles = ["/data/storage/el2/base/entry.hqf"] + quickFixManager.applyQuickFix(hapModuleQuickFixFiles, (error) => { if (error) { console.info( `applyQuickFix failed with error + ${error}`) } else { console.info( 'applyQuickFix success') } - }) + }) + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } ``` ## quickFixManager.applyQuickFix @@ -93,7 +97,7 @@ Applies a quick fix patch. This API uses a promise to return the result. | Parameter| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | hapModuleQuickFixFiles | Array\ | No| Quick fix files, each of which must contain a valid file path.| + | hapModuleQuickFixFiles | Array\ | Yes| Quick fix files, each of which must contain a valid file path.| **Return value** @@ -103,15 +107,19 @@ Applies a quick fix patch. This API uses a promise to return the result. **Example** -```js - import quickFixManager from '@ohos.application.quickFixManager' +```ts + import quickFixManager from '@ohos.app.ability.quickFixManager' let hapModuleQuickFixFiles = ["/data/storage/el2/base/entry.hqf"] - quickFixManager.applyQuickFix(hapModuleQuickFixFiles).then(() => { - console.info('applyQuickFix success') - }).catch((error) => { - console.info(`applyQuickFix err: + ${error}`) - }) + try { + quickFixManager.applyQuickFix(hapModuleQuickFixFiles).then(() => { + console.info('applyQuickFix success') + }).catch((error) => { + console.info(`applyQuickFix err: + ${error}`) + }) + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } ``` ## quickFixManager.getApplicationQuickFixInfo @@ -130,22 +138,26 @@ Obtains the quick fix information of the application. This API uses an asynchron | Parameter| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | bundleName | string | No|Bundle name of the application. | - | callback | AsyncCallback\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | No| Callback used to return the quick fix information.| + | bundleName | string | Yes|Bundle name of the application. | + | callback | AsyncCallback\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Yes| Callback used to return the quick fix information.| **Example** -```js - import quickFixManager from '@ohos.application.quickFixManager' - - let bundleName = "bundleName" - quickFixManager.getApplicationQuickFixInfo(bundleName, (error, data) => { - if (error) { - console.info(`getApplicationQuickFixInfo error: + ${error}`) - } else { - console.info(`getApplicationQuickFixInfo success: + ${data}`) - } - }) +```ts + import quickFixManager from '@ohos.app.ability.quickFixManager' + + try { + let bundleName = "bundleName" + quickFixManager.getApplicationQuickFixInfo(bundleName, (error, data) => { + if (error) { + console.info(`getApplicationQuickFixInfo error: + ${error}`) + } else { + console.info(`getApplicationQuickFixInfo success: + ${data}`) + } + }) + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } ``` ## quickFixManager.getApplicationQuickFixInfo @@ -164,7 +176,7 @@ Obtains the quick fix information of the application. This API uses a promise to | Parameter| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | bundleName | string | No| Bundle name of the application. | + | bundleName | string | Yes| Bundle name of the application. | **Return value** @@ -174,13 +186,17 @@ Obtains the quick fix information of the application. This API uses a promise to **Example** - ```js - import quickFixManager from '@ohos.application.quickFixManager' - - let bundleName = "bundleName" - quickFixManager.getApplicationQuickFixInfo(bundleName).then((data) => { - console.info(`getApplicationQuickFixInfo success: + ${data}`) - }).catch((error) => { - console.info(`getApplicationQuickFixInfo err: + ${error}`) - }) + ```ts + import quickFixManager from '@ohos.app.ability.quickFixManager' + + try { + let bundleName = "bundleName" + quickFixManager.getApplicationQuickFixInfo(bundleName).then((data) => { + console.info(`getApplicationQuickFixInfo success: + ${data}`) + }).catch((error) => { + console.info(`getApplicationQuickFixInfo err: + ${error}`) + }) + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md b/en/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md new file mode 100644 index 0000000000000000000000000000000000000000..6c3e0e6e2a0e116120aa405758506d46175c3468 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md @@ -0,0 +1,252 @@ +# @ohos.app.ability.ServiceExtensionAbility + +The **ServiceExtensionAbility** module provides APIs for Service Extension abilities. + +> **NOTE** +> +> The APIs of this module are supported and deprecated since API version 9. You are advised to use [@ohos.app.ability.ServiceExtensionAbility](js-apis-app-ability-serviceExtensionAbility.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the stage model. + +## Modules to Import + +```ts +import ServiceExtension from '@ohos.app.ability.ServiceExtensionAbility'; +``` + +## Required Permissions + +None. + +## Attributes + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| context | [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) | Yes| No| Service Extension context, which is inherited from **ExtensionContext**.| + + +## ServiceExtensionAbility.onCreate + +onCreate(want: Want): void; + +Called when a Service Extension ability is created to initialize the service logic. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-app-ability-want.md) | Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| + +**Example** + + ```ts + class ServiceExt extends ServiceExtension { + onCreate(want) { + console.log('onCreate, want:' + want.abilityName); + } + } + ``` + + +## ServiceExtensionAbility.onDestroy + +onDestroy(): void; + +Called when this Service Extension ability is destroyed to clear resources. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Example** + + ```ts + class ServiceExt extends ServiceExtension { + onDestroy() { + console.log('onDestroy'); + } + } + ``` + + +## ServiceExtensionAbility.onRequest + +onRequest(want: Want, startId: number): void; + +Called after **onCreate** is invoked when a Service Extension ability is started by calling **startAbility**. The value of **startId** is incremented for each ability that is started. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-app-ability-want.md) | Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| + | startId | number | Yes| Number of ability start times. The initial value is **1**, and the value is automatically incremented for each ability started.| + +**Example** + + ```ts + class ServiceExt extends ServiceExtension { + onRequest(want, startId) { + console.log('onRequest, want:' + want.abilityName); + } + } + ``` + + +## ServiceExtensionAbility.onConnect + +onConnect(want: Want): rpc.RemoteObject; + +Called after **onCreate** is invoked when a Service Extension ability is started by calling **connectAbility**. A **RemoteObject** object is returned for communication with the client. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-app-ability-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | rpc.RemoteObject | A **RemoteObject** object used for communication with the client.| + +**Example** + + ```ts + import rpc from '@ohos.rpc' + class StubTest extends rpc.RemoteObject{ + constructor(des) { + super(des); + } + onConnect(code, data, reply, option) { + } + } + class ServiceExt extends ServiceExtension { + onConnect(want) { + console.log('onConnect , want:' + want.abilityName); + return new StubTest("test"); + } + } + ``` + + +## ServiceExtensionAbility.onDisconnect + +onDisconnect(want: Want): void; + +Called when this Service Extension ability is disconnected. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want |[Want](js-apis-app-ability-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| + +**Example** + + ```ts + class ServiceExt extends ServiceExtension { + onDisconnect(want) { + console.log('onDisconnect, want:' + want.abilityName); + } + } + ``` + +## ServiceExtensionAbility.onReconnect + +onReconnect(want: Want): void; + +Called when this Service Extension ability is reconnected. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want |[Want](js-apis-app-ability-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| + +**Example** + + ```ts + class ServiceExt extends ServiceExtension { + onReconnect(want) { + console.log('onReconnect, want:' + want.abilityName); + } + } + ``` + +## ServiceExtensionAbility.onConfigurationUpdate + +onConfigurationUpdate(newConfig: Configuration): void; + +Called when the configuration of this Service Extension ability is updated. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | newConfig | [Configuration](js-apis-app-ability-configuration.md) | Yes| New configuration.| + +**Example** + + ```ts + class ServiceExt extends ServiceExtension { + onConfigurationUpdate(config) { + console.log('onConfigurationUpdate, config:' + JSON.stringify(config)); + } + } + ``` + +## ServiceExtensionAbility.onDump + +onDump(params: Array\): Array\; + +Dumps the client information. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | params | Array\ | Yes| Parameters in the form of a command.| + +**Example** + + ```ts + class ServiceExt extends ServiceExtension { + onDump(params) { + console.log('dump, params:' + JSON.stringify(params)); + return ["params"] + } + } + ``` diff --git a/en/application-dev/reference/apis/js-apis-application-StartOptions.md b/en/application-dev/reference/apis/js-apis-app-ability-startOptions.md similarity index 60% rename from en/application-dev/reference/apis/js-apis-application-StartOptions.md rename to en/application-dev/reference/apis/js-apis-app-ability-startOptions.md index 39f44f65437b6b91ce457228fa12153d10aed3e6..fc5215fe400919172a7c2f2dd7c5a567e44acae3 100644 --- a/en/application-dev/reference/apis/js-apis-application-StartOptions.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-startOptions.md @@ -1,4 +1,4 @@ -# StartOptions +# @ohos.app.ability.StartOptions The **StartOptions** module implements ability startup options. @@ -9,15 +9,16 @@ The **StartOptions** module implements ability startup options. ## Modules to Import -``` -import StartOptions from '@ohos.application.StartOptions'; +```ts +import StartOptions from '@ohos.app.ability.StartOptions'; ``` ## Attributes + **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name| Readable| Writable| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -------- | -------- | -| [windowMode](js-apis-application-abilityConstant.md#abilityconstantwindowmode) | Yes| No| number | No| Window mode.| -| displayId | Yes| No| number | No| Display ID.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| [windowMode](js-apis-application-abilityConstant.md#abilityconstantwindowmode) | number | No| Window mode.| +| displayId | number | No| Display ID.| diff --git a/en/application-dev/reference/apis/js-apis-app-ability-uiAbility.md b/en/application-dev/reference/apis/js-apis-app-ability-uiAbility.md new file mode 100644 index 0000000000000000000000000000000000000000..cce8b81738f29586417ae5f9814da2448f053e17 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-uiAbility.md @@ -0,0 +1,742 @@ +# @ohos.app.ability.UIAbility + +The **Ability** module manages the ability lifecycle and context, such as creating and destroying an ability, and dumping client information. + +This module provides the following common ability-related functions: + +- [Caller](#caller): implements sending of sequenceable data to the target ability when an ability (caller ability) invokes the target ability (callee ability). +- [Callee](#callee): implements callbacks for registration and deregistration of caller notifications. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the stage model. + +## Modules to Import + +```ts +import Ability from '@ohos.app.ability.UIAbility'; +``` + +## Attributes + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| context | [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) | Yes| No| Context of an ability.| +| launchWant | [Want](js-apis-app-ability-want.md) | Yes| No| Parameters for starting the ability.| +| lastRequestWant | [Want](js-apis-app-ability-want.md) | Yes| No| Parameters used when the ability was started last time.| +| callee | [Callee](#callee) | Yes| No| Object that invokes the stub service.| + +## Ability.onCreate + +onCreate(want: Want, param: AbilityConstant.LaunchParam): void; + +Called to initialize the service logic when an ability is created. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-app-ability-want.md) | Yes| Information related to this ability, including the ability name and bundle name.| + | param | AbilityConstant.LaunchParam | Yes| Parameters for starting the ability, and the reason for the last abnormal exit.| + +**Example** + + ```ts + class myAbility extends Ability { + onCreate(want, param) { + console.log('onCreate, want:' + want.abilityName); + } + } + ``` + + +## Ability.onWindowStageCreate + +onWindowStageCreate(windowStage: window.WindowStage): void + +Called when a **WindowStage** is created for this ability. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | windowStage | window.WindowStage | Yes| **WindowStage** information.| + +**Example** + + ```ts + class myAbility extends Ability { + onWindowStageCreate(windowStage) { + console.log('onWindowStageCreate'); + } + } + ``` + + +## Ability.onWindowStageDestroy + +onWindowStageDestroy(): void + +Called when the **WindowStage** is destroyed for this ability. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Example** + + ```ts + class myAbility extends Ability { + onWindowStageDestroy() { + console.log('onWindowStageDestroy'); + } + } + ``` + + +## Ability.onWindowStageRestore + +onWindowStageRestore(windowStage: window.WindowStage): void + +Called when the **WindowStage** is restored during the migration of this ability, which is a multi-instance ability. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | windowStage | window.WindowStage | Yes| **WindowStage** information.| + +**Example** + + ```ts + class myAbility extends Ability { + onWindowStageRestore(windowStage) { + console.log('onWindowStageRestore'); + } + } + ``` + + +## Ability.onDestroy + +onDestroy(): void; + +Called when this ability is destroyed to clear resources. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Example** + + ```ts + class myAbility extends Ability { + onDestroy() { + console.log('onDestroy'); + } + } + ``` + + +## Ability.onForeground + +onForeground(): void; + +Called when this ability is switched from the background to the foreground. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Example** + + ```ts + class myAbility extends Ability { + onForeground() { + console.log('onForeground'); + } + } + ``` + + +## Ability.onBackground + +onBackground(): void; + +Called when this ability is switched from the foreground to the background. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Example** + + ```ts + class myAbility extends Ability { + onBackground() { + console.log('onBackground'); + } + } + ``` + + +## Ability.onContinue + +onContinue(wantParam : {[key: string]: any}): AbilityConstant.OnContinueResult; + +Called to save data during the ability migration preparation process. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | wantParam | {[key: string]: any} | Yes| **want** parameter.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | AbilityConstant.OnContinueResult | Continuation result.| + +**Example** + + ```ts + import AbilityConstant from "@ohos.application.AbilityConstant" + class myAbility extends Ability { + onContinue(wantParams) { + console.log('onContinue'); + wantParams["myData"] = "my1234567"; + return AbilityConstant.OnContinueResult.AGREE; + } + } + ``` + + +## Ability.onNewWant + +onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void; + +Called when the ability startup mode is set to singleton. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-application-want.md) | Yes| Want parameters, such as the ability name and bundle name.| + | launchParams | AbilityConstant.LaunchParam | Yes| Reason for the ability startup and the last abnormal exit.| + +**Example** + + ```ts + class myAbility extends Ability { + onNewWant(want) { + console.log('onNewWant, want:' + want.abilityName); + } + } + ``` + +## Ability.onDump + +onDump(params: Array\): Array\; + +Dumps client information. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | params | Array\ | Yes| Parameters in the form of a command.| + +**Example** + + ```ts + class myAbility extends Ability { + onDump(params) { + console.log('dump, params:' + JSON.stringify(params)); + return ["params"] + } + } + ``` + + +## Ability.onSaveState + +onSaveState(reason: AbilityConstant.StateType, wantParam : {[key: string]: any}): AbilityConstant.OnSaveResult; + +Called when the framework automatically saves the ability state in the case of an application fault. This API is used together with [appRecovery](js-apis-app-ability-appRecovery.md). + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | reason | [AbilityConstant.StateType](js-apis-application-abilityConstant.md#abilityconstantstatetype) | Yes| Reason for triggering the callback to save the ability state.| + | wantParam | {[key: string]: any} | Yes| **want** parameter.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | AbilityConstant.OnSaveResult | Whether the ability state is saved.| + +**Example** + + ```ts +import AbilityConstant from '@ohos.application.AbilityConstant' + +class myAbility extends Ability { + onSaveState(reason, wantParam) { + console.log('onSaveState'); + wantParam["myData"] = "my1234567"; + return AbilityConstant.OnSaveResult.RECOVERY_AGREE; + } +} + ``` + + + +## Caller + +Implements sending of sequenceable data to the target ability when an ability (caller ability) invokes the target ability (callee ability). + +## Caller.call + +call(method: string, data: rpc.Sequenceable): Promise<void>; + +Sends sequenceable data to the target ability. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.| + | data | rpc.Sequenceable | Yes| Sequenceable data. You need to customize the data.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return a response.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + + ```ts + import Ability from '@ohos.app.ability.UIAbility'; + class MyMessageAble{ // Custom sequenceable data structure + name:"" + str:"" + num: 1 + constructor(name, str) { + this.name = name; + this.str = str; + } + marshalling(messageParcel) { + messageParcel.writeInt(this.num); + messageParcel.writeString(this.str); + console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']'); + return true; + } + unmarshalling(messageParcel) { + this.num = messageParcel.readInt(); + this.str = messageParcel.readString(); + console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']'); + return true; + } + }; + var method = 'call_Function'; // Notification message string negotiated by the two abilities + var caller; + export default class MainAbility extends Ability { + onWindowStageCreate(windowStage) { + this.context.startAbilityByCall({ + bundleName: "com.example.myservice", + abilityName: "MainAbility", + deviceId: "" + }).then((obj) => { + caller = obj; + let msg = new MyMessageAble("msg", "world"); // See the definition of Sequenceable. + caller.call(method, msg) + .then(() => { + console.log('Caller call() called'); + }) + .catch((callErr) => { + console.log('Caller.call catch error, error.code: ' + JSON.stringify(callErr.code) + + ' error.message: ' + JSON.stringify(callErr.message)); + }); + }).catch((err) => { + console.log('Caller GetCaller error, error.code: ' + JSON.stringify(err.code) + + ' error.message: ' + JSON.stringify(err.message)); + }); + } + } + ``` + + +## Caller.callWithResult + +callWithResult(method: string, data: rpc.Sequenceable): Promise<rpc.MessageParcel>; + +Sends sequenceable data to the target ability and obtains the sequenceable data returned by the target ability. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.| + | data | rpc.Sequenceable | Yes| Sequenceable data. You need to customize the data.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<rpc.MessageParcel> | Promise used to return the sequenceable data from the target ability.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + + ```ts + import Ability from '@ohos.app.ability.UIAbility'; + class MyMessageAble{ + name:"" + str:"" + num: 1 + constructor(name, str) { + this.name = name; + this.str = str; + } + marshalling(messageParcel) { + messageParcel.writeInt(this.num); + messageParcel.writeString(this.str); + console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']'); + return true; + } + unmarshalling(messageParcel) { + this.num = messageParcel.readInt(); + this.str = messageParcel.readString(); + console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']'); + return true; + } + }; + var method = 'call_Function'; + var caller; + export default class MainAbility extends Ability { + onWindowStageCreate(windowStage) { + this.context.startAbilityByCall({ + bundleName: "com.example.myservice", + abilityName: "MainAbility", + deviceId: "" + }).then((obj) => { + caller = obj; + let msg = new MyMessageAble(1, "world"); + caller.callWithResult(method, msg) + .then((data) => { + console.log('Caller callWithResult() called'); + let retmsg = new MyMessageAble(0, ""); + data.readSequenceable(retmsg); + }) + .catch((callErr) => { + console.log('Caller.callWithResult catch error, error.code: ' + JSON.stringify(callErr.code) + + ' error.message: ' + JSON.stringify(callErr.message)); + }); + }).catch((err) => { + console.log('Caller GetCaller error, error.code: ' + JSON.stringify(err.code) + + ' error.message: ' + JSON.stringify(err.message)); + }); + } + } + ``` + + +## Caller.release + +release(): void; + +Releases the caller interface of the target ability. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 401 | Invalid input parameter. | +| 16200001 | Caller released. The caller has been released. | +| 16200002 | Callee invalid. The callee does not exist. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + import Ability from '@ohos.app.ability.UIAbility'; + var caller; + export default class MainAbility extends Ability { + onWindowStageCreate(windowStage) { + this.context.startAbilityByCall({ + bundleName: "com.example.myservice", + abilityName: "MainAbility", + deviceId: "" + }).then((obj) => { + caller = obj; + try { + caller.release(); + } catch (releaseErr) { + console.log('Caller.release catch error, error.code: ' + JSON.stringify(releaseErr.code) + + ' error.message: ' + JSON.stringify(releaseErr.message)); + } + }).catch((err) => { + console.log('Caller GetCaller error, error.code: ' + JSON.stringify(err.code) + + ' error.message: ' + JSON.stringify(err.message)); + }); + } + } + ``` + +## Caller.onRelease + + onRelease(callback: OnReleaseCallBack): void; + +Registers a callback that is invoked when the stub on the target ability is disconnected. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | OnReleaseCallBack | Yes| Callback used for the **onRelease** API.| + +**Example** + + ```ts + import Ability from '@ohos.application.Ability'; + var caller; + export default class MainAbility extends Ability { + onWindowStageCreate(windowStage) { + this.context.startAbilityByCall({ + bundleName: "com.example.myservice", + abilityName: "MainAbility", + deviceId: "" + }).then((obj) => { + caller = obj; + try { + caller.onRelease((str) => { + console.log(' Caller OnRelease CallBack is called ' + str); + }); + } catch (error) { + console.log('Caller.on catch error, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + } + }).catch((err) => { + console.log('Caller GetCaller error, error.code: ' + JSON.stringify(err.code) + + ' error.message: ' + JSON.stringify(err.message)); + }); + } + } + ``` + +## Caller.on + + on(type: "release", callback: OnReleaseCallback): void; + +Registers a callback that is invoked when the stub on the target ability is disconnected. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is fixed at **release**.| + | callback | OnReleaseCallback | Yes| Callback used for the **onRelease** API.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + + ```ts + import Ability from '@ohos.app.ability.UIAbility'; + var caller; + export default class MainAbility extends Ability { + onWindowStageCreate(windowStage) { + this.context.startAbilityByCall({ + bundleName: "com.example.myservice", + abilityName: "MainAbility", + deviceId: "" + }).then((obj) => { + caller = obj; + try { + caller.on("release", (str) => { + console.log(' Caller OnRelease CallBack is called ' + str); + }); + } catch (error) { + console.log('Caller.on catch error, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + } + }).catch((err) => { + console.log('Caller GetCaller error, error.code: ' + JSON.stringify(err.code) + + ' error.message: ' + JSON.stringify(err.message)); + }); + } + } + ``` + + +## Callee + +Implements callbacks for caller notification registration and deregistration. + +## Callee.on + +on(method: string, callback: CalleeCallback): void; + +Registers a caller notification callback, which is invoked when the target ability registers a function. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | method | string | Yes| Notification message string negotiated between the two abilities.| + | callback | CalleeCallback | Yes| JS notification synchronization callback of the **rpc.MessageParcel** type. The callback must return at least one empty **rpc.Sequenceable** object. Otherwise, the function execution fails.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + + ```ts + import Ability from '@ohos.app.ability.UIAbility'; + class MyMessageAble{ + name:"" + str:"" + num: 1 + constructor(name, str) { + this.name = name; + this.str = str; + } + marshalling(messageParcel) { + messageParcel.writeInt(this.num); + messageParcel.writeString(this.str); + console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']'); + return true; + } + unmarshalling(messageParcel) { + this.num = messageParcel.readInt(); + this.str = messageParcel.readString(); + console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']'); + return true; + } + }; + var method = 'call_Function'; + function funcCallBack(pdata) { + console.log('Callee funcCallBack is called ' + pdata); + let msg = new MyMessageAble("test", ""); + pdata.readSequenceable(msg); + return new MyMessageAble("test1", "Callee test"); + } + export default class MainAbility extends Ability { + onCreate(want, launchParam) { + console.log('Callee onCreate is called'); + try { + this.callee.on(method, funcCallBack); + } catch (error) { + console.log('Callee.on catch error, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + } + } + } + ``` + +## Callee.off + +off(method: string): void; + +Deregisters a caller notification callback, which is invoked when the target ability registers a function. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | method | string | Yes| Registered notification message string.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + + +**Example** + + ```ts + import Ability from '@ohos.app.ability.UIAbility'; + var method = 'call_Function'; + export default class MainAbility extends Ability { + onCreate(want, launchParam) { + console.log('Callee onCreate is called'); + try { + this.callee.off(method); + } catch (error) { + console.log('Callee.off catch error, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + } + } + } + ``` + +## OnReleaseCallback + +(msg: string): void; + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +| Name| Readable| Writable| Type| Description| +| -------- | -------- | -------- | -------- | -------- | +| (msg: string) | Yes| No| function | Prototype of the listener function registered by the caller.| + +## CalleeCallback + +(indata: rpc.MessageParcel): rpc.Sequenceable; + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +| Name| Readable| Writable| Type| Description| +| -------- | -------- | -------- | -------- | -------- | +| (indata: rpc.MessageParcel) | Yes| No| rpc.Sequenceable | Prototype of the listener function registered by the callee.| diff --git a/en/application-dev/reference/apis/js-apis-app-ability-want.md b/en/application-dev/reference/apis/js-apis-app-ability-want.md index 894aaf9f13698104a821f6ebf2db303999535cad..c7bd4f6e9693c9bcc7ac71286e204f4d0b5005a8 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-want.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-want.md @@ -1,4 +1,4 @@ -# Want +# @ohos.app.ability.Want Want is a carrier for information transfer between objects (application components). Want can be used as a parameter of **startAbility** to specify a startup target and information that needs to be carried during startup, for example, **bundleName** and **abilityName**, which respectively indicate the bundle name of the target ability and the ability name in the bundle. When ability A needs to start ability B and transfer some data to ability B, it can use Want a carrier to transfer the data. diff --git a/en/application-dev/reference/apis/js-apis-app-ability-wantAgent.md b/en/application-dev/reference/apis/js-apis-app-ability-wantAgent.md new file mode 100644 index 0000000000000000000000000000000000000000..bfc8b4f99cf05e7dd20c420b3314b695c880f8d1 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-wantAgent.md @@ -0,0 +1,1647 @@ +# @ohos.app.ability.wantAgent + +The **app.ability.WantAgent** module provides APIs for triggering, canceling, and comparing **WantAgent** objects. You can use the APIs to create a **WantAgent** object, and obtain the user ID, bundle name, and want information of the object. You are advised to use this module, since it will replace the [@ohos.wantAgent](js-apis-wantAgent.md) module in the near future. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```ts +import WantAgent from '@ohos.app.ability.wantAgent'; +``` + +## WantAgent.getWantAgent + +getWantAgent(info: WantAgentInfo, callback: AsyncCallback\): void + +Obtains a **WantAgent** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------- | ---- | ----------------------- | +| info | WantAgentInfo | Yes | Information about the **WantAgent** object to obtain. | +| callback | AsyncCallback\ | Yes | Callback used to return the **WantAgent** object.| + +**Error codes** +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). +| ID | Error Message | +|-----------|--------------------| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong.| +| 16000003 | Input error. The specified id does not exist.| +| 16000004 | Visibility verification failed.| +| 16000006 | Can not cross user operations.| +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| +| 16000008 | Crowdtest App Expiration.| +| 16000009 | Can not start ability in wukong mode.| +| 16000010 | Can not operation with continue flag.| +| 16000011 | Context does not exist.| +| 16000050 | Internal Error.| +| 16000051 | Network error. The network is abnormal.| +| 16000052 | Free install not support. The application does not support free install. | +| 16000053 | Not top ability. The application is not top ability.| +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| +| 16000055 | Free install timeout.| +| 16000056 | Can not free install other ability.| +| 16000057 | Not support cross device free install.| +| 16000101 | execute shell command failed.| +| 16000151 | Invalid wantagent object.| +| 16000152 | wantAgent object not found.| +| 16000153 | wangAgent object canceled.| + + +**Example** + +```ts +import WantAgent from '@ohos.app.ability.wantAgent'; + +// WantAgent object +var wantAgent; +// WantAgentInfo object +var wantAgentInfo = { + wants: [ + { + deviceId: "deviceId", + bundleName: "com.neu.setResultOnAbilityResultTest1", + abilityName: "com.example.test.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [false, true, false], + mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +// getWantAgent callback +function getWantAgentCallback(err, data) { + if (err == undefined) { + wantAgent = data; + } else { + console.info('getWantAgent failed' + JSON.stringify(err)); + } +} +try{ + WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); +} catch(err){ + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +} +``` + + + +## WantAgent.getWantAgent + +getWantAgent(info: WantAgentInfo): Promise\ + +Obtains a **WantAgent** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ---- | ------------- | ---- | ------------- | +| info | WantAgentInfo | Yes | Information about the **WantAgent** object to obtain.| + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the **WantAgent** object.| + +**Error codes** +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). +| ID | Error Message | +|-----------|--------------------| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong.| +| 16000003 | Input error. The specified id does not exist.| +| 16000004 | Visibility verification failed.| +| 16000006 | Can not cross user operations.| +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| +| 16000008 | Crowdtest App Expiration.| +| 16000009 | Can not start ability in wukong mode.| +| 16000010 | Can not operation with continue flag.| +| 16000011 | Context does not exist.| +| 16000050 | Internal Error.| +| 16000051 | Network error. The network is abnormal.| +| 16000052 | Free install not support. The application does not support free install. | +| 16000053 | Not top ability. The application is not top ability.| +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| +| 16000055 | Free install timeout.| +| 16000056 | Can not free install other ability.| +| 16000057 | Not support cross device free install.| +| 16000101 | execute shell command failed.| +| 16000151 | Invalid wantagent object.| +| 16000152 | wantAgent object not found.| +| 16000153 | wangAgent object canceled.| + +**Example** + +```ts +import WantAgent from '@ohos.app.ability.wantAgent'; + + +// WantAgentInfo object +var wantAgentInfo = { + wants: [ + { + deviceId: "deviceId", + bundleName: "com.neu.setResultOnAbilityResultTest1", + abilityName: "com.example.test.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [false, true, false], + mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +try { + WantAgent.getWantAgent(wantAgentInfo).then((data) => { + wantAgent = data; +}).catch((err) => { + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +}); +} catch (err) { + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +} +``` + + + +## WantAgent.getBundleName + +getBundleName(agent: WantAgent, callback: AsyncCallback\): void + +Obtains the bundle name of a **WantAgent** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | --------------------------------- | +| agent | WantAgent | Yes | Target **WantAgent** object. | +| callback | AsyncCallback\ | Yes | Callback used to return the bundle name.| + +**Error codes** +| ID | Error Message | +|-----------|--------------------| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong.| +| 16000003 | Input error. The specified id does not exist.| +| 16000004 | Visibility verification failed.| +| 16000006 | Can not cross user operations.| +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| +| 16000008 | Crowdtest App Expiration.| +| 16000009 | Can not start ability in wukong mode.| +| 16000010 | Can not operation with continue flag.| +| 16000011 | Context does not exist.| +| 16000050 | Internal Error.| +| 16000051 | Network error. The network is abnormal.| +| 16000052 | Free install not support. The application does not support free install. | +| 16000053 | Not top ability. The application is not top ability.| +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| +| 16000055 | Free install timeout.| +| 16000056 | Can not free install other ability.| +| 16000057 | Not support cross device free install.| +| 16000101 | execute shell command failed.| +| 16000151 | Invalid wantagent object.| +| 16000152 | wantAgent object not found.| +| 16000153 | wangAgent object canceled.| + +**Example** + +```ts +import WantAgent from '@ohos.app.ability.wantAgent'; +// WantAgent object +var wantAgent; +// WantAgentInfo object +var wantAgentInfo = { + wants: [ + { + deviceId: "deviceId", + bundleName: "com.neu.setResultOnAbilityResultTest1", + abilityName: "com.example.test.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [false, true, false], + mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +// getWantAgent callback +function getWantAgentCallback(err, data) { + if (err == undefined) { + wantAgent = data; + } else { + console.info('getWantAgent failed' + JSON.stringify(wantAgent)); + } + // getBundleName callback + function getBundleNameCallback(err, data) { + if(err) { + console.info('getBundleName failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } else { + console.info('getBundleName ok!' + JSON.stringify(data)); + } + } + try { + WantAgent.getBundleName(wantAgent, getBundleNameCallback); + } catch(err) { + console.info('getBundleName failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } +} +try{ + WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); +} catch(err){ + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +} +``` + + + +## WantAgent.getBundleName + +getBundleName(agent: WantAgent): Promise\ + +Obtains the bundle name of a **WantAgent** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----- | --------- | ---- | ------------- | +| agent | WantAgent | Yes | Target **WantAgent** object.| + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the bundle name.| + +**Error codes** +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). +| ID | Error Message | +|-----------|--------------------| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong.| +| 16000003 | Input error. The specified id does not exist.| +| 16000004 | Visibility verification failed.| +| 16000006 | Can not cross user operations.| +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| +| 16000008 | Crowdtest App Expiration.| +| 16000009 | Can not start ability in wukong mode.| +| 16000010 | Can not operation with continue flag.| +| 16000011 | Context does not exist.| +| 16000050 | Internal Error.| +| 16000051 | Network error. The network is abnormal.| +| 16000052 | Free install not support. The application does not support free install. | +| 16000053 | Not top ability. The application is not top ability.| +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| +| 16000055 | Free install timeout.| +| 16000056 | Can not free install other ability.| +| 16000057 | Not support cross device free install.| +| 16000101 | execute shell command failed.| +| 16000151 | Invalid wantagent object.| +| 16000152 | wantAgent object not found.| +| 16000153 | wangAgent object canceled.| + +**Example** + +```ts +import WantAgent from '@ohos.app.ability.wantAgent'; + + // WantAgent object +var wantAgent; +// WantAgentInfo object +var wantAgentInfo = { + wants: [ + { + deviceId: "deviceId", + bundleName: "com.neu.setResultOnAbilityResultTest1", + abilityName: "com.example.test.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [false, true, false], + mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +// getWantAgent callback +function getWantAgentCallback(err, data) { + if (err == undefined) { + wantAgent = data; + } else { + console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); + } + try { + WantAgent.getBundleName(wantAgent).then((data)=>{ + console.info('getBundleName ok!' + JSON.stringify(data)); + }).catch((err)=>{ + console.info('getBundleName failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + }) + } catch(err){ + console.info('getBundleName failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } +} +try{ + WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); +} catch(err){ + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +} +``` + + + +## WantAgent.getUid + +getUid(agent: WantAgent, callback: AsyncCallback\): void + +Obtains the user ID of a **WantAgent** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ----------------------------------- | +| agent | WantAgent | Yes | Target **WantAgent** object. | +| callback | AsyncCallback\ | Yes | Callback used to return the user ID.| + +**Error codes** +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). +| ID | Error Message | +|-----------|--------------------| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong.| +| 16000003 | Input error. The specified id does not exist.| +| 16000004 | Visibility verification failed.| +| 16000006 | Can not cross user operations.| +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| +| 16000008 | Crowdtest App Expiration.| +| 16000009 | Can not start ability in wukong mode.| +| 16000010 | Can not operation with continue flag.| +| 16000011 | Context does not exist.| +| 16000050 | Internal Error.| +| 16000051 | Network error. The network is abnormal.| +| 16000052 | Free install not support. The application does not support free install. | +| 16000053 | Not top ability. The application is not top ability.| +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| +| 16000055 | Free install timeout.| +| 16000056 | Can not free install other ability.| +| 16000057 | Not support cross device free install.| +| 16000101 | execute shell command failed.| +| 16000151 | Invalid wantagent object.| +| 16000152 | wantAgent object not found.| +| 16000153 | wangAgent object canceled.| + +**Example** + +```ts +import WantAgent from '@ohos.app.ability.wantAgent'; +// WantAgent object +var wantAgent; +// WantAgentInfo object +var wantAgentInfo = { + wants: [ + { + deviceId: "deviceId", + bundleName: "com.neu.setResultOnAbilityResultTest1", + abilityName: "com.example.test.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [false, true, false], + mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +// getWantAgent callback +function getWantAgentCallback(err, data) { + if (err == undefined) { + wantAgent = data; + } else { + console.info('getWantAgent failed' + JSON.stringify(err)); + } + // getUid callback + function getUidCallback(err, data) { + if(err) { + console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } else { + console.info('getUid ok!' + JSON.stringify(data)); + } + } + try { + WantAgent.getUid(wantAgent, getUidCallback); + } catch(err) { + console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } +} +try{ + WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); +} catch(err){ + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +} +``` + + + +## WantAgent.getUid + +getUid(agent: WantAgent): Promise\ + +Obtains the user ID of a **WantAgent** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----- | --------- | ---- | ------------- | +| agent | WantAgent | Yes | Target **WantAgent** object.| + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the user ID.| + +**Error codes** +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). +| ID | Error Message | +|-----------|--------------------| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong.| +| 16000003 | Input error. The specified id does not exist.| +| 16000004 | Visibility verification failed.| +| 16000006 | Can not cross user operations.| +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| +| 16000008 | Crowdtest App Expiration.| +| 16000009 | Can not start ability in wukong mode.| +| 16000010 | Can not operation with continue flag.| +| 16000011 | Context does not exist.| +| 16000050 | Internal Error.| +| 16000051 | Network error. The network is abnormal.| +| 16000052 | Free install not support. The application does not support free install. | +| 16000053 | Not top ability. The application is not top ability.| +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| +| 16000055 | Free install timeout.| +| 16000056 | Can not free install other ability.| +| 16000057 | Not support cross device free install.| +| 16000101 | execute shell command failed.| +| 16000151 | Invalid wantagent object.| +| 16000152 | wantAgent object not found.| +| 16000153 | wangAgent object canceled.| + +**Example** + +```ts +import WantAgent from '@ohos.app.ability.wantAgent'; + + // WantAgent object +var wantAgent; +// WantAgentInfo object +var wantAgentInfo = { + wants: [ + { + deviceId: "deviceId", + bundleName: "com.neu.setResultOnAbilityResultTest1", + abilityName: "com.example.test.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [false, true, false], + mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +// getWantAgent callback +function getWantAgentCallback(err, data) { + if (err == undefined) { + wantAgent = data; + } else { + console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); + } + try { + WantAgent.getUid(wantAgent).then((data)=>{ + console.info('getUid ok!' + JSON.stringify(data)); + }).catch((err)=>{ + console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + }) + } catch(err){ + console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } +} +try{ + WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); +} catch(err){ + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +} +``` + + +## WantAgent.getWant + +getWant(agent: WantAgent, callback: AsyncCallback\): void + +Obtains the want in a **WantAgent** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------------------------- | +| agent | WantAgent | Yes | Target **WantAgent** object. | +| callback | AsyncCallback\ | Yes | Callback used to return the want.| + +**Error codes** +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +| ID | Error Message | +|-----------|--------------------| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong.| +| 16000003 | Input error. The specified id does not exist.| +| 16000004 | Visibility verification failed.| +| 16000006 | Can not cross user operations.| +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| +| 16000008 | Crowdtest App Expiration.| +| 16000009 | Can not start ability in wukong mode.| +| 16000010 | Can not operation with continue flag.| +| 16000011 | Context does not exist.| +| 16000050 | Internal Error.| +| 16000051 | Network error. The network is abnormal.| +| 16000052 | Free install not support. The application does not support free install. | +| 16000053 | Not top ability. The application is not top ability.| +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| +| 16000055 | Free install timeout.| +| 16000056 | Can not free install other ability.| +| 16000057 | Not support cross device free install.| +| 16000101 | execute shell command failed.| +| 16000151 | Invalid wantagent object.| +| 16000152 | wantAgent object not found.| +| 16000153 | wangAgent object canceled.| + +**Example** + +```ts +import WantAgent from '@ohos.app.ability.wantAgent'; +// WantAgent object +var wantAgent; +// WantAgentInfo object +var wantAgentInfo = { + wants: [ + { + deviceId: "deviceId", + bundleName: "com.neu.setResultOnAbilityResultTest1", + abilityName: "com.example.test.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [false, true, false], + mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +// getWantAgent callback +function getWantAgentCallback(err, data) { + if (err == undefined) { + wantAgent = data; + } else { + console.info('getWantAgent failed' + JSON.stringify(wantAgent)); + } + // getUid callback + function getWantCallback(err, data) { + if(err) { + console.info('getWant failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } else { + console.info('getWant ok!' + JSON.stringify(data)); + } + } + try { + WantAgent.getWant(wantAgent, getBundleNameCallback); + } catch(err) { + console.info('getWant failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } +} +try{ + WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); +} catch(err){ + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +} +``` + + + +## WantAgent.getWant + +getWant(agent: WantAgent): Promise\ + +Obtains the want in a **WantAgent** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----- | --------- | ---- | ------------- | +| agent | WantAgent | Yes | Target **WantAgent** object.| + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the want.| + +**Error codes** +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). +| ID | Error Message | +|-----------|--------------------| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong.| +| 16000003 | Input error. The specified id does not exist.| +| 16000004 | Visibility verification failed.| +| 16000006 | Can not cross user operations.| +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| +| 16000008 | Crowdtest App Expiration.| +| 16000009 | Can not start ability in wukong mode.| +| 16000010 | Can not operation with continue flag.| +| 16000011 | Context does not exist.| +| 16000050 | Internal Error.| +| 16000051 | Network error. The network is abnormal.| +| 16000052 | Free install not support. The application does not support free install. | +| 16000053 | Not top ability. The application is not top ability.| +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| +| 16000055 | Free install timeout.| +| 16000056 | Can not free install other ability.| +| 16000057 | Not support cross device free install.| +| 16000101 | execute shell command failed.| +| 16000151 | Invalid wantagent object.| +| 16000152 | wantAgent object not found.| +| 16000153 | wangAgent object canceled.| + +**Example** + +```ts +import WantAgent from '@ohos.app.ability.wantAgent'; + + // WantAgent object +var wantAgent; +// WantAgentInfo object +var wantAgentInfo = { + wants: [ + { + deviceId: "deviceId", + bundleName: "com.neu.setResultOnAbilityResultTest1", + abilityName: "com.example.test.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [false, true, false], + mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +// getWantAgent callback +function getWantAgentCallback(err, data) { + if (err == undefined) { + wantAgent = data; + } else { + console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); + } + try { + WantAgent.getUid(wantAgent).then((data)=>{ + console.info('getUid ok!' + JSON.stringify(data)); + }).catch((err)=>{ + console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + }) + } catch(err){ + console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } +} +try{ + WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); +} catch(err){ + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +} +``` + + + +## WantAgent.cancel + +cancel(agent: WantAgent, callback: AsyncCallback\): void + +Cancels a **WantAgent** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | --------------------------- | +| agent | WantAgent | Yes | Target **WantAgent** object. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). +| ID | Error Message | +|-----------|--------------------| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong.| +| 16000003 | Input error. The specified id does not exist.| +| 16000004 | Visibility verification failed.| +| 16000006 | Can not cross user operations.| +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| +| 16000008 | Crowdtest App Expiration.| +| 16000009 | Can not start ability in wukong mode.| +| 16000010 | Can not operation with continue flag.| +| 16000011 | Context does not exist.| +| 16000050 | Internal Error.| +| 16000051 | Network error. The network is abnormal.| +| 16000052 | Free install not support. The application does not support free install. | +| 16000053 | Not top ability. The application is not top ability.| +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| +| 16000055 | Free install timeout.| +| 16000056 | Can not free install other ability.| +| 16000057 | Not support cross device free install.| +| 16000101 | execute shell command failed.| +| 16000151 | Invalid wantagent object.| +| 16000152 | wantAgent object not found.| +| 16000153 | wangAgent object canceled.| + +**Example** + +```ts +import WantAgent from '@ohos.app.ability.wantAgent'; +// WantAgent object +var wantAgent; +// WantAgentInfo object +var wantAgentInfo = { + wants: [ + { + deviceId: "deviceId", + bundleName: "com.neu.setResultOnAbilityResultTest1", + abilityName: "com.example.test.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [false, true, false], + mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +// getWantAgent callback +function getWantAgentCallback(err, data) { + if (err == undefined) { + wantAgent = data; + } else { + console.info('getWantAgent failed' + JSON.stringify(wantAgent)); + } + // getUid callback + function cancelCallback(err, data) { + if(err) { + console.info('cancel failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } else { + console.info('cancel ok!'); + } + } + try { + WantAgent.cancel(wantAgent, getBundleNameCallback); + } catch(err) { + console.info('cancel failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } +} +try{ + WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); +} catch(err){ + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +} +``` + + + +## WantAgent.cancel + +cancel(agent: WantAgent): Promise\ + +Cancels a **WantAgent** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----- | --------- | ---- | ------------- | +| agent | WantAgent | Yes | Target **WantAgent** object.| + +**Return value** + +| Type | Description | +| --------------- | ------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). +| ID | Error Message | +|-----------|--------------------| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong.| +| 16000003 | Input error. The specified id does not exist.| +| 16000004 | Visibility verification failed.| +| 16000006 | Can not cross user operations.| +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| +| 16000008 | Crowdtest App Expiration.| +| 16000009 | Can not start ability in wukong mode.| +| 16000010 | Can not operation with continue flag.| +| 16000011 | Context does not exist.| +| 16000050 | Internal Error.| +| 16000051 | Network error. The network is abnormal.| +| 16000052 | Free install not support. The application does not support free install. | +| 16000053 | Not top ability. The application is not top ability.| +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| +| 16000055 | Free install timeout.| +| 16000056 | Can not free install other ability.| +| 16000057 | Not support cross device free install.| +| 16000101 | execute shell command failed.| +| 16000151 | Invalid wantagent object.| +| 16000152 | wantAgent object not found.| +| 16000153 | wangAgent object canceled.| + +**Example** + +```ts +import WantAgent from '@ohos.app.ability.wantAgent'; + +// WantAgent object +var wantAgent; +// WantAgentInfo object +var wantAgentInfo = { + wants: [ + { + deviceId: "deviceId", + bundleName: "com.neu.setResultOnAbilityResultTest1", + abilityName: "com.example.test.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [false, true, false], + mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +// getWantAgent callback +function getWantAgentCallback(err, data) { + if (err == undefined) { + wantAgent = data; + } else { + console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); + } + try { + WantAgent.cancel(wantAgent).then((data)=>{ + console.info('cancel ok!'); + }).catch((err)=>{ + console.info('cancel failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + }) + } catch(err){ + console.info('cancel failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } +} +try{ + WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); +} catch(err){ + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +} +``` + + +//TODO WantAgent.trigger Callback + + +## WantAgent.trigger + +trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: AsyncCallback\): void + +Triggers a **WantAgent** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ----------------------------- | ---- | ------------------------------- | +| agent | WantAgent | Yes | Target **WantAgent** object. | +| triggerInfo | TriggerInfo | Yes | **TriggerInfo** object. | +| callback | AsyncCallback\ | No | Callback used to return the result.| + +**Error codes** +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). +| ID | Error Message | +|-----------|--------------------| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong.| +| 16000003 | Input error. The specified id does not exist.| +| 16000004 | Visibility verification failed.| +| 16000006 | Can not cross user operations.| +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| +| 16000008 | Crowdtest App Expiration.| +| 16000009 | Can not start ability in wukong mode.| +| 16000010 | Can not operation with continue flag.| +| 16000011 | Context does not exist.| +| 16000050 | Internal Error.| +| 16000051 | Network error. The network is abnormal.| +| 16000052 | Free install not support. The application does not support free install. | +| 16000053 | Not top ability. The application is not top ability.| +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| +| 16000055 | Free install timeout.| +| 16000056 | Can not free install other ability.| +| 16000057 | Not support cross device free install.| +| 16000101 | execute shell command failed.| +| 16000151 | Invalid wantagent object.| +| 16000152 | wantAgent object not found.| +| 16000153 | wangAgent object canceled.| + +**Example** + +```ts +import WantAgent from '@ohos.app.ability.wantAgent'; +// WantAgent object +var wantAgent; +// triggerInfo +var triggerInfo = { + code: 0 + } +// WantAgentInfo object +var wantAgentInfo = { + wants: [ + { + deviceId: "deviceId", + bundleName: "com.neu.setResultOnAbilityResultTest1", + abilityName: "com.example.test.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [false, true, false], + mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +// getWantAgent callback +function getWantAgentCallback(err, data) { + if (err == undefined) { + wantAgent = data; + } else { + console.info('getWantAgent failed' + JSON.stringify(wantAgent)); + } + // getUid callback + function triggerCallback(err, data) { + if(err) { + console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } else { + console.info('getUid ok!' + JSON.stringify(data)); + } + } + try { + WantAgent.trigger(wantAgent, triggerInfo, triggerCallback); + } catch(err) { + console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } +} +try{ + WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); +} catch(err){ + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +} +``` + + + +## WantAgent.equal + +equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback\): void + +Checks whether two **WantAgent** objects are equal. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------ | ---- | --------------------------------------- | +| agent | WantAgent | Yes | The first **WantAgent** object. | +| otherAgent | WantAgent | Yes | The second **WantAgent** object. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). +| ID | Error Message | +|-----------|--------------------| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong.| +| 16000003 | Input error. The specified id does not exist.| +| 16000004 | Visibility verification failed.| +| 16000006 | Can not cross user operations.| +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| +| 16000008 | Crowdtest App Expiration.| +| 16000009 | Can not start ability in wukong mode.| +| 16000010 | Can not operation with continue flag.| +| 16000011 | Context does not exist.| +| 16000050 | Internal Error.| +| 16000051 | Network error. The network is abnormal.| +| 16000052 | Free install not support. The application does not support free install. | +| 16000053 | Not top ability. The application is not top ability.| +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| +| 16000055 | Free install timeout.| +| 16000056 | Can not free install other ability.| +| 16000057 | Not support cross device free install.| +| 16000101 | execute shell command failed.| +| 16000151 | Invalid wantagent object.| +| 16000152 | wantAgent object not found.| +| 16000153 | wangAgent object canceled.| + +**Example** + +```ts +import WantAgent from '@ohos.app.ability.wantAgent'; +// WantAgent object +var wantAgent1; +var wantAgent2; +// WantAgentInfo object +var wantAgentInfo = { + wants: [ + { + deviceId: "deviceId", + bundleName: "com.neu.setResultOnAbilityResultTest1", + abilityName: "com.example.test.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [false, true, false], + mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +// getWantAgent callback +function getWantAgentCallback(err, data) { + if (err == undefined) { + wantAgent1 = data; + wantAgent2 = data; + } else { + console.info('getWantAgent failed' + JSON.stringify(wantAgent)); + } + // getUid callback + function equalCallback(err, data) { + if(err) { + console.info('equal failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } else { + console.info('equal ok!' + JSON.stringify(data)); + } + } + try { + WantAgent.equal(wantAgent1,wantAgent2,equalCallback); + } catch(err) { + console.info('equal failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } +} +try{ + WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); +} catch(err){ + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +} +``` + + + +## WantAgent.equal + +equal(agent: WantAgent, otherAgent: WantAgent): Promise\ + +Checks whether two **WantAgent** objects are equal. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | --------- | ---- | ------------- | +| agent | WantAgent | Yes | The first **WantAgent** object.| +| otherAgent | WantAgent | Yes | The second **WantAgent** object.| + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.| + +**Error codes** +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). +| ID | Error Message | +|-----------|--------------------| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong.| +| 16000003 | Input error. The specified id does not exist.| +| 16000004 | Visibility verification failed.| +| 16000006 | Can not cross user operations.| +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| +| 16000008 | Crowdtest App Expiration.| +| 16000009 | Can not start ability in wukong mode.| +| 16000010 | Can not operation with continue flag.| +| 16000011 | Context does not exist.| +| 16000050 | Internal Error.| +| 16000051 | Network error. The network is abnormal.| +| 16000052 | Free install not support. The application does not support free install. | +| 16000053 | Not top ability. The application is not top ability.| +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| +| 16000055 | Free install timeout.| +| 16000056 | Can not free install other ability.| +| 16000057 | Not support cross device free install.| +| 16000101 | execute shell command failed.| +| 16000151 | Invalid wantagent object.| +| 16000152 | wantAgent object not found.| +| 16000153 | wangAgent object canceled.| + +**Example** + +```ts +import WantAgent from '@ohos.app.ability.wantAgent'; + + // WantAgent object +var wantAgent1; +var wantAgent2; +// WantAgentInfo object +var wantAgentInfo = { + wants: [ + { + deviceId: "deviceId", + bundleName: "com.neu.setResultOnAbilityResultTest1", + abilityName: "com.example.test.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [false, true, false], + mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +// getWantAgent callback +function getWantAgentCallback(err, data) { + if (err == undefined) { + wantAgent1 = data; + wantAgent2 = data; + } else { + console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); + } + try { + WantAgent.equal(wantAgent1,wantAgent2).then((data)=>{ + console.info('equal ok!' + JSON.stringify(data)); + }).catch((err)=>{ + console.info('equal failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + }) + } catch(err){ + console.info('equal failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } +} +try{ + WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); +} catch(err){ + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +} +``` + +## WantAgent.getOperationType + +getOperationType(agent: WantAgent, callback: AsyncCallback\): void; + +Obtains the operation type of a **WantAgent** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------ | ---- | --------------------------------------- | +| agent | WantAgent | Yes | Target **WantAgent** object. | +| callback | AsyncCallback\ | Yes | Callback used to return the operation type.| + +**Error codes** +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). +| ID | Error Message | +|-----------|--------------------| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong.| +| 16000003 | Input error. The specified id does not exist.| +| 16000004 | Visibility verification failed.| +| 16000006 | Can not cross user operations.| +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| +| 16000008 | Crowdtest App Expiration.| +| 16000009 | Can not start ability in wukong mode.| +| 16000010 | Can not operation with continue flag.| +| 16000011 | Context does not exist.| +| 16000050 | Internal Error.| +| 16000051 | Network error. The network is abnormal.| +| 16000052 | Free install not support. The application does not support free install. | +| 16000053 | Not top ability. The application is not top ability.| +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| +| 16000055 | Free install timeout.| +| 16000056 | Can not free install other ability.| +| 16000057 | Not support cross device free install.| +| 16000101 | execute shell command failed.| +| 16000151 | Invalid wantagent object.| +| 16000152 | wantAgent object not found.| +| 16000153 | wangAgent object canceled.| + +**Example** + +```ts +import WantAgent from '@ohos.app.ability.wantAgent'; +// WantAgent object +var wantAgent; +// WantAgentInfo object +var wantAgentInfo = { + wants: [ + { + deviceId: "deviceId", + bundleName: "com.neu.setResultOnAbilityResultTest1", + abilityName: "com.example.test.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [false, true, false], + mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +// getWantAgent callback +function getWantAgentCallback(err, data) { + if (err == undefined) { + wantAgent = data; + } else { + console.info('getWantAgent failed' + JSON.stringify(wantAgent)); + } + // getUid callback + function getOperationTypeCallback(err, data) { + if(err) { + console.info('getOperationType failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } else { + console.info('getOperationType ok!' + JSON.stringify(data)); + } + } + try { + WantAgent.getOperationTypeCallback(wantAgent, getBundleNameCallback); + } catch(err) { + console.info('getOperationTypeCallback failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } +} +try{ + WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); +} catch(err){ + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +} +``` + +## WantAgent.getOperationType + +getOperationType(agent: WantAgent): Promise\; + +Obtains the operation type of a **WantAgent** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | --------- | ---- | ------------- | +| agent | WantAgent | Yes | Target **WantAgent** object.| + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the operation type.| + +**Error codes** +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). +| ID | Error Message | +|-----------|--------------------| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong.| +| 16000003 | Input error. The specified id does not exist.| +| 16000004 | Visibility verification failed.| +| 16000006 | Can not cross user operations.| +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| +| 16000008 | Crowdtest App Expiration.| +| 16000009 | Can not start ability in wukong mode.| +| 16000010 | Can not operation with continue flag.| +| 16000011 | Context does not exist.| +| 16000050 | Internal Error.| +| 16000051 | Network error. The network is abnormal.| +| 16000052 | Free install not support. The application does not support free install. | +| 16000053 | Not top ability. The application is not top ability.| +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| +| 16000055 | Free install timeout.| +| 16000056 | Can not free install other ability.| +| 16000057 | Not support cross device free install.| +| 16000101 | execute shell command failed.| +| 16000151 | Invalid wantagent object.| +| 16000152 | wantAgent object not found.| +| 16000153 | wangAgent object canceled.| + +**Example** + +```ts +import WantAgent from '@ohos.app.ability.wantAgent'; + + // WantAgent object +var wantAgent; +// WantAgentInfo object +var wantAgentInfo = { + wants: [ + { + deviceId: "deviceId", + bundleName: "com.neu.setResultOnAbilityResultTest1", + abilityName: "com.example.test.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [false, true, false], + mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +// getWantAgent callback +function getWantAgentCallback(err, data) { + if (err == undefined) { + wantAgent = data; + } else { + console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); + } + try { + WantAgent.getOperationType(wantAgent).then((data)=>{ + console.info('getOperationType ok!' + JSON.stringify(data)); + }).catch((err)=>{ + console.info('getOperationType failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + }) + } catch(err){ + console.info('getOperationType failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } +} +try{ + WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); +} catch(err){ + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +} +``` + +## WantAgentFlags + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ------------------- | -------------- | ------------------------------------------------------------ | +| ONE_TIME_FLAG | 0 | The **WantAgent** object can be used only once. | +| NO_BUILD_FLAG | 1 | The **WantAgent** object does not exist and hence it is not created. In this case, **null** is returned. | +| CANCEL_PRESENT_FLAG | 2 | The existing **WantAgent** object should be canceled before a new object is generated.| +| UPDATE_PRESENT_FLAG | 3 | Extra information of the existing **WantAgent** object is replaced with that of the new object.| +| CONSTANT_FLAG | 4 | The **WantAgent** object is immutable. | +| REPLACE_ELEMENT | 5 | The **element** attribute of the current **Want** can be replaced by the **element** attribute of the **Want** in **WantAgent.trigger()**.| +| REPLACE_ACTION | 6 | The **action** attribute of the current **Want** can be replaced by the **action** attribute of the **Want** in **WantAgent.trigger()**.| +| REPLACE_URI | 7 | The **uri** attribute of the current **Want** can be replaced by the **uri** attribute of the **Want** in **WantAgent.trigger()**.| +| REPLACE_ENTITIES | 8 | The **entities** attribute of the current **Want** can be replaced by the **entities** attribute of the **Want** in **WantAgent.trigger()**.| +| REPLACE_BUNDLE | 9 | The **bundleName** attribute of the current **Want** can be replaced by the **bundleName** attribute of **Want** in **WantAgent.trigger()**.| + + + +## OperationType + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ----------------- | ------------- | ------------------------- | +| UNKNOWN_TYPE | 0 | Unknown operation type. | +| START_ABILITY | 1 | Starts an ability with a UI.| +| START_ABILITIES | 2 | Starts multiple abilities with a UI.| +| START_SERVICE | 3 | Starts an ability without a UI.| +| SEND_COMMON_EVENT | 4 | Sends a common event. | + + + +## CompleteData + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Type | Mandatory| Description | +| -------------- | ------------------------------ | ---- | ---------------------- | +| info | WantAgent | Yes | A triggered **WantAgent** object. | +| want | Want | Yes | An existing triggered **want**. | +| finalCode | number | Yes | Request code that triggers the **WantAgent** object.| +| finalData | string | No | Final data collected by the common event. | +| extraInfo | {[key: string]: any} | No | Extra information. | diff --git a/en/application-dev/reference/apis/js-apis-app-ability-wantConstant.md b/en/application-dev/reference/apis/js-apis-app-ability-wantConstant.md new file mode 100644 index 0000000000000000000000000000000000000000..ece4baa69e5d3b2883e971655e2367e23acf7812 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-wantConstant.md @@ -0,0 +1,95 @@ +# @ohos.app.ability.wantConstant + +The **wantConstant** module provides the actions, entities, and flags used in **Want** objects. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import wantConstant from '@ohos.app.ability.wantConstant'; +``` + +## wantConstant.Action + +Enumerates the action constants of the **Want** object. + +**System capability**: SystemCapability.Ability.AbilityBase + +| Name | Value | Description | +| ------------ | ------------------ | ---------------------- | +| ACTION_HOME | ohos.want.action.home | Action of returning to the home page. | +| ACTION_DIAL | ohos.want.action.dial | Action of launching the numeric keypad. | +| ACTION_SEARCH | ohos.want.action.search | Action of launching the search function. | +| ACTION_WIRELESS_SETTINGS | ohos.settings.wireless | Action of launching the UI that provides wireless network settings, for example, Wi-Fi options. | +| ACTION_MANAGE_APPLICATIONS_SETTINGS | ohos.settings.manage.applications | Action of launching the UI for managing installed applications. | +| ACTION_APPLICATION_DETAILS_SETTINGS | ohos.settings.application.details | Action of launching the UI that displays the details of an application. | +| ACTION_SET_ALARM | ohos.want.action.setAlarm | Action of launching the UI for setting the alarm clock. | +| ACTION_SHOW_ALARMS | ohos.want.action.showAlarms | Action of launching the UI that displays all alarms. | +| ACTION_SNOOZE_ALARM | ohos.want.action.snoozeAlarm | Action of launching the UI for snoozing an alarm. | +| ACTION_DISMISS_ALARM | ohos.want.action.dismissAlarm | Action of launching the UI for deleting an alarm. | +| ACTION_DISMISS_TIMER | ohos.want.action.dismissTimer | Action of launching the UI for dismissing a timer. | +| ACTION_SEND_SMS | ohos.want.action.sendSms | Action of launching the UI for sending an SMS message. | +| ACTION_CHOOSE | ohos.want.action.choose | Action of launching the UI for opening a contact or picture. | +| ACTION_IMAGE_CAPTURE | ohos.want.action.imageCapture | Action of launching the UI for photographing. | +| ACTION_VIDEO_CAPTURE | ohos.want.action.videoCapture | Action of launching the UI for shooting a video. | +| ACTION_SELECT | ohos.want.action.select | Action of launching the UI for application selection. | +| ACTION_SEND_DATA | ohos.want.action.sendData | Action of launching the UI for sending a single data record. | +| ACTION_SEND_MULTIPLE_DATA | ohos.want.action.sendMultipleData | Action of launching the UI for sending multiple data records. | +| ACTION_SCAN_MEDIA_FILE | ohos.want.action.scanMediaFile | Action of requesting a media scanner to scan a file and add the file to the media library. | +| ACTION_VIEW_DATA | ohos.want.action.viewData | Action of viewing data. | +| ACTION_EDIT_DATA | ohos.want.action.editData | Action of editing data. | +| INTENT_PARAMS_INTENT | ability.want.params.INTENT | Action of displaying selection options with an action selector. | +| INTENT_PARAMS_TITLE | ability.want.params.TITLE | Title of the character sequence dialog box used with the action selector. | +| ACTION_FILE_SELECT | ohos.action.fileSelect | Action of selecting a file. | +| PARAMS_STREAM | ability.params.stream | URI of the data stream associated with the target when the data is sent. | | +| ACTION_APP_ACCOUNT_AUTH | account.appAccount.action.auth | Action of providing the authentication service. | +| ACTION_MARKET_DOWNLOAD | ohos.want.action.marketDownload | Action of downloading an application from the application market.
**System API**: This is a system API and cannot be called by third-party applications. | +| ACTION_MARKET_CROWDTEST | ohos.want.action.marketCrowdTest | Action of crowdtesting an application from the application market.
**System API**: This is a system API and cannot be called by third-party applications. | +| DLP_PARAMS_SANDBOX |ohos.dlp.params.sandbox | Action of obtaining the sandbox flag.
**System API**: This is a system API and cannot be called by third-party applications. | +| DLP_PARAMS_BUNDLE_NAME |ohos.dlp.params.bundleName |Action of obtaining the DLP bundle name.
**System API**: This is a system API and cannot be called by third-party applications. | +| DLP_PARAMS_MODULE_NAME |ohos.dlp.params.moduleName |Action of obtaining the DLP module name.
**System API**: This is a system API and cannot be called by third-party applications. | +| DLP_PARAMS_ABILITY_NAME |ohos.dlp.params.abilityName |Action of obtaining the DLP ability name.
**System API**: This is a system API and cannot be called by third-party applications. | +| DLP_PARAMS_INDEX |ohos.dlp.params.index |Action of obtaining the DLP index.
**System API**: This is a system API and cannot be called by third-party applications. | + +## wantConstant.Entity + +Enumerates the entity constants of the **Want** object. + +**System capability**: SystemCapability.Ability.AbilityBase + +| Name | Value | Description | +| ------------ | ------------------ | ---------------------- | +| ENTITY_DEFAULT | entity.system.default | Default entity. The default entity is used if no entity is specified. | +| ENTITY_HOME | entity.system.home | Home screen entity. | +| ENTITY_VOICE | entity.system.voice | Voice interaction entity. | +| ENTITY_BROWSABLE | entity.system.browsable | Browser type entity. | +| ENTITY_VIDEO | entity.system.video | Video type entity. | + + +## wantConstant.Flags + +Describes flags. + +**System capability**: SystemCapability.Ability.AbilityBase + +| Name | Value | Description | +| ------------------------------------ | ---------- | ------------------------------------------------------------ | +| FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Indicates the permission to read the URI. | +| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Indicates the permission to write data to the URI. | +| FLAG_ABILITY_FORWARD_RESULT | 0x00000004 | Returns the result to the ability. | +| FLAG_ABILITY_CONTINUATION | 0x00000008 | Indicates whether the ability on the local device can be continued on a remote device. | +| FLAG_NOT_OHOS_COMPONENT | 0x00000010 | Indicates that a component does not belong to OHOS. | +| FLAG_ABILITY_FORM_ENABLED | 0x00000020 | Indicates that an ability is enabled. | +| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Indicates the permission to make the URI persistent.
**System API**: This is a system API and cannot be called by third-party applications. | +| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Indicates the permission to verify URIs by prefix matching.
**System API**: This is a system API and cannot be called by third-party applications.| +| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Supports cross-device startup in a distributed scheduler. | +| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the Service ability is started regardless of whether the host application has been started. | +| FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that ability continuation is reversible.
**System API**: This is a system API and cannot be called by third-party applications. | +| FLAG_INSTALL_ON_DEMAND | 0x00000800 | Indicates that the specific ability will be installed if it has not been installed. | +| FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | Indicates that the specific ability will be installed in the background if it has not been installed. | +| FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | Clears other operation missions. This flag can be set for the **Want** object in the **startAbility** API passed to [ohos.app.Context](js-apis-ability-context.md) and must be used together with **flag_ABILITY_NEW_MISSION**.| +| FLAG_ABILITY_NEW_MISSION | 0x10000000 | Indicates the operation of creating a mission on the history mission stack. | +| FLAG_ABILITY_MISSION_TOP | 0x20000000 | Starts the mission on the top of the existing mission stack; creates an ability instance if no mission exists.| diff --git a/en/application-dev/reference/apis/js-apis-app-form-formBindingData.md b/en/application-dev/reference/apis/js-apis-app-form-formBindingData.md new file mode 100644 index 0000000000000000000000000000000000000000..bf3f9cbb803b4bed60bba43d88813e6acf38fcb2 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-form-formBindingData.md @@ -0,0 +1,67 @@ +# @ohos.app.form.formBindingData + +The **FormBindingData** module provides APIs for widget data binding. You can use the APIs to create a **FormBindingData** object and obtain related information. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```ts +import formBindingData from '@ohos.app.form.formBindingData'; +``` + +## FormBindingData + +Describes a **FormBindingData** object. + +**System capability**: SystemCapability.Ability.Form + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| data | Object | Yes| Data to be displayed on the JS widget. The value can be an object containing multiple key-value pairs or a string in JSON format.| + + +## createFormBindingData + +createFormBindingData(obj?: Object | string): FormBindingData + +Creates a **FormBindingData** object. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------- | ---- | ------------------------------------------------------------ | +| obj | Object\|string | No | Data to be displayed on the JS widget. The value can be an object containing multiple key-value pairs or a string in JSON format. The image data is identified by "formImages", and the content is multiple key-value pairs, each of which consists of an image identifier and image file descriptor. The final format is {"formImages": {"key1": fd1, "key2": fd2}}.| + + +**Return value** + +| Type | Description | +| ----------------------------------- | --------------------------------------- | +| [FormBindingData](#formbindingdata) | **FormBindingData** object created based on the passed data.| + + +**Example** + +```ts +import featureAbility from '@ohos.ability.featureAbility'; +import fileio from '@ohos.fileio'; +let context=featureAbility.getContext(); +context.getOrCreateLocalDir((err,data)=>{ + let path=data+"/xxx.jpg"; + let fd = fileio.openSync(path); + let obj = { + "temperature": "21°", + "formImages": {"image": fd} + }; + try { + formBindingData.createFormBindingData(obj); + } catch (error) { + console.log(`catch err->${JSON.stringify(err)}`); + } +}) +``` diff --git a/en/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md b/en/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md new file mode 100644 index 0000000000000000000000000000000000000000..c2bedd6d4dc1b50b6575120b88c0ab88423e7846 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md @@ -0,0 +1,283 @@ +# @ohos.app.form.FormExtensionAbility + +The **FormExtensionAbility** module provides APIs related to Form Extension abilities. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the stage model. + +## Modules to Import + +```ts +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; +``` + +## Attributes + +**System capability**: SystemCapability.Ability.Form + +| Name | Type | Readable| Writable| Description | +| ------- | ------------------------------------------------------- | ---- | ---- | --------------------------------------------------- | +| context | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | Yes | No | Context of the **FormExtensionAbility**. This context is inherited from **ExtensionContext**.| + +## onAddForm + +onAddForm(want: Want): formBindingData.FormBindingData + +Called to notify the widget provider that a **Form** instance (widget) has been created. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------------------------------- | ---- | ------------------------------------------------------------ | +| want | [Want](js-apis-application-want.md) | Yes | Information related to the Extension ability, including the widget ID, name, and style. The information must be managed as persistent data to facilitate subsequent widget update and deletion.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ----------------------------------------------------------- | +| [formBindingData.FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | A **formBindingData.FormBindingData** object containing the data to be displayed on the widget.| + +**Example** + +```ts +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; +export default class MyFormExtensionAbility extends FormExtensionAbility { + onAddForm(want) { + console.log('FormExtensionAbility onAddForm, want:' + want.abilityName); + let dataObj1 = { + temperature:"11c", + "time":"11:00" + }; + let obj1 = formBindingData.createFormBindingData(dataObj1); + return obj1; + } +} +``` + +## onCastToNormalForm + +onCastToNormalForm(formId: string): void + +Called to notify the widget provider that a temporary widget has been converted to a normal one. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------ | +| formId | string | Yes | ID of the widget that requests to be converted to a normal one.| + +**Example** + +```ts +export default class MyFormExtensionAbility extends FormExtensionAbility { + onCastToNormalForm(formId) { + console.log('FormExtensionAbility onCastToNormalForm, formId:' + formId); + } +} +``` + +## onUpdateForm + +onUpdateForm(formId: string): void + +Called to notify the widget provider that a widget has been updated. After obtaining the latest data, the caller invokes **updateForm** of the [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) class to update the widget data. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| formId | string | Yes | ID of the widget that requests to be updated.| + +**Example** + +```ts +import formBindingData from '@ohos.app.form.formBindingData' +export default class MyFormExtensionAbility extends FormExtensionAbility { + onUpdateForm(formId) { + console.log('FormExtensionAbility onUpdateForm, formId:' + formId); + let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); + this.context.updateForm(formId, obj2).then((data)=>{ + console.log('FormExtensionAbility context updateForm, data:' + data); + }).catch((error) => { + console.error('Operation updateForm failed. Cause: ' + error);}); + } +} +``` + +## onChangeFormVisibility + +onChangeFormVisibility(newStatus: { [key: string]: number }): void + +Called to notify the widget provider of the change of visibility. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------- | ---- | ---------------------------- | +| newStatus | { [key: string]: number } | Yes | ID and visibility status of the widget to be changed.| + +**Example** + +```ts +import formBindingData from '@ohos.app.form.formBindingData' +export default class MyFormExtensionAbility extends FormExtensionAbility { + onChangeFormVisibility(newStatus) { + console.log('FormExtensionAbility onChangeFormVisibility, newStatus:' + newStatus); + let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); + + for (let key in newStatus) { + console.log('FormExtensionAbility onChangeFormVisibility, key:' + key + ", value=" + newStatus[key]); + this.context.updateForm(key, obj2).then((data)=>{ + console.log('FormExtensionAbility context updateForm, data:' + data); + }).catch((error) => { + console.error('Operation updateForm failed. Cause: ' + error);}); + } + } +} +``` + +## onFormEvent + +onFormEvent(formId: string, message: string): void + +Called to instruct the widget provider to receive and process the widget event. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ---------------------- | +| formId | string | Yes | ID of the widget that requests the event.| +| message | string | Yes | Event message. | + +**Example** + +```ts +export default class MyFormExtension extends FormExtensionAbility { + onFormEvent(formId, message) { + console.log('FormExtensionAbility onFormEvent, formId:' + formId + ", message:" + message); + } +} +``` + +## onRemoveForm + +onRemoveForm(formId: string): void + +Called to notify the widget provider that a **Form** instance (widget) has been destroyed. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| formId | string | Yes | ID of the widget to be destroyed.| + +**Example** + +```ts +export default class MyFormExtensionAbility extends FormExtensionAbility { + onRemoveForm(formId) { + console.log('FormExtensionAbility onRemoveForm, formId:' + formId); + } +} +``` + +## onConfigurationUpdate + +onConfigurationUpdate(newConfig: Configuration): void; + +Called when the configuration of the environment where the ability is running is updated. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| newConfig | [Configuration](js-apis-configuration.md) | Yes| New configuration.| + +**Example** + +```ts +class MyFormExtensionAbility extends FormExtensionAbility { + onConfigurationUpdate(config) { + console.log('onConfigurationUpdate, config:' + JSON.stringify(config)); + } +} +``` + +## onAcquireFormState + +onAcquireFormState?(want: Want): formInfo.FormState; + +Called when the widget provider receives the status query result of a widget. By default, the initial state is returned. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Description of the widget state, including the bundle name, ability name, module name, widget name, and widget dimension.| + +**Example** + +```ts +import formInfo from '@ohos.app.form.formInfo'; +class MyFormExtensionAbility extends FormExtensionAbility { + onAcquireFormState(want) { + console.log('FormExtensionAbility onAcquireFormState, want:' + want); + return formInfo.FormState.UNKNOWN; + } +} +``` + +## onShareForm + +onShareForm?(formId: string): { [key: string]: any } + +Called by the widget provider to receive shared widget data. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| formId | string | Yes | Widget ID.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ----------------------------------------------------------- | +| {[key: string]: any} | Data to be shared by the widget, in the form of key-value pairs.| + +**Example** + +```ts +class MyFormExtensionAbility extends FormExtensionAbility { + onShareForm(formId) { + console.log('FormExtensionAbility onShareForm, formId:' + formId); + let wantParams = { + "temperature":"20", + "time":"2022-8-8 09:59", + }; + return wantParams; + } +} +``` diff --git a/en/application-dev/reference/apis/js-apis-app-form-formHost.md b/en/application-dev/reference/apis/js-apis-app-form-formHost.md new file mode 100644 index 0000000000000000000000000000000000000000..826050a278af8fa031a54ddcbf701b8759e4132a --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-form-formHost.md @@ -0,0 +1,1478 @@ +# @ohos.app.form.formHost + +The **FormHost** module provides APIs related to the widget host, which is an application that displays the widget content and controls the position where the widget is displayed. You can use the APIs to delete, release, and update widgets installed by the same user, and obtain widget information and status. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs provided by this module are system APIs. + +## Modules to Import + +```ts +import formHost from '@ohos.app.form.formHost'; +``` + +## deleteForm + +deleteForm(formId: string, callback: AsyncCallback<void>): void + +Deletes a widget. After this API is called, the application can no longer use the widget, and the Widget Manager will not retain the widget information. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is deleted, **err** is undefined; otherwise, **err** is an error object.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +try { + var formId = "12400633174999288"; + formHost.deleteForm(formId, (error, data) => { + if (error) { + console.log('formHost deleteForm, error:' + JSON.stringify(error)); + } else { + console.log('formHost deleteForm success'); + } + }); +} catch (error) { + console.log(`catch err->${JSON.stringify(error)}`); +} + +``` + +## deleteForm + +deleteForm(formId: string): Promise<void> + +Deletes a widget. After this API is called, the application can no longer use the widget, and the Widget Manager will not retain the widget information. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Parameters** + +```ts +try { + var formId = "12400633174999288"; + formHost.deleteForm(formId).then(() => { + console.log('formHost deleteForm success'); + }).catch((error) => { + console.log('formHost deleteForm, error:' + JSON.stringify(error)); + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## releaseForm + +releaseForm(formId: string, callback: AsyncCallback<void>): void + +Releases a widget. After this API is called, the application can no longer use the widget, but the Widget Manager still retains the widget cache and storage information. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is released, **err** is undefined; otherwise, **err** is an error object.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +try { + var formId = "12400633174999288"; + formHost.releaseForm(formId, (error, data) => { + if (error) { + console.log('formHost releaseForm, error:' + JSON.stringify(error)); + } + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## releaseForm + +releaseForm(formId: string, isReleaseCache: boolean, callback: AsyncCallback<void>): void + +Releases a widget. After this API is called, the application can no longer use the widget, but the Widget Manager retains the storage information about the widget and retains or releases the cache information based on the setting. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ------ | ---- | ----------- | +| formId | string | Yes | Widget ID. | +| isReleaseCache | boolean | Yes | Whether to release the cache.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is released, **err** is undefined; otherwise, **err** is an error object.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +try { + var formId = "12400633174999288"; + formHost.releaseForm(formId, true, (error, data) => { + if (error) { + console.log('formHost releaseForm, error:' + JSON.stringify(error)); + } + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## releaseForm + +releaseForm(formId: string, isReleaseCache?: boolean): Promise<void> + +Releases a widget. After this API is called, the application can no longer use the widget, but the Widget Manager retains the storage information about the widget and retains or releases the cache information based on the setting. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ------ | ---- | ----------- | +| formId | string | Yes | Widget ID. | +| isReleaseCache | boolean | No | Whether to release the cache.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +try { + var formId = "12400633174999288"; + formHost.releaseForm(formId, true).then(() => { + console.log('formHost releaseForm success'); + }).catch((error) => { + console.log('formHost releaseForm, error:' + JSON.stringify(error)); + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## requestForm + +requestForm(formId: string, callback: AsyncCallback<void>): void + +Requests a widget update. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is updated, **err** is undefined; otherwise, **err** is an error object.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +try { + var formId = "12400633174999288"; + formHost.requestForm(formId, (error, data) => { + if (error) { + console.log('formHost requestForm, error:' + JSON.stringify(error)); + } + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## requestForm + +requestForm(formId: string): Promise<void> + +Requests a widget update. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +try { + var formId = "12400633174999288"; + formHost.requestForm(formId).then(() => { + console.log('formHost requestForm success'); + }).catch((error) => { + console.log('formHost requestForm, error:' + JSON.stringify(error)); + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} + +``` + +## castToNormalForm + +castToNormalForm(formId: string, callback: AsyncCallback<void>): void + +Converts a temporary widget to a normal one. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is converted to a normal one, **err** is undefined; otherwise, **err** is an error object.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +try { + var formId = "12400633174999288"; + formHost.castToNormalForm(formId, (error, data) => { + if (error) { + console.log('formHost castTempForm, error:' + JSON.stringify(error)); + } + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## castToNormalForm + +castToNormalForm(formId: string): Promise<void> + +Converts a temporary widget to a normal one. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +try { + var formId = "12400633174999288"; + formHost.castToNormalForm(formId).then(() => { + console.log('formHost castTempForm success'); + }).catch((error) => { + console.log('formHost castTempForm, error:' + JSON.stringify(error)); + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## notifyVisibleForms + +notifyVisibleForms(formIds: Array<string>, callback: AsyncCallback<void>): void + +Instructs the widget framework to make a widget visible. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget visible, **err** is undefined; otherwise, **err** is an error object.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +try { + var formId = ["12400633174999288"]; + formHost.notifyVisibleForms(formId, (error, data) => { + if (error) { + console.log('formHost notifyVisibleForms, error:' + JSON.stringify(error)); + } + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## notifyVisibleForms + +notifyVisibleForms(formIds: Array<string>): Promise<void> + +Instructs the widget framework to make a widget visible. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +try { + var formId = ["12400633174999288"]; + formHost.notifyVisibleForms(formId).then(() => { + console.log('formHost notifyVisibleForms success'); + }).catch((error) => { + console.log('formHost notifyVisibleForms, error:' + JSON.stringify(error)); + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## notifyInvisibleForms + +notifyInvisibleForms(formIds: Array<string>, callback: AsyncCallback<void>): void + +Instructs the widget framework to make a widget invisible. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget invisible, **err** is undefined; otherwise, **err** is an error object.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +try { + var formId = ["12400633174999288"]; + formHost.notifyInvisibleForms(formId, (error, data) => { + if (error) { + console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(error)); + } + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## notifyInvisibleForms + +notifyInvisibleForms(formIds: Array<string>): Promise<void> + +Instructs the widget framework to make a widget invisible. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +try { + var formId = ["12400633174999288"]; + formHost.notifyInvisibleForms(formId).then(() => { + console.log('formHost notifyInvisibleForms success'); + }).catch((error) => { + console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(error)); + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## enableFormsUpdate + +enableFormsUpdate(formIds: Array<string>, callback: AsyncCallback<void>): void + +Instructs the widget framework to make a widget updatable. After this API is called, the widget is in the enabled state and can receive updates from the widget provider. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget updatable, **err** is undefined; otherwise, **err** is an error object.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +try { + var formId = ["12400633174999288"]; + formHost.enableFormsUpdate(formId, (error, data) => { + if (error) { + console.log('formHost enableFormsUpdate, error:' + JSON.stringify(error)); + } + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## enableFormsUpdate + +enableFormsUpdate(formIds: Array<string>): Promise<void> + +Instructs the widget framework to make a widget updatable. After this API is called, the widget is in the enabled state and can receive updates from the widget provider. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +try { + var formId = ["12400633174999288"]; + formHost.enableFormsUpdate(formId).then(() => { + console.log('formHost enableFormsUpdate success'); + }).catch((error) => { + console.log('formHost enableFormsUpdate, error:' + JSON.stringify(error)); + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## disableFormsUpdate + +disableFormsUpdate(formIds: Array<string>, callback: AsyncCallback<void>): void + +Instructs the widget framework to make a widget not updatable. After this API is called, the widget cannot receive updates from the widget provider. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget not updatable, **err** is undefined; otherwise, **err** is an error object.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +try { + var formId = ["12400633174999288"]; + formHost.disableFormsUpdate(formId, (error, data) => { + if (error) { + console.log('formHost disableFormsUpdate, error:' + JSON.stringify(error)); + } + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## disableFormsUpdate + +disableFormsUpdate(formIds: Array<string>): Promise<void> + +Instructs the widget framework to make a widget not updatable. After this API is called, the widget cannot receive updates from the widget provider. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +try { + var formId = ["12400633174999288"]; + formHost.disableFormsUpdate(formId).then(() => { + console.log('formHost disableFormsUpdate success'); + }).catch((error) => { + console.log('formHost disableFormsUpdate, error:' + JSON.stringify(error)); + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## isSystemReady + +isSystemReady(callback: AsyncCallback<void>): void + +Checks whether the system is ready. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the check is successful, **err** is undefined; otherwise, **err** is an error object.| + +**Example** + +```ts +try { + var formId = "12400633174999288"; + formHost.isSystemReady((error, data) => { + if (error) { + console.log('formHost isSystemReady, error:' + JSON.stringify(error)); + } + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## isSystemReady + +isSystemReady(): Promise<void> + +Checks whether the system is ready. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +try { + var formId = "12400633174999288"; + formHost.isSystemReady().then(() => { + console.log('formHost isSystemReady success'); + }).catch((error) => { + console.log('formHost isSystemReady, error:' + JSON.stringify(error)); + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## getAllFormsInfo + +getAllFormsInfo(callback: AsyncCallback<Array<formInfo.FormInfo>>): void + +Obtains the widget information provided by all applications on the device. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| callback | AsyncCallback<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **err** is undefined and **data** is the information obtained; otherwise, **err** is an error object.| + +**Example** + +```ts +try { + formHost.getAllFormsInfo((error, data) => { + if (error) { + console.log('formHost getAllFormsInfo, error:' + JSON.stringify(error)); + } else { + console.log('formHost getAllFormsInfo, data:' + JSON.stringify(data)); + } + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## getAllFormsInfo + +getAllFormsInfo(): Promise<Array<formInfo.FormInfo>> + +Obtains the widget information provided by all applications on the device. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Promise used to return the information obtained.| + +**Example** + +```ts +try { + formHost.getAllFormsInfo().then((data) => { + console.log('formHost getAllFormsInfo data:' + JSON.stringify(data)); + }).catch((error) => { + console.log('formHost getAllFormsInfo, error:' + JSON.stringify(error)); + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## getFormsInfo + +getFormsInfo(bundleName: string, callback: AsyncCallback<Array<formInfo.FormInfo>>): void + +Obtains the widget information provided by a given application on the device. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| bundleName | string | Yes| Bundle name of the application.| +| callback | AsyncCallback<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **err** is undefined and **data** is the information obtained; otherwise, **err** is an error object.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +try { + formHost.getFormsInfo("com.example.ohos.formjsdemo", (error, data) => { + if (error) { + console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); + } else { + console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); + } + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## getFormsInfo + +getFormsInfo(bundleName: string, moduleName: string, callback: AsyncCallback<Array<formInfo.FormInfo>>): void + +Obtains the widget information provided by a given application on the device. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| bundleName | string | Yes| Bundle name of the application.| +| moduleName | string | Yes| Module name.| +| callback | AsyncCallback<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **err** is undefined and **data** is the information obtained; otherwise, **err** is an error object.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +try { + formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry", (error, data) => { + if (error) { + console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); + } else { + console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); + } + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## getFormsInfo + +getFormsInfo(bundleName: string, moduleName?: string): Promise<Array<formInfo.FormInfo>> + +Obtains the widget information provided by a given application on the device. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| bundleName | string | Yes| Bundle name of the application.| +| moduleName | string | No| Module name.| + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Promise used to return the information obtained.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +try { + formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry").then((data) => { + console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); + }).catch((error) => { + console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## deleteInvalidForms + +deleteInvalidForms(formIds: Array<string>, callback: AsyncCallback<number>): void + +Deletes invalid widgets from the list. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of valid widget IDs.| +| callback | AsyncCallback<number> | Yes| Callback used to return the result. If the invalid widgets are deleted, **err** is undefined and **data** is the number of widgets deleted; otherwise, **err** is an error object.| + +**Example** + +```ts +try { + var formIds = new Array("12400633174999288", "12400633174999289"); + formHost.deleteInvalidForms(formIds, (error, data) => { + if (error) { + console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error)); + } else { + console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); + } + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## deleteInvalidForms + +deleteInvalidForms(formIds: Array<string>): Promise<number> + +Deletes invalid widgets from the list. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of valid widget IDs.| + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<number> | Promise used to return the number of widgets deleted.| + +**Example** + +```ts +try { + var formIds = new Array("12400633174999288", "12400633174999289"); + formHost.deleteInvalidForms(formIds).then((data) => { + console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); + }).catch((error) => { + console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error)); + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## acquireFormState + +acquireFormState(want: Want, callback: AsyncCallback<formInfo.FormStateInfo>): void + +Obtains the widget state. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| want | [Want](js-apis-application-want.md) | Yes | **Want** information carried to query the widget state.| +| callback | AsyncCallback<[FormStateInfo](js-apis-app-form-formInfo.md#formstateinfo)> | Yes| Callback used to return the result. If the widget state is obtained, **err** is undefined and **data** is the widget state obtained; otherwise, **err** is an error object.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +var want = { + "deviceId": "", + "bundleName": "ohos.samples.FormApplication", + "abilityName": "FormAbility", + "parameters": { + "ohos.extra.param.key.module_name": "entry", + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.form_dimension": 2 + } +}; +try { + formHost.acquireFormState(want, (error, data) => { + if (error) { + console.log('formHost acquireFormState, error:' + JSON.stringify(error)); + } else { + console.log('formHost acquireFormState, data:' + JSON.stringify(data)); + } + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## acquireFormState + +acquireFormState(want: Want): Promise<formInfo.FormStateInfo> + +Obtains the widget state. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| want | [Want](js-apis-application-want.md) | Yes | **Want** information carried to query the widget state.| + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<[FormStateInfo](js-apis-app-form-formInfo.md#formstateinfo)> | Promise used to return the widget state obtained.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +var want = { + "deviceId": "", + "bundleName": "ohos.samples.FormApplication", + "abilityName": "FormAbility", + "parameters": { + "ohos.extra.param.key.module_name": "entry", + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.form_dimension": 2 + } +}; +try { + formHost.acquireFormState(want).then((data) => { + console.log('formHost acquireFormState, data:' + JSON.stringify(data)); + }).catch((error) => { + console.log('formHost acquireFormState, error:' + JSON.stringify(error)); + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## on("formUninstall") + +on(type: "formUninstall", callback: Callback<string>): void + +Subscribes to widget uninstall events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| type | string | Yes | Event type. The value **formUninstall** indicates a widget uninstallation event.| +| callback | Callback<string> | Yes| Callback used to return the widget ID.| + +**Example** + +```ts +let callback = function(formId) { + console.log('formHost on formUninstall, formId:' + formId); +} +formHost.on("formUninstall", callback); +``` + +## off("formUninstall") + +off(type: "formUninstall", callback?: Callback<string>): void + +Unsubscribes from widget uninstall events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| type | string | Yes | Event type. The value **formUninstall** indicates a widget uninstallation event.| +| callback | Callback<string> | No| Callback used to return the widget ID. If it is left unspecified, it indicates the callback for all the events that have been subscribed.| + +**Example** + +```ts +let callback = function(formId) { + console.log('formHost on formUninstall, formId:' + formId); +} +formHost.off("formUninstall", callback); +``` + +## notifyFormsVisible + +notifyFormsVisible(formIds: Array<string>, isVisible: boolean, callback: AsyncCallback<void>): void + +Instructs the widgets to make themselves visible. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| +| isVisible | boolean | Yes | Whether to make the widgets visible.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the notification is sent, **err** is undefined; otherwise, **err** is an error object.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +var formIds = new Array("12400633174999288", "12400633174999289"); +try { + formHost.notifyFormsVisible(formIds, true, (error, data) => { + if (error) { + console.log('formHost notifyFormsVisible, error:' + JSON.stringify(error)); + } + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## notifyFormsVisible + +notifyFormsVisible(formIds: Array<string>, isVisible: boolean): Promise<void> + +Instructs the widgets to make themselves visible. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| +| isVisible | boolean | Yes | Whether to make the widgets visible.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +var formIds = new Array("12400633174999288", "12400633174999289"); +try { + formHost.notifyFormsVisible(formIds, true).then(() => { + console.log('formHost notifyFormsVisible success'); + }).catch((error) => { + console.log('formHost notifyFormsVisible, error:' + JSON.stringify(error)); + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## notifyFormsEnableUpdate + +notifyFormsEnableUpdate(formIds: Array<string>, isEnableUpdate: boolean, callback: AsyncCallback<void>): void + +Instructs the widgets to enable or disable updates. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| +| isEnableUpdate | boolean | Yes | Whether to make the widgets updatable.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the notification is sent, **err** is undefined; otherwise, **err** is an error object.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +var formIds = new Array("12400633174999288", "12400633174999289"); +try { + formHost.notifyFormsEnableUpdate(formIds, true, (error, data) => { + if (error) { + console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); + } + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## notifyFormsEnableUpdate + +notifyFormsEnableUpdate(formIds: Array<string>, isEnableUpdate: boolean): Promise<void> + +Instructs the widgets to enable or disable updates. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| +| isEnableUpdate | boolean | Yes | Whether to make the widgets updatable.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +var formIds = new Array("12400633174999288", "12400633174999289"); +try { + formHost.notifyFormsEnableUpdate(formIds, true).then(() => { + console.log('formHost notifyFormsEnableUpdate success'); + }).catch((error) => { + console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` +## shareForm + +shareForm(formId: string, deviceId: string, callback: AsyncCallback<void>): void + +Shares a specified widget with a remote device. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM and ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| +| deviceId | string | Yes | Remote device ID.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is shared, **err** is undefined; otherwise, **err** is an error object.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + + +**Example** + +```ts +var formId = "12400633174999288"; +var deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; +try { + formHost.shareForm(formId, deviceId, (error, data) => { + if (error) { + console.log('formHost shareForm, error:' + JSON.stringify(error)); + } + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## shareForm + +shareForm(formId: string, deviceId: string): Promise<void> + +Shares a specified widget with a remote device. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM and ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| +| deviceId | string | Yes | Remote device ID.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Parameters** + +```ts +var formId = "12400633174999288"; +var deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; +try { + formHost.shareForm(formId, deviceId).then(() => { + console.log('formHost shareForm success'); + }).catch((error) => { + console.log('formHost shareForm, error:' + JSON.stringify(error)); + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## notifyFormsPrivacyProtected + +notifyFormsPrivacyProtected(formIds: Array\, isProtected: boolean, callback: AsyncCallback\): void + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| +| deviceId | string | Yes | Remote device ID.| + +```ts +var formIds = new Array("12400633174999288", "12400633174999289"); +try { + formHost.notifyFormsPrivacyProtected(formIds, true).then(() => { + console.log('formHost shareForm success'); + }).catch((error) => { + console.log('formHost shareForm, error:' + JSON.stringify(error)); + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + + \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-app-form-formInfo.md b/en/application-dev/reference/apis/js-apis-app-form-formInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..5f1ff73b163ffd2c1c5b0feeb1c26a4f3f60cb78 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-form-formInfo.md @@ -0,0 +1,141 @@ +# @ohos.app.form.formInfo + +The **FormInfo** module provides widget information and state. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```ts +import formInfo from '@ohos.app.form.formInfo'; +``` + +## FormInfo + +Describes widget information. + +**System capability**: SystemCapability.Ability.Form + +| Name | Type | Readable | Writable | Description | +| ----------- | -------- | -------- | -------------------- | ------------------------------------------------------------ | +| bundleName | string | Yes | No | Name of the bundle to which the widget belongs. | +| moduleName | string | Yes | No | Name of the module to which the widget belongs. | +| abilityName | string | Yes | No | Name of the ability to which the widget belongs. | +| name | string | Yes | No | Widget name. | +| description | string | Yes | No | Description of the widget. | +| type | [FormType](#formtype) | Yes | No | Type of the widget. Currently, only JS widgets are supported.| +| jsComponentName | string | Yes | No | Name of the component used in the JS widget. | +| colorMode | [ColorMode](#colormode) | Yes | No | Color mode of the widget. | +| isDefault | boolean | Yes | No | Whether the widget is the default one. | +| updateEnabled | boolean | Yes | No | Whether the widget is updatable. | +| formVisibleNotify | string | Yes | No | Whether to send a notification when the widget is visible. | +| relatedBundleName | string | Yes | No | Name of the associated bundle to which the widget belongs. | +| scheduledUpdateTime | string | Yes | No | Time when the widget was updated. | +| formConfigAbility | string | Yes | No | Configuration ability of the widget, that is, the ability corresponding to the option in the selection box displayed when the widget is long pressed. | +| updateDuration | string | Yes | No | Update period of the widget.| +| defaultDimension | number | Yes | No | Default dimension of the widget. | +| supportDimensions | Array<number> | Yes | No | Dimensions supported by the widget. For details, see [FormDimension](#formdimension). | +| customizeData | {[key: string]: [value: string]} | Yes | No | Custom data of the widget. | + +## FormType + +Enumerates the widget types. + +**System capability**: SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| JS | 1 | JS widget. | +| eTS | 2 | eTS widget.| + +## ColorMode + +Enumerates the color modes supported by the widget. + +**System capability**: SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| MODE_AUTO | -1 | Auto mode. | +| MODE_DARK | 0 | Dark mode. | +| MODE_LIGHT | 1 | Light mode. | + +## FormStateInfo + +Describes the widget state information. + +**System capability**: SystemCapability.Ability.Form + +| Name | Type | Readable | Writable | Description | +| ----------- | -------- | -------- | -------------------- | ------------------------------------------------------------ | +| formState | [FormState](#formstate) | Yes | No | Widget state. | +| want | Want | Yes | No | Want text. | + +## FormState + +Enumerates the widget states. + +**System capability**: SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| UNKNOWN | -1 | Unknown state. | +| DEFAULT | 0 | Default state. | +| READY | 1 | Ready state. | + +## FormParam + +Enumerates the widget parameters. + +**System capability**: SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| IDENTITY_KEY | "ohos.extra.param.key.form_identity" | Widget ID. | +| DIMENSION_KEY | "ohos.extra.param.key.form_dimension" | Widget dimension. | +| NAME_KEY | "ohos.extra.param.key.form_name" | Widget name. | +| MODULE_NAME_KEY | "ohos.extra.param.key.module_name" | Name of the module to which the widget belongs. | +| WIDTH_KEY | "ohos.extra.param.key.form_width" | Widget width. | +| HEIGHT_KEY | "ohos.extra.param.key.form_height" | Widget height. | +| TEMPORARY_KEY | "ohos.extra.param.key.form_temporary" | Temporary widget. | +| ABILITY_NAME_KEY | "ohos.extra.param.key.ability_name" | Ability name. | +| DEVICE_ID_KEY | "ohos.extra.param.key.device_id" | Device ID.
**System API**: This is a system API. | +| BUNDLE_NAME_KEY | "ohos.extra.param.key.bundle_name" | Key that specifies the target bundle name.| + +## FormDimension + +Enumerates the widget dimensions. + +**System capability**: SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| Dimension_1_2 | 1 | 1 x 2. | +| Dimension_2_2 | 2 | 2 x 2. | +| Dimension_2_4 | 3 | 2 x 4. | +| Dimension_4_4 | 4 | 4 x 4. | +| Dimension_2_1 | 5 | 2 x 1. | + + +## FormInfoFilter + +Defines the widget information filter. Only the widget information that meets the filter is returned. + +**System capability**: SystemCapability.Ability.Form + +| Name | Description | +| ----------- | ------------ | +| moduleName | Only the information about the widget whose **moduleName** is the same as the provided value is returned.| + +## VisibilityType + +Enumerates the visibility types of the widget. + +**System capability**: SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| FORM_VISIBLE | 1 | The widget is visible.| +| FORM_INVISIBLE | 2 | The widget is invisible.| diff --git a/en/application-dev/reference/apis/js-apis-app-form-formProvider.md b/en/application-dev/reference/apis/js-apis-app-form-formProvider.md new file mode 100644 index 0000000000000000000000000000000000000000..392f053b31f4fdb51033abb04a83514b8d3cfbd8 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-form-formProvider.md @@ -0,0 +1,564 @@ +# @ohos.app.form.formProvider + +The **FormProvider** module provides APIs related to the widget provider. You can use the APIs to update a widget, set the next refresh time for a widget, obtain widget information, and request a widget release. + +> **NOTE** +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```ts +import formProvider from '@ohos.app.form.formProvider'; +``` + +## setFormNextRefreshTime + +setFormNextRefreshTime(formId: string, minute: number, callback: AsyncCallback<void>): void + +Sets the next refresh time for a widget. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------- | +| formId | string | Yes | Widget ID. | +| minute | number | Yes | Refresh interval, in minutes. The value must be greater than or equal to 5. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +var formId = "12400633174999288"; +try { + formProvider.setFormNextRefreshTime(formId, 5, (error, data) => { + if (error) { + console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error)); + } else { + console.log(`formProvider setFormNextRefreshTime success`); + } + }); +} catch (error) { + console.log("error" + JSON.stringify(error)) +} +``` + +## setFormNextRefreshTime + +setFormNextRefreshTime(formId: string, minute: number): Promise<void> + +Sets the next refresh time for a widget. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------- | +| formId | string | Yes | Widget ID. | +| minute | number | Yes | Refresh interval, in minutes. The value must be greater than or equal to 5. | + +**Return value** + +| Type | Description | +| ------------- | ---------------------------------- | +| Promise\ | Promise that returns no value. | + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +var formId = "12400633174999288"; +try { + formProvider.setFormNextRefreshTime(formId, 5).then(() => { + console.log('formProvider setFormNextRefreshTime success'); + }).catch((error) => { + console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error)); + }); +} catch (error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## updateForm + +updateForm(formId: string, formBindingData: formBindingData.FormBindingData,callback: AsyncCallback<void>): void + +Updates a widget. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ---------------------------------------------------------------------- | ---- | ---------------- | +| formId | string | Yes | ID of the widget to update.| +| formBindingData.FormBindingData | [FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | Yes | Data to be used for the update. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +import formBindingData from '@ohos.application.formBindingData'; +var formId = "12400633174999288"; +try { + let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); + formProvider.updateForm(formId, obj, (error, data) => { + if (error) { + console.log('formProvider updateForm, error:' + JSON.stringify(error)); + } else { + console.log(`formProvider updateForm success`); + } + }); +} catch (error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## updateForm + +updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Promise<void> + +Updates a widget. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ---------------------------------------------------------------------- | ---- | ---------------- | +| formId | string | Yes | ID of the widget to update.| +| formBindingData.FormBindingData | [FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | Yes | Data to be used for the update. | + +**Return value** + +| Type | Description | +| -------------- | ----------------------------------- | +| Promise\ | Promise that returns no value.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +import formBindingData from '@ohos.application.formBindingData'; +var formId = "12400633174999288"; +let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); +try { + formProvider.updateForm(formId, obj).then(() => { + console.log('formProvider updateForm success'); + }).catch((error) => { + console.log('formProvider updateForm, error:' + JSON.stringify(error)); + }); +} catch (error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## getFormsInfo + +getFormsInfo(callback: AsyncCallback<Array<formInfo.FormInfo>>): void + +Obtains the application's widget information on the device. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| callback | AsyncCallback<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the information obtained.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + + +**Example** + +```ts +try { + formProvider.getFormsInfo((error, data) => { + if (error) { + console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); + } else { + console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); + } + }); +} catch (error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` +## getFormsInfo + +getFormsInfo(filter: formInfo.FormInfoFilter, callback: AsyncCallback<Array<formInfo.FormInfo>>): void + +Obtains the application's widget information that meets a filter criterion on the device. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| filter | [formInfo.FormInfoFilter](js-apis-app-form-formInfo.md#forminfofilter) | Yes| Filter criterion.| +| callback | AsyncCallback<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the information obtained.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +import formInfo from '@ohos.application.formInfo'; +const filter : formInfo.FormInfoFilter = { + // get info of forms belong to module entry. + moduleName : "entry" +}; +try { + formProvider.getFormsInfo(filter, (error, data) => { + if (error) { + console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); + } else { + console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); + } + }); +} catch(error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## getFormsInfo + +getFormsInfo(filter?: formInfo.FormInfoFilter): Promise<Array<formInfo.FormInfo>> + +Obtains the application's widget information on the device. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| filter | [formInfo.FormInfoFilter](js-apis-app-form-formInfo.md#forminfofilter) | No| Filter criterion.| + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Promise used to return the information obtained.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +import formInfo from '@ohos.application.formInfo'; +const filter : formInfo.FormInfoFilter = { + // get info of forms belong to module entry. + moduleName : "entry" +}; +try { + formProvider.getFormsInfo(filter).then((data) => { + console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); + }).catch((error) => { + console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); + }); +} catch (error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## requestPublishForm + +requestPublishForm(want: Want, formBindingData: formBindingData.FormBindingData, callback: AsyncCallback\): void + +Requests to publish a widget carrying data to the widget host. This API uses an asynchronous callback to return the result. This API is usually called by the home screen. + +**System capability**: SystemCapability.Ability.Form + +**System API**: This is a system API. + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ---------------------------------------------------------------------- | ---- | ---------------- | +| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | +| formBindingData.FormBindingData | [FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | Yes | Data used for creating the widget.| +| callback | AsyncCallback<string> | Yes| Callback used to return the widget ID.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +import formBindingData from '@ohos.application.formBindingData'; +var want = { + abilityName: "FormAbility", + parameters: { + "ohos.extra.param.key.form_dimension": 2, + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.module_name": "entry" + } +}; +try { + let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); + formProvider.requestPublishForm(want, obj, (error, data) => { + if (error) { + console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); + } else { + console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); + } + }); +} catch (error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## requestPublishForm + +requestPublishForm(want: Want, callback: AsyncCallback<string>): void + +Requests to publish a widget to the widget host. This API uses an asynchronous callback to return the result. This API is usually called by the home screen. + +**System capability**: SystemCapability.Ability.Form + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | ------------------------------------------------------------ | +| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | +| callback | AsyncCallback<string> | Yes | Callback used to return the widget ID.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +var want = { + abilityName: "FormAbility", + parameters: { + "ohos.extra.param.key.form_dimension": 2, + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.module_name": "entry" + } +}; +try { + formProvider.requestPublishForm(want, (error, data) => { + if (error) { + console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); + } else { + console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); + } + }); +} catch (error) { + console.log(`catch err->${JSON.stringify(error)}`); +} + +``` + +## requestPublishForm + +requestPublishForm(want: Want, formBindingData?: formBindingData.FormBindingData): Promise<string> + +Requests to publish a widget to the widget host. This API uses a promise to return the result. This API is usually called by the home screen. + +**System capability**: SystemCapability.Ability.Form + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | +| formBindingData.FormBindingData | [FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | No | Data used for creating the widget. | + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<string> | Promise used to return the widget ID.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | If the input parameter is not valid parameter. | +For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). + +**Example** + +```ts +var want = { + abilityName: "FormAbility", + parameters: { + "ohos.extra.param.key.form_dimension": 2, + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.module_name": "entry" + } +}; +try { + formProvider.requestPublishForm(want).then((data) => { + console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data)); + }).catch((error) => { + console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); + }); +} catch (error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## isRequestPublishFormSupported + +isRequestPublishFormSupported(callback: AsyncCallback<boolean>): void + +Checks whether a widget can be published to the widget host. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return whether the widget can be published to the widget host.| + +**Example** + +```ts +try { + formProvider.isRequestPublishFormSupported((error, isSupported) => { + if (error) { + console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error)); + } else { + if (isSupported) { + var want = { + abilityName: "FormAbility", + parameters: { + "ohos.extra.param.key.form_dimension": 2, + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.module_name": "entry" + } + }; + try { + formProvider.requestPublishForm(want, (error, data) => { + if (error) { + console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); + } else { + console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); + } + }); + } catch (error) { + console.log(`catch err->${JSON.stringify(error)}`); + } + + } + } +}); +} catch (error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + +## isRequestPublishFormSupported + +isRequestPublishFormSupported(): Promise<boolean> + +Checks whether a widget can be published to the widget host. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Ability.Form + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<boolean> | Promise used to return whether the widget can be published to the widget host.| + +**Example** + +```ts +try { + formProvider.isRequestPublishFormSupported().then((isSupported) => { + if (isSupported) { + var want = { + abilityName: "FormAbility", + parameters: { + "ohos.extra.param.key.form_dimension": 2, + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.module_name": "entry" + } + }; + try { + formProvider.requestPublishForm(want).then((data) => { + console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data)); + }).catch((error) => { + console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); + }); + } catch (error) { + console.log(`catch err->${JSON.stringify(error)}`); + } + + } + }).catch((error) => { + console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error)); + }); +} catch (error) { + console.log(`catch err->${JSON.stringify(error)}`); +} +``` + + \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-appAccount.md b/en/application-dev/reference/apis/js-apis-appAccount.md index 5814fad2cff1b347469cc49c6a51196e9beb1e80..0d2aef3e25aa21eb724c8f74f977d901ea12b290 100644 --- a/en/application-dev/reference/apis/js-apis-appAccount.md +++ b/en/application-dev/reference/apis/js-apis-appAccount.md @@ -1,4 +1,4 @@ -# App Account Management +# @ohos.account.appAccount The **appAccount** module provides APIs for adding, deleting, modifying, and querying app account information, and supports inter-app authentication and distributed data synchronization. @@ -3173,7 +3173,7 @@ Set credentials for an app account. This API uses an asynchronous callback to re | Name | Type | Mandatory | Description | | -------------- | ------------------------- | ---- | ------------- | | name | string | Yes | Name of the target app account. | -| credentialType | string | Yes | Type of the credential to delete. | +| credentialType | string | Yes | Type of the credential to set. | | credential | string | Yes | Credential value. | | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| @@ -3203,7 +3203,7 @@ Set credentials for an app account. This API uses a promise to return the result | Name | Type | Mandatory | Description | | -------------- | ------ | ---- | ---------- | | name | string | Yes | Name of the target app account. | -| credentialType | string | Yes | Type of the credential to delete.| +| credentialType | string | Yes | Type of the credential to set.| | credential | string | Yes | Credential value.| **Return value** @@ -3576,7 +3576,7 @@ Obtains the credential of an app account. This API uses an asynchronous callback | Name | Type | Mandatory | Description | | -------------- | --------------------------- | ---- | -------------- | | name | string | Yes | Name of the target app account. | -| credentialType | string | Yes | Type of the credential to delete.| +| credentialType | string | Yes | Type of the credential to obtain.| | callback | AsyncCallback<string> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the credential obtained. Otherwise, **err** is an error object.| **Example** @@ -3606,7 +3606,7 @@ Obtains the credential of an app account. This API uses a promise to return the | Name | Type | Mandatory | Description | | -------------- | ------ | ---- | ---------- | | name | string | Yes | Name of the target app account. | -| credentialType | string | Yes | Type of the credential to delete.| +| credentialType | string | Yes | Type of the credential to obtain.| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-application-ability.md b/en/application-dev/reference/apis/js-apis-application-ability.md index 7ba7d62c053ea5eb7f03e6264f959c5770e196ee..8c1c83988c352d24ac4bc7d64b61d53f3378156a 100644 --- a/en/application-dev/reference/apis/js-apis-application-ability.md +++ b/en/application-dev/reference/apis/js-apis-application-ability.md @@ -1,4 +1,4 @@ -# Ability +# @ohos.application.Ability The **Ability** module manages the ability lifecycle and context, such as creating and destroying an ability, and dumping client information. @@ -14,7 +14,7 @@ This module provides the following common ability-related functions: ## Modules to Import -``` +```ts import Ability from '@ohos.application.Ability'; ``` @@ -24,9 +24,9 @@ import Ability from '@ohos.application.Ability'; | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| context | [AbilityContext](js-apis-ability-context.md) | Yes| No| Context of an ability.| -| launchWant | [Want](js-apis-application-Want.md) | Yes| No| Parameters for starting the ability.| -| lastRequestWant | [Want](js-apis-application-Want.md) | Yes| No| Parameters used when the ability was started last time.| +| context | [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) | Yes| No| Context of an ability.| +| launchWant | [Want](js-apis-app-ability-want.md) | Yes| No| Parameters for starting the ability.| +| lastRequestWant | [Want](js-apis-app-ability-want.md) | Yes| No| Parameters used when the ability was started last time.| | callee | [Callee](#callee) | Yes| No| Object that invokes the stub service.| ## Ability.onCreate @@ -41,7 +41,7 @@ Called to initialize the service logic when an ability is created. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | Yes| Information related to this ability, including the ability name and bundle name.| + | want | [Want](js-apis-app-ability-want.md) | Yes| Information related to this ability, including the ability name and bundle name.| | param | AbilityConstant.LaunchParam | Yes| Parameters for starting the ability, and the reason for the last abnormal exit.| **Example** @@ -227,7 +227,7 @@ Called when the ability startup mode is set to singleton. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | Yes| Want parameters, such as the ability name and bundle name.| + | want | [Want](js-apis-application-want.md) | Yes| Want parameters, such as the ability name and bundle name.| | launchParams | AbilityConstant.LaunchParam | Yes| Reason for the ability startup and the last abnormal exit.| **Example** @@ -240,27 +240,26 @@ Called when the ability startup mode is set to singleton. } ``` - ## Ability.onConfigurationUpdated onConfigurationUpdated(config: Configuration): void; -Called when the configuration of the environment where the ability is running is updated. +Called when the global configuration is updated. -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore +**System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | config | [Configuration](js-apis-configuration.md) | Yes| New configuration.| + | config | [Configuration](js-apis-application-configuration.md) | Yes| Callback invoked when the global configuration is updated. The global configuration indicates the configuration of the environment where the application is running and includes the language and color mode.| **Example** ```ts class myAbility extends Ability { onConfigurationUpdated(config) { - console.log('onConfigurationUpdated, config:' + JSON.stringify(config)); + console.log('onConfigurationUpdated, language:' + config.language); } } ``` @@ -314,12 +313,11 @@ Called when the system has decided to adjust the memory level. For example, this } ``` - ## Ability.onSaveState onSaveState(reason: AbilityConstant.StateType, wantParam : {[key: string]: any}): AbilityConstant.OnSaveResult; -Called when the framework saves the ability state in the case of an application fault if automatic saving is enabled. This API is used together with [appRecovery](js-apis-app-ability-appRecovery.md). +Called when the framework automatically saves the ability state in the case of an application fault. This API is used together with [appRecovery](js-apis-app-ability-appRecovery.md). **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore @@ -338,7 +336,7 @@ Called when the framework saves the ability state in the case of an application **Example** - ```js + ```ts import AbilityConstant from '@ohos.application.AbilityConstant' class myAbility extends Ability { @@ -390,7 +388,7 @@ Sends sequenceable data to the target ability. **Example** ```ts - import Ability from '@ohos.app.ability.UIAbility'; + import Ability from '@ohos.application.Ability'; class MyMessageAble{ // Custom sequenceable data structure name:"" str:"" @@ -474,7 +472,7 @@ Sends sequenceable data to the target ability and obtains the sequenceable data **Example** ```ts - import Ability from '@ohos.app.ability.UIAbility'; + import Ability from '@ohos.application.Ability'; class MyMessageAble{ name:"" str:"" @@ -546,7 +544,7 @@ Releases the caller interface of the target ability. **Example** ```ts - import Ability from '@ohos.app.ability.UIAbility'; + import Ability from '@ohos.application.Ability'; var caller; export default class MainAbility extends Ability { onWindowStageCreate(windowStage) { @@ -570,10 +568,9 @@ Releases the caller interface of the target ability. } ``` +## Caller.onRelease -## Caller.on - - on(type: "release", callback: OnReleaseCallback): void; + onRelease(callback: OnReleaseCallBack): void; Registers a callback that is invoked when the stub on the target ability is disconnected. @@ -583,21 +580,12 @@ Registers a callback that is invoked when the stub on the target ability is disc | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is fixed at **release**.| | callback | OnReleaseCallBack | Yes| Callback used for the **onRelease** API.| -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | - **Example** ```ts - import Ability from '@ohos.app.ability.UIAbility'; + import Ability from '@ohos.application.Ability'; var caller; export default class MainAbility extends Ability { onWindowStageCreate(windowStage) { @@ -608,7 +596,7 @@ Registers a callback that is invoked when the stub on the target ability is disc }).then((obj) => { caller = obj; try { - caller.on("release", (str) => { + caller.onRelease((str) => { console.log(' Caller OnRelease CallBack is called ' + str); }); } catch (error) { @@ -654,7 +642,7 @@ Registers a caller notification callback, which is invoked when the target abili **Example** ```ts - import Ability from '@ohos.app.ability.UIAbility'; + import Ability from '@ohos.application.Ability'; class MyMessageAble{ name:"" str:"" @@ -679,9 +667,9 @@ Registers a caller notification callback, which is invoked when the target abili var method = 'call_Function'; function funcCallBack(pdata) { console.log('Callee funcCallBack is called ' + pdata); - let msg = new MyMessageAble(0, ""); + let msg = new MyMessageAble("test", ""); pdata.readSequenceable(msg); - return new MyMessageAble(10, "Callee test"); + return new MyMessageAble("test1", "Callee test"); } export default class MainAbility extends Ability { onCreate(want, launchParam) { @@ -722,7 +710,7 @@ Deregisters a caller notification callback, which is invoked when the target abi **Example** ```ts - import Ability from '@ohos.app.ability.UIAbility'; + import Ability from '@ohos.application.Ability'; var method = 'call_Function'; export default class MainAbility extends Ability { onCreate(want, launchParam) { @@ -736,8 +724,8 @@ Deregisters a caller notification callback, which is invoked when the target abi } } ``` - -## OnReleaseCallback + +## OnReleaseCallBack (msg: string): void; @@ -747,7 +735,7 @@ Deregisters a caller notification callback, which is invoked when the target abi | -------- | -------- | -------- | -------- | -------- | | (msg: string) | function | Yes| No| Prototype of the listener function registered by the caller.| -## CalleeCallback +## CalleeCallBack (indata: rpc.MessageParcel): rpc.Sequenceable; @@ -756,5 +744,3 @@ Deregisters a caller notification callback, which is invoked when the target abi | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | (indata: rpc.MessageParcel) | rpc.Sequenceable | Yes| No| Prototype of the listener function registered by the callee.| - - \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-application-abilityConstant.md b/en/application-dev/reference/apis/js-apis-application-abilityConstant.md index 50e65757431e7df6b9bc784c6169da902a04bf5d..c97e344590f1bdd6b0d0242c1b61003053908e37 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityConstant.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityConstant.md @@ -1,4 +1,4 @@ -# AbilityConstant +# @ohos.application.AbilityConstant The **AbilityConstant** module provides ability launch parameters. @@ -6,12 +6,12 @@ The parameters include the initial launch reasons, reasons for the last exit, an > **NOTE** > -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported and deprecated since API version 9. You are advised to use [@ohos.app.ability.AbilityConstant](js-apis-app-ability-abilityConstant.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. ## Modules to Import -```js +```ts import AbilityConstant from '@ohos.application.AbilityConstant'; ``` @@ -19,10 +19,10 @@ import AbilityConstant from '@ohos.application.AbilityConstant'; **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| launchReason | LaunchReason| Yes| Yes| Ability launch reason.| -| lastExitReason | LastExitReason | Yes| Yes| Reason for the last exit.| +| launchReason | LaunchReason| Yes| Yes| Ability launch reason.| +| lastExitReason | LastExitReason | Yes| Yes| Reason for the last exit.| ## AbilityConstant.LaunchReason @@ -36,6 +36,7 @@ Enumerates ability launch reasons. | START_ABILITY | 1 | Ability startup.| | CALL | 2 | Call.| | CONTINUATION | 3 | Ability continuation.| +| APP_RECOVERY | 4 | Application recovery.| ## AbilityConstant.LastExitReason @@ -88,3 +89,29 @@ Enumerates the memory levels. | MEMORY_LEVEL_MODERATE | 0 | Moderate memory usage. | | MEMORY_LEVEL_LOW | 1 | Low memory usage. | | MEMORY_LEVEL_CRITICAL | 2 | High memory usage. | + +## AbilityConstant.OnSaveResult + +Enumerates the result types for the operation of saving application data. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ----------------------------- | ---- | ------------------------------------------------------------ | +| ALL_AGREE | 0 | Agreed to save the status.| +| CONTINUATION_REJECT | 1 | Rejected to save the status in continuation.| +| CONTINUATION_MISMATCH | 2 | Continuation mismatch.| +| RECOVERY_AGREE | 3 | Agreed to restore the saved status.| +| RECOVERY_REJECT | 4 | Rejected to restore the saved state.| +| ALL_REJECT | 5 | Rejected to save the status.| + +## AbilityConstant.StateType + +Enumerates the scenarios for saving application data. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ----------------------------- | ---- | ------------------------------------------------------------ | +| CONTINUATION | 0 | Saving the status in continuation.| +| APP_RECOVERY | 1 | Saving the status in application recovery.| diff --git a/en/application-dev/reference/apis/js-apis-abilityDelegatorRegistry.md b/en/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md similarity index 81% rename from en/application-dev/reference/apis/js-apis-abilityDelegatorRegistry.md rename to en/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md index d30dce2a75e700019c9f44ce1c918a9574f3cea7..c58eae8878a6df52715e9b4ec06738aeef34bf01 100644 --- a/en/application-dev/reference/apis/js-apis-abilityDelegatorRegistry.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md @@ -1,4 +1,4 @@ -# AbilityDelegatorRegistry +# @ohos.application.abilityDelegatorRegistry The **AbilityDelegatorRegistry** module provides APIs for storing the global registers of the registered **AbilityDelegator** and **AbilityDelegatorArgs** objects. You can use the APIs to obtain the **AbilityDelegator** and **AbilityDelegatorArgs** objects of an application. @@ -8,7 +8,7 @@ The **AbilityDelegatorRegistry** module provides APIs for storing the global reg ## Modules to Import -```js +```ts import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' ``` @@ -38,18 +38,16 @@ Obtains the **AbilityDelegator** object of the application. | Type | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| [AbilityDelegator](js-apis-application-abilityDelegator.md#AbilityDelegator) | [AbilityDelegator](js-apis-application-abilityDelegator.md#AbilityDelegator) object, which can be used to schedule functions related to the test framework.| +| [AbilityDelegator](js-apis-inner-application-abilityDelegator.md#AbilityDelegator) | [AbilityDelegator](js-apis-inner-application-abilityDelegator.md#AbilityDelegator) object, which can be used to schedule functions related to the test framework.| **Example** -```js +```ts var abilityDelegator; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); ``` - - ## AbilityDelegatorRegistry.getArguments getArguments(): AbilityDelegatorArgs @@ -62,11 +60,11 @@ Obtains the **AbilityDelegatorArgs** object of the application. | Type | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| [AbilityDelegatorArgs](js-apis-application-abilityDelegatorArgs.md#AbilityDelegatorArgs) | [AbilityDelegatorArgs](js-apis-application-abilityDelegatorArgs.md#AbilityDelegatorArgs) object, which can be used to obtain test parameters.| +| [AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md#AbilityDelegatorArgs) | [AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md#AbilityDelegatorArgs) object, which can be used to obtain test parameters.| **Example** -```js +```ts var args = AbilityDelegatorRegistry.getArguments(); console.info("getArguments bundleName:" + args.bundleName); console.info("getArguments testCaseNames:" + args.testCaseNames); diff --git a/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md b/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md index 54264312fcc88ad0177473a7e4d256f566e6c2d2..cd4a4db73667651bae07a865d0a088321cda0ce6 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md @@ -1,16 +1,16 @@ -# AbilityLifecycleCallback +# @ohos.application.AbilityLifecycleCallback The **AbilityLifecycleCallback** module provides callbacks, such as **onAbilityCreate**, **onWindowStageCreate**, and **onWindowStageDestroy**, to receive lifecycle state changes in the application context. > **NOTE** > -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported and deprecated since API version 9. You are advised to use [@ohos.app.ability.AbilityLifecycleCallback](js-apis-app-ability-abilityLifecycleCallback.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. ## Modules to Import -```js +```ts import AbilityLifecycleCallback from "@ohos.application.AbilityLifecycleCallback"; ``` @@ -43,7 +43,7 @@ Called when the window stage of an ability is created. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| - | windowStage | [WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| + | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| ## AbilityLifecycleCallback.onWindowStageActive @@ -59,7 +59,7 @@ Called when the window stage of an ability gains focus. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| - | windowStage | [WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| + | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| ## AbilityLifecycleCallback.onWindowStageInactive @@ -75,7 +75,7 @@ Called when the window stage of an ability loses focus. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| - | windowStage | [WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| + | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| ## AbilityLifecycleCallback.onWindowStageDestroy @@ -91,7 +91,7 @@ Called when the window stage of an ability is destroyed. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| - | windowStage | [WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| + | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| ## AbilityLifecycleCallback.onAbilityDestroy @@ -156,16 +156,18 @@ Called when an ability is continued on another device. **Example** - ```js - import AbilityStage from "@ohos.application.AbilityStage"; - - export default class MyAbilityStage extends AbilityStage { - onCreate() { - console.log("MyAbilityStage onCreate") - let AbilityLifecycleCallback = { - onAbilityCreate(ability){ - console.log("AbilityLifecycleCallback onAbilityCreate ability:" + JSON.stringify(ability)); - }, +```ts +import AbilityStage from "@ohos.application.AbilityStage"; + +var lifecycleid; + +export default class MyAbilityStage extends AbilityStage { + onCreate() { + console.log("MyAbilityStage onCreate") + let AbilityLifecycleCallback = { + onAbilityCreate(ability){ + console.log("AbilityLifecycleCallback onAbilityCreate ability:" + JSON.stringify(ability)); + }, onWindowStageCreate(ability, windowStage){ console.log("AbilityLifecycleCallback onWindowStageCreate ability:" + JSON.stringify(ability)); console.log("AbilityLifecycleCallback onWindowStageCreate windowStage:" + JSON.stringify(windowStage)); @@ -182,24 +184,30 @@ Called when an ability is continued on another device. console.log("AbilityLifecycleCallback onWindowStageDestroy ability:" + JSON.stringify(ability)); console.log("AbilityLifecycleCallback onWindowStageDestroy windowStage:" + JSON.stringify(windowStage)); }, - onAbilityDestroy(ability){ - console.log("AbilityLifecycleCallback onAbilityDestroy ability:" + JSON.stringify(ability)); - }, - onAbilityForeground(ability){ - console.log("AbilityLifecycleCallback onAbilityForeground ability:" + JSON.stringify(ability)); - }, - onAbilityBackground(ability){ - console.log("AbilityLifecycleCallback onAbilityBackground ability:" + JSON.stringify(ability)); - }, - onAbilityContinue(ability){ - console.log("AbilityLifecycleCallback onAbilityContinue ability:" + JSON.stringify(ability)); - } - } - // 1. Obtain applicationContext through the context attribute. - let applicationContext = this.context.getApplicationContext(); - // 2. Use applicationContext to register a listener for the ability lifecycle in the application. - let lifecycleid = applicationContext.registerAbilityLifecycleCallback(AbilityLifecycleCallback); - console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleid)); - } - } - ``` + onAbilityDestroy(ability){ + console.log("AbilityLifecycleCallback onAbilityDestroy ability:" + JSON.stringify(ability)); + }, + onAbilityForeground(ability){ + console.log("AbilityLifecycleCallback onAbilityForeground ability:" + JSON.stringify(ability)); + }, + onAbilityBackground(ability){ + console.log("AbilityLifecycleCallback onAbilityBackground ability:" + JSON.stringify(ability)); + }, + onAbilityContinue(ability){ + console.log("AbilityLifecycleCallback onAbilityContinue ability:" + JSON.stringify(ability)); + } + } + // 1. Obtain applicationContext through the context attribute. + let applicationContext = this.context.getApplicationContext(); + // 2. Use applicationContext to register a listener for the ability lifecycle in the application. + lifecycleid = applicationContext.registerAbilityLifecycleCallback(AbilityLifecycleCallback); + console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleid)); + } + onDestroy() { + let applicationContext = this.context.getApplicationContext(); + applicationContext.unregisterAbilityLifecycleCallback(lifecycleid, (error, data) => { + console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error)); + }); + } +} +``` diff --git a/en/application-dev/reference/apis/js-apis-application-abilityManager.md b/en/application-dev/reference/apis/js-apis-application-abilityManager.md index e1bf96bae511de4e1fb83d92df6ee05bdddbf990..cf7f8da5870889e80853b396a433932afc895679 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityManager.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityManager.md @@ -1,4 +1,4 @@ -# AbilityManager +# @ohos.application.abilityManager The **AbilityManager** module provides APIs for obtaining, adding, and modifying ability running information and state information. @@ -9,7 +9,7 @@ The **AbilityManager** module provides APIs for obtaining, adding, and modifying ## Modules to Import -```js +```ts import AbilityManager from '@ohos.application.abilityManager' ``` @@ -43,12 +43,12 @@ Updates the configuration. This API uses an asynchronous callback to return the | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------------- | -| config | Configuration | Yes | New configuration.| +| config | [Configuration](js-apis-application-configuration.md) | Yes | New configuration.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** -```js +```ts import abilitymanager from '@ohos.application.abilityManager'; var config = { @@ -74,7 +74,7 @@ Updates the configuration. This API uses a promise to return the result. | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------------- | -| config | Configuration | Yes | New configuration.| +| config | [Configuration](js-apis-application-configuration.md) | Yes | New configuration.| **Return value** @@ -84,7 +84,7 @@ Updates the configuration. This API uses a promise to return the result. **Example** -```js +```ts import abilitymanager from '@ohos.application.abilityManager'; var config = { @@ -116,7 +116,7 @@ Obtains the ability running information. This API uses an asynchronous callback **Example** -```js +```ts import abilitymanager from '@ohos.application.abilityManager'; abilitymanager.getAbilityRunningInfos((err,data) => { @@ -142,7 +142,7 @@ Obtains the ability running information. This API uses a promise to return the r **Example** -```js +```ts import abilitymanager from '@ohos.application.abilityManager'; abilitymanager.getAbilityRunningInfos().then((data) => { @@ -171,7 +171,7 @@ Obtains the extension running information. This API uses an asynchronous callbac **Example** -```js +```ts import abilitymanager from '@ohos.application.abilityManager'; var upperLimit = 0; @@ -205,7 +205,7 @@ Obtains the extension running information. This API uses a promise to return the **Example** -```js +```ts import abilitymanager from '@ohos.application.abilityManager'; var upperLimit = 0; @@ -233,7 +233,7 @@ Obtains the top ability, which is the ability that has the window focus. This AP **Example** -```js +```ts import abilitymanager from '@ohos.application.abilityManager'; abilitymanager.getTopAbility((err,data) => { @@ -257,7 +257,7 @@ Obtains the top ability, which is the ability that has the window focus. This AP **Example** -```js +```ts import abilitymanager from '@ohos.application.abilityManager'; abilitymanager.getTopAbility().then((data) => { diff --git a/en/application-dev/reference/apis/js-apis-application-abilityMonitor.md b/en/application-dev/reference/apis/js-apis-application-abilityMonitor.md deleted file mode 100644 index 33feda3afdd757e91ed7b7f682dca1ef597a7847..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-application-abilityMonitor.md +++ /dev/null @@ -1,47 +0,0 @@ -# AbilityMonitor - -The **AbilityMonitor** module provides monitors for abilities that meet specified conditions. The latest matched abilities are stored in an **AbilityMonitor** object. - -> **NOTE** -> -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. - -## Usage - -The ability monitor is set by calling **addAbilityMonitor** in **abilityDelegator**. - -```js -import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' -var abilityDelegator; - -function onAbilityCreateCallback(data) { - console.info("onAbilityCreateCallback"); -} - -var monitor = { - abilityName: "abilityname", - onAbilityCreate: onAbilityCreateCallback -} - -abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); -abilityDelegator.addAbilityMonitor(monitor, (err : any) => { - console.info("addAbilityMonitor callback"); -}); -``` - -## AbilityMonitor - -Describes an ability monitor. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name | Type | Readable| Writable| Description | -| ------------------------------------------------------------ | -------- | ---- | ---- | ------------------------------------------------------------ | -| abilityName | string | Yes | Yes | Name of the ability bound to the ability monitor. | -| onAbilityCreate?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | Yes | Yes | Called when the ability is created.
If this attribute is not set, the corresponding lifecycle callback cannot be received. | -| onAbilityForeground?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | Yes | Yes | Called when the ability starts to run in the foreground.
If this attribute is not set, the corresponding lifecycle callback cannot be received. | -| onAbilityBackground?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | Yes | Yes | Called when the ability starts to run in the background.
If this attribute is not set, the corresponding lifecycle callback cannot be received. | -| onAbilityDestroy?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | Yes | Yes | Called when the ability is destroyed.
If this attribute is not set, the corresponding lifecycle callback cannot be received. | -| onWindowStageCreate?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | Yes | Yes | Called when the window stage is created.
If this attribute is not set, the corresponding lifecycle callback cannot be received. | -| onWindowStageRestore?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | Yes | Yes | Called when the window stage is restored.
If this attribute is not set, the corresponding lifecycle callback cannot be received. | -| onWindowStageDestroy?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | Yes | Yes | Called when the window stage is destroyed.
If this attribute is not set, the corresponding lifecycle callback cannot be received. | diff --git a/en/application-dev/reference/apis/js-apis-application-abilitystage.md b/en/application-dev/reference/apis/js-apis-application-abilityStage.md similarity index 80% rename from en/application-dev/reference/apis/js-apis-application-abilitystage.md rename to en/application-dev/reference/apis/js-apis-application-abilityStage.md index d1c8592f97d4c8b8799d5773b391bb1798663219..45227a89b2a6ed8d01997b8c699f8fc8c320b955 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilitystage.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityStage.md @@ -1,4 +1,4 @@ -# AbilityStage +# @ohos.application.AbilityStage **AbilityStage** is a runtime class for HAP files. @@ -6,12 +6,12 @@ The **AbilityStage** module notifies you of when you can perform HAP initializat > **NOTE** > -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported and deprecated since API version 9. You are advised to use [@ohos.app.ability.AbilityStage](js-apis-app-ability-abilityStage.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. ## Modules to Import -```js +```ts import AbilityStage from '@ohos.application.AbilityStage'; ``` @@ -25,7 +25,7 @@ Called when the application is created. **Example** - ```js + ```ts class MyAbilityStage extends AbilityStage { onCreate() { console.log("MyAbilityStage.onCreate is called") @@ -46,7 +46,7 @@ Called when a specified ability is started. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | Yes| Information about the ability to start, such as the ability name and bundle name.| + | want | [Want](js-apis-application-want.md) | Yes| Information about the ability to start, such as the ability name and bundle name.| **Return value** @@ -56,7 +56,7 @@ Called when a specified ability is started. **Example** - ```js + ```ts class MyAbilityStage extends AbilityStage { onAcceptWant(want) { console.log("MyAbilityStage.onAcceptWant called"); @@ -78,11 +78,11 @@ Called when the global configuration is updated. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | config | [Configuration](js-apis-configuration.md) | Yes| Callback invoked when the global configuration is updated. The global configuration indicates the configuration of the environment where the application is running and includes the language and color mode.| + | config | [Configuration](js-apis-application-configuration.md) | Yes| Callback invoked when the global configuration is updated. The global configuration indicates the configuration of the environment where the application is running and includes the language and color mode.| **Example** - ```js + ```ts class MyAbilityStage extends AbilityStage { onConfigurationUpdated(config) { console.log('onConfigurationUpdated, language:' + config.language); @@ -106,7 +106,7 @@ Called when the system has decided to adjust the memory level. For example, this **Example** - ```js + ```ts class MyAbilityStage extends AbilityStage { onMemoryLevel(level) { console.log('onMemoryLevel, level:' + JSON.stringify(level)); @@ -124,4 +124,4 @@ Describes the configuration information about the context. | Name | Type | Description | | ----------- | --------------------------- | ------------------------------------------------------------ | -| context | [AbilityStageContext](js-apis-abilitystagecontext.md) | Called when initialization is performed during ability startup.| +| context | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | Called when initialization is performed during ability startup.| diff --git a/en/application-dev/reference/apis/js-apis-application-accessibilityExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-accessibilityExtensionAbility.md index a78f8cc320a4d081f356145d8ed4c51907a025ba..a47e3e8908f69f5515beab95cea6f74351719a77 100644 --- a/en/application-dev/reference/apis/js-apis-application-accessibilityExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-accessibilityExtensionAbility.md @@ -1,12 +1,10 @@ -# Accessibility Extension Ability +# @ohos.application.AccessibilityExtensionAbility -The **AccessibilityExtensionAbility** module is based on the ExtensionAbility framework and provides the **AccessibilityExtensionAbility**. +The **AccessibilityExtensionAbility** module provides accessibility extension capabilities based on the ExtensionAbility framework. ->**NOTE** +> **NOTE** > ->The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> ->The APIs of this module can be used only in the stage model. +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -18,9 +16,9 @@ import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtens **System capability**: SystemCapability.BarrierFree.Accessibility.Core -| Name | Type | Readable | Writable | Description | +| Name | Type| Readable| Writable| Description | | --------- | -------- | ---- | ---- | ------------------------- | -| context | [AccessibilityExtensionContext](js-apis-accessibility-extension-context.md) | Yes | No | Context of the accessibility extension ability. | +| context | [AccessibilityExtensionContext](js-apis-inner-application-accessibilityExtensionContext.md) | Yes| No| Context of the accessibility extension ability.| ## AccessibilityEvent @@ -32,36 +30,10 @@ Defines an accessibility event. | Name | Type | Readable | Writable | Description | | --------- | ---------------------------------------- | ---- | ---- | ---------- | -| eventType | [EventType](js-apis-accessibility.md#eventtype) \| [WindowUpdateType](js-apis-accessibility.md#windowupdatetype) \| [TouchGuideType](#touchguidetype) \| [GestureType](#gesturetype) \| [PageUpdateType](#pageupdatetype) | Yes | No | Event type. | +| eventType | [accessibility.EventType](js-apis-accessibility.md#EventType) \| [accessibility.WindowUpdateType](js-apis-accessibility.md#WindowUpdateType) \| [TouchGuideType](#touchguidetype) \| [GestureType](#gesturetype) \| [PageUpdateType](#pageupdatetype) | Yes | No | Event type. | | target | AccessibilityElement | Yes | No | Target component where the event occurs.| | timeStamp | number | Yes | No | Timestamp of the event. | -## GesturePath - -Defines a gesture path. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -### Attributes - -| Name | Type | Readable | Writable | Description | -| ------------ | ---------------------------------------- | ---- | ---- | ------ | -| points | Array<[GesturePoint](gesturepoint)> | Yes | Yes | An array of gesture touch points. | -| durationTime | number | Yes | Yes | Total time consumed by the gesture.| - -## GesturePoint - -Defines a gesture touch point. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -### Attributes - -| Name | Type | Readable | Writable | Description | -| --------- | ------ | ---- | ---- | ------- | -| positionX | number | Yes | Yes | X-coordinate of the touch point.| -| positionY | number | Yes | Yes | Y-coordinate of the touch point.| - ## GestureType Enumerates gesture types. @@ -89,7 +61,7 @@ Enumerates gesture types. ## PageUpdateType -Enumerates the page refresh types. +Enumerates the page update types. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -106,27 +78,25 @@ Enumerates the touch guide event types. | Name | Description | | ---------- | ------------ | -| touchBegin | A touch starts in touch guide mode.| -| touchEnd | A touch ends in touch guide mode.| +| touchBegin | Start of touch in touch guide mode. | +| touchEnd | End of touch in touch guide mode. | ## AccessibilityExtensionAbility.onConnect onConnect(): void; -Called when the **AccessibilityExtensionAbility** is enabled and connected to the system service. In this API, you can initialize service logic. This API can be overridden as required. +Called when the **AccessibilityExtensionAbility** is enabled and connected to the system service. In this API, you can have the service logic initialized. This API can be overridden as required. **System capability**: SystemCapability.BarrierFree.Accessibility.Core -**Parameters** - -None - **Example** ```ts -onConnect(): void { - console.log("AxExtensionAbility onConnect"); -} +class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility { + onConnect() { + console.log('AxExtensionAbility onConnect'); + } +}; ``` ## AccessibilityExtensionAbility.onDisconnect @@ -137,16 +107,14 @@ Called when the **AccessibilityExtensionAbility** is disabled and disconnected f **System capability**: SystemCapability.BarrierFree.Accessibility.Core -**Parameters** - -None - **Example** ```ts -onDisconnect(): void { - console.log("AxExtensionAbility onDisconnect"); -} +class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility { + onDisconnect() { + console.log('AxExtensionAbility onDisconnect'); + } +}; ``` ## AccessibilityExtensionAbility.onAccessibilityEvent @@ -166,19 +134,21 @@ Called when an event that matches the specified bundle and event type occurs. In **Example** ```ts -onAccessibilityEvent(event: AccessibilityEvent): void { - console.log("AxExtensionAbility onAccessibilityEvent"); - if (event.eventType == 'click') { - console.log("AxExtensionAbility onAccessibilityEvent: click"); +class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility { + onAccessibilityEvent(event) { + console.log('AxExtensionAbility onAccessibilityEvent'); + if (event.eventType == 'click') { + console.log('AxExtensionAbility onAccessibilityEvent: click'); + } } -} +}; ``` ## AccessibilityExtensionAbility.onKeyEvent -onKeyEvent(keyEvent: inputEventClient.KeyEvent): boolean; +onKeyEvent(keyEvent: KeyEvent): boolean; -Called when a physical key is pressed. In this API, you can determine whether to intercept the key event based on the service. +Called when a physical key is pressed. In this API, you can determine whether to intercept an event based on the service. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -191,12 +161,14 @@ Called when a physical key is pressed. In this API, you can determine whether to **Example** ```ts -onKeyEvent(keyEvent: inputEventClient.KeyEvent): boolean { - console.log("AxExtensionAbility onKeyEvent"); - if (keyEvent.keyCode == 22) { - console.log("AxExtensionAbility onKeyEvent: intercept 22"); - return true; +class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility { + onKeyEvent(keyEvent) { + console.log('AxExtensionAbility onKeyEvent'); + if (keyEvent.keyCode == 22) { + console.log('AxExtensionAbility onKeyEvent: intercept 22'); + return true; + } + return false; } - return false; -} +}; ``` diff --git a/en/application-dev/reference/apis/js-apis-application-appManager.md b/en/application-dev/reference/apis/js-apis-application-appManager.md new file mode 100644 index 0000000000000000000000000000000000000000..a3f97be529cfef048393d37907a257fddf10b0bf --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-application-appManager.md @@ -0,0 +1,715 @@ +# @ohos.application.appManager + +The **appManager** module implements application management. You can use the APIs of this module to query whether the application is undergoing a stability test, whether the application is running on a RAM constrained device, the memory size of the application, and information about the running process. + +> **NOTE** +> +> The APIs of this module are supported since API version 7 and deprecated since API version 9. You are advised to use [@ohos.app.ability.appManager](js-apis-app-ability-appManager.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```ts +import app from '@ohos.application.appManager'; +``` + +## appManager.isRunningInStabilityTest8+ + +static isRunningInStabilityTest(callback: AsyncCallback<boolean>): void + +Checks whether this application is undergoing a stability test. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<boolean> | Yes| Callback used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| + +**Example** + + ```ts + import app from '@ohos.application.appManager'; + app.isRunningInStabilityTest((err, flag) => { + console.log('startAbility result:' + JSON.stringify(err)); + }) + ``` + + +## appManager.isRunningInStabilityTest8+ + +static isRunningInStabilityTest(): Promise<boolean> + +Checks whether this application is undergoing a stability test. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<boolean> | Promise used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| + +**Example** + + ```ts + import app from '@ohos.application.appManager'; + app.isRunningInStabilityTest().then((flag) => { + console.log('success:' + JSON.stringify(flag)); + }).catch((error) => { + console.log('failed:' + JSON.stringify(error)); + }); + ``` + + +## appManager.isRamConstrainedDevice + +isRamConstrainedDevice(): Promise\; + +Checks whether this application is running on a RAM constrained device. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<boolean> | Promise used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| + +**Example** + + ```ts + app.isRamConstrainedDevice().then((data) => { + console.log('success:' + JSON.stringify(data)); + }).catch((error) => { + console.log('failed:' + JSON.stringify(error)); + }); + ``` + +## appManager.isRamConstrainedDevice + +isRamConstrainedDevice(callback: AsyncCallback\): void; + +Checks whether this application is running on a RAM constrained device. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<boolean> | Yes| Callback used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| + +**Example** + + ```ts + app.isRamConstrainedDevice((err, data) => { + console.log('startAbility result failed:' + JSON.stringify(err)); + console.log('startAbility result success:' + JSON.stringify(data)); + }) + ``` + +## appManager.getAppMemorySize + +getAppMemorySize(): Promise\; + +Obtains the memory size of this application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<number> | Size of the application memory.| + +**Example** + + ```ts + app.getAppMemorySize().then((data) => { + console.log('success:' + JSON.stringify(data)); + }).catch((error) => { + console.log('failed:' + JSON.stringify(error)); + }); + ``` + +## appManager.getAppMemorySize + +getAppMemorySize(callback: AsyncCallback\): void; + +Obtains the memory size of this application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<number> | Yes| Size of the application memory.| + +**Example** + + ```ts + app.getAppMemorySize((err, data) => { + console.log('startAbility result failed :' + JSON.stringify(err)); + console.log('startAbility result success:' + JSON.stringify(data)); + }) + ``` +## appManager.getProcessRunningInfos(deprecated) + +getProcessRunningInfos(): Promise\>; + +Obtains information about the running processes. This API uses a promise to return the result. + +> This API is deprecated since API version 9. You are advised to use [appManager.getProcessRunningInformation9+](#appmanagergetprocessrunninginformation9) instead. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\> | Promise used to return the process information.| + +**Example** + + ```ts + app.getProcessRunningInfos().then((data) => { + console.log('success:' + JSON.stringify(data)); + }).catch((error) => { + console.log('failed:' + JSON.stringify(error)); + }); + ``` + +## appManager.getProcessRunningInfos(deprecated) + +getProcessRunningInfos(callback: AsyncCallback\>): void; + +Obtains information about the running processes. This API uses an asynchronous callback to return the result. + +> This API is deprecated since API version 9. You are advised to use [appManager.getProcessRunningInformation9+](#appmanagergetprocessrunninginformation9-1) instead. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback\> | Yes| Obtains information about the running processes. This API uses a promise to return the result.| + +**Example** + + ```ts + app.getProcessRunningInfos((err, data) => { + console.log('startAbility result failed :' + JSON.stringify(err)); + console.log('startAbility result success:' + JSON.stringify(data)); + }) + ``` + +## appManager.getProcessRunningInformation9+ + +getProcessRunningInformation(): Promise\>; + +Obtains information about the running processes. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\> | Obtains information about the running processes. This API uses a promise to return the result.| + +**Example** + + ```ts + app.getProcessRunningInformation().then((data) => { + console.log('success:' + JSON.stringify(data)); + }).catch((error) => { + console.log('failed:' + JSON.stringify(error)); + }); + ``` + +## appManager.getProcessRunningInformation9+ + +getProcessRunningInformation(callback: AsyncCallback\>): void; + +Obtains information about the running processes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback\> | Yes| Obtains information about the running processes. This API uses a promise to return the result.| + +**Example** + + ```ts + app.getProcessRunningInformation((err, data) => { + console.log('startAbility result failed :' + JSON.stringify(err)); + console.log('startAbility result success:' + JSON.stringify(data)); + }) + ``` + +## appManager.registerApplicationStateObserver8+ + +registerApplicationStateObserver(observer: ApplicationStateObserver): number; + +Registers an observer to listen for the state changes of all applications. + +**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| observer | [ApplicationStateObserver](js-apis-inner-application-applicationStateObserver.md) | Yes| Numeric code of the observer.| + +**Example** + + ```ts + var applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log('------------ onForegroundApplicationChanged -----------', appStateData); + }, + onAbilityStateChanged(abilityStateData) { + console.log('------------ onAbilityStateChanged -----------', abilityStateData); + }, + onProcessCreated(processData) { + console.log('------------ onProcessCreated -----------', processData); + }, + onProcessDied(processData) { + console.log('------------ onProcessDied -----------', processData); + }, + onProcessStateChanged(processData) { + console.log('------------ onProcessStateChanged -----------', processData); + } + } + const observerCode = app.registerApplicationStateObserver(applicationStateObserver); + console.log('-------- observerCode: ---------', observerCode); + ``` + +## appManager.registerApplicationStateObserver9+ + +registerApplicationStateObserver(observer: ApplicationStateObserver, bundleNameList: Array\): number; + +Registers an observer to listen for the state changes of a specified application. + +**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| observer | [ApplicationStateObserver](js-apis-inner-application-applicationStateObserver.md) | Yes| Numeric code of the observer.| +| bundleNameList | Array | Yes| **bundleName** array of the application. A maximum of 128 bundle names can be passed.| + +**Example** + + ```ts + var applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log('------------ onForegroundApplicationChanged -----------', appStateData); + }, + onAbilityStateChanged(abilityStateData) { + console.log('------------ onAbilityStateChanged -----------', abilityStateData); + }, + onProcessCreated(processData) { + console.log('------------ onProcessCreated -----------', processData); + }, + onProcessDied(processData) { + console.log('------------ onProcessDied -----------', processData); + }, + onProcessStateChanged(processData) { + console.log('------------ onProcessStateChanged -----------', processData); + } + } + var bundleNameList = ['bundleName1', 'bundleName2']; + const observerCode = app.registerApplicationStateObserver(applicationStateObserver, bundleNameList); + console.log('-------- observerCode: ---------', observerCode); + ``` +## appManager.unregisterApplicationStateObserver8+ + +unregisterApplicationStateObserver(observerId: number, callback: AsyncCallback\): void; + +Deregisters the application state observer. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| observerId | number | Yes| Numeric code of the observer.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```ts + var observerId = 100; + + function unregisterApplicationStateObserverCallback(err) { + if (err) { + console.log('------------ unregisterApplicationStateObserverCallback ------------', err); + } + } + app.unregisterApplicationStateObserver(observerId, unregisterApplicationStateObserverCallback); + ``` + +## appManager.unregisterApplicationStateObserver8+ + +unregisterApplicationStateObserver(observerId: number): Promise\; + +Deregisters the application state observer. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| observerId | number | Yes| Numeric code of the observer.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\ | Promise used to return the result.| + +**Example** + + ```ts + var observerId = 100; + + app.unregisterApplicationStateObserver(observerId) + .then((data) => { + console.log('----------- unregisterApplicationStateObserver success ----------', data); + }) + .catch((err) => { + console.log('----------- unregisterApplicationStateObserver fail ----------', err); + }) + ``` + +## appManager.getForegroundApplications8+ + +getForegroundApplications(callback: AsyncCallback\>): void; + +Obtains applications that are running in the foreground. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback\> | Yes| Callback used to return the application state data.| + +**Example** + + ```ts + function getForegroundApplicationsCallback(err, data) { + if (err) { + console.log('--------- getForegroundApplicationsCallback fail ---------', err); + } else { + console.log('--------- getForegroundApplicationsCallback success ---------', data) + } + } + app.getForegroundApplications(getForegroundApplicationsCallback); + ``` + +## appManager.getForegroundApplications8+ + +getForegroundApplications(): Promise\>; + +Obtains applications that are running in the foreground. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\> | Promise used to return the application state data.| + +**Example** + + ```ts + app.getForegroundApplications() + .then((data) => { + console.log('--------- getForegroundApplications success -------', data); + }) + .catch((err) => { + console.log('--------- getForegroundApplications fail -------', err); + }) + ``` + +## appManager.killProcessWithAccount8+ + +killProcessWithAccount(bundleName: string, accountId: number): Promise\ + +Kills a process by bundle name and account ID. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS and ohos.permission.CLEAN_BACKGROUND_PROCESSES + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | bundleName | string | Yes| Bundle name of an application.| + | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| + +**Example** + +```ts +var bundleName = 'bundleName'; +var accountId = 0; +app.killProcessWithAccount(bundleName, accountId) + .then((data) => { + console.log('------------ killProcessWithAccount success ------------', data); + }) + .catch((err) => { + console.log('------------ killProcessWithAccount fail ------------', err); + }) +``` + + +## appManager.killProcessWithAccount8+ + +killProcessWithAccount(bundleName: string, accountId: number, callback: AsyncCallback\): void + +Kills a process by bundle name and account ID. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS and ohos.permission.CLEAN_BACKGROUND_PROCESSES + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | bundleName | string | Yes| Bundle name of an application.| + | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| + | callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + +```ts +var bundleName = 'bundleName'; +var accountId = 0; +function killProcessWithAccountCallback(err, data) { + if (err) { + console.log('------------- killProcessWithAccountCallback fail, err: --------------', err); + } else { + console.log('------------- killProcessWithAccountCallback success, data: --------------', data); + } +} +app.killProcessWithAccount(bundleName, accountId, killProcessWithAccountCallback); +``` + +## appManager.killProcessesByBundleName8+ + +killProcessesByBundleName(bundleName: string, callback: AsyncCallback\); + +Kills a process by bundle name. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CLEAN_BACKGROUND_PROCESSES + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name of an application.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```ts + var bundleName = 'bundleName'; + function killProcessesByBundleNameCallback(err, data) { + if (err) { + console.log('------------- killProcessesByBundleNameCallback fail, err: --------------', err); + } else { + console.log('------------- killProcessesByBundleNameCallback success, data: --------------', data); + } + } + app.killProcessesByBundleName(bundleName, killProcessesByBundleNameCallback); + ``` + +## appManager.killProcessesByBundleName8+ + +killProcessesByBundleName(bundleName: string): Promise\; + +Kills a process by bundle name. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CLEAN_BACKGROUND_PROCESSES + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name of an application.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\ | Promise used to return the result.| + +**Example** + + ```ts + var bundleName = 'bundleName'; + app.killProcessesByBundleName(bundleName) + .then((data) => { + console.log('------------ killProcessesByBundleName success ------------', data); + }) + .catch((err) => { + console.log('------------ killProcessesByBundleName fail ------------', err); + }) + ``` + +## appManager.clearUpApplicationData8+ + +clearUpApplicationData(bundleName: string, callback: AsyncCallback\); + +Clears application data by bundle name. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CLEAN_APPLICATION_DATA + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name of an application.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```ts + var bundleName = 'bundleName'; + function clearUpApplicationDataCallback(err, data) { + if (err) { + console.log('------------- clearUpApplicationDataCallback fail, err: --------------', err); + } else { + console.log('------------- clearUpApplicationDataCallback success, data: --------------', data); + } + } + app.clearUpApplicationData(bundleName, clearUpApplicationDataCallback); + ``` + +## appManager.clearUpApplicationData8+ + +clearUpApplicationData(bundleName: string): Promise\; + +Clears application data by bundle name. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CLEAN_APPLICATION_DATA + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name of an application.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\ | Promise used to return the result.| + +**Example** + + ```ts + var bundleName = 'bundleName'; + app.clearUpApplicationData(bundleName) + .then((data) => { + console.log('------------ clearUpApplicationData success ------------', data); + }) + .catch((err) => { + console.log('------------ clearUpApplicationData fail ------------', err); + }) + ``` + +## ApplicationState9+ + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Value | Description | +| -------------------- | --- | --------------------------------- | +| STATE_CREATE | 1 | State indicating that the application is being created. | +| STATE_FOREGROUND | 2 | State indicating that the application is running in the foreground. | +| STATE_ACTIVE | 3 | State indicating that the application is active. | +| STATE_BACKGROUND | 4 | State indicating that the application is running in the background. | +| STATE_DESTROY | 5 | State indicating that the application is destroyed. | + +## ProcessState9+ + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Value | Description | +| -------------------- | --- | --------------------------------- | +| STATE_CREATE | 1 | State indicating that the process is being created. | +| STATE_FOREGROUND | 2 | State indicating that the process is running in the foreground. | +| STATE_ACTIVE | 3 | State indicating that the process is active. | +| STATE_BACKGROUND | 4 | State indicating that the process is running in the background. | +| STATE_DESTROY | 5 | State indicating that the process is destroyed. | diff --git a/en/application-dev/reference/apis/js-apis-application-configuration.md b/en/application-dev/reference/apis/js-apis-application-configuration.md index 706b2bf6ff5251c06c46ebd740c509dd237ed194..9c374059dc89f8ebdc719597df0afb7c12247d66 100644 --- a/en/application-dev/reference/apis/js-apis-application-configuration.md +++ b/en/application-dev/reference/apis/js-apis-application-configuration.md @@ -1,11 +1,10 @@ -# Configuration +# @ohos.application.Configuration The **Configuration** module defines environment change information. > **NOTE** -> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> This module is deprecated since API version 9. You are advised to use [@ohos.application.Configuration](js-apis-app-ability-configuration.md) instead. +> This module is deprecated since API version 9. You are advised to use [@ohos.app.ability.Configuration](js-apis-app-ability-configuration.md) instead. ## Modules to Import @@ -15,7 +14,7 @@ import Configuration from '@ohos.application.Configuration' **System capability**: SystemCapability.Ability.AbilityBase -| Name| Type| Readable| Writable| Description| + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | language8+ | string | Yes| Yes| Language of the application.| | colorMode8+ | [ColorMode](js-apis-application-configurationConstant.md#configurationconstantcolormode) | Yes| Yes| Color mode, which can be **COLOR_MODE_LIGHT** or **COLOR_MODE_DARK**. The default value is **COLOR_MODE_LIGHT**.| @@ -68,5 +67,3 @@ export default class MainAbility extends Ability { } } ``` - - \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-application-configurationConstant.md b/en/application-dev/reference/apis/js-apis-application-configurationConstant.md index 7d4cc25df1e77b104a4aad649a9923107ef0e5fd..863848066791fd23c5811bcc2af027552d8e5991 100644 --- a/en/application-dev/reference/apis/js-apis-application-configurationConstant.md +++ b/en/application-dev/reference/apis/js-apis-application-configurationConstant.md @@ -1,10 +1,10 @@ -# ConfigurationConstant +# @ohos.application.ConfigurationConstant The **ConfigurationConstant** module provides the enumerated values of the environment configuration information. > **NOTE** > -> The APIs of this module are supported since API version 8 and deprecated since API version 9. You are advised to use [@ohos.application.ConfigurationConstant](js-apis-app-ability-configurationConstant.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported since API version 8 and deprecated since API version 9. You are advised to use [@ohos.app.ability.ConfigurationConstant](js-apis-app-ability-configurationConstant.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -53,5 +53,3 @@ You can obtain the value of this constant by calling the **ConfigurationConstant | SCREEN_DENSITY_XLDPI | 320 | The screen resolution is xldpi.| | SCREEN_DENSITY_XXLDPI | 480 | The screen resolution is xxldpi.| | SCREEN_DENSITY_XXXLDPI | 640 | The screen resolution is xxxldpi.| - - \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-application-context.md b/en/application-dev/reference/apis/js-apis-application-context.md index 16d5fd0c3d79d097bc8f78ef24cae8f91869b8e3..88a5c84c617f675c93ea2f43de62625294025ca6 100644 --- a/en/application-dev/reference/apis/js-apis-application-context.md +++ b/en/application-dev/reference/apis/js-apis-application-context.md @@ -1,183 +1,41 @@ -# Context +# @ohos.application.context -The **Context** module provides the context for running code. You can use the APIs to query and set the application information and resource manager. +The **Context** module provides all level-2 module APIs for developers to export. > **NOTE** > -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. -## Usage +## Modules to Import -You must extend **AbilityContext** to implement this module. - - ```js -import AbilityContext from '@ohos.application.Ability' - class MainAbility extends AbilityContext { - onWindowStageCreate(windowStage) { - let test = "com.example.test"; - let context = this.context.createBundleContext(test); - } - } +```ts +import context from '@ohos.application.context' ``` -## Attributes - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| resourceManager | resmgr.ResourceManager; | Yes| No| **ResourceManager** object.| -| applicationInfo | ApplicationInfo | Yes| No| Information about the application.| -| cacheDir | string | Yes| No| Cache directory of the application on the internal storage.| -| tempDir | string | Yes| No| Temporary file directory of the application.| -| filesDir | string | Yes| No| File directory of the application on the internal storage.| -| databaseDir | string | Yes| No| Storage directory of local data.| -| bundleCodeDir | string | Yes| No| Application installation path.| -| distributedFilesDir | string | Yes| No| Storage directory of distributed application data files.| -| eventHub | [EventHub](js-apis-eventhub.md) | Yes| No| Event hub information.| -| area | [AreaMode](#areamode) | Yes| Yes| Area in which the file to be access is located.| -| preferencesDir | string | Yes| Yes| Preferences directory of the application.| - -## Context.createBundleContext - -createBundleContext(bundleName: string): Context; - -Creates a context for a given application. - -**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System capability**: SystemCapability.Ability.AbilityBase -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Application bundle name.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Context | Context created.| +| Name | Readable/Writable| Type | Mandatory| Description | +| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | +| AbilityContext | Read Only | [AbilityContext](js-apis-ability-context.md) | No | Level-2 module **AbilityContext**. | +| AbilityStageContext | Read Only | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | No | Level-2 module **AbilityStageContext**.| +| ApplicationContext | Read Only | [ApplicationContext](js-apis-inner-application-applicationContext.md) | No | Level-2 module **ApplicationContext**.| +| BaseContext | Read Only | [BaseContext](js-apis-inner-application-baseContext.md) | No | Level-2 module **BaseContext**.| +| Context | Read Only | [Context](js-apis-inner-application-context.md) | No | Level-2 module **Context**.| +| ExtensionContext | Read Only | [ExtensionContext](js-apis-inner-application-extensionContext.md) | No | Level-2 module **ExtensionContext**.| +| FormExtensionContext | Read Only | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | No | Level-2 module **FormExtensionContext**.| +| EventHub | Read Only | [EventHub](js-apis-inner-application-eventHub.md) | No | Level-2 module **EventHub**.| +| PermissionRequestResult | Read Only | [PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md) | No | Level-2 module **PermissionRequestResult**.| **Example** - - ```js - import AbilityContext from '@ohos.application.Ability' - class MainAbility extends AbilityContext { - onWindowStageCreate(windowStage) { - let test = "com.example.test"; - let context = this.context.createBundleContext(test); - } -} - - ``` - - -## Context.createModuleContext - -createModuleContext(moduleName: string): Context; - -Creates a context for a given HAP. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | moduleName | string | Yes| HAP name in the application.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Context | Context created.| - -**Example** - - ```js - import AbilityContext from '@ohos.application.Ability' - class MainAbility extends AbilityContext { - onWindowStageCreate(windowStage) { - let moduleName = "module"; - let context = this.context.createModuleContext(moduleName); - } -} - - ``` - - -## Context.createModuleContext - -createModuleContext(bundleName: string, moduleName: string): Context; - -Creates a context for a given HAP in an application. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Application bundle name.| - | moduleName | string | Yes| HAP name in the application.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Context | Context created.| - -**Example** - - ```js - import AbilityContext from '@ohos.application.Ability' - class MainAbility extends AbilityContext { - onWindowStageCreate(windowStage) { - let bundleName = "com.example.bundle"; - let moduleName = "module"; - let context = this.context.createModuleContext(bundleName, moduleName); - } -} - - ``` - - -## Context.getApplicationContext - -getApplicationContext(): ApplicationContext; - -Obtains the context of this application. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Return value** - -| Type| Description| -| -------- | -------- | -| ApplicationContext | Current application context.| - -**Example** - - ```js - // This part is mandatory. - let applicationContext = this.context.getApplicationContext(); - ``` - - -## AreaMode - -Defines the area where the file to be access is located. Each area has its own content. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name | Value | Description | -| --------------- | ---- | --------------- | -| EL1 | 0 | Device-level encryption area. | -| EL2 | 1 | User credential encryption area. The default value is **EL2**.| +```ts +let abilityContext: context.AbilityContext; +let abilityStageContext: context.AbilityStageContext; +let applicationContext: context.ApplicationContext; +let baseContext: context.BaseContext; +let context: context.Context; +let extensionContext: context.ExtensionContext; +let formExtensionContext: context.FormExtensionContext; +let eventHub: context.EventHub; +let permissionRequestResult: context.PermissionRequestResult; +``` diff --git a/en/application-dev/reference/apis/js-apis-application-environmentCallback.md b/en/application-dev/reference/apis/js-apis-application-environmentCallback.md new file mode 100644 index 0000000000000000000000000000000000000000..e1d2033c652d413ddac9933e32c3c53c1372f443 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-application-environmentCallback.md @@ -0,0 +1,61 @@ +# @ohos.application.EnvironmentCallback + +The **EnvironmentCallback** module provides the **onConfigurationUpdated** API for the application context to listen for system environment changes. + +> **NOTE** +> +> The APIs of this module are supported and deprecated since API version 9. You are advised to use [@ohos.app.ability.EnvironmentCallback](js-apis-app-ability-environmentCallback.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the stage model. + + +## Modules to Import + +```ts +import EnvironmentCallback from "@ohos.application.EnvironmentCallback"; +``` + + +## EnvironmentCallback.onConfigurationUpdated + +onConfigurationUpdated(config: Configuration): void; + +Called when the system environment changes. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| config | [Configuration](js-apis-application-configuration.md) | Yes| **Configuration** object after the change.| + +**Example** + + ```ts +import Ability from "@ohos.application.Ability"; + +var callbackId; + +export default class MyAbility extends Ability { + onCreate() { + console.log("MyAbility onCreate") + globalThis.applicationContext = this.context.getApplicationContext(); + let EnvironmentCallback = { + onConfigurationUpdated(config){ + console.log("onConfigurationUpdated config:" + JSON.stringify(config)); + }, + } + // 1. Obtain an applicationContext object. + let applicationContext = globalThis.applicationContext; + // 2. Register a listener for the environment changes through the applicationContext object. + callbackId = applicationContext.registerEnvironmentCallback(EnvironmentCallback); + console.log("registerEnvironmentCallback number: " + JSON.stringify(callbackId)); + } + onDestroy() { + let applicationContext = globalThis.applicationContext; + applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => { + console.log("unregisterEnvironmentCallback success, err: " + JSON.stringify(error)); + }); + } +} + ``` diff --git a/en/application-dev/reference/apis/js-apis-errorManager.md b/en/application-dev/reference/apis/js-apis-application-errorManager.md similarity index 72% rename from en/application-dev/reference/apis/js-apis-errorManager.md rename to en/application-dev/reference/apis/js-apis-application-errorManager.md index 4a39fdd6b0031be7e3fcbdfc7a570609ba217a1b..5326b582120b6dcbf23a88bedb1ff4dcbe6192ae 100644 --- a/en/application-dev/reference/apis/js-apis-errorManager.md +++ b/en/application-dev/reference/apis/js-apis-application-errorManager.md @@ -1,4 +1,4 @@ -# ErrorManager +# @ohos.application.errorManager The **ErrorManager** module provides APIs for registering and deregistering error observers. @@ -7,7 +7,7 @@ The **ErrorManager** module provides APIs for registering and deregistering erro > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -``` +```ts import errorManager from '@ohos.application.errorManager' ``` @@ -23,11 +23,11 @@ Registers an error observer. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| observer | [ErrorObserver](#errorobserver) | No| Numeric code of the observer.| +| observer | [ErrorObserver](js-apis-inner-application-errorObserver.md) | Yes| Numeric code of the observer.| **Example** -```js +```ts var observer = { onUnhandledException(errorMsg) { console.log('onUnhandledException, errorMsg: ', errorMsg) @@ -48,12 +48,12 @@ Deregisters an error observer. This API uses an asynchronous callback to return | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| observerId | number | No| Numeric code of the observer.| -| callback | AsyncCallback\ | No| Callback used to return the result.| +| observerId | number | Yes| Numeric code of the observer.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** -```js +```ts var observerId = 100; function unregisterErrorObserverCallback(err) { @@ -77,7 +77,7 @@ Deregisters an error observer. This API uses a promise to return the result. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| observerId | number | No| Numeric code of the observer.| +| observerId | number | Yes| Numeric code of the observer.| **Return value** @@ -87,7 +87,7 @@ Deregisters an error observer. This API uses a promise to return the result. **Example** -```js +```ts var observerId = 100; errorManager.unregisterErrorObserver(observerId) .then((data) => { @@ -98,28 +98,3 @@ errorManager.unregisterErrorObserver(observerId) }) ``` - -## ErrorObserver - -onUnhandledException(errMsg: string): void; - -Called when an unhandled exception occurs in the JS runtime. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| errMsg | string | No| Message and error stack trace about the exception.| - -**Example** - -```js -var observer = { - onUnhandledException(errorMsg) { - console.log('onUnhandledException, errorMsg: ', errorMsg) - } -} -errorManager.registerErrorObserver(observer) -``` diff --git a/en/application-dev/reference/apis/js-apis-application-extensionAbility.md b/en/application-dev/reference/apis/js-apis-application-extensionAbility.md new file mode 100644 index 0000000000000000000000000000000000000000..055980e455acb5fd56ece9d4a1a582c7868b1646 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-application-extensionAbility.md @@ -0,0 +1,62 @@ +# @ohos.application.ExtensionAbility + +The **ExtensionAbility** module manages the Extension ability lifecycle and context, such as creating and destroying an Extension ability, and dumping client information. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the stage model. + +## Modules to Import + +```ts +import ExtensionAbility from '@ohos.application.ExtensionAbility'; +``` + +## ExtensionAbility.onConfigurationUpdated + +onConfigurationUpdated(newConfig: Configuration): void; + +Called when the configuration of the environment where the ability is running is updated. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | newConfig | [Configuration](js-apis-application-configuration.md) | Yes| New configuration.| + +**Example** + + ```ts + class MyExtensionAbility extends ExtensionAbility { + onConfigurationUpdated(config) { + console.log('onConfigurationUpdated, config:' + JSON.stringify(config)); + } + } + ``` + +## ExtensionAbility.onMemoryLevel + +onMemoryLevel(level: AbilityConstant.MemoryLevel): void; + +Called when the system has decided to adjust the memory level. For example, this API can be used when there is not enough memory to run as many background processes as possible. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | level | [AbilityConstant.MemoryLevel](js-apis-application-abilityConstant.md#abilityconstantmemorylevel) | Yes| Memory level that indicates the memory usage status. When the specified memory level is reached, a callback will be invoked and the system will start adjustment.| + +**Example** + + ```ts + class MyExtensionAbility extends ExtensionAbility { + onMemoryLevel(level) { + console.log('onMemoryLevel, level:' + JSON.stringify(level)); + } + } + ``` diff --git a/en/application-dev/reference/apis/js-apis-application-formBindingData.md b/en/application-dev/reference/apis/js-apis-application-formBindingData.md new file mode 100644 index 0000000000000000000000000000000000000000..f0cdf74799a4373cfe61446191166a1e2ca0a014 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-application-formBindingData.md @@ -0,0 +1,63 @@ +# @ohos.application.formBindingData + +The **FormBindingData** module provides APIs for widget data binding. You can use the APIs to create a **FormBindingData** object and obtain related information. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> This module is deprecated since API version 9. You are advised to use [FormBindingData](js-apis-app-form-formBindingData.md) instead. +## Modules to Import + +```ts +import formBindingData from '@ohos.application.formBindingData'; +``` + +## FormBindingData + +Describes a **FormBindingData** object. + +**System capability**: SystemCapability.Ability.Form + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| data | Object | Yes| Data to be displayed on the JS widget. The value can be an object containing multiple key-value pairs or a string in JSON format.| + + +## createFormBindingData + +createFormBindingData(obj?: Object | string): FormBindingData + +Creates a **FormBindingData** object. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------- | ---- | ------------------------------------------------------------ | +| obj | Object\|string | No | Data to be displayed on the JS widget. The value can be an object containing multiple key-value pairs or a string in JSON format. The image data is identified by "formImages", and the content is multiple key-value pairs, each of which consists of an image identifier and image file descriptor. The final format is {"formImages": {"key1": fd1, "key2": fd2}}.| + + +**Return value** + +| Type | Description | +| ----------------------------------- | --------------------------------------- | +| [FormBindingData](#formbindingdata) | **FormBindingData** object created based on the passed data.| + + +**Example** + +```ts +import featureAbility from '@ohos.ability.featureAbility'; +import fileio from '@ohos.fileio'; +let context=featureAbility.getContext(); +context.getOrCreateLocalDir((err,data)=>{ + let path=data+"/xxx.jpg"; + let fd = fileio.openSync(path); + let obj = { + "temperature": "21°", + "formImages": {"image": fd} + }; + let formBindingDataObj = formBindingData.createFormBindingData(obj); +}) +``` diff --git a/en/application-dev/reference/apis/js-apis-formerror.md b/en/application-dev/reference/apis/js-apis-application-formError.md similarity index 82% rename from en/application-dev/reference/apis/js-apis-formerror.md rename to en/application-dev/reference/apis/js-apis-application-formError.md index 9425026504a875b92fe5d2312b7de6d4c1e61d84..7a9a6618cd4906b2a4894f8cdfd8c796beefc905 100644 --- a/en/application-dev/reference/apis/js-apis-formerror.md +++ b/en/application-dev/reference/apis/js-apis-application-formError.md @@ -1,14 +1,15 @@ -# FormError +# @ohos.application.formError The **FormError** module provides error codes for widgets. > **NOTE** -> +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> This module is deprecated since API version 9. You are advised to use [Form Error Codes](../errorcodes/errorcode-form.md) instead. ## Modules to Import -``` +```ts import formError from '@ohos.application.formError'; ``` @@ -16,9 +17,9 @@ import formError from '@ohos.application.formError'; None. -## enum FormError +## FormError -Enumerates the available error codes. +Enumerates the widget types. **System capability** @@ -27,12 +28,12 @@ SystemCapability.Ability.Form | Name | Value | Description | | ----------- | ---- | ------------ | | ERR_COMMON | 1 | Default error code. | -| ERR_PERMISSION_DENY | 2 | No permission to perform the operation. | +| ERR_PERMISSION_DENY | 2 | You are not authorized to perform the operation. | | ERR_GET_INFO_FAILED | 4 | Failed to obtain the widget information. | | ERR_GET_BUNDLE_FAILED | 5 | Failed to obtain the bundle information. | | ERR_GET_LAYOUT_FAILED | 6 | Failed to obtain the layout information. | -| ERR_ADD_INVALID_PARAM | 7 | Invalid parameter. | -| ERR_CFG_NOT_MATCH_ID | 8 | The widget ID does not match any widget. | +| ERR_ADD_INVALID_PARAM | 7 | Invalid parameters are detected. | +| ERR_CFG_NOT_MATCH_ID | 8 | The widget ID does not match any widget. | | ERR_NOT_EXIST_ID | 9 | The widget ID does not exist. | | ERR_BIND_PROVIDER_FAILED | 10 | Failed to bind to the widget provider. | | ERR_MAX_SYSTEM_FORMS | 11 | The number of system widgets exceeds the upper limit. | @@ -48,4 +49,6 @@ SystemCapability.Ability.Form | ERR_SYSTEM_RESPONSES_FAILED | 30 | The system service failed to respond. | | ERR_FORM_DUPLICATE_ADDED | 31 | The widget has been added. | | ERR_IN_RECOVERY | 36 | Failed to overwrite the widget data. | -| ERR_DISTRIBUTED_SCHEDULE_FAILED9+ | 37 | The distributed scheduler failed.
This is a system API. | +| ERR_DISTRIBUTED_SCHEDULE_FAILED9+ | 37 | The distributed scheduler failed.
**System API**: This is a system API. | + + \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-application-formExtension.md b/en/application-dev/reference/apis/js-apis-application-formExtension.md new file mode 100644 index 0000000000000000000000000000000000000000..a01e08710907030edfc7f0b1d04927282f5bc387 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-application-formExtension.md @@ -0,0 +1,284 @@ +# @ohos.application.FormExtension + +The **FormExtension** module provides APIs related to Form Extension abilities. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> This module is deprecated since API version 9. You are advised to use [FormExtensionAbility](js-apis-app-form-formExtensionAbility.md) instead. +> The APIs of this module can be used only in the stage model. + +## Modules to Import + +```ts +import FormExtension from '@ohos.application.FormExtension'; +``` + +## Attributes + +**System capability**: SystemCapability.Ability.Form + +| Name | Type | Readable| Writable| Description | +| ------- | ------------------------------------------------------- | ---- | ---- | --------------------------------------------------- | +| context | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | Yes | No | Context of the **FormExtension**. This context is inherited from **ExtensionContext**.| + +## onCreate + +onCreate(want: Want): formBindingData.FormBindingData + +Called to notify the widget provider that a **Form** instance (widget) has been created. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------------------------------- | ---- | ------------------------------------------------------------ | +| want | [Want](js-apis-application-want.md) | Yes | Information related to the extension, including the widget ID, name, and style. The information must be managed as persistent data to facilitate subsequent widget update and deletion.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ----------------------------------------------------------- | +| [formBindingData.FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | A **formBindingData.FormBindingData** object containing the data to be displayed on the widget.| + +**Example** + +```ts +import formBindingData from '@ohos.application.formBindingData' +export default class MyFormExtension extends FormExtension { + onCreate(want) { + console.log('FormExtension onCreate, want:' + want.abilityName); + let dataObj1 = { + temperature:"11c", + "time":"11:00" + }; + let obj1 = formBindingData.createFormBindingData(dataObj1); + return obj1; + } +} +``` + +## FormExtension.onCastToNormal + +onCastToNormal(formId: string): void + +Called to notify the widget provider that a temporary widget has been converted to a normal one. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------ | +| formId | string | Yes | ID of the widget that requests to be converted to a normal one.| + +**Example** + +```ts +export default class MyFormExtension extends FormExtension { + onCastToNormal(formId) { + console.log('FormExtension onCastToNormal, formId:' + formId); + } +} +``` + +## FormExtension.onUpdate + +onUpdate(formId: string): void + +Called to notify the widget provider that a widget has been updated. After obtaining the latest data, the caller invokes **updateForm** of the [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) class to update the widget data. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| formId | string | Yes | ID of the widget that requests to be updated.| + +**Example** + +```ts +import formBindingData from '@ohos.application.formBindingData' +export default class MyFormExtension extends FormExtension { + onUpdate(formId) { + console.log('FormExtension onUpdate, formId:' + formId); + let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); + this.context.updateForm(formId, obj2).then((data)=>{ + console.log('FormExtension context updateForm, data:' + data); + }).catch((error) => { + console.error('Operation updateForm failed. Cause: ' + error);}); + } +} +``` + +## FormExtension.onVisibilityChange + +onVisibilityChange(newStatus: { [key: string]: number }): void + +Called to notify the widget provider of the change of visibility. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------- | ---- | ---------------------------- | +| newStatus | { [key: string]: number } | Yes | ID and visibility status of the widget to be changed.| + +**Example** + +```ts +import formBindingData from '@ohos.application.formBindingData' +export default class MyFormExtension extends FormExtension { + onVisibilityChange(newStatus) { + console.log('FormExtension onVisibilityChange, newStatus:' + newStatus); + let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); + + for (let key in newStatus) { + console.log('FormExtension onVisibilityChange, key:' + key + ", value=" + newStatus[key]); + this.context.updateForm(key, obj2).then((data)=>{ + console.log('FormExtension context updateForm, data:' + data); + }).catch((error) => { + console.error('Operation updateForm failed. Cause: ' + error);}); + } + } +} +``` + +## FormExtension.onEvent + +onEvent(formId: string, message: string): void + +Called to instruct the widget provider to receive and process the widget event. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ---------------------- | +| formId | string | Yes | ID of the widget that requests the event.| +| message | string | Yes | Event message. | + +**Example** + +```ts +export default class MyFormExtension extends FormExtension { + onEvent(formId, message) { + console.log('FormExtension onEvent, formId:' + formId + ", message:" + message); + } +} +``` + +## FormExtension.onDestroy + +onDestroy(formId: string): void + +Called to notify the widget provider that a **Form** instance (widget) has been destroyed. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| formId | string | Yes | ID of the widget to be destroyed.| + +**Example** + +```ts +export default class MyFormExtension extends FormExtension { + onDestroy(formId) { + console.log('FormExtension onDestroy, formId:' + formId); + } +} +``` + +## FormExtension.onConfigurationUpdated + +onConfigurationUpdated(config: Configuration): void; + +Called when the configuration of the environment where the ability is running is updated. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| config | [Configuration](js-apis-application-configuration.md) | Yes| New configuration.| + +**Example** + +```ts +class MyFormExtension extends FormExtension { + onConfigurationUpdated(config) { + console.log('onConfigurationUpdated, config:' + JSON.stringify(config)); + } +} +``` + +## FormExtension.onAcquireFormState + +onAcquireFormState?(want: Want): formInfo.FormState; + +Called when the widget provider receives the status query result of a widget. By default, the initial state is returned. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Description of the widget state, including the bundle name, ability name, module name, widget name, and widget dimension.| + +**Example** + +```ts +import formInfo from '@ohos.application.formInfo' +class MyFormExtension extends FormExtension { + onAcquireFormState(want) { + console.log('FormExtension onAcquireFormState, want:' + want); + return formInfo.FormState.UNKNOWN; + } +} +``` + +## FormExtension.onShare + +onShare?(formId: string): {[key: string]: any}; + +Called by the widget provider to receive shared widget data. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| formId | string | Yes | Widget ID.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ----------------------------------------------------------- | +| {[key: string]: any} | Data to be shared by the widget, in the form of key-value pairs.| + +**Example** + +```ts +class MyFormExtension extends FormExtension { + onShare(formId) { + console.log('FormExtension onShare, formId:' + formId); + let wantParams = { + "temperature":"20", + "time":"2022-8-8 09:59", + }; + return wantParams; + } +} +``` diff --git a/en/application-dev/reference/apis/js-apis-application-formHost.md b/en/application-dev/reference/apis/js-apis-application-formHost.md new file mode 100644 index 0000000000000000000000000000000000000000..8b44dbf345b717b3cf1433392fd82907b6caab5f --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-application-formHost.md @@ -0,0 +1,1135 @@ +# @ohos.application.formHost + +The **FormHost** module provides APIs related to the widget host, which is an application that displays the widget content and controls the position where the widget is displayed. You can use the APIs to delete, release, and update widgets installed by the same user, and obtain widget information and status. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> This module is deprecated since API version 9. You are advised to use [FormHost](js-apis-app-form-formHost.md) instead. +> The APIs provided by this module are system APIs. + +## Modules to Import + +```ts +import formHost from '@ohos.application.formHost'; +``` + +## deleteForm + +deleteForm(formId: string, callback: AsyncCallback<void>): void + +Deletes a widget. After this API is called, the application can no longer use the widget, and the Widget Manager will not retain the widget information. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is deleted, **err** is undefined; otherwise, **err** is an error object.| + +**Example** + +```ts +var formId = "12400633174999288"; +formHost.deleteForm(formId, (error, data) => { + if (error.code) { + console.log('formHost deleteForm, error:' + JSON.stringify(error)); + } +}); +``` + +## deleteForm + +deleteForm(formId: string): Promise<void> + +Deletes a widget. After this API is called, the application can no longer use the widget, and the Widget Manager will not retain the widget information. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Parameters** + +```ts +var formId = "12400633174999288"; +formHost.deleteForm(formId).then(() => { + console.log('formHost deleteForm success'); +}).catch((error) => { + console.log('formHost deleteForm, error:' + JSON.stringify(error)); +}); +``` + +## releaseForm + +releaseForm(formId: string, callback: AsyncCallback<void>): void + +Releases a widget. After this API is called, the application can no longer use the widget, but the Widget Manager still retains the widget cache and storage information. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is released, **err** is undefined; otherwise, **err** is an error object.| + +**Example** + +```ts +var formId = "12400633174999288"; +formHost.releaseForm(formId, (error, data) => { + if (error.code) { + console.log('formHost releaseForm, error:' + JSON.stringify(error)); + } +}); +``` + +## releaseForm + +releaseForm(formId: string, isReleaseCache: boolean, callback: AsyncCallback<void>): void + +Releases a widget. After this API is called, the application can no longer use the widget, but the Widget Manager retains the storage information about the widget and retains or releases the cache information based on the setting. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ------ | ---- | ----------- | +| formId | string | Yes | Widget ID. | +| isReleaseCache | boolean | Yes | Whether to release the cache.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is released, **err** is undefined; otherwise, **err** is an error object.| + +**Example** + +```ts +var formId = "12400633174999288"; +formHost.releaseForm(formId, true, (error, data) => { + if (error.code) { + console.log('formHost releaseForm, error:' + JSON.stringify(error)); + } +}); +``` + +## releaseForm + +releaseForm(formId: string, isReleaseCache?: boolean): Promise<void> + +Releases a widget. After this API is called, the application can no longer use the widget, but the Widget Manager retains the storage information about the widget and retains or releases the cache information based on the setting. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ------ | ---- | ----------- | +| formId | string | Yes | Widget ID. | +| isReleaseCache | boolean | No | Whether to release the cache.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +var formId = "12400633174999288"; +formHost.releaseForm(formId, true).then(() => { + console.log('formHost releaseForm success'); +}).catch((error) => { + console.log('formHost releaseForm, error:' + JSON.stringify(error)); +}); +``` + +## requestForm + +requestForm(formId: string, callback: AsyncCallback<void>): void + +Requests a widget update. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is updated, **err** is undefined; otherwise, **err** is an error object.| + +**Example** + +```ts +var formId = "12400633174999288"; +formHost.requestForm(formId, (error, data) => { + if (error.code) { + console.log('formHost requestForm, error:' + JSON.stringify(error)); + } +}); +``` + +## requestForm + +requestForm(formId: string): Promise<void> + +Requests a widget update. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +var formId = "12400633174999288"; +formHost.requestForm(formId).then(() => { + console.log('formHost requestForm success'); +}).catch((error) => { + console.log('formHost requestForm, error:' + JSON.stringify(error)); +}); +``` + +## castTempForm + +castTempForm(formId: string, callback: AsyncCallback<void>): void + +Converts a temporary widget to a normal one. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is converted to a normal one, **err** is undefined; otherwise, **err** is an error object.| + +**Example** + +```ts +var formId = "12400633174999288"; +formHost.castTempForm(formId, (error, data) => { + if (error.code) { + console.log('formHost castTempForm, error:' + JSON.stringify(error)); + } +}); +``` + +## castTempForm + +castTempForm(formId: string): Promise<void> + +Converts a temporary widget to a normal one. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +var formId = "12400633174999288"; +formHost.castTempForm(formId).then(() => { + console.log('formHost castTempForm success'); +}).catch((error) => { + console.log('formHost castTempForm, error:' + JSON.stringify(error)); +}); +``` + +## notifyVisibleForms + +notifyVisibleForms(formIds: Array<string>, callback: AsyncCallback<void>): void + +Instructs the widget framework to make a widget visible. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget visible, **err** is undefined; otherwise, **err** is an error object.| + +**Example** + +```ts +var formId = ["12400633174999288"]; +formHost.notifyVisibleForms(formId, (error, data) => { + if (error.code) { + console.log('formHost notifyVisibleForms, error:' + JSON.stringify(error)); + } +}); +``` + +## notifyVisibleForms + +notifyVisibleForms(formIds: Array<string>): Promise<void> + +Instructs the widget framework to make a widget visible. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +var formId = ["12400633174999288"]; +formHost.notifyVisibleForms(formId).then(() => { + console.log('formHost notifyVisibleForms success'); +}).catch((error) => { + console.log('formHost notifyVisibleForms, error:' + JSON.stringify(error)); +}); +``` + +## notifyInvisibleForms + +notifyInvisibleForms(formIds: Array<string>, callback: AsyncCallback<void>): void + +Instructs the widget framework to make a widget invisible. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget invisible, **err** is undefined; otherwise, **err** is an error object.| + +**Example** + +```ts +var formId = ["12400633174999288"]; +formHost.notifyInvisibleForms(formId, (error, data) => { + if (error.code) { + console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(error)); + } +}); +``` + +## notifyInvisibleForms + +notifyInvisibleForms(formIds: Array<string>): Promise<void> + +Instructs the widget framework to make a widget invisible. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +var formId = ["12400633174999288"]; +formHost.notifyInvisibleForms(formId).then(() => { + console.log('formHost notifyInvisibleForms success'); +}).catch((error) => { + console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(error)); +}); +``` + +## enableFormsUpdate + +enableFormsUpdate(formIds: Array<string>, callback: AsyncCallback<void>): void + +Instructs the widget framework to make a widget updatable. After this API is called, the widget is in the enabled state and can receive updates from the widget provider. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget updatable, **err** is undefined; otherwise, **err** is an error object.| + +**Example** + +```ts +var formId = ["12400633174999288"]; +formHost.enableFormsUpdate(formId, (error, data) => { + if (error.code) { + console.log('formHost enableFormsUpdate, error:' + JSON.stringify(error)); + } +}); +``` + +## enableFormsUpdate + +enableFormsUpdate(formIds: Array<string>): Promise<void> + +Instructs the widget framework to make a widget updatable. After this API is called, the widget is in the enabled state and can receive updates from the widget provider. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +var formId = ["12400633174999288"]; +formHost.enableFormsUpdate(formId).then(() => { + console.log('formHost enableFormsUpdate success'); +}).catch((error) => { + console.log('formHost enableFormsUpdate, error:' + JSON.stringify(error)); +}); +``` + +## disableFormsUpdate + +disableFormsUpdate(formIds: Array<string>, callback: AsyncCallback<void>): void + +Instructs the widget framework to make a widget not updatable. After this API is called, the widget cannot receive updates from the widget provider. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget not updatable, **err** is undefined; otherwise, **err** is an error object.| + +**Example** + +```ts +var formId = ["12400633174999288"]; +formHost.disableFormsUpdate(formId, (error, data) => { + if (error.code) { + console.log('formHost disableFormsUpdate, error:' + JSON.stringify(error)); + } +}); +``` + +## disableFormsUpdate + +disableFormsUpdate(formIds: Array<string>): Promise<void> + +Instructs the widget framework to make a widget not updatable. After this API is called, the widget cannot receive updates from the widget provider. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +var formId = ["12400633174999288"]; +formHost.disableFormsUpdate(formId).then(() => { + console.log('formHost disableFormsUpdate success'); +}).catch((error) => { + console.log('formHost disableFormsUpdate, error:' + JSON.stringify(error)); +}); +``` + +## isSystemReady + +isSystemReady(callback: AsyncCallback<void>): void + +Checks whether the system is ready. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the check is successful, **err** is undefined; otherwise, **err** is an error object.| + +**Example** + +```ts +var formId = "12400633174999288"; +formHost.isSystemReady((error, data) => { + if (error.code) { + console.log('formHost isSystemReady, error:' + JSON.stringify(error)); + } +}); +``` + +## isSystemReady + +isSystemReady(): Promise<void> + +Checks whether the system is ready. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +var formId = "12400633174999288"; +formHost.isSystemReady().then(() => { + console.log('formHost isSystemReady success'); +}).catch((error) => { + console.log('formHost isSystemReady, error:' + JSON.stringify(error)); +}); +``` + +## getAllFormsInfo + +getAllFormsInfo(callback: AsyncCallback<Array<formInfo.FormInfo>>): void + +Obtains the widget information provided by all applications on the device. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| callback | AsyncCallback<Array<[FormInfo](js-apis-application-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **err** is undefined and **data** is the information obtained; otherwise, **err** is an error object.| + +**Example** + +```ts +formHost.getAllFormsInfo((error, data) => { + if (error.code) { + console.log('formHost getAllFormsInfo, error:' + JSON.stringify(error)); + } else { + console.log('formHost getAllFormsInfo, data:' + JSON.stringify(data)); + } +}); +``` + +## getAllFormsInfo + +getAllFormsInfo(): Promise<Array<formInfo.FormInfo>> + +Obtains the widget information provided by all applications on the device. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<Array<[FormInfo](js-apis-application-formInfo.md)>> | Promise used to return the information obtained.| + +**Example** + + ```ts + formHost.getAllFormsInfo().then((data) => { + console.log('formHost getAllFormsInfo data:' + JSON.stringify(data)); + }).catch((error) => { + console.log('formHost getAllFormsInfo, error:' + JSON.stringify(error)); + }); + ``` + +## getFormsInfo + +getFormsInfo(bundleName: string, callback: AsyncCallback<Array<formInfo.FormInfo>>): void + +Obtains the widget information provided by a given application on the device. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| bundleName | string | Yes| Bundle name of the application.| +| callback | AsyncCallback<Array<[FormInfo](js-apis-application-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **err** is undefined and **data** is the information obtained; otherwise, **err** is an error object.| + +**Example** + +```ts +formHost.getFormsInfo("com.example.ohos.formjsdemo", (error, data) => { + if (error.code) { + console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); + } else { + console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); + } +}); +``` + +## getFormsInfo + +getFormsInfo(bundleName: string, moduleName: string, callback: AsyncCallback<Array<formInfo.FormInfo>>): void + +Obtains the widget information provided by a given application on the device. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| bundleName | string | Yes| Bundle name of the application.| +| moduleName | string | Yes| Module name.| +| callback | AsyncCallback<Array<[FormInfo](js-apis-application-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **err** is undefined and **data** is the information obtained; otherwise, **err** is an error object.| + +**Example** + +```ts +formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry", (error, data) => { + if (error.code) { + console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); + } else { + console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); + } +}); +``` + +## getFormsInfo + +getFormsInfo(bundleName: string, moduleName?: string): Promise<Array<formInfo.FormInfo>> + +Obtains the widget information provided by a given application on the device. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| bundleName | string | Yes| Bundle name of the application.| +| moduleName | string | No| Module name.| + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<Array<[FormInfo](js-apis-application-formInfo.md)>> | Promise used to return the information obtained.| + +**Example** + + ```ts + formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry").then((data) => { + console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); + }).catch((error) => { + console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); + }); + ``` + +## deleteInvalidForms + +deleteInvalidForms(formIds: Array<string>, callback: AsyncCallback<number>): void + +Deletes invalid widgets from the list. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of valid widget IDs.| +| callback | AsyncCallback<number> | Yes| Callback used to return the result. If the invalid widgets are deleted, **err** is undefined and **data** is the number of widgets deleted; otherwise, **err** is an error object.| + +**Example** + +```ts +var formIds = new Array("12400633174999288", "12400633174999289"); +formHost.deleteInvalidForms(formIds, (error, data) => { + if (error.code) { + console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error)); + } else { + console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); + } +}); +``` + +## deleteInvalidForms + +deleteInvalidForms(formIds: Array<string>): Promise<number> + +Deletes invalid widgets from the list. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of valid widget IDs.| + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<number> | Promise used to return the number of widgets deleted.| + +**Example** + +```ts +var formIds = new Array("12400633174999288", "12400633174999289"); +formHost.deleteInvalidForms(formIds).then((data) => { + console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); +}).catch((error) => { + console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error)); +}); +``` + +## acquireFormState + +acquireFormState(want: Want, callback: AsyncCallback<formInfo.FormStateInfo>): void + +Obtains the widget state. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| want | [Want](js-apis-application-want.md) | Yes | **Want** information carried to query the widget state.| +| callback | AsyncCallback<[FormStateInfo](js-apis-application-formInfo.md#formstateinfo)> | Yes| Callback used to return the result. If the widget state is obtained, **err** is undefined and **data** is the widget state obtained; otherwise, **err** is an error object.| + +**Example** + +```ts +var want = { + "deviceId": "", + "bundleName": "ohos.samples.FormApplication", + "abilityName": "FormAbility", + "parameters": { + "ohos.extra.param.key.module_name": "entry", + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.form_dimension": 2 + } +}; +formHost.acquireFormState(want, (error, data) => { + if (error.code) { + console.log('formHost acquireFormState, error:' + JSON.stringify(error)); + } else { + console.log('formHost acquireFormState, data:' + JSON.stringify(data)); + } +}); +``` + +## acquireFormState + +acquireFormState(want: Want): Promise<formInfo.FormStateInfo> + +Obtains the widget state. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| want | [Want](js-apis-application-want.md) | Yes | **Want** information carried to query the widget state.| + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<[FormStateInfo](js-apis-application-formInfo.md#formstateinfo)> | Promise used to return the widget state obtained.| + +**Example** + +```ts +var want = { + "deviceId": "", + "bundleName": "ohos.samples.FormApplication", + "abilityName": "FormAbility", + "parameters": { + "ohos.extra.param.key.module_name": "entry", + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.form_dimension": 2 + } +}; +formHost.acquireFormState(want).then((data) => { + console.log('formHost acquireFormState, data:' + JSON.stringify(data)); +}).catch((error) => { + console.log('formHost acquireFormState, error:' + JSON.stringify(error)); +}); +``` + +## on("formUninstall") + +on(type: "formUninstall", callback: Callback<string>): void + +Subscribes to widget uninstall events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| type | string | Yes | Event type. The value **formUninstall** indicates a widget uninstallation event.| +| callback | Callback<string> | Yes| Callback used to return the widget ID.| + +**Example** + +```ts +let callback = function(formId) { + console.log('formHost on formUninstall, formId:' + formId); +} +formHost.on("formUninstall", callback); +``` + +## off("formUninstall") + +off(type: "formUninstall", callback?: Callback<string>): void + +Unsubscribes from widget uninstall events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| type | string | Yes | Event type. The value **formUninstall** indicates a widget uninstallation event.| +| callback | Callback<string> | No| Callback used to return the widget ID. If it is left unspecified, it indicates the callback for all the events that have been subscribed.| + +**Example** + +```ts +let callback = function(formId) { + console.log('formHost on formUninstall, formId:' + formId); +} +formHost.off("formUninstall", callback); +``` + +## notifyFormsVisible + +notifyFormsVisible(formIds: Array<string>, isVisible: boolean, callback: AsyncCallback<void>): void + +Instructs the widgets to make themselves visible. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| +| isVisible | boolean | Yes | Whether to make the widgets visible.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the notification is sent, **err** is undefined; otherwise, **err** is an error object.| + +**Example** + +```ts +var formIds = new Array("12400633174999288", "12400633174999289"); +formHost.notifyFormsVisible(formIds, true, (error, data) => { + if (error.code) { + console.log('formHost notifyFormsVisible, error:' + JSON.stringify(error)); + } +}); +``` + +## notifyFormsVisible + +notifyFormsVisible(formIds: Array<string>, isVisible: boolean): Promise<void> + +Instructs the widgets to make themselves visible. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| +| isVisible | boolean | Yes | Whether to make the widgets visible.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +var formIds = new Array("12400633174999288", "12400633174999289"); +formHost.notifyFormsVisible(formIds, true).then(() => { + console.log('formHost notifyFormsVisible success'); +}).catch((error) => { + console.log('formHost notifyFormsVisible, error:' + JSON.stringify(error)); +}); +``` + +## notifyFormsEnableUpdate + +notifyFormsEnableUpdate(formIds: Array<string>, isEnableUpdate: boolean, callback: AsyncCallback<void>): void + +Instructs the widgets to enable or disable updates. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| +| isEnableUpdate | boolean | Yes | Whether to make the widgets updatable.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the notification is sent, **err** is undefined; otherwise, **err** is an error object.| + +**Example** + +```ts +var formIds = new Array("12400633174999288", "12400633174999289"); +formHost.notifyFormsEnableUpdate(formIds, true, (error, data) => { + if (error.code) { + console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); + } +}); +``` + +## notifyFormsEnableUpdate + +notifyFormsEnableUpdate(formIds: Array<string>, isEnableUpdate: boolean): Promise<void> + +Instructs the widgets to enable or disable updates. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formIds | Array<string> | Yes | List of widget IDs.| + | isEnableUpdate | boolean | Yes | Whether to make the widgets updatable.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise that returns no value.| + +**Example** + +```ts +var formIds = new Array("12400633174999288", "12400633174999289"); +formHost.notifyFormsEnableUpdate(formIds, true).then(() => { + console.log('formHost notifyFormsEnableUpdate success'); +}).catch((error) => { + console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); +}); +``` +## shareForm9+ + +shareForm(formId: string, deviceId: string, callback: AsyncCallback<void>): void + +Shares a specified widget with a remote device. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| +| deviceId | string | Yes | Remote device ID.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is shared, **err** is undefined; otherwise, **err** is an error object.| + +**Example** + +```ts +var formId = "12400633174999288"; +var deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; +formHost.shareForm(formId, deviceId, (error, data) => { + if (error.code) { + console.log('formHost shareForm, error:' + JSON.stringify(error)); + } +}); +``` + +## shareForm9+ + +shareForm(formId: string, deviceId: string): Promise<void> + +Shares a specified widget with a remote device. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| +| deviceId | string | Yes | Remote device ID.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Parameters** + +```ts +var formId = "12400633174999288"; +var deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; +formHost.shareForm(formId, deviceId).then(() => { + console.log('formHost shareForm success'); +}).catch((error) => { + console.log('formHost shareForm, error:' + JSON.stringify(error)); +}); +``` + +## notifyFormsPrivacyProtected9+ + +notifyFormsPrivacyProtected(formIds: Array\, isProtected: boolean, callback: AsyncCallback\): void + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| +| deviceId | string | Yes | Remote device ID.| + +```ts +var formIds = new Array("12400633174999288", "12400633174999289"); +formHost.notifyFormsPrivacyProtected(formIds, true).then(() => { + console.log('formHost shareForm success'); +}).catch((error) => { + console.log('formHost shareForm, error:' + JSON.stringify(error)); +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-application-formInfo.md b/en/application-dev/reference/apis/js-apis-application-formInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..de5bd8f6b24e7bd1f6e3fe66b4f4122c9a570d16 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-application-formInfo.md @@ -0,0 +1,152 @@ +# @ohos.application.formInfo + +The **FormInfo** module provides widget information and state. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> This module is deprecated since API version 9. You are advised to use [FormInfo](js-apis-app-form-formInfo.md) instead. + +## Modules to Import + +```ts +import formInfo from '@ohos.application.formInfo'; +``` + +## FormInfo + +Describes widget information. + +**System capability**: SystemCapability.Ability.Form + +| Name | Type | Readable | Writable | Description | +| ----------- | -------- |-------- | -------------------- | ------------------------------------------------------------ | +| bundleName | string | Yes | No | Name of the bundle to which the widget belongs. | +| moduleName | string | Yes | No | Name of the module to which the widget belongs. | +| abilityName | string | Yes | No | Name of the ability to which the widget belongs. | +| name | string | Yes | No | Widget name. | +| description | string | Yes | No | Description of the widget. | +| type | [FormType](#formtype) | Yes | No | Type of the widget. Currently, only JS widgets are supported.| +| jsComponentName | string | Yes | No | Name of the component used in the JS widget. | +| colorMode | [ColorMode](#colormode) | Yes | No | Color mode of the widget. | +| isDefault | boolean | Yes | No | Whether the widget is the default one. | +| updateEnabled | boolean | Yes | No | Whether the widget is updatable. | +| formVisibleNotify | string | Yes | No | Whether to send a notification when the widget is visible. | +| relatedBundleName | string | Yes | No | Name of the associated bundle to which the widget belongs. | +| scheduledUpdateTime | string | Yes | No | Time when the widget was updated. | +| formConfigAbility | string | Yes | No | Configuration ability of the widget. | +| updateDuration | string | Yes | No | Update period of the widget.| +| defaultDimension | number | Yes | No | Default dimension of the widget. | +| supportDimensions | Array<number> | Yes | No | Dimensions supported by the widget. | +| customizeData | {[key: string]: [value: string]} | Yes | No | Custom data of the widget. | + +## FormType + +Enumerates the widget types. + +**System capability**: SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| JS | 1 | JS widget. | +| eTS9+ | 2 | eTS widget.| + +## ColorMode + +Enumerates the color modes supported by the widget. + +**System capability**: SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| MODE_AUTO | -1 | Auto mode. | +| MODE_DARK | 0 | Dark mode. | +| MODE_LIGHT | 1 | Light mode. | + +## FormStateInfo + +Describes the widget state information. + +**System capability**: SystemCapability.Ability.Form + +| Name | Type | Readable | Writable | Description | +| ----------- | -------- |-------- | -------------------- | ------------------------------------------------------------ | +| formState | [FormState](#formstate) | Yes | No | Widget state. | +| want | Want | Yes | No | Want text. | + +## FormState + +Enumerates the widget states. + +**System capability**: SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| UNKNOWN | -1 | Unknown state. | +| DEFAULT | 0 | Default state. | +| READY | 1 | Ready state. | + +## FormParam + +Enumerates the widget parameters. + +**System capability**: SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| IDENTITY_KEY9+ | "ohos.extra.param.key.form_identity" | Widget ID.
**System API**: This is a system API. | +| DIMENSION_KEY | "ohos.extra.param.key.form_dimension" | Widget dimension. | +| NAME_KEY | "ohos.extra.param.key.form_name" | Widget name. | +| MODULE_NAME_KEY | "ohos.extra.param.key.module_name" | Name of the module to which the widget belongs. | +| WIDTH_KEY | "ohos.extra.param.key.form_width" | Widget width. | +| HEIGHT_KEY | "ohos.extra.param.key.form_height" | Widget height. | +| TEMPORARY_KEY | "ohos.extra.param.key.form_temporary" | Temporary widget. | +| ABILITY_NAME_KEY9+ | "ohos.extra.param.key.ability_name" | Ability name. | +| DEVICE_ID_KEY9+ | "ohos.extra.param.key.device_id" | Device ID.
**System API**: This is a system API. | +| BUNDLE_NAME_KEY9+ | "ohos.extra.param.key.bundle_name" | Key that specifies the target bundle name.| + +## FormDimension9+ + +Enumerates the widget dimensions. + +**System capability**: SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| Dimension_1_2 9+ | 1 | 1 x 2. | +| Dimension_2_2 9+ | 2 | 2 x 2. | +| Dimension_2_4 9+ | 3 | 2 x 4. | +| Dimension_4_4 9+ | 4 | 4 x 4. | +| Dimension_2_1 9+ | 5 | 2 x 1. | + +## VisibilityType + +Enumerates the visibility types of the widget. + +**System capability**: SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| FORM_VISIBLE9+ | 1 | The card is visible. | +| FORM_INVISIBLE9+ | 2 | The card is invisible.| + +## FormInfoFilter9+ + +Defines the widget information filter. Only the widget information that meets the filter is returned. + +**System capability**: SystemCapability.Ability.Form + +| Name | Description | +| ----------- | ------------ | +| moduleName9+ | Only the information about the widget whose **moduleName** is the same as the provided value is returned.| + +## VisibilityType9+ + +Enumerates the visibility types of the widget. + +**System capability**: SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| FORM_VISIBLE9+ | 1 | The widget is visible.| +| FORM_INVISIBLE9+ | 2 | The widget is invisible.| diff --git a/en/application-dev/reference/apis/js-apis-formprovider.md b/en/application-dev/reference/apis/js-apis-application-formProvider.md similarity index 74% rename from en/application-dev/reference/apis/js-apis-formprovider.md rename to en/application-dev/reference/apis/js-apis-application-formProvider.md index 8ce539886e5460ffe712b486addf6e3813c44a90..05318bda39a220c15a328368fd5bf54c29f0ad05 100644 --- a/en/application-dev/reference/apis/js-apis-formprovider.md +++ b/en/application-dev/reference/apis/js-apis-application-formProvider.md @@ -1,42 +1,36 @@ -# FormProvider +# @ohos.application.formProvider The **FormProvider** module provides APIs related to the widget provider. You can use the APIs to update a widget, set the next refresh time for a widget, obtain widget information, and request a widget release. > **NOTE** -> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> This module is deprecated since API version 9. You are advised to use [FormProvider](js-apis-app-form-formProvider.md) instead. ## Modules to Import -``` +```ts import formProvider from '@ohos.application.formProvider'; ``` -## Required Permissions - -None. - ## setFormNextRefreshTime -setFormNextRefreshTime(formId: string, minute: number, callback: AsyncCallback<void>): void; +setFormNextRefreshTime(formId: string, minute: number, callback: AsyncCallback<void>): void Sets the next refresh time for a widget. This API uses an asynchronous callback to return the result. -**System capability** - -SystemCapability.Ability.Form +**System capability**: SystemCapability.Ability.Form **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------- | - | formId | string | Yes | ID of a widget. | + | formId | string | Yes | Widget ID. | | minute | number | Yes | Refresh interval, in minutes. The value must be greater than or equal to 5. | | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** - ```js + ```ts var formId = "12400633174999288"; formProvider.setFormNextRefreshTime(formId, 5, (error, data) => { if (error.code) { @@ -47,30 +41,28 @@ SystemCapability.Ability.Form ## setFormNextRefreshTime -setFormNextRefreshTime(formId: string, minute: number): Promise<void>; +setFormNextRefreshTime(formId: string, minute: number): Promise<void> Sets the next refresh time for a widget. This API uses a promise to return the result. -**System capability** - -SystemCapability.Ability.Form +**System capability**: SystemCapability.Ability.Form **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------- | - | formId | string | Yes | ID of a widget. | + | formId | string | Yes | Widget ID. | | minute | number | Yes | Refresh interval, in minutes. The value must be greater than or equal to 5. | **Return value** | Type | Description | | ------------- | ---------------------------------- | - | Promise\ |Promise used to return the result. | + | Promise\ | Promise that returns no value. | **Example** - ```js + ```ts var formId = "12400633174999288"; formProvider.setFormNextRefreshTime(formId, 5).then(() => { console.log('formProvider setFormNextRefreshTime success'); @@ -81,25 +73,23 @@ SystemCapability.Ability.Form ## updateForm -updateForm(formId: string, formBindingData: formBindingData.FormBindingData,callback: AsyncCallback<void>): void; +updateForm(formId: string, formBindingData: formBindingData.FormBindingData,callback: AsyncCallback<void>): void Updates a widget. This API uses an asynchronous callback to return the result. -**System capability** - -SystemCapability.Ability.Form +**System capability**: SystemCapability.Ability.Form **Parameters** | Name| Type | Mandatory| Description | | ------ | ---------------------------------------------------------------------- | ---- | ---------------- | | formId | string | Yes | ID of the widget to update.| - | formBindingData | [FormBindingData](js-apis-formbindingdata.md#formbindingdata) | Yes | Data to be used for the update. | + | formBindingData.FormBindingData | [FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | Yes | Data to be used for the update. | | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** - ```js + ```ts import formBindingData from '@ohos.application.formBindingData'; var formId = "12400633174999288"; let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); @@ -112,30 +102,28 @@ SystemCapability.Ability.Form ## updateForm -updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Promise<void>; +updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Promise<void> Updates a widget. This API uses a promise to return the result. -**System capability** - -SystemCapability.Ability.Form +**System capability**: SystemCapability.Ability.Form **Parameters** | Name| Type | Mandatory| Description | | ------ | ---------------------------------------------------------------------- | ---- | ---------------- | | formId | string | Yes | ID of the widget to update.| - | formBindingData | [FormBindingData](js-apis-formbindingdata.md#formbindingdata) | Yes | Data to be used for the update. | + | formBindingData.FormBindingData | [FormBindingData](js-apis-application-formBindingData.md#formbindingdat) | Yes | Data to be used for the update. | **Return value** | Type | Description | | -------------- | ----------------------------------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise that returns no value.| **Example** - ```js + ```ts import formBindingData from '@ohos.application.formBindingData'; var formId = "12400633174999288"; let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); @@ -148,7 +136,7 @@ SystemCapability.Ability.Form ## getFormsInfo9+ -getFormsInfo(callback: AsyncCallback<Array<formInfo.FormInfo>>): void; +getFormsInfo(callback: AsyncCallback<Array<formInfo.FormInfo>>): void Obtains the application's widget information on the device. This API uses an asynchronous callback to return the result. @@ -158,11 +146,11 @@ Obtains the application's widget information on the device. This API uses an asy | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| callback | AsyncCallback<Array<[FormInfo](./js-apis-formInfo.md#forminfo-1)>> | Yes| Callback used to return the widget information.| +| callback | AsyncCallback<Array<[FormInfo](./js-apis-application-formInfo.md#forminfo-1)>> | Yes| Callback used to return the information obtained.| **Example** -```js +```ts formProvider.getFormsInfo((error, data) => { if (error.code) { console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); @@ -173,7 +161,7 @@ formProvider.getFormsInfo((error, data) => { ``` ## getFormsInfo9+ -getFormsInfo(filter: formInfo.FormInfoFilter, callback: AsyncCallback<Array<formInfo.FormInfo>>): void; +getFormsInfo(filter: formInfo.FormInfoFilter, callback: AsyncCallback<Array<formInfo.FormInfo>>): void Obtains the application's widget information that meets a filter criterion on the device. This API uses an asynchronous callback to return the result. @@ -183,14 +171,15 @@ Obtains the application's widget information that meets a filter criterion on th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| filter | [formInfo.FormInfoFilter](./js-apis-formInfo.md#forminfofilter) | Yes| Filter criterion.| -| callback | AsyncCallback<Array<[FormInfo](./js-apis-formInfo.md#forminfo-1)>> | Yes| Callback used to return the widget information.| +| filter | [formInfo.FormInfoFilter](./js-apis-application-formInfo.md#forminfofilter) | Yes| Filter criterion.| +| callback | AsyncCallback<Array<[FormInfo](./js-apis-application-formInfo.md#forminfo-1)>> | Yes| Callback used to return the information obtained.| **Example** -```js +```ts import formInfo from '@ohos.application.formInfo'; const filter : formInfo.FormInfoFilter = { + // get info of forms belong to module entry. moduleName : "entry" }; formProvider.getFormsInfo(filter, (error, data) => { @@ -204,7 +193,7 @@ formProvider.getFormsInfo(filter, (error, data) => { ## getFormsInfo9+ -getFormsInfo(filter?: formInfo.FormInfoFilter): Promise<Array<formInfo.FormInfo>>; +getFormsInfo(filter?: formInfo.FormInfoFilter): Promise<Array<formInfo.FormInfo>> Obtains the application's widget information on the device. This API uses a promise to return the result. @@ -214,19 +203,20 @@ Obtains the application's widget information on the device. This API uses a prom | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| filter | [formInfo.FormInfoFilter](./js-apis-formInfo.md) | No| Filter criterion.| +| filter | [formInfo.FormInfoFilter](./js-apis-application-formInfo.md) | No| Filter criterion.| **Return value** | Type | Description | | :------------ | :---------------------------------- | -| Promise<Array<[FormInfo](./js-apis-formInfo.md#forminfo-1)>> | Promise used to return the widget information.| +| Promise<Array<[FormInfo](./js-apis-application-formInfo.md#forminfo-1)>> | Promise used to return the information obtained.| **Example** -```js +```ts import formInfo from '@ohos.application.formInfo'; const filter : formInfo.FormInfoFilter = { + // get info of forms belong to module entry. moduleName : "entry" }; formProvider.getFormsInfo(filter).then((data) => { @@ -238,25 +228,25 @@ formProvider.getFormsInfo(filter).then((data) => { ## requestPublishForm9+ -requestPublishForm(want: Want, formBindingData: formBindingData.FormBindingData, callback: AsyncCallback\): void; +requestPublishForm(want: Want, formBindingData: formBindingData.FormBindingData, callback: AsyncCallback\): void -Requests to publish a widget carrying data to the widget host. This API uses an asynchronous callback to return the result. +Requests to publish a widget carrying data to the widget host. This API uses an asynchronous callback to return the result. This API is usually called by the home screen. **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** | Name| Type | Mandatory| Description | | ------ | ---------------------------------------------------------------------- | ---- | ---------------- | -| want | [Want](js-apis-application-Want.md) | Yes | Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | -| formBindingData | [FormBindingData](js-apis-formbindingdata.md#formbindingdata) | Yes | Data used for creating the widget.| +| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | +| formBindingData.FormBindingData | [FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | Yes | Data used for creating the widget.| | callback | AsyncCallback<string> | Yes| Callback used to return the widget ID.| **Example** - ```js + ```ts import formBindingData from '@ohos.application.formBindingData'; var want = { abilityName: "FormAbility", @@ -278,24 +268,24 @@ Requests to publish a widget carrying data to the widget host. This API uses an ## requestPublishForm9+ -requestPublishForm(want: Want, callback: AsyncCallback<string>): void; +requestPublishForm(want: Want, callback: AsyncCallback<string>): void -Requests to publish a widget to the widget host. This API uses an asynchronous callback to return the result. +Requests to publish a widget to the widget host. This API uses an asynchronous callback to return the result. This API is usually called by the home screen. **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------------------- | ---- | ------------------------------------------------------------ | -| want | [Want](js-apis-application-Want.md) | Yes | Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | -| callback | AsyncCallback<string> | Yes | Callback used to return the widget ID. | +| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | +| callback | AsyncCallback<string> | Yes | Callback used to return the widget ID.| **Example** - ```js + ```ts var want = { abilityName: "FormAbility", parameters: { @@ -315,20 +305,20 @@ Requests to publish a widget to the widget host. This API uses an asynchronous c ## requestPublishForm9+ -requestPublishForm(want: Want, formBindingData?: formBindingData.FormBindingData): Promise<string>; +requestPublishForm(want: Want, formBindingData?: formBindingData.FormBindingData): Promise<string> -Requests to publish a widget to the widget host. This API uses a promise to return the result. +Requests to publish a widget to the widget host. This API uses a promise to return the result. This API is usually called by the home screen. **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** | Name | Type | Mandatory| Description | | --------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| want | [Want](js-apis-application-Want.md) | Yes | Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | -| formBindingData | [FormBindingData](js-apis-formbindingdata.md#formbindingdata) | No | Data used for creating the widget. | +| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | +| formBindingData.FormBindingData | [FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | No | Data used for creating the widget. | **Return value** @@ -338,7 +328,7 @@ Requests to publish a widget to the widget host. This API uses a promise to retu **Example** - ```js + ```ts var want = { abilityName: "FormAbility", parameters: { @@ -356,23 +346,23 @@ Requests to publish a widget to the widget host. This API uses a promise to retu ## isRequestPublishFormSupported9+ -isRequestPublishFormSupported(callback: AsyncCallback<boolean>): void; +isRequestPublishFormSupported(callback: AsyncCallback<boolean>): void Checks whether a widget can be published to the widget host. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Ability.Form +**System API**: This is a system API. -**System API**: This is a system API and cannot be called by third-party applications. +**System capability**: SystemCapability.Ability.Form **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| +| callback | AsyncCallback<boolean> | Yes| Callback used to return whether the widget can be published to the widget host.| **Example** -```js +```ts formProvider.isRequestPublishFormSupported((error, isSupported) => { if (error.code) { console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error)); @@ -400,23 +390,23 @@ formProvider.isRequestPublishFormSupported((error, isSupported) => { ## isRequestPublishFormSupported9+ -isRequestPublishFormSupported(): Promise<boolean>; +isRequestPublishFormSupported(): Promise<boolean> Checks whether a widget can be published to the widget host. This API uses a promise to return the result. -**System capability**: SystemCapability.Ability.Form +**System API**: This is a system API. -**System API**: This is a system API and cannot be called by third-party applications. +**System capability**: SystemCapability.Ability.Form **Return value** | Type | Description | | :------------ | :---------------------------------- | -| Promise<boolean> | Promise used to return the result.| +| Promise<boolean> | Promise used to return whether the widget can be published to the widget host.| **Example** -```js +```ts formProvider.isRequestPublishFormSupported().then((isSupported) => { if (isSupported) { var want = { diff --git a/en/application-dev/reference/apis/js-apis-missionManager.md b/en/application-dev/reference/apis/js-apis-application-missionManager.md similarity index 84% rename from en/application-dev/reference/apis/js-apis-missionManager.md rename to en/application-dev/reference/apis/js-apis-application-missionManager.md index 189042b1f1df1727423c65c0a226b11ae473db2a..c30dda422ded7148e35ebab1cc26804290bc1ea6 100644 --- a/en/application-dev/reference/apis/js-apis-missionManager.md +++ b/en/application-dev/reference/apis/js-apis-application-missionManager.md @@ -1,4 +1,4 @@ -# missionManager +# @ohos.application.missionManager The **missionManager** module provides APIs to lock, unlock, and clear missions, and switch a mission to the foreground. @@ -8,7 +8,7 @@ The **missionManager** module provides APIs to lock, unlock, and clear missions, ## Modules to Import -``` +```ts import missionManager from '@ohos.application.missionManager' ``` @@ -22,7 +22,7 @@ registerMissionListener(listener: MissionListener): number; Registers a listener to observe the mission status. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -32,7 +32,7 @@ Registers a listener to observe the mission status. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | listener | MissionListener | Yes| Listener to register.| + | listener | [MissionListener](js-apis-inner-application-missionListener.md) | Yes| Listener to register.| **Return value** @@ -42,17 +42,18 @@ Registers a listener to observe the mission status. **Example** -```js - var listener = { - onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, - onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, - onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, - onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, - onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, - onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")} - }; - console.log("registerMissionListener") - var listenerid = missionManager.registerMissionListener(listener); +```ts +var listener = { + onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, + onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, + onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, + onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, + onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, + onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}, + onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} +}; +console.log("registerMissionListener") +var listenerid = missionManager.registerMissionListener(listener); ``` @@ -62,7 +63,7 @@ unregisterMissionListener(listenerId: number, callback: AsyncCallback<void> Deregisters a mission status listener. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -77,14 +78,15 @@ Deregisters a mission status listener. This API uses an asynchronous callback to **Example** -```js +```ts var listener = { onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, - onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")} + onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}, + onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} }; console.log("registerMissionListener") var listenerid = missionManager.registerMissionListener(listener); @@ -101,7 +103,7 @@ unregisterMissionListener(listenerId: number): Promise<void>; Deregisters a mission status listener. This API uses a promise to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -121,14 +123,15 @@ Deregisters a mission status listener. This API uses a promise to return the res **Example** -```js +```ts var listener = { onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, - onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")} + onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}, + onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} }; console.log("registerMissionListener") var listenerid = missionManager.registerMissionListener(listener); @@ -145,7 +148,7 @@ getMissionInfo(deviceId: string, missionId: number, callback: AsyncCallback<M Obtains the information about a given mission. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -157,11 +160,11 @@ Obtains the information about a given mission. This API uses an asynchronous cal | -------- | -------- | -------- | -------- | | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| | missionId | number | Yes| Mission ID.| - | callback | AsyncCallback<[MissionInfo](#missioninfo)> | Yes| Callback used to return the mission information obtained.| + | callback | AsyncCallback<[MissionInfo](js-apis-inner-application-missionInfo.md)> | Yes| Callback used to return the mission information obtained.| **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' var allMissions=missionManager.getMissionInfos("",10).catch(function(err){console.log(err);}); @@ -183,7 +186,7 @@ getMissionInfo(deviceId: string, missionId: number): Promise<MissionInfo>; Obtains the information about a given mission. This API uses a promise to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -200,11 +203,11 @@ Obtains the information about a given mission. This API uses a promise to return | Type| Description| | -------- | -------- | - | Promise<[MissionInfo](#missioninfo)> | Promise used to return the mission information obtained.| + | Promise<[MissionInfo](js-apis-inner-application-missionInfo.md)> | Promise used to return the mission information obtained.| **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' var mission = missionManager.getMissionInfo("", 10).catch(function (err){ @@ -219,7 +222,7 @@ getMissionInfos(deviceId: string, numMax: number, callback: AsyncCallback<Arr Obtains information about all missions. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -231,11 +234,11 @@ Obtains information about all missions. This API uses an asynchronous callback t | -------- | -------- | -------- | -------- | | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| | numMax | number | Yes| Maximum number of missions whose information can be obtained.| - | callback | AsyncCallback<Array<[MissionInfo](#missioninfo)>> | Yes| Callback used to return the array of mission information obtained.| + | callback | AsyncCallback<Array<[MissionInfo](js-apis-inner-application-missionInfo.md)>> | Yes| Callback used to return the array of mission information obtained.| **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' missionManager.getMissionInfos("", 10, (error, missions) => { @@ -252,7 +255,7 @@ getMissionInfos(deviceId: string, numMax: number): Promise<Array<MissionIn Obtains information about all missions. This API uses a promise to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -269,11 +272,11 @@ Obtains information about all missions. This API uses a promise to return the re | Type| Description| | -------- | -------- | - | Promise<Array<[MissionInfo](#missioninfo)>> | Promise used to return the array of mission information obtained.| + | Promise<Array<[MissionInfo](js-apis-inner-application-missionInfo.md)>> | Promise used to return the array of mission information obtained.| **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' var allMissions = missionManager.getMissionInfos("", 10).catch(function (err){ @@ -288,7 +291,7 @@ getMissionSnapShot(deviceId: string, missionId: number, callback: AsyncCallback& Obtains the snapshot of a given mission. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -300,11 +303,11 @@ Obtains the snapshot of a given mission. This API uses an asynchronous callback | -------- | -------- | -------- | -------- | | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| | missionId | number | Yes| Mission ID.| - | callback | AsyncCallback<[MissionSnapshot](js-apis-application-MissionSnapshot.md)> | Yes| Callback used to return the snapshot information obtained.| + | callback | AsyncCallback<[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)> | Yes| Callback used to return the snapshot information obtained.| **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' missionManager.getMissionInfos("", 10, (error, missions) => { @@ -327,7 +330,7 @@ getMissionSnapShot(deviceId: string, missionId: number): Promise<MissionSnaps Obtains the snapshot of a given mission. This API uses a promise to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -344,11 +347,11 @@ Obtains the snapshot of a given mission. This API uses a promise to return the r | Type| Description| | -------- | -------- | - | Promise<[MissionSnapshot](js-apis-application-MissionSnapshot.md)> | Promise used to return the snapshot information obtained.| + | Promise<[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)> | Promise used to return the snapshot information obtained.| **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' var allMissions; @@ -370,7 +373,7 @@ getLowResolutionMissionSnapShot(deviceId: string, missionId: number, callback: A Obtains the low-resolution snapshot of a given mission. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -382,11 +385,11 @@ Obtains the low-resolution snapshot of a given mission. This API uses an asynchr | -------- | -------- | -------- | -------- | | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| | missionId | number | Yes| Mission ID.| - | callback | AsyncCallback<[MissionSnapshot](js-apis-application-MissionSnapshot.md)> | Yes| Callback used to return the snapshot information obtained.| + | callback | AsyncCallback<[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)> | Yes| Callback used to return the snapshot information obtained.| **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' missionManager.getMissionInfos("", 10, (error, missions) => { @@ -409,7 +412,7 @@ getLowResolutionMissionSnapShot(deviceId: string, missionId: number): Promise\ { @@ -490,7 +493,7 @@ lockMission(missionId: number): Promise<void>; Locks a given mission. This API uses a promise to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -510,7 +513,7 @@ Locks a given mission. This API uses a promise to return the result. **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' var allMissions; missionManager.getMissionInfos("",10).then(function(res){ @@ -532,7 +535,7 @@ unlockMission(missionId: number, callback: AsyncCallback<void>): void; Unlocks a given mission. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -547,7 +550,7 @@ Unlocks a given mission. This API uses an asynchronous callback to return the re **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' missionManager.getMissionInfos("", 10, (error, missions) => { @@ -569,7 +572,7 @@ unlockMission(missionId: number): Promise<void>; Unlocks a given mission. This API uses a promise to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -589,7 +592,7 @@ Unlocks a given mission. This API uses a promise to return the result. **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' var allMissions; @@ -615,7 +618,7 @@ clearMission(missionId: number, callback: AsyncCallback<void>): void; Clears a given mission, regardless of whether it is locked. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -630,7 +633,7 @@ Clears a given mission, regardless of whether it is locked. This API uses an asy **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' missionManager.getMissionInfos("", 10, (error, missions) => { @@ -652,7 +655,7 @@ clearMission(missionId: number): Promise<void>; Clears a given mission, regardless of whether it is locked. This API uses a promise to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -672,7 +675,7 @@ Clears a given mission, regardless of whether it is locked. This API uses a prom **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' var allMissions; @@ -695,7 +698,7 @@ clearAllMissions(callback: AsyncCallback<void>): void; Clears all unlocked missions. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -703,7 +706,7 @@ Clears all unlocked missions. This API uses an asynchronous callback to return t **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' missionManager.clearAllMissions().then(() => { @@ -718,7 +721,7 @@ clearAllMissions(): Promise<void>; Clears all unlocked missions. This API uses a promise to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -732,7 +735,7 @@ Clears all unlocked missions. This API uses a promise to return the result. **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' missionManager.clearAllMissions().catch(function (err){ console.log(err); @@ -746,7 +749,7 @@ moveMissionToFront(missionId: number, callback: AsyncCallback<void>): void Switches a given mission to the foreground. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -761,7 +764,7 @@ Switches a given mission to the foreground. This API uses an asynchronous callba **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' missionManager.getMissionInfos("", 10, (error, missions) => { @@ -783,7 +786,7 @@ moveMissionToFront(missionId: number, options: StartOptions, callback: AsyncCall Switches a given mission to the foreground, with the startup parameters for the switching specified. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -794,12 +797,12 @@ Switches a given mission to the foreground, with the startup parameters for the | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | missionId | number | Yes| Mission ID.| - | options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.| + | options | [StartOptions](js-apis-application-startOptions.md) | Yes| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' missionManager.getMissionInfos("", 10, (error, missions) => { @@ -821,7 +824,7 @@ moveMissionToFront(missionId: number, options?: StartOptions): Promise<void&g Switches a given mission to the foreground, with the startup parameters for the switching specified. This API uses a promise to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -832,7 +835,7 @@ Switches a given mission to the foreground, with the startup parameters for the | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | missionId | number | Yes| Mission ID.| - | options | [StartOptions](js-apis-application-StartOptions.md) | No| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.| + | options | [StartOptions](js-apis-application-startOptions.md) | No| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.| **Return value** @@ -842,7 +845,7 @@ Switches a given mission to the foreground, with the startup parameters for the **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' var allMissions; @@ -857,22 +860,3 @@ Switches a given mission to the foreground, with the startup parameters for the console.log(err); }); ``` - -## MissionInfo - -Describes the mission information. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Mission - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| missionId | number | Yes| Yes| Mission ID.| -| runningState | number | Yes| Yes| Running state of the mission.| -| lockedState | boolean | Yes| Yes| Locked state of the mission.| -| timestamp | string | Yes| Yes| Latest time when the mission was created or updated.| -| want | [Want](js-apis-application-Want.md) | Yes| Yes| **Want** information of the mission.| -| label | string | Yes| Yes| Label of the mission.| -| iconPath | string | Yes| Yes| Path of the mission icon.| -| continuable | boolean | Yes| Yes| Whether the mission can be continued on another device.| diff --git a/en/application-dev/reference/apis/js-apis-service-extension-ability.md b/en/application-dev/reference/apis/js-apis-application-serviceExtensionAbility.md similarity index 81% rename from en/application-dev/reference/apis/js-apis-service-extension-ability.md rename to en/application-dev/reference/apis/js-apis-application-serviceExtensionAbility.md index 388b4308555f8dc061bfa62da40fd4dc5d97cfee..ba59d9a6ea78434939ee99a6e25b3c2945874532 100644 --- a/en/application-dev/reference/apis/js-apis-service-extension-ability.md +++ b/en/application-dev/reference/apis/js-apis-application-serviceExtensionAbility.md @@ -1,4 +1,4 @@ -# ServiceExtensionAbility +# @ohos.application.ServiceExtensionAbility The **ServiceExtensionAbility** module provides APIs for Service Extension abilities. @@ -9,8 +9,8 @@ The **ServiceExtensionAbility** module provides APIs for Service Extension abili ## Modules to Import -``` -import ServiceExtension from '@ohos.application.ServiceExtensionAbility'; +```ts +import ServiceExtensionAbility from '@ohos.application.ServiceExtensionAbility'; ``` ## Required Permissions @@ -25,7 +25,7 @@ None. | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| context | [ServiceExtensionContext](js-apis-service-extension-context.md) | Yes| No| Service Extension context, which is inherited from **ExtensionContext**.| +| context | [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) | Yes| No| Service Extension context, which is inherited from **ExtensionContext**.| ## ServiceExtensionAbility.onCreate @@ -42,11 +42,11 @@ Called when a Service Extension ability is created to initialize the service log | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | Yes| Information related to this Service Extension ability, including the ability name and bundle name.| + | want | [Want](js-apis-application-want.md) | Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| **Example** - ```js + ```ts class ServiceExt extends ServiceExtension { onCreate(want) { console.log('onCreate, want:' + want.abilityName); @@ -67,7 +67,7 @@ Called when this Service Extension ability is destroyed to clear resources. **Example** - ```js + ```ts class ServiceExt extends ServiceExtension { onDestroy() { console.log('onDestroy'); @@ -90,12 +90,12 @@ Called after **onCreate** is invoked when a Service Extension ability is started | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | Yes| Information related to this Service Extension ability, including the ability name and bundle name.| + | want | [Want](js-apis-application-want.md) | Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| | startId | number | Yes| Number of ability start times. The initial value is **1**, and the value is automatically incremented for each ability started.| **Example** - ```js + ```ts class ServiceExt extends ServiceExtension { onRequest(want, startId) { console.log('onRequest, want:' + want.abilityName); @@ -118,7 +118,7 @@ Called after **onCreate** is invoked when a Service Extension ability is started | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md)| Yes| Information related to this Service Extension ability, including the ability name and bundle name.| + | want | [Want](js-apis-application-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| **Return value** @@ -128,7 +128,7 @@ Called after **onCreate** is invoked when a Service Extension ability is started **Example** - ```js + ```ts import rpc from '@ohos.rpc' class StubTest extends rpc.RemoteObject{ constructor(des) { @@ -160,11 +160,11 @@ Called when this Service Extension ability is disconnected. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | want |[Want](js-apis-application-Want.md)| Yes| Information related to this Service Extension ability, including the ability name and bundle name.| + | want |[Want](js-apis-application-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| **Example** - ```js + ```ts class ServiceExt extends ServiceExtension { onDisconnect(want) { console.log('onDisconnect, want:' + want.abilityName); @@ -186,11 +186,11 @@ Called when this Service Extension ability is reconnected. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | want |[Want](js-apis-application-Want.md)| Yes| Information related to this Service Extension ability, including the ability name and bundle name.| + | want |[Want](js-apis-application-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| **Example** - ```js + ```ts class ServiceExt extends ServiceExtension { onReconnect(want) { console.log('onReconnect, want:' + want.abilityName); @@ -202,7 +202,7 @@ Called when this Service Extension ability is reconnected. onConfigurationUpdated(config: Configuration): void; - Called when the configuration of this Service Extension ability is updated. +Called when the configuration of this Service Extension ability is updated. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -212,11 +212,11 @@ onConfigurationUpdated(config: Configuration): void; | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | config | [Configuration](js-apis-configuration.md) | Yes| New configuration.| + | config | [Configuration](js-apis-application-configuration.md) | Yes| New configuration.| **Example** - ```js + ```ts class ServiceExt extends ServiceExtension { onConfigurationUpdated(config) { console.log('onConfigurationUpdated, config:' + JSON.stringify(config)); @@ -242,7 +242,7 @@ Dumps the client information. **Example** - ```js + ```ts class ServiceExt extends ServiceExtension { dump(params) { console.log('dump, params:' + JSON.stringify(params)); diff --git a/en/application-dev/reference/apis/js-apis-application-startOptions.md b/en/application-dev/reference/apis/js-apis-application-startOptions.md new file mode 100644 index 0000000000000000000000000000000000000000..40ad2a516377faf476cfe688914afe3cd3eccb6c --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-application-startOptions.md @@ -0,0 +1,23 @@ +# @ohos.application.StartOptions + +The **StartOptions** module implements ability startup options. + +> **NOTE** +> +> The APIs of this module are supported and deprecated since API version 9. You are advised to use [@ohos.app.ability.StartOptions](js-apis-app-ability-startOptions.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the stage model. + +## Modules to Import + +```ts +import StartOptions from '@ohos.application.StartOptions'; +``` + +## Attributes + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| [windowMode](js-apis-application-abilityConstant.md#abilityconstantwindowmode) | number | No| Window mode.| +| displayId | number | No| Display ID.| diff --git a/en/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md index 57a313f1f600607c143aaec48205a482221ba355..b9086a6ce6cbd42c53730baa1531255c0d383ba9 100644 --- a/en/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md @@ -1,4 +1,4 @@ -# StaticSubscriberExtensionAbility +# @ohos.application.StaticSubscriberExtensionAbility The **StaticSubscriberExtensionAbility** module provides Extension abilities for static subscribers. @@ -8,7 +8,7 @@ The **StaticSubscriberExtensionAbility** module provides Extension abilities for > The APIs of this module can be used only in the stage model. ## Modules to Import -``` +```ts import StaticSubscriberExtensionAbility from '@ohos.application.StaticSubscriberExtensionAbility' ``` @@ -24,13 +24,12 @@ Callback of the common event of a static subscriber. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | event | [CommonEventData](js-apis-commonEvent.md#commoneventdata) | Yes| Common event of a static subscriber.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | [CommonEventData](js-apis-commonEvent.md#commoneventdata) | Yes| Common event of a static subscriber.| -**Example** - - ```js +**Example** + ```ts var StaticSubscriberExtensionAbility = requireNapi("application.StaticSubscriberExtensionAbility") { onReceiveEvent(event){ diff --git a/en/application-dev/reference/apis/js-apis-testRunner.md b/en/application-dev/reference/apis/js-apis-application-testRunner.md similarity index 95% rename from en/application-dev/reference/apis/js-apis-testRunner.md rename to en/application-dev/reference/apis/js-apis-application-testRunner.md index 403ec97e87bce272b6b4ee45568eb6a23590ab31..688774a0d4b840e19e398624be41ac85c07c8f37 100644 --- a/en/application-dev/reference/apis/js-apis-testRunner.md +++ b/en/application-dev/reference/apis/js-apis-application-testRunner.md @@ -1,4 +1,4 @@ -# TestRunner +# @ohos.application.testRunner The **TestRunner** module provides a test framework. You can use the APIs of this module to prepare the unit test environment and run test cases. @@ -10,7 +10,7 @@ To implement your own unit test framework, extend this class and override its AP ## Modules to Import -```js +```ts import TestRunner from '@ohos.application.testRunner' ``` @@ -24,7 +24,7 @@ Prepares the unit test environment to run test cases. **Example** -```js +```ts export default class UserTestRunner implements TestRunner { onPrepare() { console.log("Trigger onPrepare") @@ -45,7 +45,7 @@ Runs test cases. **Example** -```js +```ts export default class UserTestRunner implements TestRunner { onPrepare() {} onRun() { diff --git a/en/application-dev/reference/apis/js-apis-application-Want.md b/en/application-dev/reference/apis/js-apis-application-want.md similarity index 53% rename from en/application-dev/reference/apis/js-apis-application-Want.md rename to en/application-dev/reference/apis/js-apis-application-want.md index 9275473cd14727d8a3e8f16327d2020a1adefb4d..620885945b572e8129e4f8c61b156ef658a6805d 100644 --- a/en/application-dev/reference/apis/js-apis-application-Want.md +++ b/en/application-dev/reference/apis/js-apis-application-want.md @@ -1,14 +1,14 @@ -# Want +# @ohos.application.Want -The **Want** module provides the basic communication component of the system. +Want is a carrier for information transfer between objects (application components). Want can be used as a parameter of **startAbility** to specify a startup target and information that needs to be carried during startup, for example, **bundleName** and **abilityName**, which respectively indicate the bundle name of the target ability and the ability name in the bundle. When ability A needs to start ability B and transfer some data to ability B, it can use Want a carrier to transfer the data. > **NOTE** -> +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -``` +```ts import Want from '@ohos.application.Want'; ``` @@ -16,24 +16,24 @@ import Want from '@ohos.application.Want'; **System capability**: SystemCapability.Ability.AbilityBase -| Name | Readable/Writable| Type | Mandatory| Description | -| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | -| deviceId | Read only | string | No | ID of the device running the ability. | -| bundleName | Read only | string | No | Bundle name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability.| -| abilityName | Read only | string | No | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.| -| uri | Read only | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| -| type | Read only | string | No | MIME type, that is, the type of the file to open, for example, **text/xml** and **image/***. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com. | -| flags | Read only | number | No | How the **Want** object will be handled. For details, see [flags](js-apis-featureAbility.md#flags).| -| action | Read only | string | No | Action to take, such as viewing and sharing application details. In implicit **Want**, you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data. | -| parameters | Read only | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
**ohos.aafwk.callerPid**: PID of the caller.
**ohos.aafwk.param.callerToken**: token of the caller.
**ohos.aafwk.param.callerUid**: UID in [bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information. | -| entities | Read only | Array\ | No | Additional category information (such as browser and video player) of the target ability. It is a supplement to **action** in implicit **Want** and is used to filter ability types. | -| moduleName9+ | Read only | string | No | Module to which the ability belongs.| +| Name | Type | Mandatory| Description | +| ----------- | -------------------- | ---- | ------------------------------------------------------------ | +| deviceId | string | No | ID of the device running the ability. | +| bundleName | string | No | Bundle name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability.| +| abilityName | string | No | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.| +| uri | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| +| type | string | No | MIME type, that is, the type of the file to open, for example, **text/xml** and **image/***. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com. | +| flags | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-ability-wantConstant.md#wantConstant.Flags).| +| action | string | No | Action to take, such as viewing and sharing application details. In implicit **Want**, you can define this attribute and use it together with **uri** or **parameters** to specify the operation to be performed on the data. | +| parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
**ohos.aafwk.callerPid**: PID of the caller.
**ohos.aafwk.param.callerToken**: token of the caller.
**ohos.aafwk.param.callerUid**: UID in [bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information. | +| entities | Array\ | No | Additional category information (such as browser and video player) of the target ability. It is a supplement to **action** in implicit **Want** and is used to filter ability types. | +| moduleName9+ | string | No | Module to which the ability belongs.| **Example** - Basic usage - ``` js + ```ts var want = { "deviceId": "", // An empty deviceId indicates the local device. "bundleName": "com.extreme.test", diff --git a/en/application-dev/reference/apis/js-apis-application-windowExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-windowExtensionAbility.md index 0ee7099966ad5346598391bfe32c341a48d95536..882578cc316716db9f2f8a3c1d355e6a07b292db 100644 --- a/en/application-dev/reference/apis/js-apis-application-windowExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-windowExtensionAbility.md @@ -107,5 +107,3 @@ export default class MyWindowExtensionAbility extends WindowExtensionAbility { } ``` - - \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-appmanager.md b/en/application-dev/reference/apis/js-apis-appmanager.md deleted file mode 100644 index 3d93bdf33a527668c4c1c98ac4cfd8611ea9010a..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-appmanager.md +++ /dev/null @@ -1,1000 +0,0 @@ -# appManager - -The **appManager** module implements application management. You can use the APIs of this module to query whether the application is undergoing a stability test, whether the application is running on a RAM constrained device, the memory size of the application, and information about the running process. - -> **NOTE** -> -> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. - -## Modules to Import - -```js -import app from '@ohos.application.appManager'; -``` - -## appManager.isRunningInStabilityTest8+ - -static isRunningInStabilityTest(callback: AsyncCallback<boolean>): void - -Checks whether this application is undergoing a stability test. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | No| Callback used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| - -**Example** - - ```js - import app from '@ohos.application.appManager'; - app.isRunningInStabilityTest((err, flag) => { - console.log('startAbility result:' + JSON.stringify(err)); - }) - ``` - - -## appManager.isRunningInStabilityTest8+ - -static isRunningInStabilityTest(): Promise<boolean> - -Checks whether this application is undergoing a stability test. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| - -**Example** - - ```js - import app from '@ohos.application.appManager'; - app.isRunningInStabilityTest().then((flag) => { - console.log('success:' + JSON.stringify(flag)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - ``` - - -## appManager.isRamConstrainedDevice - -isRamConstrainedDevice(): Promise\; - -Checks whether this application is running on a RAM constrained device. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| - -**Example** - - ```js - app.isRamConstrainedDevice().then((data) => { - console.log('success:' + JSON.stringify(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - ``` - -## appManager.isRamConstrainedDevice - -isRamConstrainedDevice(callback: AsyncCallback\): void; - -Checks whether this application is running on a RAM constrained device. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | No| Callback used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| - -**Example** - - ```js - app.isRamConstrainedDevice((err, data) => { - console.log('startAbility result failed:' + JSON.stringify(err)); - console.log('startAbility result success:' + JSON.stringify(data)); - }) - ``` - -## appManager.getAppMemorySize - -getAppMemorySize(): Promise\; - -Obtains the memory size of this application. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<number> | Size of the application memory.| - -**Example** - - ```js - app.getAppMemorySize().then((data) => { - console.log('success:' + JSON.stringify(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - ``` - -## appManager.getAppMemorySize - -getAppMemorySize(callback: AsyncCallback\): void; - -Obtains the memory size of this application. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<number> | No| Size of the application memory.| - -**Example** - - ```js - app.getAppMemorySize((err, data) => { - console.log('startAbility result failed :' + JSON.stringify(err)); - console.log('startAbility result success:' + JSON.stringify(data)); - }) - ``` -## appManager.getProcessRunningInfos(deprecated) - -getProcessRunningInfos(): Promise\>; - -Obtains information about the running processes. This API uses a promise to return the result. - -> This API is deprecated since API version 9. You are advised to use [appManager.getProcessRunningInformation9+](#appmanagergetprocessrunninginformation9) instead. - -**Required permissions**: ohos.permission.GET_RUNNING_INFO - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise\> | Promise used to return the process information.| - -**Example** - - ```js - app.getProcessRunningInfos().then((data) => { - console.log('success:' + JSON.stringify(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - ``` - -## appManager.getProcessRunningInfos(deprecated) - -getProcessRunningInfos(callback: AsyncCallback\>): void; - -Obtains information about the running processes. This API uses an asynchronous callback to return the result. - -> This API is deprecated since API version 9. You are advised to use [appManager.getProcessRunningInformation9+](#appmanagergetprocessrunninginformation9-1) instead. - -**Required permissions**: ohos.permission.GET_RUNNING_INFO - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback\> | No| Callback used to return the process information.| - -**Example** - - ```js - app.getProcessRunningInfos((err, data) => { - console.log('startAbility result failed :' + JSON.stringify(err)); - console.log('startAbility result success:' + JSON.stringify(data)); - }) - ``` - -## appManager.getProcessRunningInformation9+ - -getProcessRunningInformation(): Promise\>; - -Obtains information about the running processes. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.GET_RUNNING_INFO - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise\> | Promise used to return the process information.| - -**Example** - - ```js - app.getProcessRunningInformation().then((data) => { - console.log('success:' + JSON.stringify(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - ``` - -## appManager.getProcessRunningInformation9+ - -getProcessRunningInformation(callback: AsyncCallback\>): void; - -Obtains information about the running processes. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.GET_RUNNING_INFO - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback\> | No| Callback used to return the process information.| - -**Example** - - ```js - app.getProcessRunningInformation((err, data) => { - console.log('startAbility result failed :' + JSON.stringify(err)); - console.log('startAbility result success:' + JSON.stringify(data)); - }) - ``` - -## appManager.registerApplicationStateObserver8+ - -registerApplicationStateObserver(observer: ApplicationStateObserver): number; - -Registers an observer to listen for the state changes of all applications. - -**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| observer | [ApplicationStateObserver](#applicationstateobserver) | No| Numeric code of the observer.| - -**Example** - - ```js - var applicationStateObserver = { - onForegroundApplicationChanged(appStateData) { - console.log('------------ onForegroundApplicationChanged -----------', appStateData); - }, - onAbilityStateChanged(abilityStateData) { - console.log('------------ onAbilityStateChanged -----------', abilityStateData); - }, - onProcessCreated(processData) { - console.log('------------ onProcessCreated -----------', processData); - }, - onProcessDied(processData) { - console.log('------------ onProcessDied -----------', processData); - }, - onProcessStateChanged(processData) { - console.log('------------ onProcessStateChanged -----------', processData); - } - } - const observerCode = app.registerApplicationStateObserver(applicationStateObserver); - console.log('-------- observerCode: ---------', observerCode); - - ``` - -## appManager.registerApplicationStateObserver9+ - -registerApplicationStateObserver(observer: ApplicationStateObserver, bundleNameList: Array\): number; - -Registers an observer to listen for the state changes of a specified application. - -**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| observer | [ApplicationStateObserver](#applicationstateobserver) | No| Numeric code of the observer.| -| bundleNameList | Array | No| **bundleName** array of the application. A maximum of 128 bundle names can be passed.| - -**Example** - - ```js - var applicationStateObserver = { - onForegroundApplicationChanged(appStateData) { - console.log('------------ onForegroundApplicationChanged -----------', appStateData); - }, - onAbilityStateChanged(abilityStateData) { - console.log('------------ onAbilityStateChanged -----------', abilityStateData); - }, - onProcessCreated(processData) { - console.log('------------ onProcessCreated -----------', processData); - }, - onProcessDied(processData) { - console.log('------------ onProcessDied -----------', processData); - }, - onProcessStateChanged(processData) { - console.log('------------ onProcessStateChanged -----------', processData); - } - } - var bundleNameList = ['bundleName1', 'bundleName2']; - const observerCode = app.registerApplicationStateObserver(applicationStateObserver, bundleNameList); - console.log('-------- observerCode: ---------', observerCode); - - ``` -## appManager.unregisterApplicationStateObserver8+ - -unregisterApplicationStateObserver(observerId: number, callback: AsyncCallback\): void; - -Deregisters the application state observer. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| observerId | number | No| Numeric code of the observer.| -| callback | AsyncCallback\ | No| Callback used to return the result.| - -**Example** - - ```js - var observerId = 100; - - function unregisterApplicationStateObserverCallback(err) { - if (err) { - console.log('------------ unregisterApplicationStateObserverCallback ------------', err); - } - } - app.unregisterApplicationStateObserver(observerId, unregisterApplicationStateObserverCallback); - ``` - -## appManager.unregisterApplicationStateObserver8+ - -unregisterApplicationStateObserver(observerId: number): Promise\; - -Deregisters the application state observer. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| observerId | number | No| Numeric code of the observer.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise\ | Promise used to return the result.| - -**Example** - - ```js - var observerId = 100; - - app.unregisterApplicationStateObserver(observerId) - .then((data) => { - console.log('----------- unregisterApplicationStateObserver success ----------', data); - }) - .catch((err) => { - console.log('----------- unregisterApplicationStateObserver fail ----------', err); - }) - ``` - -## appManager.getForegroundApplications8+ - -getForegroundApplications(callback: AsyncCallback\>): void; - -Obtains applications that are running in the foreground. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.GET_RUNNING_INFO - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback\> | No| Callback used to return the application state data.| - -**Example** - - ```js - function getForegroundApplicationsCallback(err, data) { - if (err) { - console.log('--------- getForegroundApplicationsCallback fail ---------', err); - } else { - console.log('--------- getForegroundApplicationsCallback success ---------', data) - } - } - app.getForegroundApplications(getForegroundApplicationsCallback); - ``` - -## appManager.getForegroundApplications8+ - -getForegroundApplications(): Promise\>; - -Obtains applications that are running in the foreground. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.GET_RUNNING_INFO - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise\> | Promise used to return the application state data.| - -**Example** - - ```js - app.getForegroundApplications() - .then((data) => { - console.log('--------- getForegroundApplications success -------', data); - }) - .catch((err) => { - console.log('--------- getForegroundApplications fail -------', err); - }) - ``` - -## appManager.killProcessWithAccount8+ - -killProcessWithAccount(bundleName: string, accountId: number): Promise\ - -Kills a process by bundle name and account ID. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS and ohos.permission.CLEAN_BACKGROUND_PROCESSES - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Bundle name of an application.| - | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| - -**Example** - -```js -var bundleName = 'bundleName'; -var accountId = 0; -app.killProcessWithAccount(bundleName, accountId) - .then((data) => { - console.log('------------ killProcessWithAccount success ------------', data); - }) - .catch((err) => { - console.log('------------ killProcessWithAccount fail ------------', err); - }) -``` - - -## appManager.killProcessWithAccount8+ - -killProcessWithAccount(bundleName: string, accountId: number, callback: AsyncCallback\): void - -Kills a process by bundle name and account ID. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS and ohos.permission.CLEAN_BACKGROUND_PROCESSES - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Bundle name of an application.| - | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| - | callback | AsyncCallback\ | Yes| Callback used to return the result.| - -**Example** - -```js -var bundleName = 'bundleName'; -var accountId = 0; -function killProcessWithAccountCallback(err, data) { - if (err) { - console.log('------------- killProcessWithAccountCallback fail, err: --------------', err); - } else { - console.log('------------- killProcessWithAccountCallback success, data: --------------', data); - } -} -app.killProcessWithAccount(bundleName, accountId, killProcessWithAccountCallback); -``` - -## appManager.killProcessesByBundleName8+ - -killProcessesByBundleName(bundleName: string, callback: AsyncCallback\); - -Kills a process by bundle name. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.CLEAN_BACKGROUND_PROCESSES - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| bundleName | string | No| Bundle name of an application.| -| callback | AsyncCallback\ | No| Callback used to return the result.| - -**Example** - - ```js - var bundleName = 'bundleName'; - function killProcessesByBundleNameCallback(err, data) { - if (err) { - console.log('------------- killProcessesByBundleNameCallback fail, err: --------------', err); - } else { - console.log('------------- killProcessesByBundleNameCallback success, data: --------------', data); - } - } - app.killProcessesByBundleName(bundleName, killProcessesByBundleNameCallback); - ``` - -## appManager.killProcessesByBundleName8+ - -killProcessesByBundleName(bundleName: string): Promise\; - -Kills a process by bundle name. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.CLEAN_BACKGROUND_PROCESSES - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| bundleName | string | No| Bundle name of an application.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise\ | Promise used to return the result.| - -**Example** - - ```js -var bundleName = 'bundleName'; -app.killProcessesByBundleName(bundleName) - .then((data) => { - console.log('------------ killProcessesByBundleName success ------------', data); - }) - .catch((err) => { - console.log('------------ killProcessesByBundleName fail ------------', err); - }) - - ``` - -## appManager.clearUpApplicationData8+ - -clearUpApplicationData(bundleName: string, callback: AsyncCallback\); - -Clears application data by bundle name. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.CLEAN_APPLICATION_DATA - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| bundleName | string | No| Bundle name of an application.| -| callback | AsyncCallback\ | No| Callback used to return the result.| - -**Example** - - ```js - var bundleName = 'bundleName'; - function clearUpApplicationDataCallback(err, data) { - if (err) { - console.log('------------- clearUpApplicationDataCallback fail, err: --------------', err); - } else { - console.log('------------- clearUpApplicationDataCallback success, data: --------------', data); - } - } - app.clearUpApplicationData(bundleName, clearUpApplicationDataCallback); - - ``` - -## appManager.clearUpApplicationData8+ - -clearUpApplicationData(bundleName: string): Promise\; - -Clears application data by bundle name. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.CLEAN_APPLICATION_DATA - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| bundleName | string | No| Bundle name of an application.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise\ | Promise used to return the result.| - -**Example** - - ```js - var bundleName = 'bundleName'; - app.clearUpApplicationData(bundleName) - .then((data) => { - console.log('------------ clearUpApplicationData success ------------', data); - }) - .catch((err) => { - console.log('------------ clearUpApplicationData fail ------------', err); - }) - - ``` - -## ApplicationStateObserver.onForegroundApplicationChanged8+ - -onForegroundApplicationChanged(appStateData: AppStateData): void; - -Called when the application state changes. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| appStateData | [AppStateData](#appstatedata) | No| Information about the application whose state is changed.| - -**Example** - -```js - var applicationStateObserver = { - onForegroundApplicationChanged(appStateData) { - console.log('------------ onForegroundApplicationChanged -----------', appStateData); - }, - onAbilityStateChanged(abilityStateData) { - console.log('------------ onAbilityStateChanged -----------', abilityStateData); - }, - onProcessCreated(processData) { - console.log('------------ onProcessCreated -----------', processData); - }, - onProcessDied(processData) { - console.log('------------ onProcessDied -----------', processData); - }, - onProcessStateChanged(processData) { - console.log('------------ onProcessStateChanged -----------', processData); - } - } - const observerCode = app.registerApplicationStateObserver(applicationStateObserver); - console.log('-------- observerCode: ---------', observerCode); - -``` - -## ApplicationStateObserver.onAbilityStateChanged8+ - -onAbilityStateChanged(abilityStateData: AbilityStateData): void; - -Called when the ability state changes. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| abilityStateData | [AbilityStateData](#abilitystatedata) | No| Information about the ability whose state is changed.| - -**Example** - -```js - var applicationStateObserver = { - onForegroundApplicationChanged(appStateData) { - console.log('------------ onForegroundApplicationChanged -----------', appStateData); - }, - onAbilityStateChanged(abilityStateData) { - console.log('------------ onAbilityStateChanged -----------', abilityStateData); - }, - onProcessCreated(processData) { - console.log('------------ onProcessCreated -----------', processData); - }, - onProcessDied(processData) { - console.log('------------ onProcessDied -----------', processData); - }, - onProcessStateChanged(processData) { - console.log('------------ onProcessStateChanged -----------', processData); - } - } - const observerCode = app.registerApplicationStateObserver(applicationStateObserver); - console.log('-------- observerCode: ---------', observerCode); -``` - -## ApplicationStateObserver.onProcessCreated8+ - -onProcessCreated(processData: ProcessData): void; - -Called when a process is created. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| processData | [ProcessData](#processdata) | No| Process information.| - -**Example** - -```js - var applicationStateObserver = { - onForegroundApplicationChanged(appStateData) { - console.log('------------ onForegroundApplicationChanged -----------', appStateData); - }, - onAbilityStateChanged(abilityStateData) { - console.log('------------ onAbilityStateChanged -----------', abilityStateData); - }, - onProcessCreated(processData) { - console.log('------------ onProcessCreated -----------', processData); - }, - onProcessDied(processData) { - console.log('------------ onProcessDied -----------', processData); - }, - onProcessStateChanged(processData) { - console.log('------------ onProcessStateChanged -----------', processData); - } - } - const observerCode = app.registerApplicationStateObserver(applicationStateObserver); - console.log('-------- observerCode: ---------', observerCode); -``` - -## ApplicationStateObserver.onProcessDied8+ - -onProcessDied(processData: ProcessData): void; - -Called when a process is terminated. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| processData | [ProcessData](#processdata) | No| Process information.| - -**Example** - -```js - var applicationStateObserver = { - onForegroundApplicationChanged(appStateData) { - console.log('------------ onForegroundApplicationChanged -----------', appStateData); - }, - onAbilityStateChanged(abilityStateData) { - console.log('------------ onAbilityStateChanged -----------', abilityStateData); - }, - onProcessCreated(processData) { - console.log('------------ onProcessCreated -----------', processData); - }, - onProcessDied(processData) { - console.log('------------ onProcessDied -----------', processData); - }, - onProcessStateChanged(processData) { - console.log('------------ onProcessStateChanged -----------', processData); - } - } - const observerCode = app.registerApplicationStateObserver(applicationStateObserver); - console.log('-------- observerCode: ---------', observerCode); -``` - -## ApplicationStateObserver.onProcessStateChanged9+ - - onProcessStateChanged(processData: ProcessData): void; - -Called when the process state changes. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| processData | [ProcessData](#processdata) | No| Process information.| - -**Example** - -```js - var applicationStateObserver = { - onForegroundApplicationChanged(appStateData) { - console.log('------------ onForegroundApplicationChanged -----------', appStateData); - }, - onAbilityStateChanged(abilityStateData) { - console.log('------------ onAbilityStateChanged -----------', abilityStateData); - }, - onProcessCreated(processData) { - console.log('------------ onProcessCreated -----------', processData); - }, - onProcessDied(processData) { - console.log('------------ onProcessDied -----------', processData); - }, - onProcessStateChanged(processData) { - console.log('------------ onProcessStateChanged -----------', processData); - } - } - const observerCode = app.registerApplicationStateObserver(applicationStateObserver); - console.log('-------- observerCode: ---------', observerCode); -``` - -## AppStateData - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name | Readable/Writable| Type | Mandatory| Description | -| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | -| bundleName8+ | Read only | string | No | Bundle name of an application. | -| uid8+ | Read only | number | No | User ID.| -| state8+ | Read only | number | No | Application state.| - -## AbilityStateData - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name | Type | Readable| Writable| Description | -| ----------------------- | ---------| ---- | ---- | ------------------------- | -| pid8+ | number | Yes | No | Process ID. | -| bundleName8+ | string | Yes | No | Bundle name of an application. | -| abilityName8+ | string | Yes | No | Ability name. | -| uid8+ | number | Yes | No | User ID. | -| state8+ | number | Yes | No | Ability state. | -| moduleName9+ | string | Yes | No | Name of the HAP file to which the ability belongs. | -| abilityType8+ | string | Yes | No | Ability type. | - -## ProcessData - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name | Type | Readable| Writable| Description | -| ----------------------- | ---------| ---- | ---- | ------------------------- | -| pid8+ | number | Yes | No | Process ID. | -| bundleName8+ | string | Yes | No | Bundle name of an application. | -| uid8+ | number | Yes | No | User ID. | -| isContinuousTask9+ | boolean | Yes | No | Whether the process is a continuous task. | -| isKeepAlive9+ | boolean | Yes | No | Whether the process remains active. | - -## ProcessRunningInfo - -**System capability**: SystemCapability.Ability.AbilityRuntime.Mission - -| Name | Readable/Writable| Type | Mandatory| Description | -| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | -| pid8+ | Read only | number | No | Process ID. | -| uid8+ | Read only | number | No | User ID.| -| processName8+ | Read only | string | No | Process name.| -| bundleNames8+ | Read only | Array\ | No | **bundleName** array in the running processes.| - -## ApplicationStateObserver - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name | Type | Readable| Writable| Description | -| ----------------------- | ---------| ---- | ---- | ------------------------- | -| [onForegroundApplicationChanged8+](#applicationstateobserveronforegroundapplicationchanged8) | AsyncCallback\ | Yes | No | Callback invoked when the foreground or background state of an application changes. | -| [onAbilityStateChanged8+](#applicationstateobserveronabilitystatechanged8) | AsyncCallback\ | Yes | No | Callback invoked when the ability state changes. | -| [onProcessCreated8+](#applicationstateobserveronprocesscreated8) | AsyncCallback\ | Yes | No | Callback invoked when a process is created. | -| [onProcessDied8+](#applicationstateobserveronprocessdied8) | AsyncCallback\ | Yes | No | Callback invoked when a process is destroyed. | - -## ProcessRunningInformation - -Defines the process running information. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name | Readable/Writable| Type | Mandatory| Description | -| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | -| pid9+ | Read only | number | No | Process ID. | -| uid9+ | Read only | number | No | User ID.| -| processName9+ | Read only | string | No | Process name.| -| bundleNames9+ | Read only | Array\ | No | **bundleName** array in the running processes.| - -## ApplicationState9+ - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name | Value | Description | -| -------------------- | --- | --------------------------------- | -| STATE_CREATE | 1 | State indicating that the application is being created. | -| STATE_FOREGROUND | 2 | State indicating that the application is running in the foreground. | -| STATE_ACTIVE | 3 | State indicating that the application is active. | -| STATE_BACKGROUND | 4 | State indicating that the application is running in the background. | -| STATE_DESTROY | 5 | State indicating that the application is destroyed. | - -## ProcessState9+ - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name | Value | Description | -| -------------------- | --- | --------------------------------- | -| STATE_CREATE | 1 | State indicating that the process is being created. | -| STATE_FOREGROUND | 2 | State indicating that the process is running in the foreground. | -| STATE_ACTIVE | 3 | State indicating that the process is active. | -| STATE_BACKGROUND | 4 | State indicating that the process is running in the background. | -| STATE_DESTROY | 5 | State indicating that the process is destroyed. | diff --git a/en/application-dev/reference/apis/js-apis-arraylist.md b/en/application-dev/reference/apis/js-apis-arraylist.md index d98422b678ea658dbe4092dc9247ca4bb551f5cc..f6334ff328c76de2d9be97b9ad430065819e53c9 100644 --- a/en/application-dev/reference/apis/js-apis-arraylist.md +++ b/en/application-dev/reference/apis/js-apis-arraylist.md @@ -1,4 +1,4 @@ -# Linear Container ArrayList +# @ohos.util.ArrayList (Linear Container ArrayList) > **NOTE** > @@ -52,11 +52,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let arrayList = new ArrayList(); -try { - let arrayList2 = ArrayList(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -90,21 +85,16 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er **Example** - ```ts - let arrayList = new ArrayList(); - let result = arrayList.add("a"); - let result1 = arrayList.add(1); - let b = [1, 2, 3]; - let result2 = arrayList.add(b); - let c = {name: "Dylon", age: "13"}; - let result3 = arrayList.add(c); - let result4 = arrayList.add(false); - try { - arrayList.add.bind({}, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. - } catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); - } - ``` +```ts +let arrayList = new ArrayList(); +let result = arrayList.add("a"); +let result1 = arrayList.add(1); +let b = [1, 2, 3]; +let result2 = arrayList.add(b); +let c = {name: "Dylon", age: "13"}; +let result3 = arrayList.add(c); +let result4 = arrayList.add(false); +``` ### insert @@ -128,7 +118,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The insert method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -137,21 +127,6 @@ let arrayList = new ArrayList(); arrayList.insert("A", 0); arrayList.insert(0, 1); arrayList.insert(true, 2); -try { - arrayList.insert.bind({}, 1, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - let res = arrayList.insert (8, 11); // Trigger an out-of-bounds exception. -} catch (err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - let res = arrayList.insert("a", "b"); // Trigger a type exception. -} catch (err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### has @@ -189,11 +164,6 @@ let arrayList = new ArrayList(); let result = arrayList.has("squirrel"); arrayList.add("squirrel"); let result1 = arrayList.has("squirrel"); -try { - arrayList.has.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getIndexOf @@ -236,11 +206,6 @@ arrayList.add(1); arrayList.add(2); arrayList.add(4); let result = arrayList.getIndexOf(2); -try { - arrayList.getIndexOf.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getLastIndexOf @@ -283,11 +248,6 @@ arrayList.add(1); arrayList.add(2); arrayList.add(4); let result = arrayList.getLastIndexOf(2); -try { - arrayList.getLastIndexOf.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### removeByIndex @@ -317,7 +277,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The removeByIndex method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -329,21 +289,6 @@ arrayList.add(5); arrayList.add(2); arrayList.add(4); let result = arrayList.removeByIndex(2); -try { - arrayList.removeByIndex.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - arrayList.removeByIndex("a"); // Trigger a type exception. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - arrayList.removeByIndex(8); // Trigger an out-of-bounds exception. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### remove @@ -383,11 +328,6 @@ arrayList.add(4); arrayList.add(5); arrayList.add(4); let result = arrayList.remove(2); -try { - arrayList.remove.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### removeByRange @@ -412,7 +352,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The removeByRange method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -423,21 +363,11 @@ arrayList.add(4); arrayList.add(5); arrayList.add(4); arrayList.removeByRange(2, 4); -try { - arrayList.removeByRange.bind({}, 2, 4)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - arrayList.removeByRange(8, 4); // Trigger an out-of-bounds exception. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### replaceAllElements -replaceAllElements(callbackfn: (value: T, index?: number, arrlist?: ArrayList<T>) => T, +replaceAllElements(callbackFn: (value: T, index?: number, arrlist?: ArrayList<T>) => T, thisArg?: Object): void Replaces all elements in this container with new elements, and returns the new ones. @@ -448,7 +378,7 @@ Replaces all elements in this container with new elements, and returns the new o | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked for the replacement.| +| callbackFn | function | Yes| Callback invoked for the replacement.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -481,18 +411,11 @@ arrayList.replaceAllElements((value: number, index: number)=> { arrayList.replaceAllElements((value: number, index: number) => { return value = value - 2; }); -try { - arrayList.replaceAllElements.bind({}, (value: number, index: number)=> { - return value = 2 * value; - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value: T, index?: number, arrlist?: ArrayList<T>) => void, +forEach(callbackFn: (value: T, index?: number, arrlist?: ArrayList<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -503,7 +426,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -533,13 +456,6 @@ arrayList.add(4); arrayList.forEach((value, index) => { console.log(`value:${value}`, index); }); -try { - arrayList.forEach.bind({}, (value, index) => { - console.log(`value:${value}`, index); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### sort @@ -582,11 +498,6 @@ arrayList.add(4); arrayList.sort((a: number, b: number) => a - b); arrayList.sort((a: number, b: number) => b - a); arrayList.sort(); -try { - arrayList.sort.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### subArrayList @@ -617,7 +528,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The subArrayList method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -630,16 +541,6 @@ arrayList.add(4); let result1 = arrayList.subArrayList(2, 4); let result2 = arrayList.subArrayList(4, 3); let result3 = arrayList.subArrayList(2, 6); -try { - arrayList.subArrayList.bind({}, 2, 4)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - arrayList.subArrayList(6, 4); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### clear @@ -667,11 +568,6 @@ arrayList.add(4); arrayList.add(5); arrayList.add(4); arrayList.clear(); -try { - arrayList.clear.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### clone @@ -706,11 +602,6 @@ arrayList.add(4); arrayList.add(5); arrayList.add(4); let result = arrayList.clone(); -try { - arrayList.clone.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getCapacity @@ -744,11 +635,6 @@ arrayList.add(4); arrayList.add(5); arrayList.add(4); let result = arrayList.getCapacity(); -try { - arrayList.getCapacity.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### convertToArray @@ -782,11 +668,6 @@ arrayList.add(4); arrayList.add(5); arrayList.add(4); let result = arrayList.convertToArray(); -try { - arrayList.convertToArray.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### isEmpty @@ -820,11 +701,6 @@ arrayList.add(4); arrayList.add(5); arrayList.add(4); let result = arrayList.isEmpty(); -try { - arrayList.isEmpty.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### increaseCapacityTo @@ -859,11 +735,6 @@ arrayList.add(5); arrayList.add(4); arrayList.increaseCapacityTo(2); arrayList.increaseCapacityTo(8); -try { - arrayList.increaseCapacityTo.bind({}, 5)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### trimToCurrentLength @@ -891,11 +762,6 @@ arrayList.add(4); arrayList.add(5); arrayList.add(4); arrayList.trimToCurrentLength(); -try { - arrayList.trimToCurrentLength.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### [Symbol.iterator] @@ -941,9 +807,4 @@ while(temp != undefined) { console.log(`value:${temp}`); temp = iter.next().value; } -try { - arrayList[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-audio.md b/en/application-dev/reference/apis/js-apis-audio.md index 8296185a2866ab0148e68ee56e52eea68e708892..48be07fbffdadd82f34eb41b6906f4a87a679e89 100644 --- a/en/application-dev/reference/apis/js-apis-audio.md +++ b/en/application-dev/reference/apis/js-apis-audio.md @@ -1,4 +1,4 @@ -# Audio Management +# @ohos.multimedia.audio (Audio Management) The **Audio** module provides basic audio management capabilities, including audio volume and audio device management, and audio data collection and rendering. @@ -9,9 +9,9 @@ This module provides the following common audio-related functions: - [AudioCapturer](#audiocapturer8): audio capture, used to record PCM audio data. - [TonePlayer](#toneplayer9): tone player, used to manage and play Dual Tone Multi Frequency (DTMF) tones, such as dial tones and ringback tones. -> **NOTE** +> **NOTE** > -> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -23,9 +23,9 @@ import audio from '@ohos.multimedia.audio'; | Name | Type | Readable | Writable| Description | | --------------------------------------- | ----------| ---- | ---- | ------------------ | -| LOCAL_NETWORK_ID9+ | string | Yes | No | Network ID of the local device.
This is a system API.
**System capability**: SystemCapability.Multimedia.Audio.Device | -| DEFAULT_VOLUME_GROUP_ID9+ | number | Yes | No | Default volume group ID.
**System capability**: SystemCapability.Multimedia.Audio.Volume | -| DEFAULT_INTERRUPT_GROUP_ID9+ | number | Yes | No | Default audio interruption group ID.
**System capability**: SystemCapability.Multimedia.Audio.Interrupt | +| LOCAL_NETWORK_ID9+ | string | Yes | No | Network ID of the local device.
This is a system API.
**System capability**: SystemCapability.Multimedia.Audio.Device | +| DEFAULT_VOLUME_GROUP_ID9+ | number | Yes | No | Default volume group ID.
**System capability**: SystemCapability.Multimedia.Audio.Volume | +| DEFAULT_INTERRUPT_GROUP_ID9+ | number | Yes | No | Default audio interruption group ID.
**System capability**: SystemCapability.Multimedia.Audio.Interrupt | **Example** @@ -74,7 +74,10 @@ Creates an **AudioRenderer** instance. This API uses an asynchronous callback to **Example** ```js +import featureAbility from '@ohos.ability.featureAbility'; +import fileio from '@ohos.fileio'; import audio from '@ohos.multimedia.audio'; + let audioStreamInfo = { samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, channels: audio.AudioChannel.CHANNEL_1, @@ -126,6 +129,8 @@ Creates an **AudioRenderer** instance. This API uses a promise to return the res **Example** ```js +import featureAbility from '@ohos.ability.featureAbility'; +import fileio from '@ohos.fileio'; import audio from '@ohos.multimedia.audio'; let audioStreamInfo = { @@ -279,9 +284,9 @@ Creates a **TonePlayer** instance. This API uses an asynchronous callback to ret import audio from '@ohos.multimedia.audio'; let audioRendererInfo = { - "contentType": audio.ContentType.CONTENT_TYPE_MUSIC, - "streamUsage": audio.StreamUsage.STREAM_USAGE_MEDIA, - "rendererFlags": 0 + content : audio.ContentType.CONTENT_TYPE_SONIFICATION, + usage : audio.StreamUsage.STREAM_USAGE_MEDIA, + rendererFlags : 0 } let tonePlayer; @@ -322,13 +327,14 @@ Creates a **TonePlayer** instance. This API uses a promise to return the result. ```js import audio from '@ohos.multimedia.audio'; -async function createTonePlayer(){ +let tonePlayer; +async function createTonePlayerBefore(){ let audioRendererInfo = { - "contentType": audio.ContentType.CONTENT_TYPE_MUSIC, - "streamUsage": audio.StreamUsage.STREAM_USAGE_MEDIA, - "rendererFlags": 0 + content : audio.ContentType.CONTENT_TYPE_SONIFICATION, + usage : audio.StreamUsage.STREAM_USAGE_MEDIA, + rendererFlags : 0 } - let tonePlayer = await audio.createTonePlayer(audioRendererInfo); + tonePlayer = await audio.createTonePlayer(audioRendererInfo); } ``` @@ -338,7 +344,7 @@ Enumerates the audio stream types. **System capability**: SystemCapability.Multimedia.Audio.Volume -| Name | Default Value| Description | +| Name | Value | Description | | ---------------------------- | ------ | ---------- | | VOICE_CALL8+ | 0 | Audio stream for voice calls.| | RINGTONE | 2 | Audio stream for ringtones. | @@ -354,7 +360,7 @@ Enumerates the result types of audio interruption requests. **System API**: This is a system API. -| Name | Default Value| Description | +| Name | Value | Description | | ---------------------------- | ------ | ---------- | | INTERRUPT_REQUEST_GRANT | 0 | The audio interruption request is accepted.| | INTERRUPT_REQUEST_REJECT | 1 | The audio interruption request is denied. There may be a stream with a higher priority.| @@ -365,7 +371,7 @@ Enumerates the audio interruption modes. **System capability**: SystemCapability.Multimedia.Audio.Interrupt -| Name | Default Value| Description | +| Name | Value | Description | | ---------------------------- | ------ | ---------- | | SHARE_MODE | 0 | Shared mode.| | INDEPENDENT_MODE | 1 | Independent mode.| @@ -376,7 +382,7 @@ Enumerates the audio device flags. **System capability**: SystemCapability.Multimedia.Audio.Device -| Name | Default Value | Description | +| Name | Value | Description | | ------------------------------- | ------ | ------------------------------------------------- | | NONE_DEVICES_FLAG9+ | 0 | No device.
This is a system API. | | OUTPUT_DEVICES_FLAG | 1 | Output device.| @@ -392,7 +398,7 @@ Enumerates the audio device roles. **System capability**: SystemCapability.Multimedia.Audio.Device -| Name | Default Value| Description | +| Name | Value | Description | | ------------- | ------ | -------------- | | INPUT_DEVICE | 1 | Input role.| | OUTPUT_DEVICE | 2 | Output role.| @@ -403,7 +409,7 @@ Enumerates the audio device types. **System capability**: SystemCapability.Multimedia.Audio.Device -| Name | Default Value| Description | +| Name | Value | Description | | ---------------------| ------ | --------------------------------------------------------- | | INVALID | 0 | Invalid device. | | EARPIECE | 1 | Earpiece. | @@ -422,7 +428,7 @@ Enumerates the device types used for communication. **System capability**: SystemCapability.Multimedia.Audio.Communication -| Name | Default Value| Description | +| Name | Value | Description | | ------------- | ------ | -------------| | SPEAKER | 2 | Speaker. | @@ -432,7 +438,7 @@ Enumerates the ringer modes. **System capability**: SystemCapability.Multimedia.Audio.Communication -| Name | Default Value| Description | +| Name | Value | Description | | ------------------- | ------ | ---------- | | RINGER_MODE_SILENT | 0 | Silent mode.| | RINGER_MODE_VIBRATE | 1 | Vibration mode.| @@ -444,7 +450,7 @@ Enumerates the audio sample formats. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Default Value| Description | +| Name | Value | Description | | ---------------------------------- | ------ | -------------------------- | | SAMPLE_FORMAT_INVALID | -1 | Invalid format. | | SAMPLE_FORMAT_U8 | 0 | Unsigned 8-bit integer. | @@ -459,15 +465,15 @@ Enumerates the audio error codes. **System capability**: SystemCapability.Multimedia.Audio.Core -| Error Message | Error Code | Error Description | +| Name | Value | Description | | ---------------------| --------| ----------------- | | ERROR_INVALID_PARAM | 6800101 | Invalid parameter. | | ERROR_NO_MEMORY | 6800102 | Memory allocation failure. | | ERROR_ILLEGAL_STATE | 6800103 | Unsupported state. | -| ERROR_UNSUPPORTED | 6800104 | Unsupported parameter value. | +| ERROR_UNSUPPORTED | 6800104 | Unsupported parameter value. | | ERROR_TIMEOUT | 6800105 | Processing timeout. | | ERROR_STREAM_LIMIT | 6800201 | Too many audio streams.| -| ERROR_SYSTEM | 6800301 | System error. | +| ERROR_SYSTEM | 6800301 | System error. | ## AudioChannel8+ @@ -475,18 +481,18 @@ Enumerates the audio channels. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Default Value | Description | +| Name | Value | Description | | --------- | -------- | -------- | | CHANNEL_1 | 0x1 << 0 | Mono.| | CHANNEL_2 | 0x1 << 1 | Dual-channel.| ## AudioSamplingRate8+ -Enumerates the audio sampling rates. +Enumerates the audio sampling rates. The sampling rates supported vary according to the device in use. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Default Value| Description | +| Name | Value | Description | | ----------------- | ------ | --------------- | | SAMPLE_RATE_8000 | 8000 | The sampling rate is 8000. | | SAMPLE_RATE_11025 | 11025 | The sampling rate is 11025.| @@ -506,7 +512,7 @@ Enumerates the audio encoding types. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Default Value| Description | +| Name | Value | Description | | --------------------- | ------ | --------- | | ENCODING_TYPE_INVALID | -1 | Invalid. | | ENCODING_TYPE_RAW | 0 | PCM encoding.| @@ -517,7 +523,7 @@ Enumerates the audio content types. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Default Value| Description | +| Name | Value | Description | | ---------------------------------- | ------ | ---------- | | CONTENT_TYPE_UNKNOWN | 0 | Unknown content.| | CONTENT_TYPE_SPEECH | 1 | Speech. | @@ -532,7 +538,7 @@ Enumerates the audio stream usage. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Default Value| Description | +| Name | Value | Description | | ------------------------------------------| ------ | ---------- | | STREAM_USAGE_UNKNOWN | 0 | Unknown usage.| | STREAM_USAGE_MEDIA | 1 | Used for media. | @@ -548,7 +554,7 @@ Enumerates the audio interruption request types. **System capability**: SystemCapability.Multimedia.Audio.Interrupt -| Name | Default Value | Description | +| Name | Value | Description | | ---------------------------------- | ------ | ------------------------- | | INTERRUPT_REQUEST_TYPE_DEFAULT | 0 | Default type, which can be used to interrupt audio requests. | @@ -558,7 +564,7 @@ Enumerates the audio states. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Default Value| Description | +| Name | Value | Description | | -------------- | ------ | ---------------- | | STATE_INVALID | -1 | Invalid state. | | STATE_NEW | 0 | Creating instance state.| @@ -574,7 +580,7 @@ Enumerates the audio renderer rates. **System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Default Value| Description | +| Name | Value | Description | | ------------------ | ------ | ---------- | | RENDER_RATE_NORMAL | 0 | Normal rate.| | RENDER_RATE_DOUBLE | 1 | Double rate. | @@ -586,7 +592,7 @@ Enumerates the audio interruption types. **System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Default Value| Description | +| Name | Value | Description | | -------------------- | ------ | ---------------------- | | INTERRUPT_TYPE_BEGIN | 1 | Audio interruption started.| | INTERRUPT_TYPE_END | 2 | Audio interruption ended.| @@ -597,7 +603,7 @@ Enumerates the types of force that causes audio interruption. **System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Default Value| Description | +| Name | Value | Description | | --------------- | ------ | ------------------------------------ | | INTERRUPT_FORCE | 0 | Forced action taken by the system. | | INTERRUPT_SHARE | 1 | The application can choose to take action or ignore.| @@ -608,7 +614,7 @@ Enumerates the hints provided along with audio interruption. **System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Default Value| Description | +| Name | Value | Description | | ---------------------------------- | ------ | -------------------------------------------- | | INTERRUPT_HINT_NONE8+ | 0 | None. | | INTERRUPT_HINT_RESUME | 1 | Resume the playback. | @@ -636,7 +642,7 @@ Describes audio renderer information. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory | Description | | ------------- | --------------------------- | ---- | ---------------- | | content | [ContentType](#contenttype) | Yes | Audio content type. | | usage | [StreamUsage](#streamusage) | Yes | Audio stream usage.| @@ -661,7 +667,7 @@ Describes audio renderer configurations. **System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory | Description | | ------------ | ---------------------------------------- | ---- | ---------------- | | streamInfo | [AudioStreamInfo](#audiostreaminfo8) | Yes | Audio stream information.| | rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | Audio renderer information.| @@ -672,7 +678,7 @@ Describes the interruption event received by the application when playback is in **System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Type | Mandatory| Description | +| Name | Type |Mandatory | Description | | --------- | ------------------------------------------ | ---- | ------------------------------------ | | eventType | [InterruptType](#interrupttype) | Yes | Whether the interruption has started or ended. | | forceType | [InterruptForceType](#interruptforcetype9) | Yes | Whether the interruption is taken by the system or to be taken by the application.| @@ -686,7 +692,7 @@ Describes the event received by the application when the volume is changed. **System capability**: SystemCapability.Multimedia.Audio.Volume -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory | Description | | ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | | volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | | volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**.| @@ -701,7 +707,7 @@ Describes the event received by the application when the microphone mute status **System capability**: SystemCapability.Multimedia.Audio.Device | Name | Type | Mandatory| Description | -| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | +| ---------- | ----------------------------------- | ---- |-------------------------------------------------------- | | mute | boolean | Yes | Mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite. | ## ConnectType9+ @@ -712,7 +718,7 @@ Enumerates the types of connected devices. **System capability**: SystemCapability.Multimedia.Audio.Volume -| Name | Default Value| Description | +| Name | Value | Description | | :------------------------------ | :----- | :--------------------- | | CONNECT_TYPE_LOCAL | 1 | Local device. | | CONNECT_TYPE_DISTRIBUTED | 2 | Distributed device. | @@ -738,7 +744,7 @@ Describes the volume group information. | networkId9+ | string | Yes | No | Network ID of the device. | | groupId9+ | number | Yes | No | Group ID of the device.| | mappingId9+ | number | Yes | No | Group mapping ID.| -| groupName9+ | number | Yes | No | Group name.| +| groupName9+ | string | Yes | No | Group name.| | type9+ | [ConnectType](#connecttype9)| Yes | No | Type of the connected device.| ## DeviceChangeAction @@ -758,7 +764,7 @@ Enumerates the device connection statuses. **System capability**: SystemCapability.Multimedia.Audio.Device -| Name | Default Value| Description | +| Name | Value | Description | | :--------- | :----- | :------------- | | CONNECT | 0 | Connected. | | DISCONNECT | 1 | Disconnected.| @@ -791,7 +797,7 @@ Enumerates the audio source types. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Default Value| Description | +| Name | Value | Description | | :------------------------------------------- | :----- | :--------------------- | | SOURCE_TYPE_INVALID | -1 | Invalid audio source. | | SOURCE_TYPE_MIC | 0 | Mic source. | @@ -804,7 +810,7 @@ Enumerates the audio scenes. **System capability**: SystemCapability.Multimedia.Audio.Communication -| Name | Default Value| Description | +| Name | Value | Description | | :--------------------- | :----- | :-------------------------------------------- | | AUDIO_SCENE_DEFAULT | 0 | Default audio scene. | | AUDIO_SCENE_RINGING | 1 | Ringing audio scene.
This is a system API.| @@ -959,7 +965,6 @@ Sets an audio scene. This API uses an asynchronous callback to return the result **Example** ```js -let audioManager = audio.getAudioManager(); audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL, (err) => { if (err) { console.error(`Failed to set the audio scene mode.​ ${err}`); @@ -994,7 +999,6 @@ Sets an audio scene. This API uses a promise to return the result. **Example** ```js -let audioManager = audio.getAudioManager(); audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL).then(() => { console.info('Promise returned to indicate a successful setting of the audio scene mode.'); }).catch ((err) => { @@ -1019,7 +1023,6 @@ Obtains the audio scene. This API uses an asynchronous callback to return the re **Example** ```js -let audioManager = audio.getAudioManager(); audioManager.getAudioScene((err, value) => { if (err) { console.error(`Failed to obtain the audio scene mode.​ ${err}`); @@ -1046,7 +1049,6 @@ Obtains the audio scene. This API uses a promise to return the result. **Example** ```js -let audioManager = audio.getAudioManager(); audioManager.getAudioScene().then((value) => { console.info(`Promise returned to indicate that the audio scene mode is obtained ${value}.`); }).catch ((err) => { @@ -1096,179 +1098,20 @@ Obtains an **AudioRoutingManager** instance. let audioRoutingManager = audioManager.getRoutingManager(); ``` -## AudioVolumeManager9+ - -Implements audio volume management. Before calling an API in **AudioVolumeManager**, you must use [getVolumeManager](#getvolumemanager9) to obtain an **AudioVolumeManager** instance. - -### getVolumeGroupInfos9+ - -getVolumeGroupInfos(networkId: string, callback: AsyncCallback\): void - -Obtains the volume groups. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Multimedia.Audio.Volume - -**Parameters** - -| Name | Type | Mandatory| Description | -| ---------- | ------------------------------------------------------------ | ---- | -------------------- | -| networkId | string | Yes | Network ID of the device. The network ID of the local device is **audio.LOCAL_NETWORK_ID**. | -| callback | AsyncCallback<[VolumeGroupInfos](#volumegroupinfos9)> | Yes | Callback used to return the volume group information array.| - -**Example** -```js -audioVolumeManager.getVolumeGroupInfos(audio.LOCAL_NETWORK_ID, (err, value) => { - if (err) { - console.error(`Failed to obtain the volume group infos list. ${err}`); - return; - } - console.info('Callback invoked to indicate that the volume group infos list is obtained.'); -}); -``` - -### getVolumeGroupInfos9+ - -getVolumeGroupInfos(networkId: string\): Promise - -Obtains the volume groups. This API uses a promise to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Multimedia.Audio.Volume - -**Parameters** - -| Name | Type | Mandatory| Description | -| ---------- | ------------------| ---- | -------------------- | -| networkId | string | Yes | Network ID of the device. The network ID of the local device is **audio.LOCAL_NETWORK_ID**. | - -**Return value** - -| Type | Description | -| ------------------- | ----------------------------- | -| Promise<[VolumeGroupInfos](#volumegroupinfos9)> | Volume group information array.| - -**Example** - -```js -async function getVolumeGroupInfos(){ - let volumegroupinfos = await audio.getAudioManager().getVolumeManager().getVolumeGroupInfos(audio.LOCAL_NETWORK_ID); - console.info('Promise returned to indicate that the volumeGroup list is obtained.'+JSON.stringify(volumegroupinfos)) -} -``` - -### getVolumeGroupManager9+ - -getVolumeGroupManager(groupId: number, callback: AsyncCallback\): void - -Obtains the audio group manager. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Audio.Volume - -**Parameters** - -| Name | Type | Mandatory| Description | -| ---------- | ------------------------------------------------------------ | ---- | -------------------- | -| groupId | number | Yes | Volume group ID. | -| callback | AsyncCallback< [AudioVolumeGroupManager](#audiovolumegroupmanager9) > | Yes | Callback used to return the audio group manager.| - -**Example** - -```js -let groupid = audio.DEFAULT_VOLUME_GROUP_ID; -audioVolumeManager.getVolumeGroupManager(groupid, (err, value) => { - if (err) { - console.error(`Failed to obtain the volume group infos list. ${err}`); - return; - } - console.info('Callback invoked to indicate that the volume group infos list is obtained.'); -}); - -``` - -### getVolumeGroupManager9+ - -getVolumeGroupManager(groupId: number\): Promise - -Obtains the audio group manager. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Audio.Volume - -**Parameters** - -| Name | Type | Mandatory| Description | -| ---------- | ---------------------------------------- | ---- | ---------------- | -| groupId | number | Yes | Volume group ID. | - -**Return value** - -| Type | Description | -| ------------------- | ----------------------------- | -| Promise< [AudioVolumeGroupManager](#audiovolumegroupmanager9) > | Promise used to return the audio group manager.| - -**Example** - -```js -let groupid = audio.DEFAULT_VOLUME_GROUP_ID; -let audioVolumeGroupManager = await audioVolumeManager.getVolumeGroupManager(groupid); -console.info('Callback invoked to indicate that the volume group infos list is obtained.'); -``` - -### on('volumeChange')9+ - -on(type: 'volumeChange', callback: Callback\): void - -Subscribes to system volume change events. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Audio.Volume - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **'volumeChange'** means the system volume change event, which is triggered when the system volume changes.| -| callback | Callback<[VolumeEvent](#volumeevent8)> | Yes | Callback used to return the system volume change event. | - -**Error codes** - -For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). - -| ID| Error Message| -| ------- | --------------------------------------------| -| 6800101 | if input parameter value error. | - -**Example** - -```js -audioVolumeManager.on('volumeChange', (volumeEvent) => { - console.info(`VolumeType of stream: ${volumeEvent.volumeType} `); - console.info(`Volume level: ${volumeEvent.volume} `); - console.info(`Whether to updateUI: ${volumeEvent.updateUi} `); -}); -``` - -## AudioVolumeGroupManager9+ - -Manages the volume of an audio group. Before calling any API in **AudioVolumeGroupManager**, you must use [getVolumeGroupManager](#getvolumegroupmanager9) to obtain an **AudioVolumeGroupManager** instance. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Multimedia.Audio.Volume - -### setVolume9+ +### setVolume(deprecated) setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback<void>): void Sets the volume for a stream. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setVolume](#setvolume9) in **AudioVolumeGroupManager**. + **Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. -**System API**: This is a system API. - **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1282,7 +1125,7 @@ This permission is required only for muting or unmuting the ringer when **volume **Example** ```js -audioVolumeGroupManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => { +audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => { if (err) { console.error(`Failed to set the volume. ${err}`); return; @@ -1291,18 +1134,20 @@ audioVolumeGroupManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => { }); ``` -### setVolume9+ +### setVolume(deprecated) setVolume(volumeType: AudioVolumeType, volume: number): Promise<void> Sets the volume for a stream. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setVolume](#setvolume9) in **AudioVolumeGroupManager**. + **Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. -**System API**: This is a system API. - **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1321,17 +1166,21 @@ This permission is required only for muting or unmuting the ringer when **volume **Example** ```js -audioVolumeGroupManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => { +audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => { console.info('Promise returned to indicate a successful volume setting.'); }); ``` -### getVolume9+ +### getVolume(deprecated) getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void Obtains the volume of a stream. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getVolume](#getvolume9) in **AudioVolumeGroupManager**. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1344,7 +1193,7 @@ Obtains the volume of a stream. This API uses an asynchronous callback to return **Example** ```js -audioVolumeGroupManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { +audioManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { console.error(`Failed to obtain the volume. ${err}`); return; @@ -1353,12 +1202,16 @@ audioVolumeGroupManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { }); ``` -### getVolume9+ +### getVolume(deprecated) getVolume(volumeType: AudioVolumeType): Promise<number> Obtains the volume of a stream. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getVolume](#getvolume9) in **AudioVolumeGroupManager**. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1376,17 +1229,21 @@ Obtains the volume of a stream. This API uses a promise to return the result. **Example** ```js -audioVolumeGroupManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promise returned to indicate that the volume is obtained ${value}.`); +audioManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promise returned to indicate that the volume is obtained ${value} .`); }); ``` -### getMinVolume9+ +### getMinVolume(deprecated) getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void Obtains the minimum volume allowed for a stream. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getMinVolume](#getminvolume9) in **AudioVolumeGroupManager**. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1399,7 +1256,7 @@ Obtains the minimum volume allowed for a stream. This API uses an asynchronous c **Example** ```js -audioVolumeGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => { +audioManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { console.error(`Failed to obtain the minimum volume. ${err}`); return; @@ -1408,12 +1265,16 @@ audioVolumeGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) = }); ``` -### getMinVolume9+ +### getMinVolume(deprecated) getMinVolume(volumeType: AudioVolumeType): Promise<number> Obtains the minimum volume allowed for a stream. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getMinVolume](#getminvolume9) in **AudioVolumeGroupManager**. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1431,17 +1292,21 @@ Obtains the minimum volume allowed for a stream. This API uses a promise to retu **Example** ```js -audioVolumeGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promised returned to indicate that the minimum volume is obtained ${value}.`); +audioManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promised returned to indicate that the minimum volume is obtained. ${value}`); }); ``` -### getMaxVolume9+ +### getMaxVolume(deprecated) getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void Obtains the maximum volume allowed for a stream. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getMaxVolume](#getmaxvolume9) in **AudioVolumeGroupManager**. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1454,7 +1319,7 @@ Obtains the maximum volume allowed for a stream. This API uses an asynchronous c **Example** ```js -audioVolumeGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => { +audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { console.error(`Failed to obtain the maximum volume. ${err}`); return; @@ -1463,12 +1328,16 @@ audioVolumeGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) = }); ``` -### getMaxVolume9+ +### getMaxVolume(deprecated) getMaxVolume(volumeType: AudioVolumeType): Promise<number> Obtains the maximum volume allowed for a stream. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getMaxVolume](#getmaxvolume9) in **AudioVolumeGroupManager**. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1486,22 +1355,20 @@ Obtains the maximum volume allowed for a stream. This API uses a promise to retu **Example** ```js -audioVolumeGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => { +audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => { console.info('Promised returned to indicate that the maximum volume is obtained.'); }); ``` -### mute9+ +### mute(deprecated) mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void>): void Mutes or unmutes a stream. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY - -This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. - -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [mute](#mute9) in **AudioVolumeGroupManager**. **System capability**: SystemCapability.Multimedia.Audio.Volume @@ -1516,7 +1383,7 @@ This permission is required only for muting or unmuting the ringer when **volume **Example** ```js -audioVolumeGroupManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { +audioManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { if (err) { console.error(`Failed to mute the stream. ${err}`); return; @@ -1525,17 +1392,15 @@ audioVolumeGroupManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { }); ``` -### mute9+ +### mute(deprecated) mute(volumeType: AudioVolumeType, mute: boolean): Promise<void> Mutes or unmutes a stream. This API uses a promise to return the result. -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY - -This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. - -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [mute](#mute9) in **AudioVolumeGroupManager**. **System capability**: SystemCapability.Multimedia.Audio.Volume @@ -1554,18 +1419,23 @@ This permission is required only for muting or unmuting the ringer when **volume **Example** + ```js -audioVolumeGroupManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => { +audioManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => { console.info('Promise returned to indicate that the stream is muted.'); }); ``` -### isMute9+ +### isMute(deprecated) isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void Checks whether a stream is muted. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isMute](#ismute9) in **AudioVolumeGroupManager**. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1578,21 +1448,25 @@ Checks whether a stream is muted. This API uses an asynchronous callback to retu **Example** ```js -audioVolumeGroupManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => { +audioManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { console.error(`Failed to obtain the mute status. ${err}`); return; } - console.info(`Callback invoked to indicate that the mute status of the stream is obtained ${value}.`); + console.info(`Callback invoked to indicate that the mute status of the stream is obtained. ${value}`); }); ``` -### isMute9+ +### isMute(deprecated) isMute(volumeType: AudioVolumeType): Promise<boolean> Checks whether a stream is muted. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isMute](#ismute9) in **AudioVolumeGroupManager**. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1610,24 +1484,89 @@ Checks whether a stream is muted. This API uses a promise to return the result. **Example** ```js -audioVolumeGroupManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => { +audioManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => { console.info(`Promise returned to indicate that the mute status of the stream is obtained ${value}.`); }); ``` -### setRingerMode9+ +### isActive(deprecated) + +isActive(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void + +Checks whether a stream is active. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isActive](#isactive9) in **AudioStreamManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite.| + +**Example** + +```js +audioManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => { + if (err) { + console.error(`Failed to obtain the active status of the stream. ${err}`); + return; + } + console.info(`Callback invoked to indicate that the active status of the stream is obtained ${value}.`); +}); +``` + +### isActive(deprecated) + +isActive(volumeType: AudioVolumeType): Promise<boolean> + +Checks whether a stream is active. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isActive](#isactive9) in **AudioStreamManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| + +**Return value** + +| Type | Description | +| ---------------------- | -------------------------------------------------------- | +| Promise<boolean> | Promise used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite.| + +**Example** + +```js +audioManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promise returned to indicate that the active status of the stream is obtained ${value}.`); +}); +``` + +### setRingerMode(deprecated) setRingerMode(mode: AudioRingMode, callback: AsyncCallback<void>): void Sets the ringer mode. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setRingerMode](#setringermode9) in **AudioVolumeGroupManager**. + **Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY This permission is required only for muting or unmuting the ringer. -**System API**: This is a system API. - -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Communication **Parameters** @@ -1639,7 +1578,7 @@ This permission is required only for muting or unmuting the ringer. **Example** ```js -audioVolumeGroupManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => { +audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => { if (err) { console.error(`Failed to set the ringer mode.​ ${err}`); return; @@ -1648,19 +1587,21 @@ audioVolumeGroupManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (e }); ``` -### setRingerMode9+ +### setRingerMode(deprecated) setRingerMode(mode: AudioRingMode): Promise<void> Sets the ringer mode. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setRingerMode](#setringermode9) in **AudioVolumeGroupManager**. + **Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY This permission is required only for muting or unmuting the ringer. -**System API**: This is a system API. - -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Communication **Parameters** @@ -1677,18 +1618,22 @@ This permission is required only for muting or unmuting the ringer. **Example** ```js -audioVolumeGroupManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => { +audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => { console.info('Promise returned to indicate a successful setting of the ringer mode.'); }); ``` -### getRingerMode9+ +### getRingerMode(deprecated) getRingerMode(callback: AsyncCallback<AudioRingMode>): void Obtains the ringer mode. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getRingerMode](#getringermode9) in **AudioVolumeGroupManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Communication **Parameters** @@ -1699,7 +1644,7 @@ Obtains the ringer mode. This API uses an asynchronous callback to return the re **Example** ```js -audioVolumeGroupManager.getRingerMode((err, value) => { +audioManager.getRingerMode((err, value) => { if (err) { console.error(`Failed to obtain the ringer mode.​ ${err}`); return; @@ -1708,13 +1653,17 @@ audioVolumeGroupManager.getRingerMode((err, value) => { }); ``` -### getRingerMode9+ +### getRingerMode(deprecated) getRingerMode(): Promise<AudioRingMode> Obtains the ringer mode. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getRingerMode](#getringermode9) in **AudioVolumeGroupManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Communication **Return value** @@ -1725,85 +1674,123 @@ Obtains the ringer mode. This API uses a promise to return the result. **Example** ```js -audioVolumeGroupManager.getRingerMode().then((value) => { +audioManager.getRingerMode().then((value) => { console.info(`Promise returned to indicate that the ringer mode is obtained ${value}.`); }); ``` -### on('ringerModeChange')9+ +### getDevices(deprecated) -on(type: 'ringerModeChange', callback: Callback\): void +getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescriptors>): void -Subscribes to ringer mode change events. +Obtains the audio devices with a specific flag. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getDevices](#getdevices9) in **AudioRoutingManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **'ringerModeChange'** means the ringer mode change event, which is triggered when a ringer mode change is detected.| -| callback | Callback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the system volume change event. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | -------------------- | +| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | +| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Yes | Callback used to return the device list.| -**Error codes** +**Example** +```js +audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) => { + if (err) { + console.error(`Failed to obtain the device list. ${err}`); + return; + } + console.info('Callback invoked to indicate that the device list is obtained.'); +}); +``` -For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). +### getDevices(deprecated) -| ID| Error Message| -| ------- | --------------------------------------------| -| 6800101 | if input parameter value error. | +getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors> + +Obtains the audio devices with a specific flag. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getDevices](#getdevices9) in **AudioRoutingManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Device + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------- | ---- | ---------------- | +| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ------------------------- | +| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise used to return the device list.| **Example** ```js -audioVolumeGroupManager.on('ringerModeChange', (ringerMode) => { - console.info(`Updated ringermode: ${ringerMode}`); +audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { + console.info('Promise returned to indicate that the device list is obtained.'); }); ``` -### setMicrophoneMute9+ -setMicrophoneMute(mute: boolean, callback: AsyncCallback<void>): void +### setDeviceActive(deprecated) -Mutes or unmutes the microphone. This API uses an asynchronous callback to return the result. +setDeviceActive(deviceType: ActiveDeviceType, active: boolean, callback: AsyncCallback<void>): void -**Required permissions**: ohos.permission.MANAGE_AUDIO_CONFIG +Sets a device to the active state. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setCommunicationDevice](#setcommunicationdevice9) in **AudioRoutingManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | --------------------------------------------- | -| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------- | ---- | ------------------------ | +| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Audio device type. | +| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** ```js -audioVolumeGroupManager.setMicrophoneMute(true, (err) => { +audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true, (err) => { if (err) { - console.error(`Failed to mute the microphone. ${err}`); + console.error(`Failed to set the active status of the device. ${err}`); return; } - console.info('Callback invoked to indicate that the microphone is muted.'); + console.info('Callback invoked to indicate that the device is set to the active status.'); }); ``` -### setMicrophoneMute9+ +### setDeviceActive(deprecated) -setMicrophoneMute(mute: boolean): Promise<void> +setDeviceActive(deviceType: ActiveDeviceType, active: boolean): Promise<void> -Mutes or unmutes the microphone. This API uses a promise to return the result. +Sets a device to the active state. This API uses a promise to return the result. -**Required permissions**: ohos.permission.MANAGE_AUDIO_CONFIG +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setCommunicationDevice](#setcommunicationdevice9) in **AudioRoutingManager**. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------- | ---- | --------------------------------------------- | -| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------- | ---- | ------------------ | +| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Audio device type.| +| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | **Return value** @@ -1813,552 +1800,539 @@ Mutes or unmutes the microphone. This API uses a promise to return the result. **Example** + ```js -audioVolumeGroupManager.setMicrophoneMute(true).then(() => { - console.info('Promise returned to indicate that the microphone is muted.'); +audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true).then(() => { + console.info('Promise returned to indicate that the device is set to the active status.'); }); ``` -### isMicrophoneMute9+ +### isDeviceActive(deprecated) -isMicrophoneMute(callback: AsyncCallback<boolean>): void +isDeviceActive(deviceType: ActiveDeviceType, callback: AsyncCallback<boolean>): void -Checks whether the microphone is muted. This API uses an asynchronous callback to return the result. +Checks whether a device is active. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isCommunicationDeviceActive](#iscommunicationdeviceactive9) in **AudioRoutingManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------- | ---- | ------------------------------------------------------- | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------- | ---- | ------------------------ | +| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Audio device type. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the active state of the device.| **Example** ```js -audioVolumeGroupManager.isMicrophoneMute((err, value) => { +audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER, (err, value) => { if (err) { - console.error(`Failed to obtain the mute status of the microphone. ${err}`); + console.error(`Failed to obtain the active status of the device. ${err}`); return; } - console.info(`Callback invoked to indicate that the mute status of the microphone is obtained ${value}.`); + console.info('Callback invoked to indicate that the active status of the device is obtained.'); }); ``` -### isMicrophoneMute9+ +### isDeviceActive(deprecated) -isMicrophoneMute(): Promise<boolean> +isDeviceActive(deviceType: ActiveDeviceType): Promise<boolean> -Checks whether the microphone is muted. This API uses a promise to return the result. +Checks whether a device is active. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isCommunicationDeviceActive](#iscommunicationdeviceactive9) in **AudioRoutingManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Device + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------- | ---- | ------------------ | +| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Audio device type.| **Return value** -| Type | Description | -| ---------------------- | ------------------------------------------------------------ | -| Promise<boolean> | Promise used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite.| +| Type | Description | +| ---------------------- | ------------------------------- | +| Promise<boolean> | Promise used to return the active state of the device.| **Example** ```js -audioVolumeGroupManager.isMicrophoneMute().then((value) => { - console.info(`Promise returned to indicate that the mute status of the microphone is obtained ${value}.`); +audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER).then((value) => { + console.info(`Promise returned to indicate that the active status of the device is obtained ${value}.`); }); ``` -### on('micStateChange')9+ +### setMicrophoneMute(deprecated) -on(type: 'micStateChange', callback: Callback<MicStateChangeEvent>): void +setMicrophoneMute(mute: boolean, callback: AsyncCallback<void>): void -Subscribes to system mic state change events. +Mutes or unmutes the microphone. This API uses an asynchronous callback to return the result. -Currently, when multiple **AudioManager** instances are used in a single process, only the subscription of the last instance takes effect, and the subscription of other instances is overwritten (even if the last instance does not initiate a subscription). Therefore, you are advised to use a single **AudioManager** instance. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setMicrophoneMute](#setmicrophonemute9) in **AudioVolumeGroupManager**. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**Required permissions**: ohos.permission.MICROPHONE + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **'micStateChange'** means the system mic state change event, which is triggered when the system mic state changes.| -| callback | Callback<[MicStateChangeEvent](#micstatechangeevent9)> | Yes | Callback used to return the changed micr state. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | --------------------------------------------- | +| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | -**Error codes** +**Example** -For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). +```js +audioManager.setMicrophoneMute(true, (err) => { + if (err) { + console.error(`Failed to mute the microphone. ${err}`); + return; + } + console.info('Callback invoked to indicate that the microphone is muted.'); +}); +``` -| ID| Error Message| -| ------- | --------------------------------------------| -| 6800101 | if input parameter value error. | +### setMicrophoneMute(deprecated) + +setMicrophoneMute(mute: boolean): Promise<void> + +Mutes or unmutes the microphone. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setMicrophoneMute](#setmicrophonemute9) in **AudioVolumeGroupManager**. + +**Required permissions**: ohos.permission.MICROPHONE + +**System capability**: SystemCapability.Multimedia.Audio.Device + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | --------------------------------------------- | +| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------- | +| Promise<void> | Promise used to return the result.| **Example** ```js -audioVolumeGroupManager.on('micStateChange', (micStateChange) => { - console.info(`Current microphone status is: ${micStateChange.mute} `); +audioManager.setMicrophoneMute(true).then(() => { + console.info('Promise returned to indicate that the microphone is muted.'); }); ``` -## AudioStreamManager9+ +### isMicrophoneMute(deprecated) -Implements audio stream management. Before calling any API in **AudioStreamManager**, you must use [getStreamManager](#getstreammanager9) to obtain an **AudioStreamManager** instance. +isMicrophoneMute(callback: AsyncCallback<boolean>): void -### getCurrentAudioRendererInfoArray9+ +Checks whether the microphone is muted. This API uses an asynchronous callback to return the result. -getCurrentAudioRendererInfoArray(callback: AsyncCallback<AudioRendererChangeInfoArray>): void +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isMicrophoneMute](#ismicrophonemute9) in **AudioVolumeGroupManager**. -Obtains the information about the current audio renderer. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.MICROPHONE -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ----------------------------------- | -------- | --------------------------- | -| callback | AsyncCallback<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Yes | Callback used to return the audio renderer information.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------------------------------- | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite.| **Example** ```js -audioStreamManager.getCurrentAudioRendererInfoArray(async (err, AudioRendererChangeInfoArray) => { - console.info('getCurrentAudioRendererInfoArray **** Get Callback Called ****'); +audioManager.isMicrophoneMute((err, value) => { if (err) { - console.error(`getCurrentAudioRendererInfoArray :ERROR: ${err}`); - } else { - if (AudioRendererChangeInfoArray != null) { - for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { - let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; - console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); - console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`); - console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); - console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); - console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); - console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`); - for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); - console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); - console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); - console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); - console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); - } - } - } + console.error(`Failed to obtain the mute status of the microphone. ${err}`); + return; } + console.info(`Callback invoked to indicate that the mute status of the microphone is obtained ${value}.`); }); ``` -### getCurrentAudioRendererInfoArray9+ +### isMicrophoneMute(deprecated) -getCurrentAudioRendererInfoArray(): Promise<AudioRendererChangeInfoArray> +isMicrophoneMute(): Promise<boolean> -Obtains the information about the current audio renderer. This API uses a promise to return the result. +Checks whether the microphone is muted. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isMicrophoneMute](#ismicrophonemute9) in **AudioVolumeGroupManager**. + +**Required permissions**: ohos.permission.MICROPHONE + +**System capability**: SystemCapability.Multimedia.Audio.Device **Return value** -| Type | Description | -| ---------------------------------------------------------------------------------| --------------------------------------- | -| Promise<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Promise used to return the audio renderer information. | +| Type | Description | +| ---------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite.| **Example** ```js -async function getCurrentAudioRendererInfoArray(){ - await audioStreamManager.getCurrentAudioRendererInfoArray().then( function (AudioRendererChangeInfoArray) { - console.info(`getCurrentAudioRendererInfoArray ######### Get Promise is called ##########`); - if (AudioRendererChangeInfoArray != null) { - for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { - let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; - console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); - console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`); - console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); - console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); - console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); - console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`); - for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); - console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); - console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); - console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); - console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); - } - } - } - }).catch((err) => { - console.error(`getCurrentAudioRendererInfoArray :ERROR: ${err}`); - }); -} +audioManager.isMicrophoneMute().then((value) => { + console.info(`Promise returned to indicate that the mute status of the microphone is obtained ${value}.`); +}); ``` -### getCurrentAudioCapturerInfoArray9+ +### on('volumeChange')(deprecated) -getCurrentAudioCapturerInfoArray(callback: AsyncCallback<AudioCapturerChangeInfoArray>): void +on(type: 'volumeChange', callback: Callback\): void -Obtains the information about the current audio capturer. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [on](#on9) in **AudioVolumeManager**. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +Subscribes to system volume change events. + +**System API**: This is a system API. + +Currently, when multiple **AudioManager** instances are used in a single process, only the subscription of the last instance takes effect, and the subscription of other instances is overwritten (even if the last instance does not initiate a subscription). Therefore, you are advised to use a single **AudioManager** instance. + +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | -------------------------------------------------------- | -| callback | AsyncCallback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Yes | Callback used to return the audio capturer information.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **'volumeChange'** means the system volume change event, which is triggered when a system volume change is detected.| +| callback | Callback<[VolumeEvent](#volumeevent8)> | Yes | Callback used to return the system volume change event. | **Example** ```js -audioStreamManager.getCurrentAudioCapturerInfoArray(async (err, AudioCapturerChangeInfoArray) => { - console.info('getCurrentAudioCapturerInfoArray **** Get Callback Called ****'); - if (err) { - console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`); - } else { - if (AudioCapturerChangeInfoArray != null) { - for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); - console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); - console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); - console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); - console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); - for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); - console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); - console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); - console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); - console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); - } - } - } - } +audioManager.on('volumeChange', (volumeEvent) => { + console.info(`VolumeType of stream: ${volumeEvent.volumeType} `); + console.info(`Volume level: ${volumeEvent.volume} `); + console.info(`Whether to updateUI: ${volumeEvent.updateUi} `); }); ``` -### getCurrentAudioCapturerInfoArray9+ +### on('ringerModeChange')(deprecated) -getCurrentAudioCapturerInfoArray(): Promise<AudioCapturerChangeInfoArray> +on(type: 'ringerModeChange', callback: Callback\): void -Obtains the information about the current audio capturer. This API uses a promise to return the result. +Subscribes to ringer mode change events. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [on('ringerModeChange')](#onringermodechange9) in **AudioVolumeGroupManager**. -**Return value** +**System API**: This is a system API. -| Type | Description | -| -----------------------------------------------------------------------------| ----------------------------------- | -| Promise<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Promise used to return the audio capturer information. | +**System capability**: SystemCapability.Multimedia.Audio.Communication + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **'ringerModeChange'** means the ringer mode change event, which is triggered when a ringer mode change is detected.| +| callback | Callback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the ringer mode change event. | **Example** ```js -async function getCurrentAudioCapturerInfoArray(){ - await audioStreamManager.getCurrentAudioCapturerInfoArray().then( function (AudioCapturerChangeInfoArray) { - console.info('getCurrentAudioCapturerInfoArray **** Get Promise Called ****'); - if (AudioCapturerChangeInfoArray != null) { - for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); - console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); - console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); - console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); - console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); - for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); - console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); - console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); - console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); - console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); - } - } - } - }).catch((err) => { - console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`); - }); -} +audioManager.on('ringerModeChange', (ringerMode) => { + console.info(`Updated ringermode: ${ringerMode}`); +}); ``` -### on('audioRendererChange')9+ - -on(type: "audioRendererChange", callback: Callback<AudioRendererChangeInfoArray>): void - -Subscribes to audio renderer change events. +### on('deviceChange')(deprecated) -**System capability**: SystemCapability.Multimedia.Audio.Renderer +on(type: 'deviceChange', callback: Callback): void -**Parameters** +Subscribes to device change events. When a device is connected or disconnected, registered clients will receive the callback. -| Name | Type | Mandatory | Description | -| -------- | ---------- | --------- | ------------------------------------------------------------------------ | -| type | string | Yes | Event type. The event `'audioRendererChange'` is triggered when the audio renderer changes. | -| callback | Callback<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Yes | Callback used to return the result. | +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [on](#on9) in **AudioRoutingManager**. -**Error codes** +**System capability**: SystemCapability.Multimedia.Audio.Device -For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). +**Parameters** -| ID| Error Message| -| ------- | --------------------------------------------| -| 6800101 | if input parameter value error. | +| Name | Type | Mandatory| Description | +| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- | +| type | string | Yes | Event type. The value **'deviceChange'** means the device change event, which is triggered when a device connection status change is detected.| +| callback | Callback<[DeviceChangeAction](#devicechangeaction)\> | Yes | Callback used to return the device update details. | **Example** ```js -audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => { - for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { - let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; - console.info(`## RendererChange on is called for ${i} ##`); - console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); - console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`); - console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); - console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); - console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); - console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`); - for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); - console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); - console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); - console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); - console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); - } - } +audioManager.on('deviceChange', (deviceChanged) => { + console.info(`device change type : ${deviceChanged.type} `); + console.info(`device descriptor size : ${deviceChanged.deviceDescriptors.length} `); + console.info(`device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceRole} `); + console.info(`device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceType} `); }); ``` -### off('audioRendererChange')9+ - -off(type: "audioRendererChange"): void - -Unsubscribes from audio renderer change events. +### off('deviceChange')(deprecated) -**System capability**: SystemCapability.Multimedia.Audio.Renderer +off(type: 'deviceChange', callback?: Callback): void -**Parameters** +Unsubscribes from device change events. -| Name | Type | Mandatory| Description | -| -------- | ------- | ---- | ---------------- | -| type | string | Yes | Event type. The event `'audioRendererChange'` is triggered when the audio renderer changes.| +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [off](#off9) in **AudioRoutingManager**. -**Error codes** +**System capability**: SystemCapability.Multimedia.Audio.Device -For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). +**Parameters** -| ID| Error Message| -| ------- | --------------------------------------------| -| 6800101 | if input parameter value error. | +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ------------------------------------------ | +| type | string | Yes | Event type. The value **'deviceChange'** means the device change event, which is triggered when a device connection status change is detected.| +| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | No | Callback used to return the device update details. | **Example** ```js -audioStreamManager.off('audioRendererChange'); -console.info('######### RendererChange Off is called #########'); +audioManager.off('deviceChange', (deviceChanged) => { + console.info('Should be no callback.'); +}); ``` -### on('audioCapturerChange')9+ +### on('interrupt')(deprecated) -on(type: "audioCapturerChange", callback: Callback<AudioCapturerChangeInfoArray>): void +on(type: 'interrupt', interrupt: AudioInterrupt, callback: Callback\): void -Subscribes to audio capturer change events. +Subscribes to audio interruption events. When the application's audio is interrupted by another playback event, the application will receive the callback. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +Same as [on('audioInterrupt')](#onaudiointerrupt9), this API is used to listen for focus changes. However, this API is used in scenarios without audio streams (no **AudioRenderer** instance is created), such as frequency modulation (FM) and voice wakeup. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------- | --------- | ----------------------------------------------------------------------- | -| type | string | Yes | Event type. The event `'audioCapturerChange'` is triggered when the audio capturer changes. | -| callback | Callback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **'interrupt'** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application.| +| interrupt | AudioInterrupt | Yes | Audio interruption event type. | +| callback | Callback<[InterruptAction](#interruptactiondeprecated)> | Yes | Callback invoked for the audio interruption event. | **Example** ```js -audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { - for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - console.info(`## CapChange on is called for element ${i} ##`); - console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); - console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); - console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); - console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); - console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); - let devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors; - for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); - console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); - console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); - console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); - console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); - } +let interAudioInterrupt = { + streamUsage:2, + contentType:0, + pauseWhenDucked:true +}; +audioManager.on('interrupt', interAudioInterrupt, (InterruptAction) => { + if (InterruptAction.actionType === 0) { + console.info('An event to gain the audio focus starts.'); + console.info(`Focus gain event: ${InterruptAction} `); + } + if (InterruptAction.actionType === 1) { + console.info('An audio interruption event starts.'); + console.info(`Audio interruption event: ${InterruptAction} `); } }); ``` -### off('audioCapturerChange')9+ +### off('interrupt')(deprecated) -off(type: "audioCapturerChange"): void; +off(type: 'interrupt', interrupt: AudioInterrupt, callback?: Callback\): void -Unsubscribes from audio capturer change events. +Unsubscribes from audio interruption events. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------- | --- | ------------------------------------------------------------- | -| type | string |Yes | Event type. The event `'audioCapturerChange'` is triggered when the audio capturer changes.| +| Name | Type | Mandatory| Description | +| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **'interrupt'** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application.| +| interrupt | AudioInterrupt | Yes | Audio interruption event type. | +| callback | Callback<[InterruptAction](#interruptactiondeprecated)> | No | Callback invoked for the audio interruption event. | **Example** ```js -audioStreamManager.off('audioCapturerChange'); -console.info('######### CapturerChange Off is called #########'); - +let interAudioInterrupt = { + streamUsage:2, + contentType:0, + pauseWhenDucked:true +}; +audioManager.off('interrupt', interAudioInterrupt, (InterruptAction) => { + if (InterruptAction.actionType === 0) { + console.info('An event to release the audio focus starts.'); + console.info(`Focus release event: ${InterruptAction} `); + } +}); ``` -### isActive9+ +## AudioVolumeManager9+ -isActive(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void +Implements audio volume management. Before calling an API in **AudioVolumeManager**, you must use [getVolumeManager](#getvolumemanager9) to obtain an **AudioVolumeManager** instance. -Checks whether a stream is active. This API uses an asynchronous callback to return the result. +### getVolumeGroupInfos9+ -**System capability**: SystemCapability.Multimedia.Audio.Renderer +getVolumeGroupInfos(networkId: string, callback: AsyncCallback\): void + +Obtains the volume groups. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ----------------------------------- | ---- | ------------------------------------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | -------------------- | +| networkId | string | Yes | Network ID of the device. The network ID of the local device is **audio.LOCAL_NETWORK_ID**. | +| callback | AsyncCallback<[VolumeGroupInfos](#volumegroupinfos9)> | Yes | Callback used to return the volume group information array.| **Example** - ```js -audioStreamManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => { +audioVolumeManager.getVolumeGroupInfos(audio.LOCAL_NETWORK_ID, (err, value) => { if (err) { - console.error(`Failed to obtain the active status of the stream. ${err}`); + console.error(`Failed to obtain the volume group infos list. ${err}`); return; } - console.info(`Callback invoked to indicate that the active status of the stream is obtained ${value}.`); + console.info('Callback invoked to indicate that the volume group infos list is obtained.'); }); ``` -### isActive9+ +### getVolumeGroupInfos9+ -isActive(volumeType: AudioVolumeType): Promise<boolean> +getVolumeGroupInfos(networkId: string\): Promise -Checks whether a stream is active. This API uses a promise to return the result. +Obtains the volume groups. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ----------------------------------- | ---- | ------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------| ---- | -------------------- | +| networkId | string | Yes | Network ID of the device. The network ID of the local device is **audio.LOCAL_NETWORK_ID**. | **Return value** -| Type | Description | -| ---------------------- | -------------------------------------------------------- | -| Promise<boolean> | Promise used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite.| +| Type | Description | +| ------------------- | ----------------------------- | +| Promise<[VolumeGroupInfos](#volumegroupinfos9)> | Volume group information array.| **Example** ```js -audioStreamManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promise returned to indicate that the active status of the stream is obtained ${value}.`); -}); -``` - -## AudioRoutingManager9+ - -Implements audio routing management. Before calling any API in **AudioRoutingManager**, you must use [getRoutingManager](#getroutingmanager9) to obtain an **AudioRoutingManager** instance. +async function getVolumeGroupInfos(){ + let volumegroupinfos = await audio.getAudioManager().getVolumeManager().getVolumeGroupInfos(audio.LOCAL_NETWORK_ID); + console.info('Promise returned to indicate that the volumeGroup list is obtained.'+JSON.stringify(volumegroupinfos)) +} +``` -### getDevices9+ +### getVolumeGroupManager9+ -getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescriptors>): void +getVolumeGroupManager(groupId: number, callback: AsyncCallback\): void -Obtains the audio devices with a specific flag. This API uses an asynchronous callback to return the result. +Obtains the audio group manager. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | -------------------- | -| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | -| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Yes | Callback used to return the device list.| +| groupId | number | Yes | Volume group ID. | +| callback | AsyncCallback<[AudioVolumeGroupManager](#audiovolumegroupmanager9)> | Yes | Callback used to return the audio group manager.| **Example** ```js -audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) => { +let groupid = audio.DEFAULT_VOLUME_GROUP_ID; +audioVolumeManager.getVolumeGroupManager(groupid, (err, value) => { if (err) { - console.error(`Failed to obtain the device list. ${err}`); + console.error(`Failed to obtain the volume group infos list. ${err}`); return; } - console.info('Callback invoked to indicate that the device list is obtained.'); + console.info('Callback invoked to indicate that the volume group infos list is obtained.'); }); + ``` -### getDevices9+ +### getVolumeGroupManager9+ -getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors> +getVolumeGroupManager(groupId: number\): Promise -Obtains the audio devices with a specific flag. This API uses a promise to return the result. +Obtains the audio group manager. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------- | ---- | ---------------- | -| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag.| +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------------- | ---- | ---------------- | +| groupId | number | Yes | Volume group ID. | **Return value** -| Type | Description | -| ------------------------------------------------------------ | ------------------------- | -| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise used to return the device list.| +| Type | Description | +| ------------------- | ----------------------------- | +| Promise< [AudioVolumeGroupManager](#audiovolumegroupmanager9) > | Promise used to return the audio group manager.| **Example** ```js -audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { - console.info('Promise returned to indicate that the device list is obtained.'); -}); +let groupid = audio.DEFAULT_VOLUME_GROUP_ID; +let audioVolumeGroupManager; +getVolumeGroupManager(); +async function getVolumeGroupManager(){ + audioVolumeGroupManager = await audioVolumeManager.getVolumeGroupManager(groupid); + console.info('Callback invoked to indicate that the volume group infos list is obtained.'); +} + ``` -### on9+ +### on('volumeChange')9+ -on(type: 'deviceChange', deviceFlag: DeviceFlag, callback: Callback): void +on(type: 'volumeChange', callback: Callback\): void -Subscribes to device change events. When a device is connected or disconnected, registered clients will receive the callback. +Subscribes to system volume change events. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- | -| type | string | Yes | Event type. The value **'deviceChange'** means the device change event, which is triggered when a device connection status change is detected.| -| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | -| callback | Callback<[DeviceChangeAction](#devicechangeaction)\> | Yes | Callback used to return the device update details. | +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **'volumeChange'** means the system volume change event, which is triggered when the system volume changes.| +| callback | Callback<[VolumeEvent](#volumeevent8)> | Yes | Callback used to return the system volume change event. | **Error codes** @@ -2366,2108 +2340,2324 @@ For details about the error codes, see [Audio Error Codes](../errorcodes/errorco | ID| Error Message| | ------- | --------------------------------------------| -| 6800101 | if input parameter value error. | +| 6800101 | if input parameter value error | **Example** ```js -audioRoutingManager.on('deviceChange', audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (deviceChanged) => { - console.info('device change type : ' + deviceChanged.type); - console.info('device descriptor size : ' + deviceChanged.deviceDescriptors.length); - console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceRole); - console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceType); +audioVolumeManager.on('volumeChange', (volumeEvent) => { + console.info(`VolumeType of stream: ${volumeEvent.volumeType} `); + console.info(`Volume level: ${volumeEvent.volume} `); + console.info(`Whether to updateUI: ${volumeEvent.updateUi} `); }); ``` -### off9+ - -off(type: 'deviceChange', callback?: Callback): void - -Unsubscribes from device change events. - -**System capability**: SystemCapability.Multimedia.Audio.Device - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------------------- | ---- | ------------------------------------------ | -| type | string | Yes | Event type. The value **'deviceChange'** means the device change event, which is triggered when a device connection status change is detected.| -| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | No | Callback used to return the device update details. | +## AudioVolumeGroupManager9+ -**Error codes** +Manages the volume of an audio group. Before calling any API in **AudioVolumeGroupManager**, you must use [getVolumeGroupManager](#getvolumegroupmanager9) to obtain an **AudioVolumeGroupManager** instance. -For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). +**System API**: This is a system API. -| ID| Error Message| -| ------- | --------------------------------------------| -| 6800101 | if input parameter value error. | +**System capability**: SystemCapability.Multimedia.Audio.Volume -**Example** +### setVolume9+ -```js -audioRoutingManager.off('deviceChange', (deviceChanged) => { - console.info('Should be no callback.'); -}); -``` +setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback<void>): void -### selectInputDevice9+ +Sets the volume for a stream. This API uses an asynchronous callback to return the result. -selectInputDevice(inputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY -Selects an audio input device. Currently, only one input device can be selected. This API uses an asynchronous callback to return the result. +This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. **System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | -| inputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Input device. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** -```js -let inputAudioDeviceDescriptor = [{ - "deviceRole":audio.DeviceRole.INPUT_DEVICE, - "networkId":audio.LOCAL_NETWORK_ID, - "interruptGroupId":1, - "volumeGroupId":1 }]; -async function selectInputDevice(){ - audioRoutingManager.selectInputDevice(inputAudioDeviceDescriptor, (err) => { - if (err) { - console.error(`Result ERROR: ${err}`); - } else { - console.info('Select input devices result callback: SUCCESS'); } - }); -} +```js +audioVolumeGroupManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => { + if (err) { + console.error(`Failed to set the volume. ${err}`); + return; + } + console.info('Callback invoked to indicate a successful volume setting.'); +}); ``` -### selectInputDevice9+ +### setVolume9+ -selectInputDevice(inputAudioDevices: AudioDeviceDescriptors): Promise<void> +setVolume(volumeType: AudioVolumeType, volume: number): Promise<void> -**System API**: This is a system API. +Sets the volume for a stream. This API uses a promise to return the result. -Selects an audio input device. Currently, only one input device can be selected. This API uses a promise to return the result. +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY -**System capability**: SystemCapability.Multimedia.Audio.Device +This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | -| inputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Input device. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**.| **Return value** -| Type | Description | -| --------------------- | --------------------------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| ------------------- | ----------------------------- | +| Promise<void> | Promise used to return the result.| **Example** ```js -let inputAudioDeviceDescriptor =[{ - "deviceRole":audio.DeviceRole.INPUT_DEVICE, - "networkId":audio.LOCAL_NETWORK_ID, - "interruptGroupId":1, - "volumeGroupId":1 }]; - -async function getRoutingManager(){ - audioRoutingManager.selectInputDevice(inputAudioDeviceDescriptor).then(() => { - console.info('Select input devices result promise: SUCCESS'); - }).catch((err) => { - console.error(`Result ERROR: ${err}`); - }); -} +audioVolumeGroupManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => { + console.info('Promise returned to indicate a successful volume setting.'); +}); ``` -### setCommunicationDevice9+ +### getVolume9+ -setCommunicationDevice(deviceType: CommunicationDeviceType, active: boolean, callback: AsyncCallback<void>): void +getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void -Sets a communication device to the active state. This API uses an asynchronous callback to return the result. +Obtains the volume of a stream. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------------------- | ---- | ------------------------ | -| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type. | -| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<number> | Yes | Callback used to return the volume.| **Example** ```js -audioRoutingManager.setCommunicationDevice(audio.CommunicationDeviceType.SPEAKER, true, (err) => { +audioVolumeGroupManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error(`Failed to set the active status of the device. ${err}`); + console.error(`Failed to obtain the volume. ${err}`); return; } - console.info('Callback invoked to indicate that the device is set to the active status.'); + console.info('Callback invoked to indicate that the volume is obtained.'); }); ``` -### setCommunicationDevice9+ +### getVolume9+ -setCommunicationDevice(deviceType: CommunicationDeviceType, active: boolean): Promise<void> +getVolume(volumeType: AudioVolumeType): Promise<number> -Sets a communication device to the active state. This API uses a promise to return the result. +Obtains the volume of a stream. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ----------------------------------------------------- | ---- | ------------------ | -| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type.| -| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| **Return value** -| Type | Description | -| ------------------- | ------------------------------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| --------------------- | ------------------------- | +| Promise<number> | Promise used to return the volume.| **Example** ```js -audioRoutingManager.setCommunicationDevice(audio.CommunicationDeviceType.SPEAKER, true).then(() => { - console.info('Promise returned to indicate that the device is set to the active status.'); +audioVolumeGroupManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promise returned to indicate that the volume is obtained ${value}.`); }); ``` -### isCommunicationDeviceActive9+ +### getMinVolume9+ -isCommunicationDeviceActive(deviceType: CommunicationDeviceType, callback: AsyncCallback<boolean>): void +getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void -Checks whether a communication device is active. This API uses an asynchronous callback to return the result. +Obtains the minimum volume allowed for a stream. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ---------------------------------------------------- | ---- | ------------------------ | -| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the active state of the device.| +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<number> | Yes | Callback used to return the minimum volume.| **Example** ```js -audioRoutingManager.isCommunicationDeviceActive(audio.CommunicationDeviceType.SPEAKER, (err, value) => { +audioVolumeGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error(`Failed to obtain the active status of the device. ${err}`); + console.error(`Failed to obtain the minimum volume. ${err}`); return; } - console.info('Callback invoked to indicate that the active status of the device is obtained.'); + console.info(`Callback invoked to indicate that the minimum volume is obtained. ${value}`); }); ``` -### isCommunicationDeviceActive9+ +### getMinVolume9+ -isCommunicationDeviceActive(deviceType: CommunicationDeviceType): Promise<boolean> +getMinVolume(volumeType: AudioVolumeType): Promise<number> -Checks whether a communication device is active. This API uses a promise to return the result. +Obtains the minimum volume allowed for a stream. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ---------------------------------------------------- | ---- | ------------------ | -| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type.| +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| **Return value** -| Type | Description | -| ---------------------- | ------------------------------- | -| Promise<boolean> | Promise used to return the active state of the device.| +| Type | Description | +| --------------------- | ------------------------- | +| Promise<number> | Promise used to return the minimum volume.| **Example** ```js -audioRoutingManager.isCommunicationDeviceActive(audio.CommunicationDeviceType.SPEAKER).then((value) => { - console.info(`Promise returned to indicate that the active status of the device is obtained ${value}.`); +audioVolumeGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promised returned to indicate that the minimum volume is obtained ${value}.`); }); ``` -### selectOutputDevice9+ - -selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void +### getMaxVolume9+ -Selects an audio output device. Currently, only one output device can be selected. This API uses an asynchronous callback to return the result. +getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void -**System API**: This is a system API. +Obtains the maximum volume allowed for a stream. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | -| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ---------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<number> | Yes | Callback used to return the maximum volume.| **Example** + ```js -let outputAudioDeviceDescriptor = [{ - "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, - "networkId":audio.LOCAL_NETWORK_ID, - "interruptGroupId":1, - "volumeGroupId":1 }]; -async function selectOutputDevice(){ - audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor, (err) => { - if (err) { - console.error(`Result ERROR: ${err}`); - } else { - console.info('Select output devices result callback: SUCCESS'); } - }); -} +audioVolumeGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => { + if (err) { + console.error(`Failed to obtain the maximum volume. ${err}`); + return; + } + console.info(`Callback invoked to indicate that the maximum volume is obtained. ${value}`); +}); ``` -### selectOutputDevice9+ - -selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors): Promise<void> +### getMaxVolume9+ -**System API**: This is a system API. +getMaxVolume(volumeType: AudioVolumeType): Promise<number> -Selects an audio output device. Currently, only one output device can be selected. This API uses a promise to return the result. +Obtains the maximum volume allowed for a stream. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | -| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| **Return value** -| Type | Description | -| --------------------- | --------------------------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| --------------------- | ----------------------------- | +| Promise<number> | Promise used to return the maximum volume.| **Example** ```js -let outputAudioDeviceDescriptor =[{ - "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, - "networkId":audio.LOCAL_NETWORK_ID, - "interruptGroupId":1, - "volumeGroupId":1 }]; - -async function selectOutputDevice(){ - audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor).then(() => { - console.info('Select output devices result promise: SUCCESS'); - }).catch((err) => { - console.error(`Result ERROR: ${err}`); - }); -} +audioVolumeGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => { + console.info('Promised returned to indicate that the maximum volume is obtained.'); +}); ``` -### selectOutputDeviceByFilter9+ +### mute9+ -selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void +mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void>): void -**System API**: This is a system API. +Mutes or unmutes a stream. This API uses an asynchronous callback to return the result. -Selects an audio output device based on the filter criteria. Currently, only one output device can be selected. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY -**System capability**: SystemCapability.Multimedia.Audio.Device +This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | -| filter | [AudioRendererFilter](#audiorendererfilter9) | Yes | Filter criteria. | -| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| mute | boolean | Yes | Mute status to set. The value **true** means to mute the stream, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** -```js -let outputAudioRendererFilter = { - "uid":20010041, - "rendererInfo": { - "contentType":audio.ContentType.CONTENT_TYPE_MUSIC, - "streamUsage":audio.StreamUsage.STREAM_USAGE_MEDIA, - "rendererFlags":0 }, - "rendererId":0 }; -let outputAudioDeviceDescriptor = [{ - "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, - "networkId":audio.LOCAL_NETWORK_ID, - "interruptGroupId":1, - "volumeGroupId":1 }]; -async function selectOutputDeviceByFilter(){ - audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor, (err) => { - if (err) { - console.error(`Result ERROR: ${err}`); - } else { - console.info('Select output devices by filter result callback: SUCCESS'); } - }); -} +```js +audioVolumeGroupManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { + if (err) { + console.error(`Failed to mute the stream. ${err}`); + return; + } + console.info('Callback invoked to indicate that the stream is muted.'); +}); ``` -### selectOutputDeviceByFilter9+ +### mute9+ -selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors): Promise<void> +mute(volumeType: AudioVolumeType, mute: boolean): Promise<void> -**System API**: This is a system API. +Mutes or unmutes a stream. This API uses a promise to return the result. -Selects an audio output device based on the filter criteria. Currently, only one output device can be selected. This API uses a promise to return the result. +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY -**System capability**: SystemCapability.Multimedia.Audio.Device +This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| ----------------------| ------------------------------------------------------------ | ---- | ------------------------- | -| filter | [AudioRendererFilter](#audiorendererfilter9) | Yes | Filter criteria. | -| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| mute | boolean | Yes | Mute status to set. The value **true** means to mute the stream, and **false** means the opposite.| **Return value** -| Type | Description | -| --------------------- | --------------------------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| ------------------- | ----------------------------- | +| Promise<void> | Promise used to return the result.| **Example** ```js -let outputAudioRendererFilter = { - "uid":20010041, - "rendererInfo": { - "contentType":audio.ContentType.CONTENT_TYPE_MUSIC, - "streamUsage":audio.StreamUsage.STREAM_USAGE_MEDIA, - "rendererFlags":0 }, - "rendererId":0 }; -let outputAudioDeviceDescriptor = [{ - "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, - "networkId":audio.LOCAL_NETWORK_ID, - "interruptGroupId":1, - "volumeGroupId":1 }]; - -async function selectOutputDeviceByFilter(){ - audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor).then(() => { - console.info('Select output devices by filter result promise: SUCCESS'); - }).catch((err) => { - console.error(`Result ERROR: ${err}`); - }) -} +audioVolumeGroupManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => { + console.info('Promise returned to indicate that the stream is muted.'); +}); ``` -## AudioRendererChangeInfoArray9+ - -Defines an **AudioRenderChangeInfo** array, which is read-only. +### isMute9+ -**System capability**: SystemCapability.Multimedia.Audio.Renderer +isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void -## AudioRendererChangeInfo9+ +Checks whether a stream is muted. This API uses an asynchronous callback to return the result. -Describes the audio renderer change event. +**System capability**: SystemCapability.Multimedia.Audio.Volume -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**Parameters** -| Name | Type | Readable | Writable | Description | -| ------------- | ---------------------------------------- | -------- | -------- | ---------------------------------------------------------- | -| streamId | number | Yes | No | Unique ID of an audio stream. | -| clientUid | number | Yes | No | UID of the audio renderer client.
This is a system API. | -| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | No | Audio renderer information. | -| rendererState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ----------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the mute status of the stream. The value **true** means that the stream is muted, and **false** means the opposite.| **Example** ```js -import audio from '@ohos.multimedia.audio'; - -let audioStreamManager; -let resultFlag = false; -let audioManager = audio.getAudioManager(); - -audioManager.getStreamManager((err, data) => { +audioVolumeGroupManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error(`Get AudioStream Manager : ERROR : ${err}`); - } else { - audioStreamManager = data; - console.info('Get AudioStream Manager : Success'); + console.error(`Failed to obtain the mute status. ${err}`); + return; } + console.info(`Callback invoked to indicate that the mute status of the stream is obtained ${value}.`); }); +``` -audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => { - for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { - console.info(`## RendererChange on is called for ${i} ##`); - console.info(`StreamId for ${i} is: ${AudioRendererChangeInfoArray[i].streamId}`); - console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfoArray[i].clientUid}`); - console.info(`Content for ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.content}`); - console.info(`Stream for ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.usage}`); - console.info(`Flag ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.rendererFlags}`); - console.info(`State for ${i} is: ${AudioRendererChangeInfoArray[i].rendererState}`); - let devDescriptor = AudioRendererChangeInfoArray[i].deviceDescriptors; - for (let j = 0; j < AudioRendererChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].name}`); - console.info(`Addr: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].address}`); - console.info(`SR: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); - console.info(`C ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); - console.info(`CM: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); - } - if (AudioRendererChangeInfoArray[i].rendererState == 1 && devDescriptor != null) { - resultFlag = true; - console.info(`ResultFlag for ${i} is: ${resultFlag}`); - } - } +### isMute9+ + +isMute(volumeType: AudioVolumeType): Promise<boolean> + +Checks whether a stream is muted. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| + +**Return value** + +| Type | Description | +| ---------------------- | ------------------------------------------------------ | +| Promise<boolean> | Promise used to return the mute status of the stream. The value **true** means that the stream is muted, and **false** means the opposite.| + +**Example** + +```js +audioVolumeGroupManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promise returned to indicate that the mute status of the stream is obtained ${value}.`); }); ``` +### setRingerMode9+ -## AudioCapturerChangeInfoArray9+ +setRingerMode(mode: AudioRingMode, callback: AsyncCallback<void>): void -Defines an **AudioCapturerChangeInfo** array, which is read-only. +Sets the ringer mode. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY -## AudioCapturerChangeInfo9+ +This permission is required only for muting or unmuting the ringer. -Describes the audio capturer change event. +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Volume -| Name | Type | Readable | Writable | Description | -| ------------- | ---------------------------------------- | -------- | -------- | ---------------------------------------------------------- | -| streamId | number | Yes | No | Unique ID of an audio stream. | -| clientUid | number | Yes | No | UID of the audio capturer client.
This is a system API. | -| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | No | Audio capturer information. | -| capturerState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API. | +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------- | ---- | ------------------------ | +| mode | [AudioRingMode](#audioringmode) | Yes | Ringer mode. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** ```js -import audio from '@ohos.multimedia.audio'; - -const audioManager = audio.getAudioManager(); -let audioStreamManager; -audioManager.getStreamManager((err, data) => { +audioVolumeGroupManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => { if (err) { - console.error(`getStreamManager : Error: ${err}`); - } else { - console.info('getStreamManager : Success : SUCCESS'); - audioStreamManager = data; - } -}); - -let resultFlag = false; -audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { - for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - console.info(`## CapChange on is called for element ${i} ##`); - console.info(`StrId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); - console.info(`CUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); - console.info(`Src for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); - console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); - console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); - let devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors; - for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); - console.info(`Addr: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); - console.info(`SR: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); - console.info(`C ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); - console.info(`CM ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); - } - if (AudioCapturerChangeInfoArray[i].capturerState == 1 && devDescriptor != null) { - resultFlag = true; - console.info(`ResultFlag for element ${i} is: ${resultFlag}`); - } + console.error(`Failed to set the ringer mode.​ ${err}`); + return; } + console.info('Callback invoked to indicate a successful setting of the ringer mode.'); }); ``` -## AudioDeviceDescriptors +### setRingerMode9+ -Defines an [AudioDeviceDescriptor](#audiodevicedescriptor) array, which is read-only. +setRingerMode(mode: AudioRingMode): Promise<void> -## AudioDeviceDescriptor +Sets the ringer mode. This API uses a promise to return the result. -Describes an audio device. +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY -**System capability**: SystemCapability.Multimedia.Audio.Device +This permission is required only for muting or unmuting the ringer. -| Name | Type | Readable | Writable | Description | -| ----------------------------- | ------------------------- | -------- | -------- | ------------------------------------------------------------ | -| deviceRole | [DeviceRole](#devicerole) | Yes | No | Device role. | -| deviceType | [DeviceType](#devicetype) | Yes | No | Device type. | -| id9+ | number | Yes | No | Device ID. | -| name9+ | string | Yes | No | Device name. | -| address9+ | string | Yes | No | Device address. | -| sampleRates9+ | Array<number> | Yes | No | Supported sampling rates. | -| channelCounts9+ | Array<number> | Yes | No | Number of channels supported. | -| channelMasks9+ | Array<number> | Yes | No | Supported channel masks. | -| networkId9+ | string | Yes | No | ID of the device network.
This is a system API. | -| interruptGroupId9+ | number | Yes | No | ID of the interruption group to which the device belongs.
This is a system API. | -| volumeGroupId9+ | number | Yes | No | ID of the volume group to which the device belongs.
This is a system API. | +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------- | ---- | -------------- | +| mode | [AudioRingMode](#audioringmode) | Yes | Ringer mode.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------- | +| Promise<void> | Promise used to return the result.| **Example** ```js -import audio from '@ohos.multimedia.audio'; +audioVolumeGroupManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => { + console.info('Promise returned to indicate a successful setting of the ringer mode.'); +}); +``` -function displayDeviceProp(value) { - deviceRoleValue = value.deviceRole; - deviceTypeValue = value.deviceType; -} +### getRingerMode9+ -let deviceRoleValue = null; -let deviceTypeValue = null; -const promise = audio.getAudioManager().getDevices(1); -promise.then(function (value) { - console.info('AudioFrameworkTest: Promise: getDevices OUTPUT_DEVICES_FLAG'); - value.forEach(displayDeviceProp); - if (deviceTypeValue != null && deviceRoleValue != null){ - console.info('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : PASS'); - } else { - console.error('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : FAIL'); +getRingerMode(callback: AsyncCallback<AudioRingMode>): void + +Obtains the ringer mode. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | ------------------------ | +| callback | AsyncCallback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the ringer mode.| + +**Example** + +```js +audioVolumeGroupManager.getRingerMode((err, value) => { + if (err) { + console.error(`Failed to obtain the ringer mode.​ ${err}`); + return; } + console.info(`Callback invoked to indicate that the ringer mode is obtained ${value}.`); }); ``` -## AudioRendererFilter9+ +### getRingerMode9+ + +getRingerMode(): Promise<AudioRingMode> + +Obtains the ringer mode. This API uses a promise to return the result. -Implements filter criteria. Before calling **selectOutputDeviceByFilter**, you must obtain an **AudioRendererFilter** instance. +**System capability**: SystemCapability.Multimedia.Audio.Volume -**System API**: This is a system API. +**Return value** -| Name | Type | Mandatory | Description | -| ------------ | ---------------------------------------- | --------- | ------------------------------------------------------------ | -| uid | number | Yes | Application ID.
**System capability**: SystemCapability.Multimedia.Audio.Core | -| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | No | Audio renderer information.
**System capability**: SystemCapability.Multimedia.Audio.Renderer | -| rendererId | number | No | Unique ID of an audio stream.
**System capability**: SystemCapability.Multimedia.Audio.Renderer | +| Type | Description | +| ---------------------------------------------- | ------------------------------- | +| Promise<[AudioRingMode](#audioringmode)> | Promise used to return the ringer mode.| **Example** ```js -let outputAudioRendererFilter = { - "uid":20010041, - "rendererInfo": { - "contentType":audio.ContentType.CONTENT_TYPE_MUSIC, - "streamUsage":audio.StreamUsage.STREAM_USAGE_MEDIA, - "rendererFlags":0 }, - "rendererId":0 }; +audioVolumeGroupManager.getRingerMode().then((value) => { + console.info(`Promise returned to indicate that the ringer mode is obtained ${value}.`); +}); ``` -## AudioRenderer8+ +### on('ringerModeChange')9+ -Provides APIs for audio rendering. Before calling any API in **AudioRenderer**, you must use [createAudioRenderer](#audiocreateaudiorenderer8) to create an **AudioRenderer** instance. +on(type: 'ringerModeChange', callback: Callback\): void -### Attributes +Subscribes to ringer mode change events. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Volume -| Name | Type | Readable | Writable | Description | -| ------------------ | -------------------------- | -------- | -------- | --------------------- | -| state8+ | [AudioState](#audiostate8) | Yes | No | Audio renderer state. | +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **'ringerModeChange'** means the ringer mode change event, which is triggered when a ringer mode change is detected.| +| callback | Callback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the system volume change event. | + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | **Example** ```js -let state = audioRenderer.state; +audioVolumeGroupManager.on('ringerModeChange', (ringerMode) => { + console.info(`Updated ringermode: ${ringerMode}`); +}); ``` +### setMicrophoneMute9+ -### getRendererInfo8+ +setMicrophoneMute(mute: boolean, callback: AsyncCallback<void>): void -getRendererInfo(callback: AsyncCallback): void +Mutes or unmutes the microphone. This API uses an asynchronous callback to return the result. -Obtains the renderer information of this **AudioRenderer** instance. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.MANAGE_AUDIO_CONFIG -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------------------------------------------- | :-------- | :------------------------------------------------ | -| callback | AsyncCallback<[AudioRendererInfo](#audiorendererinfo8)\> | Yes | Callback used to return the renderer information. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | --------------------------------------------- | +| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -audioRenderer.getRendererInfo((err, rendererInfo) => { - console.info('Renderer GetRendererInfo:'); - console.info(`Renderer content: ${rendererInfo.content}`); - console.info(`Renderer usage: ${rendererInfo.usage}`); - console.info(`Renderer flags: ${rendererInfo.rendererFlags}`); +audioVolumeGroupManager.setMicrophoneMute(true, (err) => { + if (err) { + console.error(`Failed to mute the microphone. ${err}`); + return; + } + console.info('Callback invoked to indicate that the microphone is muted.'); }); ``` -### getRendererInfo8+ +### setMicrophoneMute9+ -getRendererInfo(): Promise +setMicrophoneMute(mute: boolean): Promise<void> -Obtains the renderer information of this **AudioRenderer** instance. This API uses a promise to return the result. +Mutes or unmutes the microphone. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**Required permissions**: ohos.permission.MANAGE_AUDIO_CONFIG + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | --------------------------------------------- | +| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite.| **Return value** -| Type | Description | -| -------------------------------------------------- | ------------------------------------------------ | -| Promise<[AudioRendererInfo](#audiorendererinfo8)\> | Promise used to return the renderer information. | +| Type | Description | +| ------------------- | ------------------------------- | +| Promise<void> | Promise used to return the result.| **Example** ```js -audioRenderer.getRendererInfo().then((rendererInfo) => { - console.info('Renderer GetRendererInfo:'); - console.info(`Renderer content: ${rendererInfo.content}`); - console.info(`Renderer usage: ${rendererInfo.usage}`); - console.info(`Renderer flags: ${rendererInfo.rendererFlags}`) -}).catch((err) => { - console.error(`AudioFrameworkRenderLog: RendererInfo :ERROR: ${err}`); +audioVolumeGroupManager.setMicrophoneMute(true).then(() => { + console.info('Promise returned to indicate that the microphone is muted.'); }); ``` -### getStreamInfo8+ +### isMicrophoneMute9+ -getStreamInfo(callback: AsyncCallback): void +isMicrophoneMute(callback: AsyncCallback<boolean>): void -Obtains the stream information of this **AudioRenderer** instance. This API uses an asynchronous callback to return the result. +Checks whether the microphone is muted. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------------------------------------- | :-------- | :---------------------------------------------- | -| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------------------------------- | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite.| **Example** ```js -audioRenderer.getStreamInfo((err, streamInfo) => { - console.info('Renderer GetStreamInfo:'); - console.info(`Renderer sampling rate: ${streamInfo.samplingRate}`); - console.info(`Renderer channel: ${streamInfo.channels}`); - console.info(`Renderer format: ${streamInfo.sampleFormat}`); - console.info(`Renderer encoding type: ${streamInfo.encodingType}`); +audioVolumeGroupManager.isMicrophoneMute((err, value) => { + if (err) { + console.error(`Failed to obtain the mute status of the microphone. ${err}`); + return; + } + console.info(`Callback invoked to indicate that the mute status of the microphone is obtained ${value}.`); }); ``` -### getStreamInfo8+ +### isMicrophoneMute9+ -getStreamInfo(): Promise +isMicrophoneMute(): Promise<boolean> -Obtains the stream information of this **AudioRenderer** instance. This API uses a promise to return the result. +Checks whether the microphone is muted. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Volume **Return value** -| Type | Description | -| :--------------------------------------------- | :--------------------------------------------- | -| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information. | +| Type | Description | +| ---------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite.| **Example** ```js -audioRenderer.getStreamInfo().then((streamInfo) => { - console.info('Renderer GetStreamInfo:'); - console.info(`Renderer sampling rate: ${streamInfo.samplingRate}`); - console.info(`Renderer channel: ${streamInfo.channels}`); - console.info(`Renderer format: ${streamInfo.sampleFormat}`); - console.info(`Renderer encoding type: ${streamInfo.encodingType}`); -}).catch((err) => { - console.error(`ERROR: ${err}`); +audioVolumeGroupManager.isMicrophoneMute().then((value) => { + console.info(`Promise returned to indicate that the mute status of the microphone is obtained ${value}.`); }); +``` + +### on('micStateChange')9+ +on(type: 'micStateChange', callback: Callback<MicStateChangeEvent>): void + +Subscribes to system microphone state change events. + +Currently, when multiple **AudioManager** instances are used in a single process, only the subscription of the last instance takes effect, and the subscription of other instances is overwritten (even if the last instance does not initiate a subscription). Therefore, you are advised to use a single **AudioManager** instance. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **'micStateChange'** means the system microphone state change event, which is triggered when the system microphone state changes.| +| callback | Callback<[MicStateChangeEvent](#micstatechangeevent9)> | Yes | Callback used to return the changed microphone state. | + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | + +**Example** + +```js +audioVolumeGroupManager.on('micStateChange', (micStateChange) => { + console.info(`Current microphone status is: ${micStateChange.mute} `); +}); ``` -### getAudioStreamId9+ +## AudioStreamManager9+ -getAudioStreamId(callback: AsyncCallback): void +Implements audio stream management. Before calling any API in **AudioStreamManager**, you must use [getStreamManager](#getstreammanager9) to obtain an **AudioStreamManager** instance. -Obtains the stream ID of this **AudioRenderer** instance. This API uses an asynchronous callback to return the result. +### getCurrentAudioRendererInfoArray9+ + +getCurrentAudioRendererInfoArray(callback: AsyncCallback<AudioRendererChangeInfoArray>): void + +Obtains the information about the current audio renderer. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------- | :-------- | :------------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the stream ID. | +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | -------- | --------------------------- | +| callback | AsyncCallback<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Yes | Callback used to return the audio renderer information.| **Example** ```js -audioRenderer.getAudioStreamId((err, streamid) => { - console.info(`Renderer GetStreamId: ${streamid}`); +audioStreamManager.getCurrentAudioRendererInfoArray(async (err, AudioRendererChangeInfoArray) => { + console.info('getCurrentAudioRendererInfoArray **** Get Callback Called ****'); + if (err) { + console.error(`getCurrentAudioRendererInfoArray :ERROR: ${err}`); + } else { + if (AudioRendererChangeInfoArray != null) { + for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { + let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; + console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); + console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`); + console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); + console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); + console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); + console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`); + for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); + } + } + } + } }); - ``` -### getAudioStreamId9+ +### getCurrentAudioRendererInfoArray9+ -getAudioStreamId(): Promise +getCurrentAudioRendererInfoArray(): Promise<AudioRendererChangeInfoArray> -Obtains the stream ID of this **AudioRenderer** instance. This API uses a promise to return the result. +Obtains the information about the current audio renderer. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** -| Type | Description | -| :--------------- | :------------------------------------ | -| Promise | Promise used to return the stream ID. | +| Type | Description | +| ---------------------------------------------------------------------------------| --------------------------------------- | +| Promise<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Promise used to return the audio renderer information. | **Example** ```js -audioRenderer.getAudioStreamId().then((streamid) => { - console.info(`Renderer getAudioStreamId: ${streamid}`); -}).catch((err) => { - console.error(`ERROR: ${err}`); -}); - +async function getCurrentAudioRendererInfoArray(){ + await audioStreamManager.getCurrentAudioRendererInfoArray().then( function (AudioRendererChangeInfoArray) { + console.info(`getCurrentAudioRendererInfoArray ######### Get Promise is called ##########`); + if (AudioRendererChangeInfoArray != null) { + for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { + let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; + console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); + console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`); + console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); + console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); + console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); + console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`); + for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); + } + } + } + }).catch((err) => { + console.error(`getCurrentAudioRendererInfoArray :ERROR: ${err}`); + }); +} ``` -### start8+ +### getCurrentAudioCapturerInfoArray9+ -start(callback: AsyncCallback): void +getCurrentAudioCapturerInfoArray(callback: AsyncCallback<AudioCapturerChangeInfoArray>): void -Starts the renderer. This API uses an asynchronous callback to return the result. +Obtains the information about the current audio capturer. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------- | --------- | ----------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| ---------- | ----------------------------------- | --------- | -------------------------------------------------------- | +| callback | AsyncCallback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Yes | Callback used to return the audio capturer information.| **Example** ```js -audioRenderer.start((err) => { +audioStreamManager.getCurrentAudioCapturerInfoArray(async (err, AudioCapturerChangeInfoArray) => { + console.info('getCurrentAudioCapturerInfoArray **** Get Callback Called ****'); if (err) { - console.error('Renderer start failed.'); + console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`); } else { - console.info('Renderer start success.'); + if (AudioCapturerChangeInfoArray != null) { + for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { + console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); + console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); + console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); + console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); + console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); + for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); + } + } + } } }); - ``` -### start8+ +### getCurrentAudioCapturerInfoArray9+ -start(): Promise +getCurrentAudioCapturerInfoArray(): Promise<AudioCapturerChangeInfoArray> -Starts the renderer. This API uses a promise to return the result. +Obtains the information about the current audio capturer. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** -| Type | Description | -| -------------- | ---------------------------------- | -| Promise\ | Promise used to return the result. | +| Type | Description | +| -----------------------------------------------------------------------------| ----------------------------------- | +| Promise<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Promise used to return the audio capturer information. | **Example** ```js -audioRenderer.start().then(() => { - console.info('Renderer started'); -}).catch((err) => { - console.error(`ERROR: ${err}`); -}); - +async function getCurrentAudioCapturerInfoArray(){ + await audioStreamManager.getCurrentAudioCapturerInfoArray().then( function (AudioCapturerChangeInfoArray) { + console.info('getCurrentAudioCapturerInfoArray **** Get Promise Called ****'); + if (AudioCapturerChangeInfoArray != null) { + for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { + console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); + console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); + console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); + console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); + console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); + for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); + } + } + } + }).catch((err) => { + console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`); + }); +} ``` -### pause8+ +### on('audioRendererChange')9+ -pause(callback: AsyncCallback\): void +on(type: "audioRendererChange", callback: Callback<AudioRendererChangeInfoArray>): void -Pauses rendering. This API uses an asynchronous callback to return the result. +Subscribes to audio renderer change events. **System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------- | --------- | ----------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ---------- | --------- | ------------------------------------------------------------------------ | +| type | string | Yes | Event type. The event `'audioRendererChange'` is triggered when the audio renderer changes. | +| callback | Callback<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | **Example** ```js -audioRenderer.pause((err) => { - if (err) { - console.error('Renderer pause failed'); - } else { - console.info('Renderer paused.'); +audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => { + for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { + let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; + console.info(`## RendererChange on is called for ${i} ##`); + console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); + console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`); + console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); + console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); + console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); + console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`); + for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); + } } }); - ``` -### pause8+ +### off('audioRendererChange')9+ -pause(): Promise\ +off(type: "audioRendererChange"): void -Pauses rendering. This API uses a promise to return the result. +Unsubscribes from audio renderer change events. **System capability**: SystemCapability.Multimedia.Audio.Renderer -**Return value** +**Parameters** -| Type | Description | -| -------------- | ---------------------------------- | -| Promise\ | Promise used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ------- | ---- | ---------------- | +| type | string | Yes | Event type. The event `'audioRendererChange'` is triggered when the audio renderer changes.| + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | **Example** ```js -audioRenderer.pause().then(() => { - console.info('Renderer paused'); -}).catch((err) => { - console.error(`ERROR: ${err}`); -}); - +audioStreamManager.off('audioRendererChange'); +console.info('######### RendererChange Off is called #########'); ``` -### drain8+ +### on('audioCapturerChange')9+ -drain(callback: AsyncCallback\): void +on(type: "audioCapturerChange", callback: Callback<AudioCapturerChangeInfoArray>): void -Drains the playback buffer. This API uses an asynchronous callback to return the result. +Subscribes to audio capturer change events. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------- | --------- | ----------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------------------------------------------------------------------- | +| type | string | Yes | Event type. The event `'audioCapturerChange'` is triggered when the audio capturer changes. | +| callback | Callback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | **Example** ```js -audioRenderer.drain((err) => { - if (err) { - console.error('Renderer drain failed'); - } else { - console.info('Renderer drained.'); +audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { + for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { + console.info(`## CapChange on is called for element ${i} ##`); + console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); + console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); + console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); + console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); + console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); + let devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors; + for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); + } } }); - ``` -### drain8+ +### off('audioCapturerChange')9+ -drain(): Promise\ +off(type: "audioCapturerChange"): void; -Drains the playback buffer. This API uses a promise to return the result. +Unsubscribes from audio capturer change events. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Capturer -**Return value** +**Parameters** -| Type | Description | -| -------------- | ---------------------------------- | -| Promise\ | Promise used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | -------- | --- | ------------------------------------------------------------- | +| type | string |Yes | Event type. The event `'audioCapturerChange'` is triggered when the audio capturer changes.| + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | **Example** ```js -audioRenderer.drain().then(() => { - console.info('Renderer drained successfully'); -}).catch((err) => { - console.error(`ERROR: ${err}`); -}); +audioStreamManager.off('audioCapturerChange'); +console.info('######### CapturerChange Off is called #########'); ``` -### stop8+ +### isActive9+ -stop(callback: AsyncCallback\): void +isActive(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void -Stops rendering. This API uses an asynchronous callback to return the result. +Checks whether a stream is active. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------- | --------- | ----------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream types. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite.| **Example** ```js -audioRenderer.stop((err) => { +audioStreamManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error('Renderer stop failed'); - } else { - console.info('Renderer stopped.'); + console.error(`Failed to obtain the active status of the stream. ${err}`); + return; } + console.info(`Callback invoked to indicate that the active status of the stream is obtained ${value}.`); }); - ``` -### stop8+ +### isActive9+ -stop(): Promise\ +isActive(volumeType: AudioVolumeType): Promise<boolean> -Stops rendering. This API uses a promise to return the result. +Checks whether a stream is active. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream types.| + **Return value** -| Type | Description | -| -------------- | ---------------------------------- | -| Promise\ | Promise used to return the result. | +| Type | Description | +| ---------------------- | -------------------------------------------------------- | +| Promise<boolean> | Promise used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite.| **Example** ```js -audioRenderer.stop().then(() => { - console.info('Renderer stopped successfully'); -}).catch((err) => { - console.error(`ERROR: ${err}`); +audioStreamManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promise returned to indicate that the active status of the stream is obtained ${value}.`); }); - ``` -### release8+ +## AudioRoutingManager9+ -release(callback: AsyncCallback\): void +Implements audio routing management. Before calling any API in **AudioRoutingManager**, you must use [getRoutingManager](#getroutingmanager9) to obtain an **AudioRoutingManager** instance. -Releases the renderer. This API uses an asynchronous callback to return the result. +### getDevices9+ -**System capability**: SystemCapability.Multimedia.Audio.Renderer +getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescriptors>): void + +Obtains the audio devices with a specific flag. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------- | --------- | ----------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | -------------------- | +| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | +| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Yes | Callback used to return the device list.| **Example** ```js -audioRenderer.release((err) => { +audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) => { if (err) { - console.error('Renderer release failed'); - } else { - console.info('Renderer released.'); + console.error(`Failed to obtain the device list. ${err}`); + return; } + console.info('Callback invoked to indicate that the device list is obtained.'); }); - ``` -### release8+ +### getDevices9+ -release(): Promise\ +getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors> -Releases the renderer. This API uses a promise to return the result. +Obtains the audio devices with a specific flag. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Device + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------- | ---- | ---------------- | +| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag.| **Return value** -| Type | Description | -| -------------- | ---------------------------------- | -| Promise\ | Promise used to return the result. | +| Type | Description | +| ------------------------------------------------------------ | ------------------------- | +| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise used to return the device list.| **Example** ```js -audioRenderer.release().then(() => { - console.info('Renderer released successfully'); -}).catch((err) => { - console.error(`ERROR: ${err}`); +audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { + console.info('Promise returned to indicate that the device list is obtained.'); }); - ``` -### write8+ +### on9+ -write(buffer: ArrayBuffer, callback: AsyncCallback\): void +on(type: 'deviceChange', deviceFlag: DeviceFlag, callback: Callback): void -Writes the buffer. This API uses an asynchronous callback to return the result. +Subscribes to device change events. When a device is connected or disconnected, registered clients will receive the callback. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | --------- | ------------------------------------------------------------ | -| buffer | ArrayBuffer | Yes | Buffer to be written. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned. | +| Name | Type | Mandatory| Description | +| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- | +| type | string | Yes | Event type. The value **'deviceChange'** means the device change event, which is triggered when a device connection status change is detected.| +| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | +| callback | Callback<[DeviceChangeAction](#devicechangeaction)\> | Yes | Callback used to return the device update details. | + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | **Example** ```js -let bufferSize; -audioRenderer.getBufferSize().then((data)=> { - console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); - bufferSize = data; - }).catch((err) => { - console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); - }); -console.info(`Buffer size: ${bufferSize}`); -let context = featureAbility.getContext(); -let path; -async function getCacheDir(){ - path = await context.getCacheDir(); -} -let filePath = path + '/StarWars10s-2C-48000-4SW.wav'; -let ss = fileio.createStreamSync(filePath, 'r'); -let buf = new ArrayBuffer(bufferSize); -ss.readSync(buf); -audioRenderer.write(buf, (err, writtenbytes) => { - if (writtenbytes < 0) { - console.error('write failed.'); - } else { - console.info(`Actual written bytes: ${writtenbytes}`); - } +audioRoutingManager.on('deviceChange', audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (deviceChanged) => { + console.info('device change type : ' + deviceChanged.type); + console.info('device descriptor size : ' + deviceChanged.deviceDescriptors.length); + console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceRole); + console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceType); }); - ``` -### write8+ +### off9+ -write(buffer: ArrayBuffer): Promise\ +off(type: 'deviceChange', callback?: Callback): void -Writes the buffer. This API uses a promise to return the result. +Unsubscribes from device change events. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Device -**Return value** +**Parameters** -| Type | Description | -| ---------------- | ------------------------------------------------------------ | -| Promise\ | Promise used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned. | +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ------------------------------------------ | +| type | string | Yes | Event type. The value **'deviceChange'** means the device change event, which is triggered when a device connection status change is detected.| +| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | No | Callback used to return the device update details. | + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | **Example** ```js -let bufferSize; -audioRenderer.getBufferSize().then((data) => { - console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); - bufferSize = data; - }).catch((err) => { - console.info(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); - }); -console.info(`BufferSize: ${bufferSize}`); -let context = featureAbility.getContext(); -let path; -async function getCacheDir(){ - path = await context.getCacheDir(); -} -let filePath = path + '/StarWars10s-2C-48000-4SW.wav'; -let ss = fileio.createStreamSync(filePath, 'r'); -let buf = new ArrayBuffer(bufferSize); -ss.readSync(buf); -audioRenderer.write(buf).then((writtenbytes) => { - if (writtenbytes < 0) { - console.error('write failed.'); - } else { - console.info(`Actual written bytes: ${writtenbytes}`); - } -}).catch((err) => { - console.error(`ERROR: ${err}`); +audioRoutingManager.off('deviceChange', (deviceChanged) => { + console.info('Should be no callback.'); }); - ``` -### getAudioTime8+ +### selectInputDevice9+ -getAudioTime(callback: AsyncCallback\): void +selectInputDevice(inputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void -Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses an asynchronous callback to return the result. +Selects an audio input device. Only one input device can be selected. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | --------- | -------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the timestamp. | +| Name | Type | Mandatory| Description | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| inputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Input device. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** - ```js -audioRenderer.getAudioTime((err, timestamp) => { - console.info(`Current timestamp: ${timestamp}`); -}); +let inputAudioDeviceDescriptor = [{ + deviceRole : audio.DeviceRole.INPUT_DEVICE, + deviceType : audio.DeviceType.EARPIECE, + id : 1, + name : "", + address : "", + sampleRates : [44100], + channelCounts : [2], + channelMasks : [0], + networkId : audio.LOCAL_NETWORK_ID, + interruptGroupId : 1, + volumeGroupId : 1, +}]; +async function selectInputDevice(){ + audioRoutingManager.selectInputDevice(inputAudioDeviceDescriptor, (err) => { + if (err) { + console.error(`Result ERROR: ${err}`); + } else { + console.info('Select input devices result callback: SUCCESS'); } + }); +} ``` -### getAudioTime8+ +### selectInputDevice9+ -getAudioTime(): Promise\ +selectInputDevice(inputAudioDevices: AudioDeviceDescriptors): Promise<void> -Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses a promise to return the result. +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +Selects an audio input device. Only one input device can be selected. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Device + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| inputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Input device. | **Return value** -| Type | Description | -| ---------------- | ------------------------------------- | -| Promise\ | Promise used to return the timestamp. | +| Type | Description | +| --------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| **Example** ```js -audioRenderer.getAudioTime().then((timestamp) => { - console.info(`Current timestamp: ${timestamp}`); -}).catch((err) => { - console.error(`ERROR: ${err}`); -}); +let inputAudioDeviceDescriptor = [{ + deviceRole : audio.DeviceRole.INPUT_DEVICE, + deviceType : audio.DeviceType.EARPIECE, + id : 1, + name : "", + address : "", + sampleRates : [44100], + channelCounts : [2], + channelMasks : [0], + networkId : audio.LOCAL_NETWORK_ID, + interruptGroupId : 1, + volumeGroupId : 1, +}]; +async function getRoutingManager(){ + audioRoutingManager.selectInputDevice(inputAudioDeviceDescriptor).then(() => { + console.info('Select input devices result promise: SUCCESS'); + }).catch((err) => { + console.error(`Result ERROR: ${err}`); + }); +} ``` -### getBufferSize8+ +### setCommunicationDevice9+ -getBufferSize(callback: AsyncCallback\): void +setCommunicationDevice(deviceType: CommunicationDeviceType, active: boolean, callback: AsyncCallback<void>): void -Obtains a reasonable minimum buffer size in bytes for rendering. This API uses an asynchronous callback to return the result. +Sets a communication device to the active state. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Communication **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | --------- | ---------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the buffer size. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------- | ---- | ------------------------ | +| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type. | +| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** ```js -let bufferSize = audioRenderer.getBufferSize(async(err, bufferSize) => { +audioRoutingManager.setCommunicationDevice(audio.CommunicationDeviceType.SPEAKER, true, (err) => { if (err) { - console.error('getBufferSize error'); + console.error(`Failed to set the active status of the device. ${err}`); + return; } + console.info('Callback invoked to indicate that the device is set to the active status.'); }); - ``` -### getBufferSize8+ +### setCommunicationDevice9+ -getBufferSize(): Promise\ +setCommunicationDevice(deviceType: CommunicationDeviceType, active: boolean): Promise<void> -Obtains a reasonable minimum buffer size in bytes for rendering. This API uses a promise to return the result. +Sets a communication device to the active state. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Communication + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------------------------- | ---- | ------------------ | +| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type.| +| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | **Return value** -| Type | Description | -| ---------------- | --------------------------------------- | -| Promise\ | Promise used to return the buffer size. | +| Type | Description | +| ------------------- | ------------------------------- | +| Promise<void> | Promise used to return the result.| **Example** ```js -let bufferSize; -audioRenderer.getBufferSize().then((data) => { - console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); - bufferSize = data; -}).catch((err) => { - console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); +audioRoutingManager.setCommunicationDevice(audio.CommunicationDeviceType.SPEAKER, true).then(() => { + console.info('Promise returned to indicate that the device is set to the active status.'); }); - ``` -### setRenderRate8+ +### isCommunicationDeviceActive9+ -setRenderRate(rate: AudioRendererRate, callback: AsyncCallback\): void +isCommunicationDeviceActive(deviceType: CommunicationDeviceType, callback: AsyncCallback<boolean>): void -Sets the render rate. This API uses an asynchronous callback to return the result. +Checks whether a communication device is active. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Communication **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | --------- | ----------------------------------- | -| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------------------------- | ---- | ------------------------ | +| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the active state of the device.| **Example** ```js -audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL, (err) => { +audioRoutingManager.isCommunicationDeviceActive(audio.CommunicationDeviceType.SPEAKER, (err, value) => { if (err) { - console.error('Failed to set params'); - } else { - console.info('Callback invoked to indicate a successful render rate setting.'); + console.error(`Failed to obtain the active status of the device. ${err}`); + return; } + console.info('Callback invoked to indicate that the active status of the device is obtained.'); }); - ``` -### setRenderRate8+ +### isCommunicationDeviceActive9+ -setRenderRate(rate: AudioRendererRate): Promise\ +isCommunicationDeviceActive(deviceType: CommunicationDeviceType): Promise<boolean> -Sets the render rate. This API uses a promise to return the result. +Checks whether a communication device is active. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Communication **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ---------------------------------------- | --------- | ------------------ | -| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. | +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------------------------- | ---- | ------------------ | +| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type.| **Return value** -| Type | Description | -| -------------- | ---------------------------------- | -| Promise\ | Promise used to return the result. | +| Type | Description | +| ---------------------- | ------------------------------- | +| Promise<boolean> | Promise used to return the active state of the device.| **Example** ```js -audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL).then(() => { - console.info('setRenderRate SUCCESS'); -}).catch((err) => { - console.error(`ERROR: ${err}`); +audioRoutingManager.isCommunicationDeviceActive(audio.CommunicationDeviceType.SPEAKER).then((value) => { + console.info(`Promise returned to indicate that the active status of the device is obtained ${value}.`); }); - ``` -### getRenderRate8+ +### selectOutputDevice9+ -getRenderRate(callback: AsyncCallback\): void +selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void -Obtains the current render rate. This API uses an asynchronous callback to return the result. +Selects an audio output device. Currently, only one output device can be selected. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------------------------------- | --------- | ---------------------------------------------- | -| callback | AsyncCallback<[AudioRendererRate](#audiorendererrate8)> | Yes | Callback used to return the audio render rate. | +| Name | Type | Mandatory| Description | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** - ```js -audioRenderer.getRenderRate((err, renderrate) => { - console.info(`getRenderRate: ${renderrate}`); -}); +let outputAudioDeviceDescriptor = [{ + deviceRole : audio.DeviceRole.OUTPUT_DEVICE, + deviceType : audio.DeviceType.SPEAKER, + id : 1, + name : "", + address : "", + sampleRates : [44100], + channelCounts : [2], + channelMasks : [0], + networkId : audio.LOCAL_NETWORK_ID, + interruptGroupId : 1, + volumeGroupId : 1, +}]; +async function selectOutputDevice(){ + audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor, (err) => { + if (err) { + console.error(`Result ERROR: ${err}`); + } else { + console.info('Select output devices result callback: SUCCESS'); } + }); +} ``` -### getRenderRate8+ - -getRenderRate(): Promise\ - -Obtains the current render rate. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Audio.Renderer - -**Return value** - -| Type | Description | -| ------------------------------------------------- | --------------------------------------------- | -| Promise<[AudioRendererRate](#audiorendererrate8)> | Promise used to return the audio render rate. | - -**Example** - -```js -audioRenderer.getRenderRate().then((renderRate) => { - console.info(`getRenderRate: ${renderRate}`); -}).catch((err) => { - console.error(`ERROR: ${err}`); -}); - -``` +### selectOutputDevice9+ -### setInterruptMode9+ +selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors): Promise<void> -setInterruptMode(mode: InterruptMode): Promise<void> +**System API**: This is a system API. -Sets the audio interruption mode for the application. This API uses a promise to return the result. +Selects an audio output device. Currently, only one output device can be selected. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Interrupt +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| ---- | -------------------------------- | --------- | ------------------------ | -| mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode. | +| Name | Type | Mandatory| Description | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | **Return value** -| Type | Description | -| ------------------- | ------------------------------------------------------------ | -| Promise<void> | Promise used to return the result. If the operation is successful, **undefined** is returned. Otherwise, **error** is returned. | +| Type | Description | +| --------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| **Example** ```js -let mode = 0; -audioRenderer.setInterruptMode(mode).then(data=>{ - console.info('setInterruptMode Success!'); -}).catch((err) => { - console.error(`setInterruptMode Fail: ${err}`); -}); +let outputAudioDeviceDescriptor = [{ + deviceRole : audio.DeviceRole.OUTPUT_DEVICE, + deviceType : audio.DeviceType.SPEAKER, + id : 1, + name : "", + address : "", + sampleRates : [44100], + channelCounts : [2], + channelMasks : [0], + networkId : audio.LOCAL_NETWORK_ID, + interruptGroupId : 1, + volumeGroupId : 1, +}]; +async function selectOutputDevice(){ + audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor).then(() => { + console.info('Select output devices result promise: SUCCESS'); + }).catch((err) => { + console.error(`Result ERROR: ${err}`); + }); +} ``` -### setInterruptMode9+ +### selectOutputDeviceByFilter9+ -setInterruptMode(mode: InterruptMode, callback: AsyncCallback\): void +selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void -Sets the audio interruption mode for the application. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Interrupt +Selects an audio output device based on the filter criteria. Currently, only one output device can be selected. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------------------- | --------- | ----------------------------------- | -| mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| filter | [AudioRendererFilter](#audiorendererfilter9) | Yes | Filter criteria. | +| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** - ```js -let mode = 1; -audioRenderer.setInterruptMode(mode, (err, data)=>{ - if(err){ - console.error(`setInterruptMode Fail: ${err}`); - } - console.info('setInterruptMode Success!'); -}); +let outputAudioRendererFilter = { + uid : 20010041, + rendererInfo : { + content : audio.ContentType.CONTENT_TYPE_MUSIC, + usage : audio.StreamUsage.STREAM_USAGE_MEDIA, + rendererFlags : 0 }, + rendererId : 0 }; + +let outputAudioDeviceDescriptor = [{ + deviceRole : audio.DeviceRole.OUTPUT_DEVICE, + deviceType : audio.DeviceType.SPEAKER, + id : 1, + name : "", + address : "", + sampleRates : [44100], + channelCounts : [2], + channelMasks : [0], + networkId : audio.LOCAL_NETWORK_ID, + interruptGroupId : 1, + volumeGroupId : 1, +}]; +async function selectOutputDeviceByFilter(){ + audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor, (err) => { + if (err) { + console.error(`Result ERROR: ${err}`); + } else { + console.info('Select output devices by filter result callback: SUCCESS'); } + }); +} ``` -### setVolume9+ +### selectOutputDeviceByFilter9+ -setVolume(volume: number): Promise<void> +selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors): Promise<void> -Sets the volume for the application. This API uses a promise to return the result. +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +Selects an audio output device based on the filter criteria. Currently, only one output device can be selected. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | --------- | -------------- | -| volume | number | Yes | Volume to set. | +| Name | Type | Mandatory| Description | +| ----------------------| ------------------------------------------------------------ | ---- | ------------------------- | +| filter | [AudioRendererFilter](#audiorendererfilter9) | Yes | Filter criteria. | +| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | **Return value** -| Type | Description | -| ------------------- | ------------------------------------------------------------ | -| Promise<void> | Promise used to return the result. If the operation is successful, **undefined** is returned. Otherwise, **error** is returned. | +| Type | Description | +| --------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| **Example** ```js -audioRenderer.setVolume(10).then(data=>{ - console.info('setVolume Success!'); -}).catch((err) => { - console.error(`setVolume Fail: ${err}`); -}); +let outputAudioRendererFilter = { + uid : 20010041, + rendererInfo : { + content : audio.ContentType.CONTENT_TYPE_MUSIC, + usage : audio.StreamUsage.STREAM_USAGE_MEDIA, + rendererFlags : 0 }, + rendererId : 0 }; -``` +let outputAudioDeviceDescriptor = [{ + deviceRole : audio.DeviceRole.OUTPUT_DEVICE, + deviceType : audio.DeviceType.SPEAKER, + id : 1, + name : "", + address : "", + sampleRates : [44100], + channelCounts : [2], + channelMasks : [0], + networkId : audio.LOCAL_NETWORK_ID, + interruptGroupId : 1, + volumeGroupId : 1, +}]; -### setVolume9+ +async function selectOutputDeviceByFilter(){ + audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor).then(() => { + console.info('Select output devices by filter result promise: SUCCESS'); + }).catch((err) => { + console.error(`Result ERROR: ${err}`); + }) +} +``` -setVolume(volume: number, callback: AsyncCallback\): void +## AudioRendererChangeInfoArray9+ -Sets the volume for the application. This API uses an asynchronous callback to return the result. +Defines an **AudioRenderChangeInfo** array, which is read-only. **System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters** +## AudioRendererChangeInfo9+ -| Name | Type | Mandatory | Description | -| -------- | -------------------- | --------- | ----------------------------------- | -| volume | number | Yes | Volume to set. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +Describes the audio renderer change event. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer + +| Name | Type | Readable | Writable | Description | +| ------------- | ---------------------------------------- | -------- | -------- | ---------------------------------------------------------- | +| streamId | number | Yes | No | Unique ID of an audio stream. | +| clientUid | number | Yes | No | UID of the audio renderer client.
This is a system API. | +| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | No | Audio renderer information. | +| rendererState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API. | **Example** ```js -audioRenderer.setVolume(10, (err, data)=>{ - if(err){ - console.error(`setVolume Fail: ${err}`); +import audio from '@ohos.multimedia.audio'; + +const audioManager = audio.getAudioManager(); +let audioStreamManager = audioManager.getStreamManager(); +let resultFlag = false; + +audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => { + for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { + console.info(`## RendererChange on is called for ${i} ##`); + console.info(`StreamId for ${i} is: ${AudioRendererChangeInfoArray[i].streamId}`); + console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfoArray[i].clientUid}`); + console.info(`Content for ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.content}`); + console.info(`Stream for ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.usage}`); + console.info(`Flag ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.rendererFlags}`); + console.info(`State for ${i} is: ${AudioRendererChangeInfoArray[i].rendererState}`); + let devDescriptor = AudioRendererChangeInfoArray[i].deviceDescriptors; + for (let j = 0; j < AudioRendererChangeInfoArray[i].deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].name}`); + console.info(`Addr: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].address}`); + console.info(`SR: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); + console.info(`C ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); + console.info(`CM: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); + } + if (AudioRendererChangeInfoArray[i].rendererState == 1 && devDescriptor != null) { + resultFlag = true; + console.info(`ResultFlag for ${i} is: ${resultFlag}`); + } } - console.info('setVolume Success!'); }); - ``` -### on('audioInterrupt')9+ - -on(type: 'audioInterrupt', callback: Callback\): void - -Subscribes to audio interruption events. This API uses a callback to get interrupt events. -Same as [on('interrupt')](#oninterruptdeprecated), this API has obtained the focus before **start**, **pause**, or **stop** of **AudioRenderer** is called. Therefore, you do not need to request the focus. +## AudioCapturerChangeInfoArray9+ -**System capability**: SystemCapability.Multimedia.Audio.Interrupt +Defines an **AudioCapturerChangeInfo** array, which is read-only. -**Parameters** +**System capability**: SystemCapability.Multimedia.Audio.Capturer -| Name | Type | Mandatory | Description | -| -------- | -------------------------------------------- | --------- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **'audioInterrupt'** means the audio interruption event, which is triggered when audio playback is interrupted. | -| callback | Callback<[InterruptEvent](#interruptevent9)> | Yes | Callback used to return the audio interruption event. | +## AudioCapturerChangeInfo9+ -**Error codes** +Describes the audio capturer change event. -For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). +**System capability**: SystemCapability.Multimedia.Audio.Capturer -| ID | Error Message | -| ------- | ------------------------------- | -| 6800101 | if input parameter value error. | +| Name | Type | Readable | Writable | Description | +| ------------- | ---------------------------------------- | -------- | -------- | ---------------------------------------------------------- | +| streamId | number | Yes | No | Unique ID of an audio stream. | +| clientUid | number | Yes | No | UID of the audio capturer client.
This is a system API. | +| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | No | Audio capturer information. | +| capturerState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API. | **Example** ```js -let isPlay; -let started; -audioRenderer.on('audioInterrupt', async(interruptEvent) => { - if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { - switch (interruptEvent.hintType) { - case audio.InterruptHint.INTERRUPT_HINT_PAUSE: - console.info('Force paused. Stop writing'); - isPlay = false; - break; - case audio.InterruptHint.INTERRUPT_HINT_STOP: - console.info('Force stopped. Stop writing'); - isPlay = false; - break; +import audio from '@ohos.multimedia.audio'; + +const audioManager = audio.getAudioManager(); +let audioStreamManager = audioManager.getStreamManager(); + +let resultFlag = false; +audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { + for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { + console.info(`## CapChange on is called for element ${i} ##`); + console.info(`StrId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); + console.info(`CUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); + console.info(`Src for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); + console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); + console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); + let devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors; + for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); + console.info(`Addr: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); + console.info(`SR: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); + console.info(`C ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); + console.info(`CM ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); } - } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { - switch (interruptEvent.hintType) { - case audio.InterruptHint.INTERRUPT_HINT_RESUME: - console.info('Resume force paused renderer or ignore'); - await audioRenderer.start().then(async function () { - console.info('AudioInterruptMusic: renderInstant started :SUCCESS '); - started = true; - }).catch((err) => { - console.error(`AudioInterruptMusic: renderInstant start :ERROR : ${err}`); - started = false; - }); - if (started) { - isPlay = true; - console.info(`AudioInterruptMusic Renderer started : isPlay : ${isPlay}`); - } else { - console.error('AudioInterruptMusic Renderer start failed'); - } - break; - case audio.InterruptHint.INTERRUPT_HINT_PAUSE: - console.info('Choose to pause or ignore'); - if (isPlay == true) { - isPlay == false; - console.info('AudioInterruptMusic: Media PAUSE : TRUE'); - } else { - isPlay = true; - console.info('AudioInterruptMusic: Media PLAY : TRUE'); - } - break; + if (AudioCapturerChangeInfoArray[i].capturerState == 1 && devDescriptor != null) { + resultFlag = true; + console.info(`ResultFlag for element ${i} is: ${resultFlag}`); } } }); - ``` -### on('markReach')8+ +## AudioDeviceDescriptors -on(type: "markReach", frame: number, callback: Callback<number>): void +Defines an [AudioDeviceDescriptor](#audiodevicedescriptor) array, which is read-only. -Subscribes to mark reached events. When the number of frames rendered reaches the value of the **frame** parameter, a callback is invoked. +## AudioDeviceDescriptor -**System capability**: SystemCapability.Multimedia.Audio.Renderer +Describes an audio device. -**Parameters** +**System capability**: SystemCapability.Multimedia.Audio.Device -| Name | Type | Mandatory | Description | -| :------- | :---------------- | :-------- | :----------------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'markReach'**. | -| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | -| callback | Callback\ | Yes | Callback invoked when the event is triggered. | +| Name | Type | Readable | Writable | Description | +| ----------------------------- | ------------------------- | -------- | -------- | ------------------------------------------------------------ | +| deviceRole | [DeviceRole](#devicerole) | Yes | No | Device role. | +| deviceType | [DeviceType](#devicetype) | Yes | No | Device type. | +| id9+ | number | Yes | No | Device ID. | +| name9+ | string | Yes | No | Device name. | +| address9+ | string | Yes | No | Device address. | +| sampleRates9+ | Array<number> | Yes | No | Supported sampling rates. | +| channelCounts9+ | Array<number> | Yes | No | Number of channels supported. | +| channelMasks9+ | Array<number> | Yes | No | Supported channel masks. | +| networkId9+ | string | Yes | No | ID of the device network.
This is a system API. | +| interruptGroupId9+ | number | Yes | No | ID of the interruption group to which the device belongs.
This is a system API. | +| volumeGroupId9+ | number | Yes | No | ID of the volume group to which the device belongs.
This is a system API. | **Example** ```js -audioRenderer.on('markReach', 1000, (position) => { - if (position == 1000) { - console.info('ON Triggered successfully'); +import audio from '@ohos.multimedia.audio'; + +function displayDeviceProp(value) { + deviceRoleValue = value.deviceRole; + deviceTypeValue = value.deviceType; +} + +let deviceRoleValue = null; +let deviceTypeValue = null; +const promise = audio.getAudioManager().getDevices(1); +promise.then(function (value) { + console.info('AudioFrameworkTest: Promise: getDevices OUTPUT_DEVICES_FLAG'); + value.forEach(displayDeviceProp); + if (deviceTypeValue != null && deviceRoleValue != null){ + console.info('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : PASS'); + } else { + console.error('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : FAIL'); } }); - ``` +## AudioRendererFilter9+ -### off('markReach') 8+ +Implements filter criteria. Before calling **selectOutputDeviceByFilter**, you must obtain an **AudioRendererFilter** instance. -off(type: 'markReach'): void +**System API**: This is a system API. -Unsubscribes from mark reached events. +| Name | Type | Mandatory | Description | +| ------------ | ---------------------------------------- | --------- | ------------------------------------------------------------ | +| uid | number | Yes | Application ID.
**System capability**: SystemCapability.Multimedia.Audio.Core | +| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | No | Audio renderer information.
**System capability**: SystemCapability.Multimedia.Audio.Renderer | +| rendererId | number | No | Unique ID of an audio stream.
**System capability**: SystemCapability.Multimedia.Audio.Renderer | -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**Example** -**Parameters** +```js +let outputAudioRendererFilter = { + "uid":20010041, + "rendererInfo": { + "contentType":audio.ContentType.CONTENT_TYPE_MUSIC, + "streamUsage":audio.StreamUsage.STREAM_USAGE_MEDIA, + "rendererFlags":0 }, + "rendererId":0 }; +``` -| Name | Type | Mandatory | Description | -| :--- | :----- | :-------- | :------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'markReach'**. | +## AudioRenderer8+ + +Provides APIs for audio rendering. Before calling any API in **AudioRenderer**, you must use [createAudioRenderer](#audiocreateaudiorenderer8) to create an **AudioRenderer** instance. + +### Attributes + +**System capability**: SystemCapability.Multimedia.Audio.Renderer + +| Name | Type | Readable | Writable | Description | +| ------------------ | -------------------------- | -------- | -------- | --------------------- | +| state8+ | [AudioState](#audiostate8) | Yes | No | Audio renderer state. | **Example** ```js -audioRenderer.off('markReach'); - +let state = audioRenderer.state; ``` -### on('periodReach') 8+ +### getRendererInfo8+ -on(type: "periodReach", frame: number, callback: Callback<number>): void +getRendererInfo(callback: AsyncCallback): void -Subscribes to period reached events. When the number of frames rendered reaches the value of the **frame** parameter, a callback is triggered and the specified value is returned. +Obtains the renderer information of this **AudioRenderer** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :---------------- | :-------- | :----------------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | -| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | -| callback | Callback\ | Yes | Callback invoked when the event is triggered. | +| Name | Type | Mandatory | Description | +| :------- | :------------------------------------------------------- | :-------- | :------------------------------------------------ | +| callback | AsyncCallback<[AudioRendererInfo](#audiorendererinfo8)\> | Yes | Callback used to return the renderer information. | **Example** ```js -audioRenderer.on('periodReach', 1000, (position) => { - if (position == 1000) { - console.info('ON Triggered successfully'); - } +audioRenderer.getRendererInfo((err, rendererInfo) => { + console.info('Renderer GetRendererInfo:'); + console.info(`Renderer content: ${rendererInfo.content}`); + console.info(`Renderer usage: ${rendererInfo.usage}`); + console.info(`Renderer flags: ${rendererInfo.rendererFlags}`); }); - ``` -### off('periodReach') 8+ +### getRendererInfo8+ -off(type: 'periodReach'): void +getRendererInfo(): Promise -Unsubscribes from period reached events. +Obtains the renderer information of this **AudioRenderer** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters** +**Return value** -| Name | Type | Mandatory | Description | -| :--- | :----- | :-------- | :--------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | +| Type | Description | +| -------------------------------------------------- | ------------------------------------------------ | +| Promise<[AudioRendererInfo](#audiorendererinfo8)\> | Promise used to return the renderer information. | **Example** ```js -audioRenderer.off('periodReach') - +audioRenderer.getRendererInfo().then((rendererInfo) => { + console.info('Renderer GetRendererInfo:'); + console.info(`Renderer content: ${rendererInfo.content}`); + console.info(`Renderer usage: ${rendererInfo.usage}`); + console.info(`Renderer flags: ${rendererInfo.rendererFlags}`) +}).catch((err) => { + console.error(`AudioFrameworkRenderLog: RendererInfo :ERROR: ${err}`); +}); ``` -### on('stateChange')8+ +### getStreamInfo8+ -on(type: 'stateChange', callback: Callback): void +getStreamInfo(callback: AsyncCallback): void -Subscribes to state change events. +Obtains the stream information of this **AudioRenderer** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------------- | :-------- | :----------------------------------------------------------- | -| type | string | Yes | Event type. The value **stateChange** means the state change event. | -| callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. | +| Name | Type | Mandatory | Description | +| :------- | :--------------------------------------------------- | :-------- | :---------------------------------------------- | +| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information. | **Example** ```js -audioRenderer.on('stateChange', (state) => { - if (state == 1) { - console.info('audio renderer state is: STATE_PREPARED'); - } - if (state == 2) { - console.info('audio renderer state is: STATE_RUNNING'); - } +audioRenderer.getStreamInfo((err, streamInfo) => { + console.info('Renderer GetStreamInfo:'); + console.info(`Renderer sampling rate: ${streamInfo.samplingRate}`); + console.info(`Renderer channel: ${streamInfo.channels}`); + console.info(`Renderer format: ${streamInfo.sampleFormat}`); + console.info(`Renderer encoding type: ${streamInfo.encodingType}`); }); - ``` -## AudioCapturer8+ +### getStreamInfo8+ -Provides APIs for audio capture. Before calling any API in **AudioCapturer**, you must use [createAudioCapturer](#audiocreateaudiocapturer8) to create an **AudioCapturer** instance. +getStreamInfo(): Promise -### Attributes +Obtains the stream information of this **AudioRenderer** instance. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Type | Readable | Writable | Description | -| :----------------- | :------------------------- | :------- | :------- | :-------------------- | -| state8+ | [AudioState](#audiostate8) | Yes | No | Audio capturer state. | +**Return value** + +| Type | Description | +| :--------------------------------------------- | :--------------------------------------------- | +| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information. | **Example** ```js -let state = audioCapturer.state; +audioRenderer.getStreamInfo().then((streamInfo) => { + console.info('Renderer GetStreamInfo:'); + console.info(`Renderer sampling rate: ${streamInfo.samplingRate}`); + console.info(`Renderer channel: ${streamInfo.channels}`); + console.info(`Renderer format: ${streamInfo.sampleFormat}`); + console.info(`Renderer encoding type: ${streamInfo.encodingType}`); +}).catch((err) => { + console.error(`ERROR: ${err}`); +}); ``` -### getCapturerInfo8+ +### getAudioStreamId9+ -getCapturerInfo(callback: AsyncCallback): void +getAudioStreamId(callback: AsyncCallback): void -Obtains the capturer information of this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. +Obtains the stream ID of this **AudioRenderer** instance. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :-------------------------------- | :-------- | :------------------------------------------------ | -| callback | AsyncCallback | Yes | Callback used to return the capturer information. | +| Name | Type | Mandatory | Description | +| :------- | :--------------------- | :-------- | :------------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the stream ID. | **Example** ```js -audioCapturer.getCapturerInfo((err, capturerInfo) => { - if (err) { - console.error('Failed to get capture info'); - } else { - console.info('Capturer getCapturerInfo:'); - console.info(`Capturer source: ${capturerInfo.source}`); - console.info(`Capturer flags: ${capturerInfo.capturerFlags}`); - } +audioRenderer.getAudioStreamId((err, streamid) => { + console.info(`Renderer GetStreamId: ${streamid}`); }); ``` +### getAudioStreamId9+ -### getCapturerInfo8+ - -getCapturerInfo(): Promise +getAudioStreamId(): Promise -Obtains the capturer information of this **AudioCapturer** instance. This API uses a promise to return the result. +Obtains the stream ID of this **AudioRenderer** instance. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** -| Type | Description | -| :------------------------------------------------ | :----------------------------------------------- | -| Promise<[AudioCapturerInfo](#audiocapturerinfo)\> | Promise used to return the capturer information. | +| Type | Description | +| :--------------- | :------------------------------------ | +| Promise | Promise used to return the stream ID. | **Example** ```js -audioCapturer.getCapturerInfo().then((audioParamsGet) => { - if (audioParamsGet != undefined) { - console.info('AudioFrameworkRecLog: Capturer CapturerInfo:'); - console.info(`AudioFrameworkRecLog: Capturer SourceType: ${audioParamsGet.source}`); - console.info(`AudioFrameworkRecLog: Capturer capturerFlags: ${audioParamsGet.capturerFlags}`); - } else { - console.info(`AudioFrameworkRecLog: audioParamsGet is : ${audioParamsGet}`); - console.info('AudioFrameworkRecLog: audioParams getCapturerInfo are incorrect'); - } +audioRenderer.getAudioStreamId().then((streamid) => { + console.info(`Renderer getAudioStreamId: ${streamid}`); }).catch((err) => { - console.error(`AudioFrameworkRecLog: CapturerInfo :ERROR: ${err}`); + console.error(`ERROR: ${err}`); }); ``` -### getStreamInfo8+ +### start8+ -getStreamInfo(callback: AsyncCallback): void +start(callback: AsyncCallback): void -Obtains the stream information of this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. +Starts the renderer. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------------------------------------- | :-------- | :---------------------------------------------- | -| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information. | +| Name | Type | Mandatory | Description | +| -------- | -------------------- | --------- | ----------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```js -audioCapturer.getStreamInfo((err, streamInfo) => { +audioRenderer.start((err) => { if (err) { - console.error('Failed to get stream info'); + console.error('Renderer start failed.'); } else { - console.info('Capturer GetStreamInfo:'); - console.info(`Capturer sampling rate: ${streamInfo.samplingRate}`); - console.info(`Capturer channel: ${streamInfo.channels}`); - console.info(`Capturer format: ${streamInfo.sampleFormat}`); - console.info(`Capturer encoding type: ${streamInfo.encodingType}`); + console.info('Renderer start success.'); } }); ``` -### getStreamInfo8+ +### start8+ -getStreamInfo(): Promise +start(): Promise -Obtains the stream information of this **AudioCapturer** instance. This API uses a promise to return the result. +Starts the renderer. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** -| Type | Description | -| :--------------------------------------------- | :--------------------------------------------- | -| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information. | +| Type | Description | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** ```js -audioCapturer.getStreamInfo().then((audioParamsGet) => { - console.info('getStreamInfo:'); - console.info(`sampleFormat: ${audioParamsGet.sampleFormat}`); - console.info(`samplingRate: ${audioParamsGet.samplingRate}`); - console.info(`channels: ${audioParamsGet.channels}`); - console.info(`encodingType: ${audioParamsGet.encodingType}`); +audioRenderer.start().then(() => { + console.info('Renderer started'); }).catch((err) => { - console.error(`getStreamInfo :ERROR: ${err}`); + console.error(`ERROR: ${err}`); }); ``` -### getAudioStreamId9+ +### pause8+ -getAudioStreamId(callback: AsyncCallback): void +pause(callback: AsyncCallback\): void -Obtains the stream ID of this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. +Pauses rendering. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------- | :-------- | :------------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the stream ID. | +| Name | Type | Mandatory | Description | +| -------- | -------------------- | --------- | ----------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```js -audioCapturer.getAudioStreamId((err, streamid) => { - console.info(`audioCapturer GetStreamId: ${streamid}`); +audioRenderer.pause((err) => { + if (err) { + console.error('Renderer pause failed'); + } else { + console.info('Renderer paused.'); + } }); ``` -### getAudioStreamId9+ +### pause8+ -getAudioStreamId(): Promise +pause(): Promise\ -Obtains the stream ID of this **AudioCapturer** instance. This API uses a promise to return the result. +Pauses rendering. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** -| Type | Description | -| :--------------- | :------------------------------------ | -| Promise | Promise used to return the stream ID. | +| Type | Description | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** ```js -audioCapturer.getAudioStreamId().then((streamid) => { - console.info(`audioCapturer getAudioStreamId: ${streamid}`); +audioRenderer.pause().then(() => { + console.info('Renderer paused'); }).catch((err) => { console.error(`ERROR: ${err}`); }); ``` -### start8+ +### drain8+ -start(callback: AsyncCallback): void +drain(callback: AsyncCallback\): void -Starts capturing. This API uses an asynchronous callback to return the result. +Drains the playback buffer. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** | Name | Type | Mandatory | Description | -| :------- | :------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| -------- | -------------------- | --------- | ----------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```js -audioCapturer.start((err) => { +audioRenderer.drain((err) => { if (err) { - console.error('Capturer start failed.'); + console.error('Renderer drain failed'); } else { - console.info('Capturer start success.'); + console.info('Renderer drained.'); } }); ``` +### drain8+ -### start8+ - -start(): Promise +drain(): Promise\ -Starts capturing. This API uses a promise to return the result. +Drains the playback buffer. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** | Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** ```js -audioCapturer.start().then(() => { - console.info('AudioFrameworkRecLog: ---------START---------'); - console.info('AudioFrameworkRecLog: Capturer started: SUCCESS'); - console.info(`AudioFrameworkRecLog: AudioCapturer: STATE: ${audioCapturer.state}`); - console.info('AudioFrameworkRecLog: Capturer started: SUCCESS'); - if ((audioCapturer.state == audio.AudioState.STATE_RUNNING)) { - console.info('AudioFrameworkRecLog: AudioCapturer is in Running State'); - } +audioRenderer.drain().then(() => { + console.info('Renderer drained successfully'); }).catch((err) => { - console.info(`AudioFrameworkRecLog: Capturer start :ERROR : ${err}`); + console.error(`ERROR: ${err}`); }); ``` ### stop8+ -stop(callback: AsyncCallback): void +stop(callback: AsyncCallback\): void -Stops capturing. This API uses an asynchronous callback to return the result. +Stops rendering. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** | Name | Type | Mandatory | Description | -| :------- | :------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| -------- | -------------------- | --------- | ----------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```js -audioCapturer.stop((err) => { +audioRenderer.stop((err) => { if (err) { - console.error('Capturer stop failed'); + console.error('Renderer stop failed'); } else { - console.info('Capturer stopped.'); + console.info('Renderer stopped.'); } }); ``` - ### stop8+ -stop(): Promise +stop(): Promise\ -Stops capturing. This API uses a promise to return the result. +Stops rendering. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** | Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** ```js -audioCapturer.stop().then(() => { - console.info('AudioFrameworkRecLog: ---------STOP RECORD---------'); - console.info('AudioFrameworkRecLog: Capturer stopped: SUCCESS'); - if ((audioCapturer.state == audio.AudioState.STATE_STOPPED)){ - console.info('AudioFrameworkRecLog: State is Stopped:'); - } +audioRenderer.stop().then(() => { + console.info('Renderer stopped successfully'); }).catch((err) => { - console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); + console.error(`ERROR: ${err}`); }); ``` ### release8+ -release(callback: AsyncCallback): void +release(callback: AsyncCallback\): void -Releases this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. +Releases the renderer. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** | Name | Type | Mandatory | Description | -| :------- | :------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| -------- | -------------------- | --------- | ----------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```js -audioCapturer.release((err) => { +audioRenderer.release((err) => { if (err) { - console.error('capturer release failed'); + console.error('Renderer release failed'); } else { - console.info('capturer released.'); + console.info('Renderer released.'); } }); ``` - ### release8+ -release(): Promise +release(): Promise\ -Releases this **AudioCapturer** instance. This API uses a promise to return the result. +Releases the renderer. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** | Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** ```js -let stateFlag; -audioCapturer.release().then(() => { - console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------'); - console.info('AudioFrameworkRecLog: Capturer release : SUCCESS'); - console.info(`AudioFrameworkRecLog: AudioCapturer : STATE : ${audioCapturer.state}`); - console.info(`AudioFrameworkRecLog: stateFlag : ${stateFlag}`); +audioRenderer.release().then(() => { + console.info('Renderer released successfully'); }).catch((err) => { - console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); + console.error(`ERROR: ${err}`); }); ``` -### read8+ +### write8+ -read(size: number, isBlockingRead: boolean, callback: AsyncCallback): void +write(buffer: ArrayBuffer, callback: AsyncCallback\): void -Reads the buffer. This API uses an asynchronous callback to return the result. +Writes the buffer. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------------- | :-------------------------- | :-------- | :----------------------------------- | -| size | number | Yes | Number of bytes to read. | -| isBlockingRead | boolean | Yes | Whether to block the read operation. | -| callback | AsyncCallback | Yes | Callback used to return the buffer. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | --------- | ------------------------------------------------------------ | +| buffer | ArrayBuffer | Yes | Buffer to be written. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned. | **Example** ```js let bufferSize; -audioCapturer.getBufferSize().then((data) => { - console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`); +audioRenderer.getBufferSize().then((data)=> { + console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); bufferSize = data; }).catch((err) => { - console.error(`AudioFrameworkRecLog: getBufferSize: ERROR: ${err}`); + console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); }); -audioCapturer.read(bufferSize, true, async(err, buffer) => { - if (!err) { - console.info('Success in reading the buffer data'); +console.info(`Buffer size: ${bufferSize}`); +let context = featureAbility.getContext(); +let path; +async function getCacheDir(){ + path = await context.getCacheDir(); +} +let filePath = path + '/StarWars10s-2C-48000-4SW.wav'; +let ss = fileio.createStreamSync(filePath, 'r'); +let buf = new ArrayBuffer(bufferSize); +ss.readSync(buf); +audioRenderer.write(buf, (err, writtenbytes) => { + if (writtenbytes < 0) { + console.error('write failed.'); + } else { + console.info(`Actual written bytes: ${writtenbytes}`); } }); ``` -### read8+ - -read(size: number, isBlockingRead: boolean): Promise - -Reads the buffer. This API uses a promise to return the result. +### write8+ -**System capability**: SystemCapability.Multimedia.Audio.Capturer +write(buffer: ArrayBuffer): Promise\ -**Parameters** +Writes the buffer. This API uses a promise to return the result. -| Name | Type | Mandatory | Description | -| :------------- | :------ | :-------- | :----------------------------------- | -| size | number | Yes | Number of bytes to read. | -| isBlockingRead | boolean | Yes | Whether to block the read operation. | +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** -| Type | Description | -| :-------------------- | :----------------------------------------------------------- | -| Promise | Promise used to return the result. If the operation is successful, the buffer data read is returned; otherwise, an error code is returned. | +| Type | Description | +| ---------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned. | **Example** ```js let bufferSize; -audioCapturer.getBufferSize().then((data) => { - console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`); +audioRenderer.getBufferSize().then((data) => { + console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); bufferSize = data; }).catch((err) => { - console.info(`AudioFrameworkRecLog: getBufferSize: ERROR ${err}`); + console.info(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); }); -console.info(`Buffer size: ${bufferSize}`); -audioCapturer.read(bufferSize, true).then((buffer) => { - console.info('buffer read successfully'); +console.info(`BufferSize: ${bufferSize}`); +let context = featureAbility.getContext(); +let path; +async function getCacheDir(){ + path = await context.getCacheDir(); +} +let filePath = path + '/StarWars10s-2C-48000-4SW.wav'; +let ss = fileio.createStreamSync(filePath, 'r'); +let buf = new ArrayBuffer(bufferSize); +ss.readSync(buf); +audioRenderer.write(buf).then((writtenbytes) => { + if (writtenbytes < 0) { + console.error('write failed.'); + } else { + console.info(`Actual written bytes: ${writtenbytes}`); + } }).catch((err) => { - console.info(`ERROR : ${err}`); + console.error(`ERROR: ${err}`); }); ``` ### getAudioTime8+ -getAudioTime(callback: AsyncCallback): void +getAudioTime(callback: AsyncCallback\): void Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | --------- | -------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the timestamp. | **Example** ```js -audioCapturer.getAudioTime((err, timestamp) => { +audioRenderer.getAudioTime((err, timestamp) => { console.info(`Current timestamp: ${timestamp}`); }); @@ -4475,54 +4665,49 @@ audioCapturer.getAudioTime((err, timestamp) => { ### getAudioTime8+ -getAudioTime(): Promise +getAudioTime(): Promise\ Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** | Type | Description | -| :--------------- | :------------------------------------ | -| Promise | Promise used to return the timestamp. | +| ---------------- | ------------------------------------- | +| Promise\ | Promise used to return the timestamp. | **Example** ```js -audioCapturer.getAudioTime().then((audioTime) => { - console.info(`AudioFrameworkRecLog: AudioCapturer getAudioTime : Success ${audioTime}`); +audioRenderer.getAudioTime().then((timestamp) => { + console.info(`Current timestamp: ${timestamp}`); }).catch((err) => { - console.info(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`); + console.error(`ERROR: ${err}`); }); ``` ### getBufferSize8+ -getBufferSize(callback: AsyncCallback): void +getBufferSize(callback: AsyncCallback\): void -Obtains a reasonable minimum buffer size in bytes for capturing. This API uses an asynchronous callback to return the result. +Obtains a reasonable minimum buffer size in bytes for rendering. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** | Name | Type | Mandatory | Description | -| :------- | :--------------------- | :-------- | :--------------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the buffer size. | +| -------- | ---------------------- | --------- | ---------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the buffer size. | **Example** ```js -audioCapturer.getBufferSize((err, bufferSize) => { - if (!err) { - console.info(`BufferSize : ${bufferSize}`); - audioCapturer.read(bufferSize, true).then((buffer) => { - console.info(`Buffer read is ${buffer}`); - }).catch((err) => { - console.error(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`); - }); +let bufferSize = audioRenderer.getBufferSize(async(err, bufferSize) => { + if (err) { + console.error('getBufferSize error'); } }); @@ -4530,1546 +4715,1425 @@ audioCapturer.getBufferSize((err, bufferSize) => { ### getBufferSize8+ -getBufferSize(): Promise +getBufferSize(): Promise\ -Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a promise to return the result. +Obtains a reasonable minimum buffer size in bytes for rendering. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** | Type | Description | -| :--------------- | :-------------------------------------- | -| Promise | Promise used to return the buffer size. | +| ---------------- | --------------------------------------- | +| Promise\ | Promise used to return the buffer size. | **Example** ```js let bufferSize; -audioCapturer.getBufferSize().then((data) => { - console.info(`AudioFrameworkRecLog: getBufferSize :SUCCESS ${data}`); +audioRenderer.getBufferSize().then((data) => { + console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); bufferSize = data; }).catch((err) => { - console.info(`AudioFrameworkRecLog: getBufferSize :ERROR : ${err}`); + console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); }); ``` -### on('markReach')8+ +### setRenderRate8+ -on(type: "markReach", frame: number, callback: Callback<number>): void +setRenderRate(rate: AudioRendererRate, callback: AsyncCallback\): void -Subscribes to mark reached events. When the number of frames captured reaches the value of the **frame** parameter, a callback is invoked. +Sets the render rate. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :---------------- | :-------- | :----------------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'markReach'**. | -| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | -| callback | Callback\ | Yes | Callback invoked when the event is triggered. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | --------- | ----------------------------------- | +| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```js -audioCapturer.on('markReach', 1000, (position) => { - if (position == 1000) { - console.info('ON Triggered successfully'); +audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL, (err) => { + if (err) { + console.error('Failed to set params'); + } else { + console.info('Callback invoked to indicate a successful render rate setting.'); } }); ``` -### off('markReach')8+ - -off(type: 'markReach'): void - -Unsubscribes from mark reached events. - -**System capability**: SystemCapability.Multimedia.Audio.Capturer - -**Parameters** - -| Name | Type | Mandatory | Description | -| :--- | :----- | :-------- | :------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'markReach'**. | - -**Example** - -```js -audioCapturer.off('markReach'); - -``` - -### on('periodReach')8+ +### setRenderRate8+ -on(type: "periodReach", frame: number, callback: Callback<number>): void +setRenderRate(rate: AudioRendererRate): Promise\ -Subscribes to period reached events. When the number of frames captured reaches the value of the **frame** parameter, a callback is triggered and the specified value is returned. +Sets the render rate. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :---------------- | :-------- | :----------------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | -| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | -| callback | Callback\ | Yes | Callback invoked when the event is triggered. | +| Name | Type | Mandatory | Description | +| ---- | ---------------------------------------- | --------- | ------------------ | +| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. | + +**Return value** + +| Type | Description | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** ```js -audioCapturer.on('periodReach', 1000, (position) => { - if (position == 1000) { - console.info('ON Triggered successfully'); - } +audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL).then(() => { + console.info('setRenderRate SUCCESS'); +}).catch((err) => { + console.error(`ERROR: ${err}`); }); ``` -### off('periodReach')8+ +### getRenderRate8+ -off(type: 'periodReach'): void +getRenderRate(callback: AsyncCallback\): void -Unsubscribes from period reached events. +Obtains the current render rate. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :--- | :----- | :-------- | :--------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ---------------------------------------------- | +| callback | AsyncCallback<[AudioRendererRate](#audiorendererrate8)> | Yes | Callback used to return the audio render rate. | **Example** ```js -audioCapturer.off('periodReach') +audioRenderer.getRenderRate((err, renderrate) => { + console.info(`getRenderRate: ${renderrate}`); +}); ``` -### on('stateChange')8+ +### getRenderRate8+ -on(type: 'stateChange', callback: Callback): void +getRenderRate(): Promise\ -Subscribes to state change events. +Obtains the current render rate. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters** +**Return value** -| Name | Type | Mandatory | Description | -| :------- | :------------------------- | :-------- | :----------------------------------------------------------- | -| type | string | Yes | Event type. The value **stateChange** means the state change event. | -| callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. | +| Type | Description | +| ------------------------------------------------- | --------------------------------------------- | +| Promise<[AudioRendererRate](#audiorendererrate8)> | Promise used to return the audio render rate. | **Example** ```js -audioCapturer.on('stateChange', (state) => { - if (state == 1) { - console.info('audio capturer state is: STATE_PREPARED'); - } - if (state == 2) { - console.info('audio capturer state is: STATE_RUNNING'); - } +audioRenderer.getRenderRate().then((renderRate) => { + console.info(`getRenderRate: ${renderRate}`); +}).catch((err) => { + console.error(`ERROR: ${err}`); }); ``` -## ToneType9+ +### setInterruptMode9+ -Enumerates the tone types of the player. +setInterruptMode(mode: InterruptMode): Promise<void> -**System API**: This is a system API. +Sets the audio interruption mode for the application. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Tone +**System capability**: SystemCapability.Multimedia.Audio.Interrupt -| Name | Default Value | Description | -| :----------------------------------------------- | :------------ | :-------------------------------------------- | -| TONE_TYPE_DIAL_0 | 0 | DTMF tone of key 0. | -| TONE_TYPE_DIAL_1 | 1 | DTMF tone of key 1. | -| TONE_TYPE_DIAL_2 | 2 | DTMF tone of key 2. | -| TONE_TYPE_DIAL_3 | 3 | DTMF tone of key 3. | -| TONE_TYPE_DIAL_4 | 4 | DTMF tone of key 4. | -| TONE_TYPE_DIAL_5 | 5 | DTMF tone of key 5. | -| TONE_TYPE_DIAL_6 | 6 | DTMF tone of key 6. | -| TONE_TYPE_DIAL_7 | 7 | DTMF tone of key 7. | -| TONE_TYPE_DIAL_8 | 8 | DTMF tone of key 8. | -| TONE_TYPE_DIAL_9 | 9 | DTMF tone of key 9. | -| TONE_TYPE_DIAL_S | 10 | DTMF tone of the star key (*). | -| TONE_TYPE_DIAL_P | 11 | DTMF tone of the pound key (#). | -| TONE_TYPE_DIAL_A | 12 | DTMF tone of key A. | -| TONE_TYPE_DIAL_B | 13 | DTMF tone of key B. | -| TONE_TYPE_DIAL_C | 14 | DTMF tone of key C. | -| TONE_TYPE_DIAL_D | 15 | DTMF tone of key D. | -| TONE_TYPE_COMMON_SUPERVISORY_DIAL | 100 | Supervisory tone - dial tone. | -| TONE_TYPE_COMMON_SUPERVISORY_BUSY | 101 | Supervisory tone - busy. | -| TONE_TYPE_COMMON_SUPERVISORY_CONGESTION | 102 | Supervisory tone - congestion. | -| TONE_TYPE_COMMON_SUPERVISORY_RADIO_ACK | 103 | Supervisory tone - radio path acknowledgment. | -| TONE_TYPE_COMMON_SUPERVISORY_RADIO_NOT_AVAILABLE | 104 | Supervisory tone - radio path not available. | -| TONE_TYPE_COMMON_SUPERVISORY_CALL_WAITING | 106 | Supervisory tone - call waiting tone. | -| TONE_TYPE_COMMON_SUPERVISORY_RINGTONE | 107 | Supervisory tone - ringing tone. | -| TONE_TYPE_COMMON_PROPRIETARY_BEEP | 200 | Proprietary tone - beep tone. | -| TONE_TYPE_COMMON_PROPRIETARY_ACK | 201 | Proprietary tone - ACK. | -| TONE_TYPE_COMMON_PROPRIETARY_PROMPT | 203 | Proprietary tone - PROMPT. | -| TONE_TYPE_COMMON_PROPRIETARY_DOUBLE_BEEP | 204 | Proprietary tone - double beep tone. | +**Parameters** -## TonePlayer9+ +| Name | Type | Mandatory | Description | +| ---- | -------------------------------- | --------- | ------------------------ | +| mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode. | -Provides APIs for playing and managing DTMF tones, such as dial tones, ringback tones, supervisory tones, and proprietary tones. +**Return value** -**System API**: This is a system API. +| Type | Description | +| ------------------- | ------------------------------------------------------------ | +| Promise<void> | Promise used to return the result. If the operation is successful, **undefined** is returned. Otherwise, **error** is returned. | -### load9+ +**Example** -load(type: ToneType, callback: AsyncCallback<void>): void +```js +let mode = 0; +audioRenderer.setInterruptMode(mode).then(data=>{ + console.info('setInterruptMode Success!'); +}).catch((err) => { + console.error(`setInterruptMode Fail: ${err}`); +}); -Loads the DTMF tone configuration. This API uses an asynchronous callback to return the result. +``` -**System capability**: SystemCapability.Multimedia.Audio.Tone +### setInterruptMode9+ + +setInterruptMode(mode: InterruptMode, callback: AsyncCallback\): void + +Sets the audio interruption mode for the application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Interrupt **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------- | :-------- | :---------------------------------- | -| type | [ToneType](#tonetype9) | Yes | Tone type. | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | -------------------------------- | --------- | ----------------------------------- | +| mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```js -tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_5, (err) => { - if (err) { - console.error(`callback call load failed error: ${err.message}`); - return; - } else { - console.info('callback call load success'); +let mode = 1; +audioRenderer.setInterruptMode(mode, (err, data)=>{ + if(err){ + console.error(`setInterruptMode Fail: ${err}`); } + console.info('setInterruptMode Success!'); }); ``` -### load9+ +### setVolume9+ -load(type: ToneType): Promise<void> +setVolume(volume: number): Promise<void> -Loads the DTMF tone configuration. This API uses a promise to return the result. +Sets the volume for the application. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Tone +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :--- | :--------------------- | :-------- | ----------- | -| type | [ToneType](#tonetype9) | Yes | Tone type. | +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | ------------------------------------------------------------ | +| volume | number | Yes | Volume to set, which can be within the range from 0.0 to 1.0. | **Return value** -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| Type | Description | +| ------------------- | ------------------------------------------------------------ | +| Promise<void> | Promise used to return the result. If the operation is successful, **undefined** is returned. Otherwise, **error** is returned. | **Example** ```js -tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_1).then(() => { - console.info('promise call load '); -}).catch(() => { - console.error('promise call load fail'); +audioRenderer.setVolume(0.5).then(data=>{ + console.info('setVolume Success!'); +}).catch((err) => { + console.error(`setVolume Fail: ${err}`); }); ``` -### start9+ +### setVolume9+ -start(callback: AsyncCallback<void>): void +setVolume(volume: number, callback: AsyncCallback\): void -Starts DTMF tone playing. This API uses an asynchronous callback to return the result. +Sets the volume for the application. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Tone +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | -------------------- | --------- | ------------------------------------------------------------ | +| volume | number | Yes | Volume to set, which can be within the range from 0.0 to 1.0. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```js -tonePlayer.start((err) => { - if (err) { - console.error(`callback call start failed error: ${err.message}`); - return; - } else { - console.info('callback call start success'); +audioRenderer.setVolume(0.5, (err, data)=>{ + if(err){ + console.error(`setVolume Fail: ${err}`); } + console.info('setVolume Success!'); }); ``` -### start9+ +### on('audioInterrupt')9+ -start(): Promise<void> +on(type: 'audioInterrupt', callback: Callback\): void -Starts DTMF tone playing. This API uses a promise to return the result. +Subscribes to audio interruption events. This API uses a callback to get interrupt events. -**System capability**: SystemCapability.Multimedia.Audio.Tone +Same as [on('interrupt')](#oninterruptdeprecated), this API has obtained the focus before **start**, **pause**, or **stop** of **AudioRenderer** is called. Therefore, you do not need to request the focus. -**Return value** +**System capability**: SystemCapability.Multimedia.Audio.Interrupt -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **'audioInterrupt'** means the audio interruption event, which is triggered when audio playback is interrupted. | +| callback | Callback<[InterruptEvent](#interruptevent9)> | Yes | Callback used to return the audio interruption event. | + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 6800101 | if input parameter value error | **Example** ```js -tonePlayer.start().then(() => { - console.info('promise call start'); -}).catch(() => { - console.error('promise call start fail'); -}); +let isPlay; +let started; +onAudioInterrupt(); + +async function onAudioInterrupt(){ + audioRenderer.on('audioInterrupt', async(interruptEvent) => { + if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { + switch (interruptEvent.hintType) { + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + console.info('Force paused. Stop writing'); + isPlay = false; + break; + case audio.InterruptHint.INTERRUPT_HINT_STOP: + console.info('Force stopped. Stop writing'); + isPlay = false; + break; + } + } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { + switch (interruptEvent.hintType) { + case audio.InterruptHint.INTERRUPT_HINT_RESUME: + console.info('Resume force paused renderer or ignore'); + await audioRenderer.start().then(async function () { + console.info('AudioInterruptMusic: renderInstant started :SUCCESS '); + started = true; + }).catch((err) => { + console.error(`AudioInterruptMusic: renderInstant start :ERROR : ${err}`); + started = false; + }); + if (started) { + isPlay = true; + console.info(`AudioInterruptMusic Renderer started : isPlay : ${isPlay}`); + } else { + console.error('AudioInterruptMusic Renderer start failed'); + } + break; + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + console.info('Choose to pause or ignore'); + if (isPlay == true) { + isPlay == false; + console.info('AudioInterruptMusic: Media PAUSE : TRUE'); + } else { + isPlay = true; + console.info('AudioInterruptMusic: Media PLAY : TRUE'); + } + break; + } + } + }); +} ``` -### stop9+ +### on('markReach')8+ -stop(callback: AsyncCallback<void>): void +on(type: "markReach", frame: number, callback: Callback<number>): void -Stops the tone that is being played. This API uses an asynchronous callback to return the result. +Subscribes to mark reached events. When the number of frames rendered reaches the value of the **frame** parameter, a callback is invoked. -**System capability**: SystemCapability.Multimedia.Audio.Tone +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| :------- | :---------------- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'markReach'**. | +| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | +| callback | Callback\ | Yes | Callback invoked when the event is triggered. | **Example** ```js -tonePlayer.stop((err) => { - if (err) { - console.error(`callback call stop error: ${err.message}`); - return; - } else { - console.error('callback call stop success '); +audioRenderer.on('markReach', 1000, (position) => { + if (position == 1000) { + console.info('ON Triggered successfully'); } }); ``` -### stop9+ -stop(): Promise<void> +### off('markReach') 8+ -Stops the tone that is being played. This API uses a promise to return the result. +off(type: 'markReach'): void -**System capability**: SystemCapability.Multimedia.Audio.Tone +Unsubscribes from mark reached events. -**Return value** +**System capability**: SystemCapability.Multimedia.Audio.Renderer -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +**Parameters** + +| Name | Type | Mandatory | Description | +| :--- | :----- | :-------- | :------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'markReach'**. | **Example** ```js -tonePlayer.stop().then(() => { - console.info('promise call stop finish'); -}).catch(() => { - console.error('promise call stop fail'); -}); +audioRenderer.off('markReach'); ``` -### release9+ +### on('periodReach') 8+ -release(callback: AsyncCallback<void>): void +on(type: "periodReach", frame: number, callback: Callback<number>): void -Releases the resources associated with the **TonePlayer** instance. This API uses an asynchronous callback to return the result. +Subscribes to period reached events. When the number of frames rendered reaches the value of the **frame** parameter, a callback is triggered and the specified value is returned. -**System capability**: SystemCapability.Multimedia.Audio.Tone +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| :------- | :---------------- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | +| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | +| callback | Callback\ | Yes | Callback invoked when the event is triggered. | **Example** ```js -tonePlayer.release((err) => { - if (err) { - console.error(`callback call release failed error: ${err.message}`); - return; - } else { - console.info('callback call release success '); +audioRenderer.on('periodReach', 1000, (position) => { + if (position == 1000) { + console.info('ON Triggered successfully'); } }); ``` -### release9+ +### off('periodReach') 8+ -release(): Promise<void> +off(type: 'periodReach'): void -Releases the resources associated with the **TonePlayer** instance. This API uses a promise to return the result. +Unsubscribes from period reached events. -**System capability**: SystemCapability.Multimedia.Audio.Tone +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Return value** +**Parameters** -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| Name | Type | Mandatory | Description | +| :--- | :----- | :-------- | :--------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | **Example** ```js -tonePlayer.release().then(() => { - console.info('promise call release'); -}).catch(() => { - console.error('promise call release fail'); -}); +audioRenderer.off('periodReach') ``` -## ActiveDeviceType(deprecated) - -Enumerates the active device types. - -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [CommunicationDeviceType](#communicationdevicetype9) instead. - -**System capability**: SystemCapability.Multimedia.Audio.Device - -| Name | Default Value | Description | -| ------------- | ------------- | ------------------------------------------------------------ | -| SPEAKER | 2 | Speaker. | -| BLUETOOTH_SCO | 7 | Bluetooth device using Synchronous Connection Oriented (SCO) links. | - -## InterruptActionType(deprecated) +### on('stateChange')8+ -Enumerates the returned event types for audio interruption events. +on(type: 'stateChange', callback: Callback): void -> **NOTE** -> This API is supported since API version 7 and deprecated since API version 9. +Subscribes to state change events. **System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Default Value | Description | -| -------------- | ------------- | ------------------------- | -| TYPE_ACTIVATED | 0 | Focus gain event. | -| TYPE_INTERRUPT | 1 | Audio interruption event. | - -## AudioInterrupt(deprecated) +**Parameters** -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. +| Name | Type | Mandatory | Description | +| :------- | :------------------------------------ | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value **stateChange** means the state change event. | +| callback | Callback\<[AudioState](#audiostate8)> | Yes | Callback used to return the state change. | -Describes input parameters of audio interruption events. +**Example** -**System capability**: SystemCapability.Multimedia.Audio.Renderer +```js +audioRenderer.on('stateChange', (state) => { + if (state == 1) { + console.info('audio renderer state is: STATE_PREPARED'); + } + if (state == 2) { + console.info('audio renderer state is: STATE_RUNNING'); + } +}); -| Name | Type | Mandatory | Description | -| --------------- | --------------------------- | --------- | ------------------------------------------------------------ | -| streamUsage | [StreamUsage](#streamusage) | Yes | Audio stream usage. | -| contentType | [ContentType](#contenttype) | Yes | Audio content type. | -| pauseWhenDucked | boolean | Yes | Whether audio playback can be paused during audio interruption. The value **true** means that audio playback can be paused during audio interruption, and **false** means the opposite. | +``` -## InterruptAction(deprecated) +## AudioCapturer8+ -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. +Provides APIs for audio capture. Before calling any API in **AudioCapturer**, you must use [createAudioCapturer](#audiocreateaudiocapturer8) to create an **AudioCapturer** instance. -Describes the callback invoked for audio interruption or focus gain events. +### Attributes -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Capturer -| Name | Type | Mandatory | Description | -| ---------- | ------------------------------------------- | --------- | ------------------------------------------------------------ | -| actionType | [InterruptActionType](#interruptactiontype) | Yes | Returned event type. The value **TYPE_ACTIVATED** means the focus gain event, and **TYPE_INTERRUPT** means the audio interruption event. | -| type | [InterruptType](#interrupttype) | No | Type of the audio interruption event. | -| hint | [InterruptHint](#interrupthint) | No | Hint provided along with the audio interruption event. | -| activated | boolean | No | Whether the focus is gained or released. The value **true** means that the focus is gained or released, and **false** means that the focus fails to be gained or released. | +| Name | Type | Readable | Writable | Description | +| :----------------- | :------------------------- | :------- | :------- | :-------------------- | +| state8+ | [AudioState](#audiostate8) | Yes | No | Audio capturer state. | -### setVolume(deprecated) +**Example** -setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback<void>): void +```js +let state = audioCapturer.state; -Sets the volume for a stream. This API uses an asynchronous callback to return the result. +``` -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setVolume](#setvolume9) in **AudioVolumeGroupManager**. +### getCapturerInfo8+ -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY +getCapturerInfo(callback: AsyncCallback): void -This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. +Obtains the capturer information of this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------------------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| :------- | :-------------------------------- | :-------- | :------------------------------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the capturer information. | **Example** ```js -audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => { +audioCapturer.getCapturerInfo((err, capturerInfo) => { if (err) { - console.error(`Failed to set the volume. ${err}`); - return; + console.error('Failed to get capture info'); + } else { + console.info('Capturer getCapturerInfo:'); + console.info(`Capturer source: ${capturerInfo.source}`); + console.info(`Capturer flags: ${capturerInfo.capturerFlags}`); } - console.info('Callback invoked to indicate a successful volume setting.'); }); ``` -### setVolume(deprecated) - -setVolume(volumeType: AudioVolumeType, volume: number): Promise<void> - -Sets the volume for a stream. This API uses a promise to return the result. - -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setVolume](#setvolume9) in **AudioVolumeGroupManager**. - -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY -This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. +### getCapturerInfo8+ -**System capability**: SystemCapability.Multimedia.Audio.Volume +getCapturerInfo(): Promise -**Parameters** +Obtains the capturer information of this **AudioCapturer** instance. This API uses a promise to return the result. -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------------------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**. | +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Return value** -| Type | Description | -| ------------------- | ---------------------------------- | -| Promise<void> | Promise used to return the result. | +| Type | Description | +| :------------------------------------------------ | :----------------------------------------------- | +| Promise<[AudioCapturerInfo](#audiocapturerinfo)\> | Promise used to return the capturer information. | **Example** ```js -audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => { - console.info('Promise returned to indicate a successful volume setting.'); +audioCapturer.getCapturerInfo().then((audioParamsGet) => { + if (audioParamsGet != undefined) { + console.info('AudioFrameworkRecLog: Capturer CapturerInfo:'); + console.info(`AudioFrameworkRecLog: Capturer SourceType: ${audioParamsGet.source}`); + console.info(`AudioFrameworkRecLog: Capturer capturerFlags: ${audioParamsGet.capturerFlags}`); + } else { + console.info(`AudioFrameworkRecLog: audioParamsGet is : ${audioParamsGet}`); + console.info('AudioFrameworkRecLog: audioParams getCapturerInfo are incorrect'); + } +}).catch((err) => { + console.error(`AudioFrameworkRecLog: CapturerInfo :ERROR: ${err}`); }); ``` -### getVolume(deprecated) - -getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void +### getStreamInfo8+ -Obtains the volume of a stream. This API uses an asynchronous callback to return the result. +getStreamInfo(callback: AsyncCallback): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getVolume](#getvolume9) in **AudioVolumeGroupManager**. +Obtains the stream information of this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ----------------------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| callback | AsyncCallback<number> | Yes | Callback used to return the volume. | +| Name | Type | Mandatory | Description | +| :------- | :--------------------------------------------------- | :-------- | :---------------------------------------------- | +| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information. | **Example** ```js -audioManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { +audioCapturer.getStreamInfo((err, streamInfo) => { if (err) { - console.error(`Failed to obtain the volume. ${err}`); - return; + console.error('Failed to get stream info'); + } else { + console.info('Capturer GetStreamInfo:'); + console.info(`Capturer sampling rate: ${streamInfo.samplingRate}`); + console.info(`Capturer channel: ${streamInfo.channels}`); + console.info(`Capturer format: ${streamInfo.sampleFormat}`); + console.info(`Capturer encoding type: ${streamInfo.encodingType}`); } - console.info('Callback invoked to indicate that the volume is obtained.'); }); ``` -### getVolume(deprecated) - -getVolume(volumeType: AudioVolumeType): Promise<number> - -Obtains the volume of a stream. This API uses a promise to return the result. - -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getVolume](#getvolume9) in **AudioVolumeGroupManager**. +### getStreamInfo8+ -**System capability**: SystemCapability.Multimedia.Audio.Volume +getStreamInfo(): Promise -**Parameters** +Obtains the stream information of this **AudioCapturer** instance. This API uses a promise to return the result. -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Return value** -| Type | Description | -| --------------------- | ---------------------------------- | -| Promise<number> | Promise used to return the volume. | +| Type | Description | +| :--------------------------------------------- | :--------------------------------------------- | +| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information. | **Example** ```js -audioManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promise returned to indicate that the volume is obtained ${value} .`); +audioCapturer.getStreamInfo().then((audioParamsGet) => { + console.info('getStreamInfo:'); + console.info(`sampleFormat: ${audioParamsGet.sampleFormat}`); + console.info(`samplingRate: ${audioParamsGet.samplingRate}`); + console.info(`channels: ${audioParamsGet.channels}`); + console.info(`encodingType: ${audioParamsGet.encodingType}`); +}).catch((err) => { + console.error(`getStreamInfo :ERROR: ${err}`); }); ``` -### getMinVolume(deprecated) - -getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void +### getAudioStreamId9+ -Obtains the minimum volume allowed for a stream. This API uses an asynchronous callback to return the result. +getAudioStreamId(callback: AsyncCallback): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getMinVolume](#getminvolume9) in **AudioVolumeGroupManager**. +Obtains the stream ID of this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| callback | AsyncCallback<number> | Yes | Callback used to return the minimum volume. | +| Name | Type | Mandatory | Description | +| :------- | :--------------------- | :-------- | :------------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the stream ID. | **Example** ```js -audioManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => { - if (err) { - console.error(`Failed to obtain the minimum volume. ${err}`); - return; - } - console.info(`Callback invoked to indicate that the minimum volume is obtained. ${value}`); +audioCapturer.getAudioStreamId((err, streamid) => { + console.info(`audioCapturer GetStreamId: ${streamid}`); }); -``` - -### getMinVolume(deprecated) - -getMinVolume(volumeType: AudioVolumeType): Promise<number> - -Obtains the minimum volume allowed for a stream. This API uses a promise to return the result. - -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getMinVolume](#getminvolume9) in **AudioVolumeGroupManager**. +``` -**System capability**: SystemCapability.Multimedia.Audio.Volume +### getAudioStreamId9+ -**Parameters** +getAudioStreamId(): Promise + +Obtains the stream ID of this **AudioCapturer** instance. This API uses a promise to return the result. -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Return value** -| Type | Description | -| --------------------- | ------------------------------------------ | -| Promise<number> | Promise used to return the minimum volume. | +| Type | Description | +| :--------------- | :------------------------------------ | +| Promise | Promise used to return the stream ID. | **Example** ```js -audioManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promised returned to indicate that the minimum volume is obtained. ${value}`); +audioCapturer.getAudioStreamId().then((streamid) => { + console.info(`audioCapturer getAudioStreamId: ${streamid}`); +}).catch((err) => { + console.error(`ERROR: ${err}`); }); ``` -### getMaxVolume(deprecated) - -getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void +### start8+ -Obtains the maximum volume allowed for a stream. This API uses an asynchronous callback to return the result. +start(callback: AsyncCallback): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getMaxVolume](#getmaxvolume9) in **AudioVolumeGroupManager**. +Starts capturing. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| callback | AsyncCallback<number> | Yes | Callback used to return the maximum volume. | +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => { +audioCapturer.start((err) => { if (err) { - console.error(`Failed to obtain the maximum volume. ${err}`); - return; + console.error('Capturer start failed.'); + } else { + console.info('Capturer start success.'); } - console.info(`Callback invoked to indicate that the maximum volume is obtained. ${value}`); }); ``` -### getMaxVolume(deprecated) - -getMaxVolume(volumeType: AudioVolumeType): Promise<number> - -Obtains the maximum volume allowed for a stream. This API uses a promise to return the result. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getMaxVolume](#getmaxvolume9) in **AudioVolumeGroupManager**. +### start8+ -**System capability**: SystemCapability.Multimedia.Audio.Volume +start(): Promise -**Parameters** +Starts capturing. This API uses a promise to return the result. -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Return value** -| Type | Description | -| --------------------- | ------------------------------------------ | -| Promise<number> | Promise used to return the maximum volume. | +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** ```js -audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => { - console.info('Promised returned to indicate that the maximum volume is obtained.'); +audioCapturer.start().then(() => { + console.info('AudioFrameworkRecLog: ---------START---------'); + console.info('AudioFrameworkRecLog: Capturer started: SUCCESS'); + console.info(`AudioFrameworkRecLog: AudioCapturer: STATE: ${audioCapturer.state}`); + console.info('AudioFrameworkRecLog: Capturer started: SUCCESS'); + if ((audioCapturer.state == audio.AudioState.STATE_RUNNING)) { + console.info('AudioFrameworkRecLog: AudioCapturer is in Running State'); + } +}).catch((err) => { + console.info(`AudioFrameworkRecLog: Capturer start :ERROR : ${err}`); }); ``` -### mute(deprecated) - -mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void>): void - -Mutes or unmutes a stream. This API uses an asynchronous callback to return the result. - -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [mute](#mute9) in **AudioVolumeGroupManager**. +### stop8+ -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY +stop(callback: AsyncCallback): void -This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. +Stops capturing. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------------------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| mute | boolean | Yes | Mute status to set. The value **true** means to mute the stream, and **false** means the opposite. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -audioManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { +audioCapturer.stop((err) => { if (err) { - console.error(`Failed to mute the stream. ${err}`); - return; + console.error('Capturer stop failed'); + } else { + console.info('Capturer stopped.'); } - console.info('Callback invoked to indicate that the stream is muted.'); }); ``` -### mute(deprecated) - -mute(volumeType: AudioVolumeType, mute: boolean): Promise<void> - -Mutes or unmutes a stream. This API uses a promise to return the result. - -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [mute](#mute9) in **AudioVolumeGroupManager**. - -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY -This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. +### stop8+ -**System capability**: SystemCapability.Multimedia.Audio.Volume +stop(): Promise -**Parameters** +Stops capturing. This API uses a promise to return the result. -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------------------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| mute | boolean | Yes | Mute status to set. The value **true** means to mute the stream, and **false** means the opposite. | +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Return value** -| Type | Description | -| ------------------- | ---------------------------------- | -| Promise<void> | Promise used to return the result. | +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** - ```js -audioManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => { - console.info('Promise returned to indicate that the stream is muted.'); +audioCapturer.stop().then(() => { + console.info('AudioFrameworkRecLog: ---------STOP RECORD---------'); + console.info('AudioFrameworkRecLog: Capturer stopped: SUCCESS'); + if ((audioCapturer.state == audio.AudioState.STATE_STOPPED)){ + console.info('AudioFrameworkRecLog: State is Stopped:'); + } +}).catch((err) => { + console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); }); ``` -### isMute(deprecated) - -isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void +### release8+ -Checks whether a stream is muted. This API uses an asynchronous callback to return the result. +release(callback: AsyncCallback): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isMute](#ismute9) in **AudioVolumeGroupManager**. +Releases this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------------------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the mute status of the stream. The value **true** means that the stream is muted, and **false** means the opposite. | +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -audioManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => { +audioCapturer.release((err) => { if (err) { - console.error(`Failed to obtain the mute status. ${err}`); - return; + console.error('capturer release failed'); + } else { + console.info('capturer released.'); } - console.info(`Callback invoked to indicate that the mute status of the stream is obtained. ${value}`); }); ``` -### isMute(deprecated) - -isMute(volumeType: AudioVolumeType): Promise<boolean> - -Checks whether a stream is muted. This API uses a promise to return the result. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isMute](#ismute9) in **AudioVolumeGroupManager**. +### release8+ -**System capability**: SystemCapability.Multimedia.Audio.Volume +release(): Promise -**Parameters** +Releases this **AudioCapturer** instance. This API uses a promise to return the result. -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Return value** -| Type | Description | -| ---------------------- | ------------------------------------------------------------ | -| Promise<boolean> | Promise used to return the mute status of the stream. The value **true** means that the stream is muted, and **false** means the opposite. | +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** ```js -audioManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promise returned to indicate that the mute status of the stream is obtained ${value}.`); +let stateFlag; +audioCapturer.release().then(() => { + console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------'); + console.info('AudioFrameworkRecLog: Capturer release : SUCCESS'); + console.info(`AudioFrameworkRecLog: AudioCapturer : STATE : ${audioCapturer.state}`); + console.info(`AudioFrameworkRecLog: stateFlag : ${stateFlag}`); +}).catch((err) => { + console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); }); ``` -### isActive(deprecated) - -isActive(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void +### read8+ -Checks whether a stream is active. This API uses an asynchronous callback to return the result. +read(size: number, isBlockingRead: boolean, callback: AsyncCallback): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isActive](#isactive9) in **AudioStreamManager**. +Reads the buffer. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------------------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite. | +| Name | Type | Mandatory | Description | +| :------------- | :-------------------------- | :-------- | :----------------------------------- | +| size | number | Yes | Number of bytes to read. | +| isBlockingRead | boolean | Yes | Whether to block the read operation. | +| callback | AsyncCallback | Yes | Callback used to return the buffer. | **Example** ```js -audioManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => { - if (err) { - console.error(`Failed to obtain the active status of the stream. ${err}`); - return; +let bufferSize; +audioCapturer.getBufferSize().then((data) => { + console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`); + bufferSize = data; + }).catch((err) => { + console.error(`AudioFrameworkRecLog: getBufferSize: ERROR: ${err}`); + }); +audioCapturer.read(bufferSize, true, async(err, buffer) => { + if (!err) { + console.info('Success in reading the buffer data'); } - console.info(`Callback invoked to indicate that the active status of the stream is obtained ${value}.`); }); ``` -### isActive(deprecated) - -isActive(volumeType: AudioVolumeType): Promise<boolean> +### read8+ -Checks whether a stream is active. This API uses a promise to return the result. +read(size: number, isBlockingRead: boolean): Promise -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isActive](#isactive9) in **AudioStreamManager**. +Reads the buffer. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| Name | Type | Mandatory | Description | +| :------------- | :------ | :-------- | :----------------------------------- | +| size | number | Yes | Number of bytes to read. | +| isBlockingRead | boolean | Yes | Whether to block the read operation. | **Return value** -| Type | Description | -| ---------------------- | ------------------------------------------------------------ | -| Promise<boolean> | Promise used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite. | +| Type | Description | +| :-------------------- | :----------------------------------------------------------- | +| Promise | Promise used to return the result. If the operation is successful, the buffer data read is returned; otherwise, an error code is returned. | **Example** ```js -audioManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promise returned to indicate that the active status of the stream is obtained ${value}.`); +let bufferSize; +audioCapturer.getBufferSize().then((data) => { + console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`); + bufferSize = data; + }).catch((err) => { + console.info(`AudioFrameworkRecLog: getBufferSize: ERROR ${err}`); + }); +console.info(`Buffer size: ${bufferSize}`); +audioCapturer.read(bufferSize, true).then((buffer) => { + console.info('buffer read successfully'); +}).catch((err) => { + console.info(`ERROR : ${err}`); }); -``` - -### setRingerMode(deprecated) - -setRingerMode(mode: AudioRingMode, callback: AsyncCallback<void>): void - -Sets the ringer mode. This API uses an asynchronous callback to return the result. - -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setRingerMode](#setringermode9) in **AudioVolumeGroupManager**. +``` -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY +### getAudioTime8+ -This permission is required only for muting or unmuting the ringer. +getAudioTime(callback: AsyncCallback): void -**System capability**: SystemCapability.Multimedia.Audio.Communication +Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------- | --------- | ----------------------------------- | -| mode | [AudioRingMode](#audioringmode) | Yes | Ringer mode. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| :------- | :--------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => { - if (err) { - console.error(`Failed to set the ringer mode.​ ${err}`); - return; - } - console.info('Callback invoked to indicate a successful setting of the ringer mode.'); +audioCapturer.getAudioTime((err, timestamp) => { + console.info(`Current timestamp: ${timestamp}`); }); ``` -### setRingerMode(deprecated) - -setRingerMode(mode: AudioRingMode): Promise<void> - -Sets the ringer mode. This API uses a promise to return the result. - -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setRingerMode](#setringermode9) in **AudioVolumeGroupManager**. - -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY - -This permission is required only for muting or unmuting the ringer. +### getAudioTime8+ -**System capability**: SystemCapability.Multimedia.Audio.Communication +getAudioTime(): Promise -**Parameters** +Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses a promise to return the result. -| Name | Type | Mandatory | Description | -| ---- | ------------------------------- | --------- | ------------ | -| mode | [AudioRingMode](#audioringmode) | Yes | Ringer mode. | +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Return value** -| Type | Description | -| ------------------- | ---------------------------------- | -| Promise<void> | Promise used to return the result. | +| Type | Description | +| :--------------- | :------------------------------------ | +| Promise | Promise used to return the timestamp. | **Example** ```js -audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => { - console.info('Promise returned to indicate a successful setting of the ringer mode.'); +audioCapturer.getAudioTime().then((audioTime) => { + console.info(`AudioFrameworkRecLog: AudioCapturer getAudioTime : Success ${audioTime}`); +}).catch((err) => { + console.info(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`); }); ``` -### getRingerMode(deprecated) - -getRingerMode(callback: AsyncCallback<AudioRingMode>): void +### getBufferSize8+ -Obtains the ringer mode. This API uses an asynchronous callback to return the result. +getBufferSize(callback: AsyncCallback): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getRingerMode](#getringermode9) in **AudioVolumeGroupManager**. +Obtains a reasonable minimum buffer size in bytes for capturing. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------------------- | --------- | ---------------------------------------- | -| callback | AsyncCallback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the ringer mode. | +| Name | Type | Mandatory | Description | +| :------- | :--------------------- | :-------- | :--------------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the buffer size. | **Example** ```js -audioManager.getRingerMode((err, value) => { - if (err) { - console.error(`Failed to obtain the ringer mode.​ ${err}`); - return; +audioCapturer.getBufferSize((err, bufferSize) => { + if (!err) { + console.info(`BufferSize : ${bufferSize}`); + audioCapturer.read(bufferSize, true).then((buffer) => { + console.info(`Buffer read is ${buffer}`); + }).catch((err) => { + console.error(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`); + }); } - console.info(`Callback invoked to indicate that the ringer mode is obtained ${value}.`); }); ``` -### getRingerMode(deprecated) - -getRingerMode(): Promise<AudioRingMode> +### getBufferSize8+ -Obtains the ringer mode. This API uses a promise to return the result. +getBufferSize(): Promise -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getRingerMode](#getringermode9) in **AudioVolumeGroupManager**. +Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Return value** -| Type | Description | -| ---------------------------------------------- | --------------------------------------- | -| Promise<[AudioRingMode](#audioringmode)> | Promise used to return the ringer mode. | +| Type | Description | +| :--------------- | :-------------------------------------- | +| Promise | Promise used to return the buffer size. | **Example** ```js -audioManager.getRingerMode().then((value) => { - console.info(`Promise returned to indicate that the ringer mode is obtained ${value}.`); +let bufferSize; +audioCapturer.getBufferSize().then((data) => { + console.info(`AudioFrameworkRecLog: getBufferSize :SUCCESS ${data}`); + bufferSize = data; +}).catch((err) => { + console.info(`AudioFrameworkRecLog: getBufferSize :ERROR : ${err}`); }); ``` -### getDevices(deprecated) - -getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescriptors>): void +### on('markReach')8+ -Obtains the audio devices with a specific flag. This API uses an asynchronous callback to return the result. +on(type: "markReach", frame: number, callback: Callback<number>): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getDevices](#getdevices9) in **AudioRoutingManager**. +Subscribes to mark reached events. When the number of frames captured reaches the value of the **frame** parameter, a callback is invoked. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ------------------------------------------------------------ | --------- | ---------------------------------------- | -| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | -| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Yes | Callback used to return the device list. | +| Name | Type | Mandatory | Description | +| :------- | :---------------- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'markReach'**. | +| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | +| callback | Callback\ | Yes | Callback invoked when the event is triggered. | **Example** ```js -audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) => { - if (err) { - console.error(`Failed to obtain the device list. ${err}`); - return; +audioCapturer.on('markReach', 1000, (position) => { + if (position == 1000) { + console.info('ON Triggered successfully'); } - console.info('Callback invoked to indicate that the device list is obtained.'); }); ``` -### getDevices(deprecated) - -getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors> +### off('markReach')8+ -Obtains the audio devices with a specific flag. This API uses a promise to return the result. +off(type: 'markReach'): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getDevices](#getdevices9) in **AudioRoutingManager**. +Unsubscribes from mark reached events. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ------------------------- | --------- | ------------------ | -| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | - -**Return value** - -| Type | Description | -| ------------------------------------------------------------ | --------------------------------------- | -| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise used to return the device list. | +| Name | Type | Mandatory | Description | +| :--- | :----- | :-------- | :------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'markReach'**. | **Example** ```js -audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { - console.info('Promise returned to indicate that the device list is obtained.'); -}); +audioCapturer.off('markReach'); ``` -### setDeviceActive(deprecated) - -setDeviceActive(deviceType: ActiveDeviceType, active: boolean, callback: AsyncCallback<void>): void +### on('periodReach')8+ -Sets a device to the active state. This API uses an asynchronous callback to return the result. +on(type: "periodReach", frame: number, callback: Callback<number>): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setCommunicationDevice](#setcommunicationdevice9) in **AudioRoutingManager**. +Subscribes to period reached events. When the number of frames captured reaches the value of the **frame** parameter, a callback is triggered and the specified value is returned. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ------------------------------------- | --------- | ------------------------------------------------------------ | -| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type. | -| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| :------- | :---------------- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | +| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | +| callback | Callback\ | Yes | Callback invoked when the event is triggered. | **Example** ```js -audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true, (err) => { - if (err) { - console.error(`Failed to set the active status of the device. ${err}`); - return; +audioCapturer.on('periodReach', 1000, (position) => { + if (position == 1000) { + console.info('ON Triggered successfully'); } - console.info('Callback invoked to indicate that the device is set to the active status.'); }); ``` -### setDeviceActive(deprecated) - -setDeviceActive(deviceType: ActiveDeviceType, active: boolean): Promise<void> +### off('periodReach')8+ -Sets a device to the active state. This API uses a promise to return the result. +off(type: 'periodReach'): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setCommunicationDevice](#setcommunicationdevice9) in **AudioRoutingManager**. +Unsubscribes from period reached events. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ------------------------------------- | --------- | ------------------------------------------------------------ | -| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type. | -| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | - -**Return value** - -| Type | Description | -| ------------------- | ---------------------------------- | -| Promise<void> | Promise used to return the result. | +| Name | Type | Mandatory | Description | +| :--- | :----- | :-------- | :--------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | **Example** - ```js -audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true).then(() => { - console.info('Promise returned to indicate that the device is set to the active status.'); -}); +audioCapturer.off('periodReach') ``` -### isDeviceActive(deprecated) - -isDeviceActive(deviceType: ActiveDeviceType, callback: AsyncCallback<boolean>): void +### on('stateChange')8+ -Checks whether a device is active. This API uses an asynchronous callback to return the result. +on(type: 'stateChange', callback: Callback): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isCommunicationDeviceActive](#iscommunicationdeviceactive9) in **AudioRoutingManager**. +Subscribes to state change events. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ------------------------------------- | --------- | ------------------------------------------------------- | -| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the active state of the device. | +| Name | Type | Mandatory | Description | +| :------- | :------------------------------------ | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value **stateChange** means the state change event. | +| callback | Callback\<[AudioState](#audiostate8)> | Yes | Callback used to return the state change. | **Example** ```js -audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER, (err, value) => { - if (err) { - console.error(`Failed to obtain the active status of the device. ${err}`); - return; +audioCapturer.on('stateChange', (state) => { + if (state == 1) { + console.info('audio capturer state is: STATE_PREPARED'); + } + if (state == 2) { + console.info('audio capturer state is: STATE_RUNNING'); } - console.info('Callback invoked to indicate that the active status of the device is obtained.'); }); ``` -### isDeviceActive(deprecated) - -isDeviceActive(deviceType: ActiveDeviceType): Promise<boolean> - -Checks whether a device is active. This API uses a promise to return the result. - -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isCommunicationDeviceActive](#iscommunicationdeviceactive9) in **AudioRoutingManager**. - -**System capability**: SystemCapability.Multimedia.Audio.Device - -**Parameters** +## ToneType9+ -| Name | Type | Mandatory | Description | -| ---------- | ------------------------------------- | --------- | ------------------ | -| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type. | +Enumerates the tone types of the player. -**Return value** +**System API**: This is a system API. -| Type | Description | -| ---------------------- | ------------------------------------------------------ | -| Promise<boolean> | Promise used to return the active state of the device. | +**System capability**: SystemCapability.Multimedia.Audio.Tone -**Example** +| Name | Value | Description | +| :----------------------------------------------- | :---- | :-------------------------------------------- | +| TONE_TYPE_DIAL_0 | 0 | DTMF tone of key 0. | +| TONE_TYPE_DIAL_1 | 1 | DTMF tone of key 1. | +| TONE_TYPE_DIAL_2 | 2 | DTMF tone of key 2. | +| TONE_TYPE_DIAL_3 | 3 | DTMF tone of key 3. | +| TONE_TYPE_DIAL_4 | 4 | DTMF tone of key 4. | +| TONE_TYPE_DIAL_5 | 5 | DTMF tone of key 5. | +| TONE_TYPE_DIAL_6 | 6 | DTMF tone of key 6. | +| TONE_TYPE_DIAL_7 | 7 | DTMF tone of key 7. | +| TONE_TYPE_DIAL_8 | 8 | DTMF tone of key 8. | +| TONE_TYPE_DIAL_9 | 9 | DTMF tone of key 9. | +| TONE_TYPE_DIAL_S | 10 | DTMF tone of the star key (*). | +| TONE_TYPE_DIAL_P | 11 | DTMF tone of the pound key (#). | +| TONE_TYPE_DIAL_A | 12 | DTMF tone of key A. | +| TONE_TYPE_DIAL_B | 13 | DTMF tone of key B. | +| TONE_TYPE_DIAL_C | 14 | DTMF tone of key C. | +| TONE_TYPE_DIAL_D | 15 | DTMF tone of key D. | +| TONE_TYPE_COMMON_SUPERVISORY_DIAL | 100 | Supervisory tone - dial tone. | +| TONE_TYPE_COMMON_SUPERVISORY_BUSY | 101 | Supervisory tone - busy. | +| TONE_TYPE_COMMON_SUPERVISORY_CONGESTION | 102 | Supervisory tone - congestion. | +| TONE_TYPE_COMMON_SUPERVISORY_RADIO_ACK | 103 | Supervisory tone - radio path acknowledgment. | +| TONE_TYPE_COMMON_SUPERVISORY_RADIO_NOT_AVAILABLE | 104 | Supervisory tone - radio path not available. | +| TONE_TYPE_COMMON_SUPERVISORY_CALL_WAITING | 106 | Supervisory tone - call waiting tone. | +| TONE_TYPE_COMMON_SUPERVISORY_RINGTONE | 107 | Supervisory tone - ringing tone. | +| TONE_TYPE_COMMON_PROPRIETARY_BEEP | 200 | Proprietary tone - beep tone. | +| TONE_TYPE_COMMON_PROPRIETARY_ACK | 201 | Proprietary tone - ACK. | +| TONE_TYPE_COMMON_PROPRIETARY_PROMPT | 203 | Proprietary tone - PROMPT. | +| TONE_TYPE_COMMON_PROPRIETARY_DOUBLE_BEEP | 204 | Proprietary tone - double beep tone. | -```js -audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER).then((value) => { - console.info(`Promise returned to indicate that the active status of the device is obtained ${value}.`); -}); +## TonePlayer9+ -``` +Provides APIs for playing and managing DTMF tones, such as dial tones, ringback tones, supervisory tones, and proprietary tones. -### setMicrophoneMute(deprecated) +**System API**: This is a system API. -setMicrophoneMute(mute: boolean, callback: AsyncCallback<void>): void +### load9+ -Mutes or unmutes the microphone. This API uses an asynchronous callback to return the result. +load(type: ToneType, callback: AsyncCallback<void>): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setMicrophoneMute](#setmicrophonemute9) in **AudioVolumeGroupManager**. +Loads the DTMF tone configuration. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.MICROPHONE +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Tone **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | --------- | ------------------------------------------------------------ | -| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| :------- | :--------------------- | :-------- | :---------------------------------- | +| type | [ToneType](#tonetype9) | Yes | Tone type. | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -audioManager.setMicrophoneMute(true, (err) => { +tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_5, (err) => { if (err) { - console.error(`Failed to mute the microphone. ${err}`); + console.error(`callback call load failed error: ${err.message}`); return; + } else { + console.info('callback call load success'); } - console.info('Callback invoked to indicate that the microphone is muted.'); }); ``` -### setMicrophoneMute(deprecated) - -setMicrophoneMute(mute: boolean): Promise<void> +### load9+ -Mutes or unmutes the microphone. This API uses a promise to return the result. +load(type: ToneType): Promise<void> -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setMicrophoneMute](#setmicrophonemute9) in **AudioVolumeGroupManager**. +Loads the DTMF tone configuration. This API uses a promise to return the result. -**Required permissions**: ohos.permission.MICROPHONE +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Tone **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------- | --------- | ------------------------------------------------------------ | -| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite. | +| Name | Type | Mandatory | Description | +| :--- | :--------------------- | :-------- | ----------- | +| type | [ToneType](#tonetype9) | Yes | Tone type. | **Return value** -| Type | Description | -| ------------------- | ---------------------------------- | -| Promise<void> | Promise used to return the result. | +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** ```js -audioManager.setMicrophoneMute(true).then(() => { - console.info('Promise returned to indicate that the microphone is muted.'); +tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_1).then(() => { + console.info('promise call load '); +}).catch(() => { + console.error('promise call load fail'); }); ``` -### isMicrophoneMute(deprecated) - -isMicrophoneMute(callback: AsyncCallback<boolean>): void +### start9+ -Checks whether the microphone is muted. This API uses an asynchronous callback to return the result. +start(callback: AsyncCallback<void>): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isMicrophoneMute](#ismicrophonemute9) in **AudioVolumeGroupManager**. +Starts DTMF tone playing. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.MICROPHONE +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Tone **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------- | --------- | ------------------------------------------------------------ | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite. | +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -audioManager.isMicrophoneMute((err, value) => { +tonePlayer.start((err) => { if (err) { - console.error(`Failed to obtain the mute status of the microphone. ${err}`); + console.error(`callback call start failed error: ${err.message}`); return; + } else { + console.info('callback call start success'); } - console.info(`Callback invoked to indicate that the mute status of the microphone is obtained ${value}.`); }); ``` -### isMicrophoneMute(deprecated) - -isMicrophoneMute(): Promise<boolean> +### start9+ -Checks whether the microphone is muted. This API uses a promise to return the result. +start(): Promise<void> -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isMicrophoneMute](#ismicrophonemute9) in **AudioVolumeGroupManager**. +Starts DTMF tone playing. This API uses a promise to return the result. -**Required permissions**: ohos.permission.MICROPHONE +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Tone **Return value** -| Type | Description | -| ---------------------- | ------------------------------------------------------------ | -| Promise<boolean> | Promise used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite. | +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** ```js -audioManager.isMicrophoneMute().then((value) => { - console.info(`Promise returned to indicate that the mute status of the microphone is obtained ${value}.`); +tonePlayer.start().then(() => { + console.info('promise call start'); +}).catch(() => { + console.error('promise call start fail'); }); ``` -### on('volumeChange')(deprecated) - -on(type: 'volumeChange', callback: Callback\): void +### stop9+ -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [on](#on9) in **AudioVolumeManager**. +stop(callback: AsyncCallback<void>): void -Subscribes to system volume change events. +Stops the tone that is being played. This API uses an asynchronous callback to return the result. **System API**: This is a system API. -Currently, when multiple **AudioManager** instances are used in a single process, only the subscription of the last instance takes effect, and the subscription of other instances is overwritten (even if the last instance does not initiate a subscription). Therefore, you are advised to use a single **AudioManager** instance. - -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Tone **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------------------------- | --------- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **'volumeChange'** means the system volume change event, which is triggered when a system volume change is detected. | -| callback | Callback<[VolumeEvent](#volumeevent8)> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -audioManager.on('volumeChange', (volumeEvent) => { - console.info(`VolumeType of stream: ${volumeEvent.volumeType} `); - console.info(`Volume level: ${volumeEvent.volume} `); - console.info(`Whether to updateUI: ${volumeEvent.updateUi} `); +tonePlayer.stop((err) => { + if (err) { + console.error(`callback call stop error: ${err.message}`); + return; + } else { + console.error('callback call stop success '); + } }); ``` -### on('ringerModeChange')(deprecated) - -on(type: 'ringerModeChange', callback: Callback\): void +### stop9+ -Subscribes to ringer mode change events. +stop(): Promise<void> -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [on('ringerModeChange')](#onringermodechange9) in **AudioVolumeGroupManager**. +Stops the tone that is being played. This API uses a promise to return the result. **System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Tone -**Parameters** +**Return value** -| Name | Type | Mandatory | Description | -| -------- | ----------------------------------------- | --------- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **'ringerModeChange'** means the ringer mode change event, which is triggered when a ringer mode change is detected. | -| callback | Callback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the result. | +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** ```js -audioManager.on('ringerModeChange', (ringerMode) => { - console.info(`Updated ringermode: ${ringerMode}`); +tonePlayer.stop().then(() => { + console.info('promise call stop finish'); +}).catch(() => { + console.error('promise call stop fail'); }); ``` -### on('deviceChange')(deprecated) +### release9+ -on(type: 'deviceChange', callback: Callback): void +release(callback: AsyncCallback<void>): void -Subscribes to device change events. When a device is connected or disconnected, registered clients will receive the callback. +Releases the resources associated with the **TonePlayer** instance. This API uses an asynchronous callback to return the result. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [on](#on9) in **AudioRoutingManager**. +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Tone **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------------------------------------- | :-------- | :----------------------------------------------------------- | -| type | string | Yes | Event type. The value **'deviceChange'** means the device change event, which is triggered when a device connection status change is detected. | -| callback | Callback<[DeviceChangeAction](#devicechangeaction)\> | Yes | Callback used to return the device update details. | +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -audioManager.on('deviceChange', (deviceChanged) => { - console.info(`device change type : ${deviceChanged.type} `); - console.info(`device descriptor size : ${deviceChanged.deviceDescriptors.length} `); - console.info(`device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceRole} `); - console.info(`device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceType} `); +tonePlayer.release((err) => { + if (err) { + console.error(`callback call release failed error: ${err.message}`); + return; + } else { + console.info('callback call release success '); + } }); ``` -### off('deviceChange')(deprecated) +### release9+ -off(type: 'deviceChange', callback?: Callback): void +release(): Promise<void> -Unsubscribes from device change events. +Releases the resources associated with the **TonePlayer** instance. This API uses a promise to return the result. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [off](#off9) in **AudioRoutingManager**. +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Tone -**Parameters** +**Return value** -| Name | Type | Mandatory | Description | -| -------- | --------------------------------------------------- | --------- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **'deviceChange'** means the device change event, which is triggered when a device connection status change is detected. | -| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | No | Callback used to return the device update details. | +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** ```js -audioManager.off('deviceChange', (deviceChanged) => { - console.info('Should be no callback.'); +tonePlayer.release().then(() => { + console.info('promise call release'); +}).catch(() => { + console.error('promise call release fail'); }); + ``` -### on('interrupt')(deprecated) +## ActiveDeviceType(deprecated) -on(type: 'interrupt', interrupt: AudioInterrupt, callback: Callback\): void +Enumerates the active device types. -Subscribes to audio interruption events. When the application's audio is interrupted by another playback event, the application will receive the callback. +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [CommunicationDeviceType](#communicationdevicetype9) instead. -Same as [on('audioInterrupt')](#onaudiointerrupt9), this API is used to listen for focus changes. However, this API is used in scenarios without audio streams (no **AudioRenderer** instance is created), such as frequency modulation (FM) and voice wakeup. +**System capability**: SystemCapability.Multimedia.Audio.Device + +| Name | Value | Description | +| ------------- | ----- | ------------------------------------------------------------ | +| SPEAKER | 2 | Speaker. | +| BLUETOOTH_SCO | 7 | Bluetooth device using Synchronous Connection Oriented (SCO) links. | + +## InterruptActionType(deprecated) + +Enumerates the returned event types for audio interruption events. > **NOTE** > @@ -6077,40 +6141,30 @@ Same as [on('audioInterrupt')](#onaudiointerrupt9), this API is used to listen f **System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters** +| Name | Value | Description | +| -------------- | ----- | ------------------------- | +| TYPE_ACTIVATED | 0 | Focus gain event. | +| TYPE_INTERRUPT | 1 | Audio interruption event. | -| Name | Type | Mandatory | Description | -| --------- | --------------------------------------------- | --------- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **'interrupt'** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application. | -| interrupt | AudioInterrupt | Yes | Audio interruption event type. | -| callback | Callback<[InterruptAction](#interruptaction)> | Yes | Callback invoked for the audio interruption event. | +## AudioInterrupt(deprecated) -**Example** +Describes input parameters of audio interruption events. -```js -let interAudioInterrupt = { - streamUsage:2, - contentType:0, - pauseWhenDucked:true -}; -audioManager.on('interrupt', interAudioInterrupt, (InterruptAction) => { - if (InterruptAction.actionType === 0) { - console.info('An event to gain the audio focus starts.'); - console.info(`Focus gain event: ${InterruptAction} `); - } - if (InterruptAction.actionType === 1) { - console.info('An audio interruption event starts.'); - console.info(`Audio interruption event: ${InterruptAction} `); - } -}); +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. -``` +**System capability**: SystemCapability.Multimedia.Audio.Renderer -### off('interrupt')(deprecated) +| Name | Type | Mandatory | Description | +| --------------- | --------------------------- | --------- | ------------------------------------------------------------ | +| streamUsage | [StreamUsage](#streamusage) | Yes | Audio stream usage. | +| contentType | [ContentType](#contenttype) | Yes | Audio content type. | +| pauseWhenDucked | boolean | Yes | Whether audio playback can be paused during audio interruption. The value **true** means that audio playback can be paused during audio interruption, and **false** means the opposite. | -off(type: 'interrupt', interrupt: AudioInterrupt, callback?: Callback\): void +## InterruptAction(deprecated) -Unsubscribes from audio interruption events. +Describes the callback invoked for audio interruption or focus gain events. > **NOTE** > @@ -6118,26 +6172,9 @@ Unsubscribes from audio interruption events. **System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters** - -| Name | Type | Mandatory | Description | -| --------- | --------------------------------------------- | --------- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **'interrupt'** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application. | -| interrupt | AudioInterrupt | Yes | Audio interruption event type. | -| callback | Callback<[InterruptAction](#interruptaction)> | No | Callback invoked for the audio interruption event. | - -**Example** - -```js -let interAudioInterrupt = { - streamUsage:2, - contentType:0, - pauseWhenDucked:true -}; -audioManager.off('interrupt', interAudioInterrupt, (InterruptAction) => { - if (InterruptAction.actionType === 0) { - console.info('An event to release the audio focus starts.'); - console.info(`Focus release event: ${InterruptAction} `); - } -}); -``` \ No newline at end of file +| Name | Type | Mandatory | Description | +| ---------- | ----------------------------------------------------- | --------- | ------------------------------------------------------------ | +| actionType | [InterruptActionType](#interruptactiontypedeprecated) | Yes | Returned event type. The value **TYPE_ACTIVATED** means the focus gain event, and **TYPE_INTERRUPT** means the audio interruption event. | +| type | [InterruptType](#interrupttype) | No | Type of the audio interruption event. | +| hint | [InterruptHint](#interrupthint) | No | Hint provided along with the audio interruption event. | +| activated | boolean | No | Whether the focus is gained or released. The value **true** means that the focus is gained or released, and **false** means that the focus fails to be gained or released. | \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md index c03f26ef70644a43ec969a5288843838b266f883..49032dcbd7b58a404bd779635fc109a5f2336c38 100644 --- a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md +++ b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md @@ -1,4 +1,4 @@ -# Background Task Management +# @ohos.backgroundTaskManager (Background Task Management) The **BackgroundTaskManager** module provides APIs to manage background tasks. @@ -161,7 +161,7 @@ Requests a continuous task from the system. This API uses an asynchronous callba | Name | Type | Mandatory | Description | | --------- | ---------------------------------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| | bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | | wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. | @@ -253,7 +253,7 @@ Requests a continuous task from the system. This API uses a promise to return th | Name | Type | Mandatory | Description | | --------- | ---------------------------------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| | bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | | wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | @@ -339,7 +339,7 @@ Requests to cancel a continuous task. This API uses an asynchronous callback to | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -395,7 +395,7 @@ Requests to cancel a continuous task. This API uses a promise to return the resu | Name | Type | Mandatory | Description | | ------- | ------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| **Return value** @@ -452,14 +452,14 @@ Provides the information about the suspension delay. **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask -| Name | Description | -| ----------------------- | --------------------- | -| DATA_TRANSFER | Data transfer. | -| AUDIO_PLAYBACK | Audio playback. | -| AUDIO_RECORDING | Audio recording. | -| LOCATION | Positioning and navigation. | -| BLUETOOTH_INTERACTION | Bluetooth-related task. | -| MULTI_DEVICE_CONNECTION | Multi-device connection. | -| WIFI_INTERACTION | WLAN-related (system API).| -| VOIP | Audio and video calls (system API). | -| TASK_KEEPING | Computing task (effective only for specific devices). | +| Name | Value | Description | +| ----------------------- | ---- | --------------------- | +| DATA_TRANSFER | 1 | Data transfer. | +| AUDIO_PLAYBACK | 2 | Audio playback. | +| AUDIO_RECORDING | 3 | Audio recording. | +| LOCATION | 4 | Positioning and navigation. | +| BLUETOOTH_INTERACTION | 5 | Bluetooth-related task. | +| MULTI_DEVICE_CONNECTION | 6 | Multi-device connection. | +| WIFI_INTERACTION | 7 | WLAN-related.
This is a system API.| +| VOIP | 8 | Audio and video calls.
This is a system API. | +| TASK_KEEPING | 9 | Computing task (effective only for specific devices). | diff --git a/en/application-dev/reference/apis/js-apis-battery-info.md b/en/application-dev/reference/apis/js-apis-battery-info.md index 2d7e9fab8a62e7d68dae92e66359a2704414bc01..197e25cfce48edc49798b438745adc13c35ab9d5 100644 --- a/en/application-dev/reference/apis/js-apis-battery-info.md +++ b/en/application-dev/reference/apis/js-apis-battery-info.md @@ -1,11 +1,10 @@ # Battery Info ->**NOTE** -> ->The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. - The Battery Info module provides APIs for querying the charger type, battery health status, and battery charging status. +> **NOTE** +> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. + ## Modules to Import @@ -13,67 +12,100 @@ The Battery Info module provides APIs for querying the charger type, battery hea import batteryInfo from '@ohos.batteryInfo'; ``` -## System Capabilities - -SystemCapability.PowerManager.BatteryManager - ## Attributes Describes battery information. -| Name | Type | Readable | Writable | Description | -| ----------------------------- | ----------------------------------------- | -------- | -------- | ------------------------------------------------------------ | -| batterySOC | number | Yes | No | Battery state of charge (SoC) of the current device, in unit of percentage. | -| chargingStatus | [BatteryChargeState](#batterychargestate) | Yes | No | Battery charging state of the current device. | -| healthStatus | [BatteryHealthState](#batteryhealthstate) | Yes | No | Battery health state of the current device. | -| pluggedType | [BatteryPluggedType](#batterypluggedtype) | Yes | No | Charger type of the current device. | -| voltage | number | Yes | No | Battery voltage of the current device, in unit of microvolt. | -| technology | string | Yes | No | Battery technology of the current device. | -| batteryTemperature | number | Yes | No | Battery temperature of the current device, in unit of 0.1°C. | -| isBatteryPresent7+ | boolean | Yes | No | Whether the battery is supported or present. | - -**Example** - -```js -import batteryInfo from '@ohos.batteryInfo'; -var batterySoc = batteryInfo.batterySOC; -``` - +**System capability**: SystemCapability.PowerManager.BatteryManager.Core + +| Name | Type | Readable| Writable| Description | +| --------------- | ------------------- | ---- | ---- | ---------------------| +| batterySOC | number | Yes | No | Battery state of charge (SoC) of the device, in unit of percentage. | +| chargingStatus | [BatteryChargeState](#batterychargestate) | Yes | No | Battery charging state of the device. | +| healthStatus | [BatteryHealthState](#batteryhealthstate) | Yes | No | Battery health state of the device. | +| pluggedType | [BatteryPluggedType](#batterypluggedtype) | Yes | No | Charger type of the device. | +| voltage | number | Yes | No | Battery voltage of the device, in unit of microvolt. | +| technology | string | Yes | No | Battery technology of the device. | +| batteryTemperature | number | Yes | No | Battery temperature of the device, in unit of 0.1°C. | +| isBatteryPresent7+ | boolean | Yes | No | Whether the battery is supported or present. | +| batteryCapacityLevel9+ | [BatteryCapacityLevel](#batterycapacitylevel9) | Yes | No | Battery level of the device. | +| estimatedRemainingChargeTime9+ | number | Yes | No | Estimated time for fully charging the current device, in unit of milliseconds. | +| totalEnergy9+ | number | Yes | No | Total battery capacity of the device, in unit of mAh. This is a system API. | +| nowCurrent9+ | number | Yes | No | Battery current of the device, in unit of mA. This is a system API. | +| remainingEnergy9+ | number | Yes | No | Remaining battery capacity of the device, in unit of mAh. This is a system API.| ## BatteryPluggedType Enumerates charger types. -| Name | Default Value | Description | -| -------- | ------------- | ----------------- | -| NONE | 0 | Unknown type. | -| AC | 1 | AC charger. | -| USB | 2 | USB charger. | -| WIRELESS | 3 | Wireless charger. | +**System capability**: SystemCapability.PowerManager.BatteryManager.Core +| Name | Value | Description | +| -------- | ---- | ----------------- | +| NONE | 0 | Unknown type | +| AC | 1 | AC charger| +| USB | 2 | USB charger | +| WIRELESS | 3 | Wireless charger| ## BatteryChargeState Enumerates charging states. -| Name | Default Value | Description | -| ------- | ------------- | --------------------------------- | -| NONE | 0 | Unknown state. | -| ENABLE | 1 | The battery is being charged. | -| DISABLE | 2 | The battery is not being charged. | -| FULL | 3 | The battery is fully charged. | +**System capability**: SystemCapability.PowerManager.BatteryManager.Core +| Name | Value | Description | +| ------- | ---- | --------------- | +| NONE | 0 | Unknown state. | +| ENABLE | 1 | The battery is being charged. | +| DISABLE | 2 | The battery is not being charged. | +| FULL | 3 | The battery is fully charged.| ## BatteryHealthState Enumerates battery health states. -| Name | Default Value | Description | -| ----------- | ------------- | ------------------------------------ | -| UNKNOWN | 0 | Unknown state. | -| GOOD | 1 | The battery is in the healthy state. | -| OVERHEAT | 2 | The battery is overheated. | -| OVERVOLTAGE | 3 | The battery voltage is over high. | -| COLD | 4 | The battery temperature is low. | -| DEAD | 5 | The battery is dead. | - +**System capability**: SystemCapability.PowerManager.BatteryManager.Core + +| Name | Value | Description | +| ----------- | ---- | -------------- | +| UNKNOWN | 0 | Unknown state. | +| GOOD | 1 | The battery is in the healthy state. | +| OVERHEAT | 2 | The battery is overheated. | +| OVERVOLTAGE | 3 | The battery voltage is over high. | +| COLD | 4 | The battery temperature is low. | +| DEAD | 5 | The battery is dead.| + +## BatteryCapacityLevel9+ + +Enumerates battery levels. + +**System capability**: SystemCapability.PowerManager.BatteryManager.Core + +| Name | Value| Description | +| -------------- | ------ | ---------------------------- | +| LEVEL_NONE | 0 | Unknown battery level. | +| LEVEL_FULL | 1 | Full battery level. | +| LEVEL_HIGH | 2 | High battery level. | +| LEVEL_NORMAL | 3 | Normal battery level.| +| LEVEL_LOW | 4 | Low battery level. | +| LEVEL_CRITICAL | 5 | Ultra-low battery level.| + +## CommonEventBatteryChangedCode9+ + +Enumerates keys for querying the additional information about the **COMMON_EVENT_BATTERY_CHANGED** event. + +**System capability**: SystemCapability.PowerManager.BatteryManager.Core + +| Name | Value| Description | +| -------------------- | ------ | -------------------------------------------------- | +| EXTRA_SOC | 0 | Remaining battery level in percentage. | +| EXTRA_VOLTAGE | 1 | Battery voltage of the device. | +| EXTRA_TEMPERATURE | 2 | Battery temperature of the device. | +| EXTRA_HEALTH_STATE | 3 | Battery health status of the device. | +| EXTRA_PLUGGED_TYPE | 4 | Type of the charger connected to the device. | +| EXTRA_MAX_CURRENT | 5 | Maximum battery current of the device. | +| EXTRA_MAX_VOLTAGE | 6 | Maximum battery voltage of the device. | +| EXTRA_CHARGE_STATE | 7 | Battery charging status of the device. | +| EXTRA_CHARGE_COUNTER | 8 | Number of battery charging times of the device. | +| EXTRA_PRESENT | 9 | Whether the battery is supported by the device or installed.| +| EXTRA_TECHNOLOGY | 10 | Battery technology of the device. | diff --git a/en/application-dev/reference/apis/js-apis-batteryStatistics.md b/en/application-dev/reference/apis/js-apis-batteryStatistics.md new file mode 100644 index 0000000000000000000000000000000000000000..917bc81d2f3eecef3f25d609db686b0d9dae44a2 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-batteryStatistics.md @@ -0,0 +1,287 @@ +# Battery Statistics + +This module provides APIs for querying software and hardware power consumption statistics. + +> **NOTE** +> +> - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> - The APIs provided by this module are system APIs. + +## Modules to Import + +```js +import batteryStats from '@ohos.batteryStatistics'; +``` + +## batteryStats.getBatteryStats + +getBatteryStats(): Promise + +Obtains the power consumption information list, using a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.PowerManager.BatteryStatistics + +**Return value** + +| Type | Description | +| ----------------------------------------------------- | ------------------------------- | +| Promise> | Promise used to return the power consumption information list.| + +**Error codes** + +For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md). + +| Code| Error Message | +| -------- | -------------- | +| 4600101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +batteryStats.getBatteryStats() +.then(data => { + console.info('battery statistics info: ' + data); +}) +.catch(err => { + console.error('get battery statisitics failed, err: ' + err); +}); +``` + +## batteryStats.getBatteryStats + +getBatteryStats(callback: AsyncCallback): void + +Obtains the power consumption information list. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.PowerManager.BatteryStatistics + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the array of power consumption information obtained. If the operation failed, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md). + +| Code| Error Message | +| -------- | -------------- | +| 4600101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +batteryStats.getBatteryStats((err, data) => { + if (typeof err === 'undefined') { + console.info('battery statistics info: ' + data); + } else { + console.error('get battery statisitics failed, err: ' + err); + } +}); +``` + +## batteryStats.getAppPowerValue + +getAppPowerValue(uid: number): number + +Obtains the power consumption of an application. + +**System API**: This is a system API. + +**System capability**: SystemCapability.PowerManager.BatteryStatistics + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ----------- | +| uid | number | Yes | Application UID.| + +**Return value** + +| Type | Description | +| ------ | --------------------------------- | +| number | Power consumption of the application with this UID, in unit of mAh.| + +**Error codes** + +For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md). + +| Code| Error Message | +| -------- | -------------- | +| 4600101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + var value = batteryStats.getAppPowerValue(10021); + console.info('battery statistics value of app is: ' + value); +} catch(err) { + console.error('get battery statisitics value of app failed, err: ' + err); +} +``` + +## batteryStats.getAppPowerPercent + +getAppPowerPercent(uid: number): number + +Obtains the proportion of the power consumption of an application. + +**System API**: This is a system API. + +**System capability**: SystemCapability.PowerManager.BatteryStatistics + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ----------- | +| uid | number | Yes | Application UID.| + +**Return value** + +| Type | Description | +| ------ | ------------------------- | +| number | Proportion of the power consumption of an application with this UID.| + +**Error codes** + +For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md). + +| Code| Error Message | +| -------- | -------------- | +| 4600101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + var percent = batteryStats.getAppPowerPercent(10021); + console.info('battery statistics percent of app is: ' + percent); +} catch(err) { + console.error('get battery statisitics percent of app failed, err: ' + err); +} +``` + +## batteryStats.getHardwareUnitPowerValue + +getHardwareUnitPowerValue(type: ConsumptionType): number + +Obtains the power consumption of a hardware unit according to the consumption type. + +**System API**: This is a system API. + +**System capability**: SystemCapability.PowerManager.BatteryStatistics + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------- | ---- | -------------- | +| type | [ConsumptionType](#consumptiontype) | Yes | Power consumption type.| + +**Return value** + +| Type | Description | +| ------ | ------------------------------------------ | +| number | Power consumption of the hardware unit corresponding to the power consumption type, in unit of mAh.| + +**Error codes** + +For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md). + +| Code| Error Message | +| -------- | -------------- | +| 4600101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + var value = batteryStats.getHardwareUnitPowerValue(ConsumptionType.CONSUMPTION_TYPE_SCREEN); + console.info('battery statistics percent of hardware is: ' + percent); +} catch(err) { + console.error('get battery statisitics percent of hardware failed, err: ' + err); +} +``` + +## batteryStats.getHardwareUnitPowerPercent + +getHardwareUnitPowerPercent(type: ConsumptionType): number + +Obtains the proportion of the power consumption of a hardware unit according to the power consumption type. + +**System API**: This is a system API. + +**System capability**: SystemCapability.PowerManager.BatteryStatistics + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------- | ---- | -------------- | +| type | [ConsumptionType](#consumptiontype) | Yes | Power consumption type.| + +**Return value** + +| Type | Description | +| ------ | ---------------------------------- | +| number | Proportion of the power consumption of the hardware unit corresponding to the power consumption type.| + +**Error codes** + +For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md). + +| Code| Error Message | +| -------- | -------------- | +| 4600101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + var value = batteryStats.getHardwareUnitPowerPercent(ConsumptionType.CONSUMPTION_TYPE_SCREEN); + console.info('battery statistics percent of hardware is: ' + percent); +} catch(err) { + console.error('get battery statisitics percent of hardware failed, err: ' + err); +} +``` + +## BatteryStatsInfo + +Describes the device power consumption information. + +**System API**: This is a system API. + +**System capability**: SystemCapability.PowerManager.BatteryStatistics + +### Attributes + +| Name | Type | Readable| Writable| Description | +| ----- | ----------------------------------- | ---- | ---- | ---------------------- | +| uid | number | Yes | No | UID related to power consumption information. | +| type | [ConsumptionType](#consumptiontype) | Yes | No | Power consumption type. | +| power | number | Yes | No | Power consumption, in unit of mAh.| + +## ConsumptionType + +Enumerates power consumption types. + +**System API**: This is a system API. + +**System capability**: SystemCapability.PowerManager.BatteryStatistics + +| Name | Value | Description | +| -------------------------- | ---- | ----------------------------- | +| CONSUMPTION_TYPE_INVALID | -17 | Unknown type. | +| CONSUMPTION_TYPE_APP | -16 | Power consumption of an application. | +| CONSUMPTION_TYPE_BLUETOOTH | -15 | Power consumption of Bluetooth. | +| CONSUMPTION_TYPE_IDLE | -14 | Power consumption when the CPU is idle.| +| CONSUMPTION_TYPE_PHONE | -13 | Power consumption of a phone call. | +| CONSUMPTION_TYPE_RADIO | -12 | Power consumption of wireless communication. | +| CONSUMPTION_TYPE_SCREEN | -11 | Power consumption of the screen. | +| CONSUMPTION_TYPE_USER | -10 | Power consumption of the user. | +| CONSUMPTION_TYPE_WIFI | -9 | Power consumption of Wi-Fi. | diff --git a/en/application-dev/reference/apis/js-apis-bluetooth.md b/en/application-dev/reference/apis/js-apis-bluetooth.md index b852a673ab6ca120497e1c40443d19990cfbd74b..aa9e1937cd66e83262211280f42f11f468e2d200 100644 --- a/en/application-dev/reference/apis/js-apis-bluetooth.md +++ b/en/application-dev/reference/apis/js-apis-bluetooth.md @@ -1,8 +1,9 @@ -# Bluetooth +# @ohos.bluetooth The **Bluetooth** module provides classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -202,7 +203,7 @@ Obtains the connection state of a profile. | Name | Type | Mandatory | Description | | --------- | --------- | ---- | ------------------------------------- | -| ProfileId | profileId | Yes | ID of the target profile, for example, **PROFILE_A2DP_SOURCE**.| +| ProfileId | profileId | Yes | ID of the profile to obtain, for example, **PROFILE_A2DP_SOURCE**.| **Return value** @@ -1280,10 +1281,6 @@ Obtains the connected devices. **System capability**: SystemCapability.Communication.Bluetooth.Core -**Parameters** - -No value is returned. - **Return value** | Type | Description | @@ -2695,8 +2692,6 @@ Obtains all services of the remote BLE device. This API uses a promise to return **System capability**: SystemCapability.Communication.Bluetooth.Core -**Parameters** - **Return value** | Type | Description | @@ -2830,7 +2825,7 @@ Reads the descriptor contained in the specific characteristic of the remote BLE | Name | Type | Mandatory | Description | | ---------- | ---------------------------------------- | ---- | ----------------------- | | descriptor | [BLEDescriptor](#bledescriptor) | Yes | Descriptor to read. | -| callback | AsyncCallback<[BLECharacteristic](#blecharacteristic)> | Yes | Callback invoked to return the descriptor read.| +| callback | AsyncCallback<[BLEDescriptor](#bledescriptor)> | Yes | Callback invoked to return the descriptor read.| **Return value** @@ -3309,7 +3304,7 @@ Enumerates the scan modes. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | ---------------------------------------- | ---- | --------------- | | SCAN_MODE_NONE | 0 | No scan mode. | | SCAN_MODE_CONNECTABLE | 1 | Connectable mode. | @@ -3324,7 +3319,7 @@ Enumerates the pairing states. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | ------------------ | ---- | ------ | | BOND_STATE_INVALID | 0 | Invalid pairing.| | BOND_STATE_BONDING | 1 | Pairing. | @@ -3350,7 +3345,7 @@ Enumerates the SPP link types. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | ---------- | ---- | ------------- | | SPP_RFCOMM | 0 | Radio frequency communication (RFCOMM) link type.| @@ -3510,7 +3505,7 @@ Enumerates the profile connection states. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | ------------------- | ---- | -------------- | | STATE_DISCONNECTED | 0 | Disconnected. | | STATE_CONNECTING | 1 | Connecting.| @@ -3558,7 +3553,7 @@ Enumerates the scan duty options. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | --------------------- | ---- | ------------ | | SCAN_MODE_LOW_POWER | 0 | Low-power mode, which is the default value.| | SCAN_MODE_BALANCED | 1 | Balanced mode. | @@ -3571,7 +3566,7 @@ Enumerates the hardware match modes of BLE scan filters. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | --------------------- | ---- | ---------------------------------------- | | MATCH_MODE_AGGRESSIVE | 1 | Hardware reports the scan result with a lower threshold of signal strength and few number of matches in a duration. This is the default value.| | MATCH_MODE_STICKY | 2 | Hardware reports the scan result with a higher threshold of signal strength and sightings. | @@ -3596,7 +3591,7 @@ Enumerates the Bluetooth states. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | --------------------- | ---- | ------------------ | | STATE_OFF | 0 | Bluetooth is turned off. | | STATE_TURNING_ON | 1 | Bluetooth is being turned on. | @@ -3641,7 +3636,7 @@ Defines the content of a BLE advertisement packet. | Name | Type | Readable | Writable | Description | | ---------------- | ------------------- | ---- | ---- | ------------------ | -| manufactureId | Array<string> | Yes | Yes | Manufacturer ID allocated by the Bluetooth SIG.| +| manufactureId | number | Yes | Yes | Manufacturer ID allocated by the Bluetooth SIG.| | manufactureValue | ArrayBuffer | Yes | Yes | Manufacturer data. | @@ -3713,7 +3708,7 @@ Enumerates the major classes of Bluetooth devices. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | ------------------- | ------ | ---------- | | MAJOR_MISC | 0x0000 | Miscellaneous device. | | MAJOR_COMPUTER | 0x0100 | Computer. | @@ -3734,7 +3729,7 @@ Enumerates the major and minor classes of Bluetooth devices. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | ---------------------------------------- | ------ | --------------- | | COMPUTER_UNCATEGORIZED | 0x0100 | Unclassified computer. | | COMPUTER_DESKTOP | 0x0104 | Desktop computer. | @@ -3830,7 +3825,7 @@ Enumerates the A2DP playing states. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | ----------------- | ------ | ------- | | STATE_NOT_PLAYING | 0x0000 | Not playing. | | STATE_PLAYING | 0x0001 | Playing.| @@ -3842,9 +3837,9 @@ Enumerates the Bluetooth profiles. API version 9 is added with **PROFILE_HID_HOS **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | -------------------------------- | ------ | --------------- | -| PROFILE_A2DP_SOURCE | 0x0001 | A2DP profile.| -| PROFILE_HANDS_FREE_AUDIO_GATEWAY | 0x0004 | HFP profile. | -| PROFILE_HID_HOST9+ | 0x0006 | Human Interface Device (HID) profile. | -| PROFILE_PAN_NETWORK9+ | 0x0007 | PAN profile. | +| PROFILE_A2DP_SOURCE | 1 | A2DP profile.| +| PROFILE_HANDS_FREE_AUDIO_GATEWAY | 4 | HFP profile. | +| PROFILE_HID_HOST9+ | 6 | Human Interface Device (HID) profile. | +| PROFILE_PAN_NETWORK9+ | 7 | PAN profile. | diff --git a/en/application-dev/reference/apis/js-apis-brightness.md b/en/application-dev/reference/apis/js-apis-brightness.md index 6bbea8b08a752972bcc9354b63841831ae837a88..df783bbda132f5da29e152e146cc6cb56316f083 100644 --- a/en/application-dev/reference/apis/js-apis-brightness.md +++ b/en/application-dev/reference/apis/js-apis-brightness.md @@ -1,10 +1,12 @@ -# Brightness - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
-> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +# Screen Brightness The Brightness module provides an API for setting the screen brightness. +> **NOTE** +> +> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> - The APIs provided by this module are system APIs. ## Modules to Import @@ -18,18 +20,30 @@ setValue(value: number): void Sets the screen brightness. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. -**System capability:** SystemCapability.PowerManager.DisplayPowerManager +**System capability**: SystemCapability.PowerManager.DisplayPowerManager **Parameters** -| Name | Type | Mandatory | Description | -| ----- | ------ | ---- | ----------- | -| value | number | Yes | Brightness value, ranging from **0** to **255**.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ----------------------- | +| value | number | Yes | Brightness value. The value ranges from 0 to 255.| + +**Error codes** + +For details about the error codes, see [Screen Brightness Error Codes](../errorcodes/errorcode-brightness.md). + +| Code | Error Message | +|---------|---------| +| 4700101 | Operation failed. Cannot connect to service.| **Example** ```js -brightness.setValue(128); +try { + brightness.setValue(128); +} catch(err) { + console.error('set brightness failed, err: ' + err); +} ``` diff --git a/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md index 7f6d5b0196b97a252564d4c29f761aefa2117db3..315e7c0f045ba3b26520ed2a69f41f242872b8e6 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md @@ -1,6 +1,6 @@ # AbilityInfo -Unless otherwise specified, ability information is obtained through **GET_BUNDLE_DEFAULT**. +The **AbilityInfo** module provides information about an ability. Unless otherwise specified, the information is obtained through [GET_BUNDLE_DEFAULT](js-apis-Bundle.md). > **NOTE** > @@ -8,13 +8,13 @@ Unless otherwise specified, ability information is obtained through **GET_BUNDLE ## AbilityInfo(deprecated) -> This API is deprecated since API version 9. You are advised to use [AbilityInfo](js-apis-bundleManager-abilityInfo.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-AbilityInfo](js-apis-bundleManager-abilityInfo.md) instead. **System capability**: SystemCapability.BundleManager.BundleFramework | Name | Type | Readable| Writable| Description | | --------------------- | -------------------------------------------------------- | ---- | ---- | ----------------------------------------- | -| bundleName | string | Yes | No | Bundle name of the application. | +| bundleName | string | Yes | No | Bundle name. | | name | string | Yes | No | Ability name. | | label | string | Yes | No | Ability name visible to users. | | description | string | Yes | No | Ability description. | @@ -25,17 +25,17 @@ Unless otherwise specified, ability information is obtained through **GET_BUNDLE | process | string | Yes | No | Process in which the ability runs. If this parameter is not set, the bundle name is used.| | targetAbility | string | Yes | No | Target ability that the ability alias points to.
This attribute can be used only in the FA model.| | backgroundModes | number | Yes | No | Background service mode of the ability.
This attribute can be used only in the FA model. | -| isVisible | boolean | Yes | No | Whether the ability can be called by other applications. | +| isVisible | boolean | Yes | No | Whether the ability can be called by other bundles. | | formEnabled | boolean | Yes | No | Whether the ability provides the service widget capability.
This attribute can be used only in the FA model.| | type | AbilityType | Yes | No | Ability type.
This attribute can be used only in the FA model. | -| orientation | DisplayOrientation | Yes | No | Ability display orientation. | -| launchMode | LaunchMode | Yes | No | Ability launch mode. | +| orientation | [DisplayOrientation](js-apis-Bundle.md#displayorientationdeprecated) | Yes | No | Ability display orientation. | +| launchMode | [LaunchMode](js-apis-Bundle.md#launchmodedeprecated) | Yes | No | Ability launch mode. | | permissions | Array\ | Yes | No | Permissions required for other applications to call the ability.
The value is obtained by passing **GET_ABILITY_INFO_WITH_PERMISSION**.| | deviceTypes | Array\ | Yes | No | Device types supported by the ability. | | deviceCapabilities | Array\ | Yes | No | Device capabilities required for the ability. | | readPermission | string | Yes | No | Permission required for reading the ability data.
This attribute can be used only in the FA model.| | writePermission | string | Yes | No | Permission required for writing data to the ability.
This attribute can be used only in the FA model.| -| applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information.
The value is obtained by passing **GET_ABILITY_INFO_WITH_APPLICATION**.| +| applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information.
The value is obtained by passing [GET_ABILITY_INFO_WITH_APPLICATION](js-apis-Bundle.md).| | uri | string | Yes | No | URI of the ability.
This attribute can be used only in the FA model.| | labelId | number | Yes | No | Ability label ID. | | subType | AbilitySubType | Yes | No | Subtype of the template that can be used by the ability.
This attribute can be used only in the FA model.| diff --git a/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md b/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md index fb5aa288eaaf2f8eb65940f33902906c04c654c2..c1667a66eb011d24a1b7ce79061eab0f454604a3 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md @@ -1,6 +1,6 @@ # ApplicationInfo -The **ApplicationInfo** module provides application information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**. +The **ApplicationInfo** module provides application information. Unless otherwise specified, the information is obtained through [GET_BUNDLE_DEFAULT](js-apis-Bundle.md). > **NOTE** > @@ -8,30 +8,30 @@ The **ApplicationInfo** module provides application information. Unless otherwis ## ApplicationInfo(deprecated) -> This API is deprecated since API version 9. You are advised to use [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-ApplicationInfo](js-apis-bundleManager-applicationInfo.md) instead. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type | Readable| Writable| Description | -| -------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | -| name | string | Yes | No | Application name. | -| description | string | Yes | No | Application description. | -| descriptionId | number | Yes | No | Application description ID. | -| systemApp | boolean | Yes | No | Whether the application is a system application. The default value is **false**. | -| enabled | boolean | Yes | No | Whether the application is enabled. The default value is **true**. | -| label | string | Yes | No | Application label. | -| labelId(deprecated) | string | Yes | No | Application label ID.
\- **NOTE**: This attribute is deprecated from API version 9. Use **labelIndex** instead.| -| icon | string | Yes | No | Application icon. | -| iconId(deprecated) | string | Yes | No | Application icon ID.
\- **NOTE**: This attribute is deprecated from API version 9. Use **iconIndex** instead.| -| process | string | Yes | No | Process in which the application runs. If this parameter is not set, the bundle name is used. | -| supportedModes | number | Yes | No | Running modes supported by the application. | -| moduleSourceDirs | Array\ | Yes | No | Relative paths for storing application resources. | -| permissions | Array\ | Yes | No | Permissions required for accessing the application.
The value is obtained by passing **GET_APPLICATION_INFO_WITH_PERMISSION**.| -| moduleInfos | Array\<[ModuleInfo](js-apis-bundle-ModuleInfo.md)> | Yes | No | Application module information. | -| entryDir | string | Yes | No | Path for storing application files. | -| codePath8+ | string | Yes | No | Installation directory of the application. | -| metaData8+ | Map\> | Yes | No | Custom metadata of the application.
The value is obtained by passing **GET_APPLICATION_INFO_WITH_METADATA**.| -| removable8+ | boolean | Yes | No | Whether the application is removable. | -| accessTokenId8+ | number | Yes | No | Access token ID of the application. | -| uid8+ | number | Yes | No | UID of the application. | -| entityType8+ | string | Yes | No | Entity type of the application. | +| Name | Type | Readable | Writable | Description | +|----------------------------|------------------------------------------------------------------------|-----|-----|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| name | string | Yes | No | Application name. | +| description | string | Yes | No | Application description. | +| descriptionId | number | Yes | No | Application description ID. | +| systemApp | boolean | Yes | No | Whether the application is a system application. The default value is **false**. | +| enabled | boolean | Yes | No | Whether the application is enabled. The default value is **true**. | +| label | string | Yes | No | Application label. | +| labelId | string | Yes | No | Application label ID. | +| icon | string | Yes | No | Application icon. | +| iconId | string | Yes | No | Application icon ID. | +| process | string | Yes | No | Process in which the application runs. If this parameter is not set, the bundle name is used. | +| supportedModes | number | Yes | No | Modes supported by the application. Currently, only the **drive** mode is defined. This attribute applies only to head units. | +| moduleSourceDirs | Array\ | Yes | No | Relative paths for storing application resources. | +| permissions | Array\ | Yes | No | Permissions required for accessing the application.
The value is obtained by passing [GET_APPLICATION_INFO_WITH_PERMISSION](js-apis-Bundle.md). | +| moduleInfos | Array\<[ModuleInfo](js-apis-bundle-ModuleInfo.md)> | Yes | No | Application module information. | +| entryDir | string | Yes | No | Path for storing application files. | +| codePath8+ | string | Yes | No | Installation directory of the application. | +| metaData8+ | Map\> | Yes | No | Custom metadata of the application.
The value is obtained by passing [GET_APPLICATION_INFO_WITH_METADATA](js-apis-Bundle.md). | +| removable8+ | boolean | Yes | No | Whether the application is removable. | +| accessTokenId8+ | number | Yes | No | Access token ID of the application. | +| uid8+ | number | Yes | No | UID of the application. | +| entityType8+ | string | Yes | No | Category of the application, which can be **game**, **media**, **communication**, **news**, **travel**, **utility**, **shopping**, **education**, **kids**, **business**, and **photography**.| diff --git a/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md b/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md index f1d0240513193f217b71ccfc900acc5a211d07c3..c14419e736e1c2142fb47157826c42fb0d5cff34 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md @@ -1,18 +1,16 @@ # BundleInfo -The **BundleInfo** module provides bundle information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**. +The **BundleInfo** module provides bundle information. Unless otherwise specified, the information is obtained through [GET_BUNDLE_DEFAULT](js-apis-Bundle.md). > **NOTE** > > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. - - ## BundleInfo(deprecated) -> This API is deprecated since API version 9. You are advised to use [BundleInfo](js-apis-bundleManager-bundleInfo.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-BundleInfo](js-apis-bundleManager-bundleInfo.md) instead. - **System capability**: SystemCapability.BundleManager.BundleFramework +**System capability**: SystemCapability.BundleManager.BundleFramework | Name | Type | Readable| Writable| Description | | --------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | @@ -25,7 +23,7 @@ The **BundleInfo** module provides bundle information. Unless otherwise specifie | appInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information. | | abilityInfos | Array\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | No | Ability configuration information.
The value is obtained by passing **GET_BUNDLE_WITH_ABILITIES**.| | reqPermissions | Array\ | Yes | No | Permissions to request from the system for running the application.
The value is obtained by passing **GET_BUNDLE_WITH_REQUESTED_PERMISSION**.| -| reqPermissionDetails | Array\<[ReqPermissionDetail](#reqpermissiondetail)> | Yes | No | Detailed information of the permissions to request from the system.
The value is obtained by passing **GET_BUNDLE_WITH_REQUESTED_PERMISSION**.| +| reqPermissionDetails | Array\<[ReqPermissionDetail](#reqpermissiondetaildeprecated)> | Yes | No | Detailed information of the permissions to request from the system.
The value is obtained by passing **GET_BUNDLE_WITH_REQUESTED_PERMISSION**.| | vendor | string | Yes | No | Vendor of the bundle. | | versionCode | number | Yes | No | Version number of the bundle. | | versionName | string | Yes | No | Version description of the bundle. | @@ -38,7 +36,7 @@ The **BundleInfo** module provides bundle information. Unless otherwise specifie | isSilentInstallation | string | Yes | No | Whether the application can be installed in silent mode. | | minCompatibleVersionCode | number | Yes | No | Earliest version compatible with the bundle in the distributed scenario. | | entryInstallationFree | boolean | Yes | No | Whether installation-free is supported for the entry module. | -| reqPermissionStates8+ | Array\ | Yes | No | Permission grant state. | +| reqPermissionStates8+ | Array\ | Yes | No | Permission grant state. The value **0** means that the request is successful, and **-1** means the opposite. | @@ -54,7 +52,7 @@ Provides the detailed information of the permissions to request from the system. | --------------------- | ----------------------- | ---- | ---- | ---------------------- | | name | string | Yes | Yes | Name of the permission to request. | | reason | string | Yes | Yes | Reason for requesting the permission. | -| usedScene | [UsedScene](#usedscene) | Yes | Yes | Application scenario and timing for using the permission.| +| usedScene | [UsedScene](#usedscenedeprecated) | Yes | Yes | Application scenario and timing for using the permission.| diff --git a/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md b/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md index 9ab7fb823fc00cc663c909c48fca2e6cee047545..0570453b5cb9c1bfa6a1e0f0acb9dda16562005e 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md +++ b/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md @@ -12,7 +12,7 @@ The **BundleInstaller** module provides APIs for you to install, uninstall, and install(bundleFilePaths: Array<string>, param: InstallParam, callback: AsyncCallback<InstallStatus>): void; -Installs a bundle. This API uses an asynchronous callback to return the result. +Installs a bundle. Multiple HAP files can be installed. This API uses an asynchronous callback to return the result. **Required permissions** @@ -28,9 +28,33 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | --------------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | -| bundleFilePaths | Array<string> | Yes | Paths where the HAP files of the bundle are stored. Each path should point to a relative directory of the current bundle's data directory.| -| param | [InstallParam](#installparam) | Yes | Parameters required for bundle installation. | -| callback | AsyncCallback<[InstallStatus](#installstatus)> | Yes | Callback used to return the installation status. | +| bundleFilePaths | Array<string> | Yes | Sandbox path where the HAP files of the bundle are stored. For details about how to obtain the sandbox path, see [Obtaining the Sandbox Path](#obtaining-the-sandbox-path).| +| param | [InstallParam](#installparamdeprecated) | Yes | Parameters required for bundle installation. | +| callback | AsyncCallback<[InstallStatus](#installstatusdeprecated)> | Yes | Callback used to return the installation status. | + +**Example** + +```ts +import bundle from '@ohos.bundle'; +let hapFilePaths = ['/data/storage/el2/base/haps/entry/files/']; +let installParam = { + userId: 100, + isKeepData: false, + installFlag: 1, +}; + +bundle.getBundleInstaller().then(installer=>{ + installer.install(hapFilePaths, installParam, err => { + if (err) { + console.error('install failed:' + JSON.stringify(err)); + } else { + console.info('install successfully.'); + } + }); +}).catch(error => { + console.error('getBundleInstaller failed. Cause: ' + error.message); +}); +``` ## BundleInstaller.uninstall(deprecated) @@ -55,16 +79,39 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | ---------------------------------------------------- | ---- | ---------------------------------------------- | | bundleName | string | Yes | Bundle name. | -| param | [InstallParam](#installparam) | Yes | Parameters required for bundle uninstall. | -| callback | AsyncCallback<[InstallStatus](#installstatus)> | Yes | Callback used to return the installation status.| - +| param | [InstallParam](#installparamdeprecated) | Yes | Parameters required for bundle uninstall. | +| callback | AsyncCallback<[InstallStatus](#installstatusdeprecated)> | Yes | Callback used to return the installation status.| + +**Example** + +```ts +import bundle from '@ohos.bundle'; +let bundleName = 'com.example.myapplication'; +let installParam = { + userId: 100, + isKeepData: false, + installFlag: 1, +}; + +bundle.getBundleInstaller().then(installer=>{ + installer.uninstall(bundleName, installParam, err => { + if (err) { + console.error('uninstall failed:' + JSON.stringify(err)); + } else { + console.info('uninstall successfully.'); + } + }); +}).catch(error => { + console.error('getBundleInstaller failed. Cause: ' + error.message); +}); +``` ## BundleInstaller.recover(deprecated) > This API is deprecated since API version 9. You are advised to use [recover](js-apis-installer.md) instead. recover(bundleName: string, param: InstallParam, callback: AsyncCallback<InstallStatus>): void; -Recovers a bundle. This API uses an asynchronous callback to return the result. +Recovers a bundle. This API uses an asynchronous callback to return the result. After a pre-installed bundle is uninstalled, you can call this API to recover it. **Required permissions** @@ -81,12 +128,37 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | ---------------------------------------------------- | ---- | ---------------------------------------------- | | bundleName | string | Yes | Bundle name. | -| param | [InstallParam](#installparam) | Yes | Parameters required for bundle recovering. | -| callback | AsyncCallback<[InstallStatus](#installstatus)> | Yes | Callback used to return the installation status.| +| param | [InstallParam](#installparamdeprecated) | Yes | Parameters required for bundle recovery. | +| callback | AsyncCallback<[InstallStatus](#installstatusdeprecated)> | Yes | Callback used to return the recovery status.| + +**Example** + +```ts +import bundle from '@ohos.bundle'; + +let bundleName = 'com.example.myapplication'; +let installParam = { + userId: 100, + isKeepData: false, + installFlag: 1, +}; + +bundle.getBundleInstaller().then(installer=>{ + installer.recover(bundleName, installParam, err => { + if (err) { + console.error('recover failed:' + JSON.stringify(err)); + } else { + console.info('recover successfully.'); + } + }); +}).catch(error => { + console.error('getBundleInstaller failed. Cause: ' + error.message); +}); +``` ## InstallParam(deprecated) -Describes the parameters required for bundle installation or uninstall. +Describes the parameters required for bundle installation, recovery, or uninstall. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -100,7 +172,7 @@ Describes the parameters required for bundle installation or uninstall. ## InstallStatus(deprecated) -Describes the bundle installation status. +Describes the bundle installation or uninstall status. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -110,3 +182,27 @@ Describes the bundle installation status. | ------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------ | | status | bundle.[InstallErrorCode](js-apis-Bundle.md#installerrorcode) | Yes | No | Installation or uninstall error code. | | statusMessage | string | Yes | No | Installation or uninstall status message.| + +## Obtaining the Sandbox Path +For the FA model, the sandbox path of a bundle can be obtained using the APIs in [Context](js-apis-inner-app-context.md). For the sage model, the sandbox path can be obtained using the attribute in [Context](js-apis-ability-context.md#abilitycontext). The following describes how to obtain the sandbox path. + +**Example** +``` ts +// Stage model +import Ability from '@ohos.application.Ability'; +class MainAbility extends Ability { + onWindowStageCreate(windowStage) { + let context = this.context; + let pathDir = context.filesDir; + console.info('sandbox path is ' + pathDir); + } +} + +// FA model +import featureAbility from '@ohos.ability.featureAbility'; +let context = featureAbility.getContext(); +context.getFilesDir().then((data) => { + let pathDir = data; + console.info('sandbox path is ' + pathDir); +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-bundle-CustomizeData.md b/en/application-dev/reference/apis/js-apis-bundle-CustomizeData.md index 246f1420fbb328cab877fa7e83476a558530b9f9..e54a37c697a4b44df566aa8f517a4b0befd8297b 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-CustomizeData.md +++ b/en/application-dev/reference/apis/js-apis-bundle-CustomizeData.md @@ -14,6 +14,6 @@ The **CustomizeData** module provides custom metadata. | Name | Type | Readable| Writable| Description | | ------------------ | ------ | ---- | ---- | ---------------- | -| name | string | Yes | Yes | Custom metadata name.| -| value | string | Yes | Yes | Custom metadata value. | -| extra8+ | string | Yes | Yes | Custom metadata resources. | +| name | string | Yes | Yes | Key that identifies a data element.| +| value | string | Yes | Yes | Value of the data element. | +| extra8+ | string | Yes | Yes | Custom format of the data element. The value is an index to the resource that identifies the data. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-ElementName.md b/en/application-dev/reference/apis/js-apis-bundle-ElementName.md index 54f43e7a56376caf4ea623d358fc27bec2d54dbc..b20de58d074a83dea5cb0992e21087ae64b990bb 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ElementName.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ElementName.md @@ -1,6 +1,6 @@ # ElementName -The **ElementName** module provides the element name information, which can be obtained through [Context.getElementName](js-apis-Context.md). +The **ElementName** module provides element name information, which can be obtained through [Context.getElementName](js-apis-inner-app-context.md). > **NOTE** > @@ -8,7 +8,9 @@ The **ElementName** module provides the element name information, which can be o ## ElementName(deprecated) -> This API is deprecated since API version 9. You are advised to use [ElementName](js-apis-bundleManager-elementName.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-ElementName](js-apis-bundleManager-elementName.md) instead. + +Describes the element name information, which identifies the basic information about an ability and is obtained through [Context.getElementName](js-apis-inner-app-context.md). **System capability**: SystemCapability.BundleManager.BundleFramework diff --git a/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md b/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md index 0e252cc3fe46c45114a2d9cb9738c6ec3e0a9ffe..5540aa2bc56b9f8e34fda11d11048b8177816b95 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md @@ -1,6 +1,6 @@ # HapModuleInfo -The **HapModuleInfo** module provides module information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**. +The **HapModuleInfo** module provides information about an HAP module. Unless otherwise specified, the information is obtained through [GET_BUNDLE_DEFAULT](js-apis-Bundle.md). > **NOTE** > @@ -8,7 +8,7 @@ The **HapModuleInfo** module provides module information. Unless otherwise speci ## HapModuleInfo(deprecated) -> This API is deprecated since API version 9. You are advised to use [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) instead. **System capability**: SystemCapability.BundleManager.BundleFramework diff --git a/en/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md b/en/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md index 781b34f89b8a954c5f0be626fcbfe0d3fc5ab3f8..18707feeb05902b5740b00544b3a23a43c09acce 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md @@ -7,10 +7,9 @@ The **ModuleInfo** module provides module information of an application. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## ModuleInfo(deprecated) -> This API is deprecated since API version 9. You are advised to use [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) instead. **System capability**: SystemCapability.BundleManager.BundleFramework - | Name | Type | Readable| Writable| Description | | --------------- | ------ | ---- | ---- | -------- | | moduleName | string | Yes | No | Module name.| diff --git a/en/application-dev/reference/apis/js-apis-bundle-PermissionDef.md b/en/application-dev/reference/apis/js-apis-bundle-PermissionDef.md index aa7b5da045a32bb53590a8b3a5f9ec1f3dffce0e..ded02c772794179d9e8276292ab1be939a208d8f 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-PermissionDef.md +++ b/en/application-dev/reference/apis/js-apis-bundle-PermissionDef.md @@ -8,7 +8,7 @@ The **PermissionDef** module provides permission details defined in the configur ## **PermissionDef**(deprecated) -> This API is deprecated since API version 9. You are advised to use [PermissionDef](js-apis-bundleManager-permissionDef.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-PermissionDef](js-apis-bundleManager-permissionDef.md) instead. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -17,6 +17,6 @@ The **PermissionDef** module provides permission details defined in the configur | Name | Type | Readable| Writable| Description | | -------------- | ------ | ---- | ---- | -------------- | | permissionName | string | Yes | No | Name of the permission. | -| grantMode | number | Yes | No | Grant mode of the permission.| +| grantMode | number | Yes | No | Grant mode of the permission. The value **0** means that the system automatically grants the permission after the application installation, and **1** means that the application needs to dynamically request the permission from the user.| | labelId | number | Yes | No | Label ID of the permission. | | descriptionId | number | Yes | No | Description ID of the permission. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md b/en/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md index adf30d8b7442dd67e822f200a0114f93957bd892..1a603da33b3403dafbac79e1bfcd31c5dde9896c 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md @@ -1,16 +1,14 @@ -# ShortcutInfo(deprecated) +# shortcutInfo -The **ShortcutInfo** module provides shortcut information defined in the configuration file. For details about the configuration in the FA model, see [config.json](../../quick-start/package-structure.md). For details about the configuration in the stage model, see [Internal Structure of the shortcuts Attribute](../../quick-start/stage-structure.md#internal-structure-of-the-shortcuts-attribute). +The **shortcutInfo** module defines shortcut information configured in the configuration file. For the FA model, the shortcut information is configured in the [config.json](../../quick-start/application-configuration-file-overview-fa.md) file. For the stage model, the information is configured in the configuration file under **resources/base/profile** in the development view. > **NOTE** > -> This module is deprecated since API version 9. You are advised to use [ShortcutInfo](js-apis-bundleManager-shortcutInfo.md) instead. -> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## ShortcutWant(deprecated) -> This API is deprecated since API version 9. You are advised to use [ShortcutWant](js-apis-bundleManager-shortcutInfo.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-ShortcutWant](js-apis-bundleManager-shortcutInfo.md) instead. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -23,7 +21,7 @@ The **ShortcutInfo** module provides shortcut information defined in the configu ## ShortcutInfo(deprecated) -> This API is deprecated since API version 9. You are advised to use [ShortcutInfo](js-apis-bundleManager-shortcutInfo.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-ShortcutInfo](js-apis-bundleManager-shortcutInfo.md) instead. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -35,10 +33,12 @@ The **ShortcutInfo** module provides shortcut information defined in the configu | hostAbility | string | Yes | No | Local ability information of the shortcut. | | icon | string | Yes | No | Icon of the shortcut. | | iconId8+ | number | Yes | No | Icon ID of the shortcut. | -| label | string | Yes | No | Label of the shortcut. | -| labelId8+ | number | Yes | No | Label ID of the shortcut. | +| label | string | Yes | No | Name of the shortcut. | +| labelId8+ | number | Yes | No | Name ID of the shortcut. | | disableMessage | string | Yes | No | Message displayed when the shortcut is disabled. | -| wants | Array<[ShortcutWant](#shortcutwant)> | Yes | No | Want information required for the shortcut. | +| wants | Array<[ShortcutWant](#shortcutwant)> | Yes | No | Want list for the shortcut. | | isStatic | boolean | Yes | No | Whether the shortcut is static. | | isHomeShortcut | boolean | Yes | No | Whether the shortcut is a home shortcut.| | isEnabled | boolean | Yes | No | Whether the shortcut is enabled. | + + \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md index ffde8d4356caee1dde9f47bdbb424d2dbdda57bb..f95125fb1c7228f9eade37f423b624c3289c0e34 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md @@ -8,7 +8,7 @@ The **RemoteAbilityInfo** module provides information about a remote ability. ## RemoteAbilityInfo(deprecated) -> This API is deprecated since API version 9. You are advised to use [RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md) instead. **System capability**: SystemCapability.BundleManager.DistributedBundleFramework @@ -16,6 +16,6 @@ The **RemoteAbilityInfo** module provides information about a remote ability. | Name | Type | Readable| Writable| Description | | ----------- | -------------------------------------------- | ---- | ---- | ----------------------- | -| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | No | Element name of the ability. | -| label | string | Yes | No | Label of the ability. | +| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | No | Element name information of the ability. | +| label | string | Yes | No | Ability name. | | icon | string | Yes | No | Icon of the ability.| diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-elementName.md b/en/application-dev/reference/apis/js-apis-bundleManager-elementName.md index 6948fac50faf7146b4bc0a8aabfb1eef2d1c719f..662f0e37640287de5e10273a45d8db327a4551da 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-elementName.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-elementName.md @@ -1,6 +1,6 @@ # ElementName -The **ElementName** module provides information about an element name. The information can be obtained through [Context.getElementName](js-apis-Context.md). +The **ElementName** module provides element name information, which can be obtained through [Context.getElementName](js-apis-inner-app-context.md). > **NOTE** diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md b/en/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md index 0f1d6b7e992484875d65479a3734b00484141d21..2c06d138b5bfda6383fabc14e28d3fb008af0bf0 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md @@ -1,10 +1,12 @@ # ShortcutInfo -The **ShortcutInfo** module provides shortcut information defined in the configuration file. For details about the configuration in the FA model, see [config.json](../../quick-start/package-structure.md). For details about the configuration in the stage model, see [Internal Structure of the shortcuts Attribute](../../quick-start/stage-structure.md#internal-structure-of-the-shortcuts-attribute). +The **ShortcutInfo** module defines shortcut information configured in the configuration file. The information can be obtained through [getShortcutInfo](js-apis-launcherBundleManager.md#launcherbundlemanagergetshortcutinfo9). > **NOTE** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> For the FA model, the shortcut information is configured in the [config.json](../../quick-start/module-structure.md) file. For details about the shortcut information in the stage model, see [shortcuts](../../quick-start/module-configuration-file.md#shortcuts). ## ShortcutWant @@ -16,7 +18,7 @@ The **ShortcutInfo** module provides shortcut information defined in the configu | ------------------------- | ------ | ---- | ---- | -------------------- | | targetBundle | string | Yes | No | Target bundle name of the shortcut.| | targetModule | string | Yes | No | Target module name of the shortcut. | -| targetAbility | string | Yes | No | Target ability name of the shortcut.| +| targetAbility | string | Yes | No | Target ability name of the shortcut.| ## ShortcutInfo @@ -35,3 +37,5 @@ The **ShortcutInfo** module provides shortcut information defined in the configu | label | string | Yes | No | Label of the shortcut. | | labelId | number | Yes | No | Label ID of the shortcut. | | wants | Array\<[ShortcutWant](#shortcutwant)> | Yes | No | Want information required for the shortcut. | + + \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-bundleManager.md b/en/application-dev/reference/apis/js-apis-bundleManager.md index ef3ef84fab57b0ca3e10e2ea27aede219b2e4e6c..525f882052397b5d59e5d4a22c79dc013c847e6a 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager.md @@ -1,4 +1,4 @@ -# bundleManager +# @ohos.bundle.bundleManager The **bundleManager** module provides APIs for querying information about bundles, applications, abilities, Extension abilities, and more. @@ -96,10 +96,10 @@ Enumerates the types of Extension abilities. | Name| Value| Description| |:----------------:|:---:|-----| -| FORM | 0 | [FormExtensionAbility](../../ability/stage-formextension.md): provides APIs for widget development.| +| FORM | 0 | [FormExtensionAbility](../../application-models/widget-development-stage.md): provides APIs for widget development.| | WORK_SCHEDULER | 1 | [WorkSchedulerExtensionAbility](../../task-management/work-scheduler-dev-guide.md): enables applications to execute non-real-time tasks when the system is idle.| | INPUT_METHOD | 2 | [InputMethodExtensionAbility](js-apis-inputmethod-extension-ability.md): provides APIs for developing input method applications.| -| SERVICE | 3 | [ServiceExtensionAbility](../../ability/stage-serviceextension.md): enables applications to run in the background and provide services.| +| SERVICE | 3 | [ServiceExtensionAbility](../../application-models/serviceextensionability.md): enables applications to run in the background and provide services.| | ACCESSIBILITY | 4 | [AccessibilityExtensionAbility](js-apis-application-accessibilityExtensionAbility.md): provides accessibility for access to and operations on the UI.| | DATA_SHARE | 5 | [DataShareExtensionAbility](../../database/database-datashare-guidelines.md): enables applications to read and write data.| | FILE_SHARE | 6 | FileShareExtensionAbility: enables file sharing between applications. This ability is reserved.| @@ -2181,8 +2181,8 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 17700002 | The specified moduleName is not existed. | -| 17700003 | The specified abilityName is not existed. | +| 17700002 | The specified moduleName does not exist. | +| 17700003 | The specified abilityName does not exist. | | 17700024 | Failed to get the profile because there is no profile in the HAP. | | 17700026 | The specified bundle is disabled. | | 17700029 | The specified ability is disabled. | @@ -2236,8 +2236,8 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 17700002 | The specified moduleName is not existed. | -| 17700003 | The specified abilityName is not existed. | +| 17700002 | The specified moduleName does not exist. | +| 17700003 | The specified abilityName does not exist. | | 17700024 | Failed to get the profile because there is no profile in the HAP. | | 17700026 | The specified bundle is disabled. | | 17700029 | The specified ability is disabled. | @@ -2299,7 +2299,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 17700002 | The specified moduleName is not existed. | +| 17700002 | The specified moduleName does not exist. | | 17700003 | The specified extensionAbilityName not existed. | | 17700024 | Failed to get the profile because there is no profile in the HAP. | | 17700026 | The specified bundle is disabled. | @@ -2353,7 +2353,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 17700002 | The specified moduleName is not existed. | +| 17700002 | The specified moduleName does not exist. | | 17700003 | The specified extensionAbilityName not existed. | | 17700024 | Failed to get the profile because there is no profile in the HAP. | | 17700026 | The specified bundle is disabled. | @@ -2903,3 +2903,5 @@ try { console.error('getBundleInfoSync failed:' + err.message); } ``` + + \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-bundleMonitor.md b/en/application-dev/reference/apis/js-apis-bundleMonitor.md index ceef9d85218006916a52300887103c838d5bcd56..cf2d7aab46c5d8ea80d49fe66b61ae68e56885a0 100644 --- a/en/application-dev/reference/apis/js-apis-bundleMonitor.md +++ b/en/application-dev/reference/apis/js-apis-bundleMonitor.md @@ -1,4 +1,4 @@ -# Bundle.bundleMonitor +# @ohos.bundle.bundleMonitor The **Bundle.bundleMonitor** module provides APIs for listens for bundle installation, uninstall, and updates. @@ -18,7 +18,7 @@ import bundleMonitor from '@ohos.bundle.bundleMonitor'; | ------------------------------------ | ----------- | ------------------------------ | | ohos.permission.LISTEN_BUNDLE_CHANGE | system_core | Permission to listen for bundle installation, uninstall, and updates.| -For details, see [Permission Levels](../../security/accesstoken-overview.md#permission-levels). +For details, see [Permission Levels](../../security/accesstoken-overview.md). ## BundleChangeInfo @@ -50,10 +50,6 @@ Subscribes to bundle installation, uninstall, and update events. | BundleChangedEvent | string | Yes | Type of the event to subscribe to.| | Callback\ | callback | Yes | Callback used for the subscription.| -**Error codes** - -For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). - **Example** ```ts @@ -87,10 +83,6 @@ Unsubscribes from bundle installation, uninstall, and update events. | BundleChangedEvent | string | Yes | Type of the event to unsubscribe from. | | Callback\ | callback | Yes | Callback used for the unsubscription. If this parameter is left empty, all callbacks of the current event are unsubscribed from.| -**Error codes** - -For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). - **Example** ```ts diff --git a/en/application-dev/reference/apis/js-apis-cardEmulation.md b/en/application-dev/reference/apis/js-apis-cardEmulation.md index b4f3906b02b1dea7dabd558173010a37e65c2c19..329a2e6126de45fe401a748bd580a372cd1dc18e 100644 --- a/en/application-dev/reference/apis/js-apis-cardEmulation.md +++ b/en/application-dev/reference/apis/js-apis-cardEmulation.md @@ -1,11 +1,11 @@ -# Standard NFC Card Emulation +# @ohos.nfc.cardEmulation The **cardEmulation** module implements Near-Field Communication (NFC) card emulation. You can use the APIs provided by this module to determine the card emulation type supported and implement Host-based Card Emulation (HCE). -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. - ## Modules to Import ``` @@ -18,7 +18,7 @@ Enumerates the NFC card emulation types. **System capability**: SystemCapability.Communication.NFC.Core -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | HCE | 0 | HCE.| | UICC | 1 | Subscriber identity module (SIM) card emulation.| @@ -30,8 +30,6 @@ isSupported(feature: number): boolean Checks whether a certain type of card emulation is supported. -**Required permissions**: ohos.permission.NFC_CARD_EMULATION - **System capability**: SystemCapability.Communication.NFC.Core **Parameters** @@ -42,9 +40,9 @@ Checks whether a certain type of card emulation is supported. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the card emulation type is supported; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the card emulation type is supported; returns **false** otherwise.| ## HceService8+ diff --git a/en/application-dev/reference/apis/js-apis-commonEvent.md b/en/application-dev/reference/apis/js-apis-commonEvent.md index 5aaacbe7d104cf965d398240ff8e19468644713b..12fc260b45b0364ae5a4fc1218f45f6f2ed9df44 100644 --- a/en/application-dev/reference/apis/js-apis-commonEvent.md +++ b/en/application-dev/reference/apis/js-apis-commonEvent.md @@ -1,10 +1,10 @@ -# CommonEvent +# @ohos.commonEvent The **CommonEvent** module provides common event capabilities, including the capabilities to publish, subscribe to, and unsubscribe from common events, as well obtaining and setting the common event result code and result data. > **NOTE** -> -> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs provided by this module are no longer maintained since API version 9. You are advised to use [@ohos.commonEventManager](js-apis-commonEventManager.md). +> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -14,7 +14,7 @@ import CommonEvent from '@ohos.commonEvent'; ## Support -Provides the event types supported by the **CommonEvent** module. The name and value indicate the macro and name of a common event, respectively. +The table below lists the event types supported by the **CommonEvent** module. The name and value indicate the macro and name of a common event, respectively. **System capability**: SystemCapability.Notification.CommonEvent @@ -167,8 +167,8 @@ Provides the event types supported by the **CommonEvent** module. The name and v | COMMON_EVENT_ACCOUNT_DELETED | usual.event.data.ACCOUNT_DELETED | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | Indicates the common event that the account was deleted. | | COMMON_EVENT_FOUNDATION_READY | usual.event.data.FOUNDATION_READY | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the foundation is ready. | | COMMON_EVENT_AIRPLANE_MODE_CHANGED | usual.event.AIRPLANE_MODE | - | Indicates the common event that the airplane mode of the device has changed. | -| COMMON_EVENT_SPLIT_SCREEN8+ | usual.event.SPLIT_SCREEN | - | Indicates the common event of screen splitting. | -| COMMON_EVENT_SLOT_CHANGE9+ | usual.event.SLOT_CHANGE | ohos.permission.NOTIFICATION_CONTROLLER | Indicates the common event that the notification slot has changed. | +| COMMON_EVENT_SPLIT_SCREEN8+ | usual.event.SPLIT_SCREEN | - | Indicates the common event of screen splitting. | +| COMMON_EVENT_SLOT_CHANGE9+ | usual.event.SLOT_CHANGE | ohos.permission.NOTIFICATION_CONTROLLER | Indicates the common event that the notification slot has been updated. | | COMMON_EVENT_SPN_INFO_CHANGED 9+ | usual.event.SPN_INFO_CHANGED | - | Indicates the common event that the SPN displayed has been updated. | | COMMON_EVENT_QUICK_FIX_APPLY_RESULT 9+ | usual.event.QUICK_FIX_APPLY_RESULT | - | Indicates the common event that a quick fix is applied to the application. | @@ -192,7 +192,7 @@ Publishes a common event. This API uses an asynchronous callback to return the r ```js // Callback for common event publication -function PublishCallBack(err) { +function publishCallBack(err) { if (err.code) { console.error("publish failed " + JSON.stringify(err)); } else { @@ -201,7 +201,7 @@ function PublishCallBack(err) { } // Publish a common event. -CommonEvent.publish("event", PublishCallBack); +CommonEvent.publish("event", publishCallBack); ``` @@ -234,7 +234,7 @@ let options = { } // Callback for common event publication -function PublishCallBack(err) { +function publishCallBack(err) { if (err.code) { console.error("publish failed " + JSON.stringify(err)); } else { @@ -243,7 +243,7 @@ function PublishCallBack(err) { } // Publish a common event. -CommonEvent.publish("event", options, PublishCallBack); +CommonEvent.publish("event", options, publishCallBack); ``` @@ -270,7 +270,7 @@ Publishes a common event to a specific user. This API uses an asynchronous callb ```js // Callback for common event publication -function PublishAsUserCallBack(err) { +function publishAsUserCallBack(err) { if (err.code) { console.error("publishAsUser failed " + JSON.stringify(err)); } else { @@ -282,7 +282,7 @@ function PublishAsUserCallBack(err) { let userId = 100; // Publish a common event. -CommonEvent.publishAsUser("event", userId, PublishAsUserCallBack); +CommonEvent.publishAsUser("event", userId, publishAsUserCallBack); ``` @@ -317,7 +317,7 @@ let options = { } // Callback for common event publication -function PublishAsUserCallBack(err) { +function publishAsUserCallBack(err) { if (err.code) { console.error("publishAsUser failed " + JSON.stringify(err)); } else { @@ -329,7 +329,7 @@ function PublishAsUserCallBack(err) { let userId = 100; // Publish a common event. -CommonEvent.publishAsUser("event", userId, options, PublishAsUserCallBack); +CommonEvent.publishAsUser("event", userId, options, publishAsUserCallBack); ``` @@ -361,7 +361,7 @@ let subscribeInfo = { }; // Callback for subscriber creation. -function CreateSubscriberCallBack(err, commonEventSubscriber) { +function createSubscriberCallBack(err, commonEventSubscriber) { if (err.code) { console.error("createSubscriber failed " + JSON.stringify(err)); } else { @@ -371,7 +371,7 @@ function CreateSubscriberCallBack(err, commonEventSubscriber) { } // Create a subscriber. -CommonEvent.createSubscriber(subscribeInfo, CreateSubscriberCallBack); +CommonEvent.createSubscriber(subscribeInfo, createSubscriberCallBack); ``` @@ -442,7 +442,7 @@ let subscribeInfo = { }; // Callback for common event subscription. -function SubscribeCallBack(err, data) { +function subscribeCallBack(err, data) { if (err.code) { console.error("subscribe failed " + JSON.stringify(err)); } else { @@ -451,19 +451,19 @@ function SubscribeCallBack(err, data) { } // Callback for subscriber creation. -function CreateSubscriberCallBack(err, commonEventSubscriber) { +function createSubscriberCallBack(err, commonEventSubscriber) { if (err.code) { console.error("createSubscriber failed " + JSON.stringify(err)); } else { console.info("createSubscriber"); subscriber = commonEventSubscriber; // Subscribe to a common event. - CommonEvent.subscribe(subscriber, SubscribeCallBack); + CommonEvent.subscribe(subscriber, subscribeCallBack); } } // Create a subscriber. -CommonEvent.createSubscriber(subscribeInfo, CreateSubscriberCallBack); +CommonEvent.createSubscriber(subscribeInfo, createSubscriberCallBack); ``` @@ -494,7 +494,7 @@ let subscribeInfo = { }; // Callback for common event subscription. -function SubscribeCallBack(err, data) { +function subscribeCallBack(err, data) { if (err.code) { console.info("subscribe failed " + JSON.stringify(err)); } else { @@ -503,19 +503,19 @@ function SubscribeCallBack(err, data) { } // Callback for subscriber creation. -function CreateSubscriberCallBack(err, commonEventSubscriber) { +function createSubscriberCallBack(err, commonEventSubscriber) { if (err.code) { console.info("createSubscriber failed " + JSON.stringify(err)); } else { console.info("createSubscriber"); subscriber = commonEventSubscriber; // Subscribe to a common event. - CommonEvent.subscribe(subscriber, SubscribeCallBack); + CommonEvent.subscribe(subscriber, subscribeCallBack); } } // Callback for common event unsubscription. -function UnsubscribeCallBack(err) { +function unsubscribeCallBack(err) { if (err.code) { console.info("unsubscribe failed " + JSON.stringify(err)); } else { @@ -524,10 +524,10 @@ function UnsubscribeCallBack(err) { } // Create a subscriber. -CommonEvent.createSubscriber(subscribeInfo, CreateSubscriberCallBack); +CommonEvent.createSubscriber(subscribeInfo, createSubscriberCallBack); // Unsubscribe from the common event. -CommonEvent.unsubscribe(subscriber, UnsubscribeCallBack); +CommonEvent.unsubscribe(subscriber, unsubscribeCallBack); ``` ## CommonEventSubscriber @@ -1233,39 +1233,45 @@ subscriber.finishCommonEvent().then(() => { ## CommonEventData +Describes the common event data body. + **System capability**: SystemCapability.Notification.CommonEvent -| Name | Readable| Writable| Type | Description | -| ---------- | ---- | ---- | -------------------- | ------------------------------------------------------- | -| event | Yes | No | string | Name of the common event that is being received. | -| bundleName | Yes | No | string | Bundle name. | -| code | Yes | No | number | Result code of the common event, which is used to transfer data of the int type. | -| data | Yes | No | string | Custom result data of the common event, which is used to transfer data of the string type.| -| parameters | Yes | No | {[key: string]: any} | Additional information about the common event. | +| Name | Type | Readable| Writable| Description | +| ---------- |-------------------- | ---- | ---- | ------------------------------------------------------- | +| event | string | Yes | No | Name of the common event that is being received. | +| bundleName | string | Yes | No | Bundle name. | +| code | number | Yes | No | Result code of the common event, which is used to transfer data of the int type. | +| data | string | Yes | No | Custom result data of the common event, which is used to transfer data of the string type.| +| parameters | {[key: string]: any} | Yes | No | Additional information about the common event. | ## CommonEventPublishData +Describes the data body published by a common event, including the common event content and attributes. + **System capability**: SystemCapability.Notification.CommonEvent -| Name | Readable| Writable| Type | Description | -| --------------------- | ---- | ---- | -------------------- | ---------------------------- | -| bundleName | Yes | No | string | Bundle name. | -| code | Yes | No | number | Result code of the common event. | -| data | Yes | No | string | Custom result data of the common event.| -| subscriberPermissions | Yes | No | Array\ | Permissions required for subscribers to receive the common event. | -| isOrdered | Yes | No | boolean | Whether the common event is an ordered one. | -| isSticky | Yes | No | boolean | Whether the common event is a sticky one. | -| parameters | Yes | No | {[key: string]: any} | Additional information about the common event. | +| Name | Type | Readable| Writable| Description | +| --------------------- | -------------------- | ---- | ---- | ---------------------------- | +| bundleName | string | Yes | No | Bundle name. | +| code | number | Yes | No | Result code of the common event. | +| data | string | Yes | No | Custom result data of the common event.| +| subscriberPermissions | Array\ | Yes | No | Permissions required for subscribers to receive the common event. | +| isOrdered | boolean | Yes | No | Whether the common event is an ordered one. | +| isSticky | boolean | Yes | No | Whether the common event is a sticky one. Only system applications and system services are allowed to send sticky events.| +| parameters | {[key: string]: any} | Yes | No | Additional information about the common event. | ## CommonEventSubscribeInfo +Provides the subscriber information. + **System capability**: SystemCapability.Notification.CommonEvent -| Name | Readable| Writable| Type | Description | -| ------------------- | ---- | ---- | -------------- | ------------------------------------------------------------ | -| events | Yes | No | Array\ | Name of the common event to publish. | -| publisherPermission | Yes | No | string | Permissions required for publishers to publish the common event. | -| publisherDeviceId | Yes | No | string | Device ID. The value must be the ID of an existing device on the same network. | -| userId | Yes | No | number | User ID. The default value is the ID of the current user. If this parameter is specified, the value must be an existing user ID in the system.| -| priority | Yes | No | number | Subscriber priority. The value ranges from -100 to 1000. | +| Name | Type | Readable| Writable| Description | +| ------------------- | -------------- | ---- | ---- | ------------------------------------------------------------ | +| events | Array\ | Yes | No | Name of the common event to publish. | +| publisherPermission | string | Yes | No | Permissions required for publishers to publish the common event. | +| publisherDeviceId | string | Yes | No | Device ID. The value must be the ID of an existing device on the same network. | +| userId | number | Yes | No | User ID. The default value is the ID of the current user. If this parameter is specified, the value must be an existing user ID in the system.| +| priority | number | Yes | No | Subscriber priority. The value ranges from -100 to +1000. | diff --git a/en/application-dev/reference/apis/js-apis-commonEventManager.md b/en/application-dev/reference/apis/js-apis-commonEventManager.md new file mode 100644 index 0000000000000000000000000000000000000000..502603da539a71e465fcfbffb8e69ba696d4e6ea --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-commonEventManager.md @@ -0,0 +1,1353 @@ +# @ohos.commonEventManager + +The **CommonEventManager** module provides common event capabilities, including the capabilities to publish, subscribe to, and unsubscribe from common events, as well obtaining and setting the common event result code and result data. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```ts +import CommonEventManager from '@ohos.commonEventManager'; +``` + +## Support + +The table below lists the event types supported by the **CommonEventManager** module. The name and value indicate the macro and name of a common event, respectively. + +**System capability**: SystemCapability.Notification.CommonEvent + +| Name | Value | Subscriber Permission | Description | +| ------------ | ------------------ | ---------------------- | -------------------- | +| COMMON_EVENT_BOOT_COMPLETED | usual.event.BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the user has finished booting and the system has been loaded. | +| COMMON_EVENT_LOCKED_BOOT_COMPLETED | usual.event.LOCKED_BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the user has finished booting and the system has been loaded but the screen is still locked. | +| COMMON_EVENT_SHUTDOWN | usual.event.SHUTDOWN | - | Indicates the common event that the device is being shut down and the final shutdown will proceed. | +| COMMON_EVENT_BATTERY_CHANGED | usual.event.BATTERY_CHANGED | - | Indicates the common event that the charging state, level, and other information about the battery have changed. | +| COMMON_EVENT_BATTERY_LOW | usual.event.BATTERY_LOW | - | Indicates the common event that the battery level is low. | +| COMMON_EVENT_BATTERY_OKAY | usual.event.BATTERY_OKAY | - | Indicates the common event that the battery exits the low state. | +| COMMON_EVENT_POWER_CONNECTED | usual.event.POWER_CONNECTED | - | Indicates the common event that the device is connected to an external power supply. | +| COMMON_EVENT_POWER_DISCONNECTED | usual.event.POWER_DISCONNECTED | - | Indicates the common event that the device is disconnected from the external power supply. | +| COMMON_EVENT_SCREEN_OFF | usual.event.SCREEN_OFF | - | Indicates the common event that the device screen is off and the device is sleeping. | +| COMMON_EVENT_SCREEN_ON | usual.event.SCREEN_ON | - | Indicates the common event that the device screen is on and the device is in interactive state. | +| COMMON_EVENT_THERMAL_LEVEL_CHANGED | usual.event.THERMAL_LEVEL_CHANGED | - | Indicates the common event that the device's thermal level has changed. | +| COMMON_EVENT_USER_PRESENT | usual.event.USER_PRESENT | - | Indicates the common event that the user unlocks the device. | +| COMMON_EVENT_TIME_TICK | usual.event.TIME_TICK | - | Indicates the common event that the system time has changed. | +| COMMON_EVENT_TIME_CHANGED | usual.event.TIME_CHANGED | - | Indicates the common event that the system time is set. | +| COMMON_EVENT_DATE_CHANGED | usual.event.DATE_CHANGED | - | Indicates the common event that the system time has changed. | +| COMMON_EVENT_TIMEZONE_CHANGED | usual.event.TIMEZONE_CHANGED | - | Indicates the common event that the system time zone has changed. | +| COMMON_EVENT_CLOSE_SYSTEM_DIALOGS | usual.event.CLOSE_SYSTEM_DIALOGS | - | Indicates the common event that a user closes a temporary system dialog box. | +| COMMON_EVENT_PACKAGE_ADDED | usual.event.PACKAGE_ADDED | - | Indicates the common event that a new application package has been installed on the device. | +| COMMON_EVENT_PACKAGE_REPLACED | usual.event.PACKAGE_REPLACED | - | Indicates the common event that a later version of an installed application package has replaced the previous one on the device. | +| COMMON_EVENT_MY_PACKAGE_REPLACED | usual.event.MY_PACKAGE_REPLACED | - | Indicates the common event that a later version of your application package has replaced the previous one. +| COMMON_EVENT_PACKAGE_REMOVED | usual.event.PACKAGE_REMOVED | - | Indicates the common event that an installed application has been uninstalled from the device with the application data retained. | +| COMMON_EVENT_BUNDLE_REMOVED | usual.event.BUNDLE_REMOVED | - | Indicates the common event that an installed bundle has been uninstalled from the device with the application data retained. | +| COMMON_EVENT_PACKAGE_FULLY_REMOVED | usual.event.PACKAGE_FULLY_REMOVED | - | Indicates the common event that an installed application, including both the application data and code, has been completely uninstalled from the device. | +| COMMON_EVENT_PACKAGE_CHANGED | usual.event.PACKAGE_CHANGED | - | Indicates the common event that an application package has been changed (for example, a component in the package has been enabled or disabled). | +| COMMON_EVENT_PACKAGE_RESTARTED | usual.event.PACKAGE_RESTARTED | - | Indicates the common event that the user has restarted the application package and killed all its processes. | +| COMMON_EVENT_PACKAGE_DATA_CLEARED | usual.event.PACKAGE_DATA_CLEARED | - | Indicates the common event that the user has cleared the application package data. | +| COMMON_EVENT_PACKAGE_CACHE_CLEARED9+ | usual.event.PACKAGE_CACHE_CLEARED | - | Indicates the common event that the user has cleared the application package data. | +| COMMON_EVENT_PACKAGES_SUSPENDED | usual.event.PACKAGES_SUSPENDED | - | Indicates the common event that application packages have been suspended. | +| COMMON_EVENT_PACKAGES_UNSUSPENDED | usual.event.PACKAGES_UNSUSPENDED | - | Indicates the common event that application package has not been suspended. | +| COMMON_EVENT_MY_PACKAGE_SUSPENDED | usual.event.MY_PACKAGE_SUSPENDED | - | Indicates the common event that an application package has been suspended. | +| COMMON_EVENT_MY_PACKAGE_UNSUSPENDED | usual.event.MY_PACKAGE_UNSUSPENDED | - | Indicates the common event that application package has not been suspended. | +| COMMON_EVENT_UID_REMOVED | usual.event.UID_REMOVED | - | Indicates the common event that a user ID has been removed from the system. | +| COMMON_EVENT_PACKAGE_FIRST_LAUNCH | usual.event.PACKAGE_FIRST_LAUNCH | - | Indicates the common event that an installed application is started for the first time. | +| COMMON_EVENT_PACKAGE_NEEDS_VERIFICATION | usual.event.PACKAGE_NEEDS_VERIFICATION | - | Indicates the common event that an application requires system verification. | +| COMMON_EVENT_PACKAGE_VERIFIED | usual.event.PACKAGE_VERIFIED | - | Indicates the common event that an application has been verified by the system. | +| COMMON_EVENT_EXTERNAL_APPLICATIONS_AVAILABLE | usual.event.EXTERNAL_APPLICATIONS_AVAILABLE | - | Indicates the common event that applications installed on the external storage become available for the system. | +| COMMON_EVENT_EXTERNAL_APPLICATIONS_UNAVAILABLE | usual.event.EXTERNAL_APPLICATIONS_UNAVAILABLE | - | Indicates the common event that applications installed on the external storage become unavailable for the system. | +| COMMON_EVENT_CONFIGURATION_CHANGED | usual.event.CONFIGURATION_CHANGED | - | Indicates the common event that the device state (for example, orientation and locale) has changed. | +| COMMON_EVENT_LOCALE_CHANGED | usual.event.LOCALE_CHANGED | - | Indicates the common event that the device locale has changed. | +| COMMON_EVENT_MANAGE_PACKAGE_STORAGE | usual.event.MANAGE_PACKAGE_STORAGE | - | Indicates the common event that the device storage is insufficient. | +| COMMON_EVENT_DRIVE_MODE | common.event.DRIVE_MODE | - | Indicates the common event that the system is in driving mode. | +| COMMON_EVENT_HOME_MODE | common.event.HOME_MODE | - | Indicates the common event that the system is in home mode. | +| COMMON_EVENT_OFFICE_MODE | common.event.OFFICE_MODE | - | Indicates the common event that the system is in office mode. | +| COMMON_EVENT_USER_STARTED | usual.event.USER_STARTED | - | Indicates the common event that the user has been started. | +| COMMON_EVENT_USER_BACKGROUND | usual.event.USER_BACKGROUND | - | Indicates the common event that the user has been brought to the background. | +| COMMON_EVENT_USER_FOREGROUND | usual.event.USER_FOREGROUND | - | Indicates the common event that the user has been brought to the foreground. | +| COMMON_EVENT_USER_SWITCHED | usual.event.USER_SWITCHED | ohos.permission.MANAGE_LOCAL_ACCOUNTS | Indicates the common event that user switching is happening. | +| COMMON_EVENT_USER_STARTING | usual.event.USER_STARTING | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | Indicates the common event that the user is going to be started. | +| COMMON_EVENT_USER_UNLOCKED | usual.event.USER_UNLOCKED | - | Indicates the common event that the credential-encrypted storage has been unlocked for the current user when the device is unlocked after being restarted. | +| COMMON_EVENT_USER_STOPPING | usual.event.USER_STOPPING | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | Indicates the common event that the user is going to be stopped. | +| COMMON_EVENT_USER_STOPPED | usual.event.USER_STOPPED | - | Indicates the common event that the user has been stopped. | +| COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGIN | usual.event.DISTRIBUTED_ACCOUNT_LOGIN | - | Indicates the action of successful login using a distributed account. | +| COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOUT | usual.event.DISTRIBUTED_ACCOUNT_LOGOUT | - | Indicates the action of successful logout of a distributed account. | +| COMMON_EVENT_DISTRIBUTED_ACCOUNT_TOKEN_INVALID | usual.event.DISTRIBUTED_ACCOUNT_TOKEN_INVALID | - | Indicates the action when the token of a distributed account is invalid. | +| COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOFF | usual.event.DISTRIBUTED_ACCOUNT_LOGOFF | - | Indicates the action of deregistering a distributed account. | +| COMMON_EVENT_WIFI_POWER_STATE | usual.event.wifi.POWER_STATE | - | Indicates the common event about the Wi-Fi network state, such as enabled and disabled. | +| COMMON_EVENT_WIFI_SCAN_FINISHED | usual.event.wifi.SCAN_FINISHED | ohos.permission.LOCATION | Indicates the common event that the Wi-Fi access point has been scanned and proven to be available. | +| COMMON_EVENT_WIFI_RSSI_VALUE | usual.event.wifi.RSSI_VALUE | ohos.permission.GET_WIFI_INFO | Indicates the common event that the Wi-Fi signal strength (RSSI) has changed. | +| COMMON_EVENT_WIFI_CONN_STATE | usual.event.wifi.CONN_STATE | - | Indicates the common event that the Wi-Fi connection state has changed. | +| COMMON_EVENT_WIFI_HOTSPOT_STATE | usual.event.wifi.HOTSPOT_STATE | - | Indicates the common event about the Wi-Fi hotspot state, such as enabled or disabled. | +| COMMON_EVENT_WIFI_AP_STA_JOIN | usual.event.wifi.WIFI_HS_STA_JOIN | ohos.permission.GET_WIFI_INFO | Indicates the common event that a client has joined the Wi-Fi hotspot of the current device. | +| COMMON_EVENT_WIFI_AP_STA_LEAVE | usual.event.wifi.WIFI_HS_STA_LEAVE | ohos.permission.GET_WIFI_INFO |Indicates the common event that a client has disconnected from the Wi-Fi hotspot of the current device. | +| COMMON_EVENT_WIFI_MPLINK_STATE_CHANGE | usual.event.wifi.mplink.STATE_CHANGE | ohos.permission.MPLINK_CHANGE_STATE | Indicates the common event that the state of MPLINK (an enhanced Wi-Fi feature) has changed. | +| COMMON_EVENT_WIFI_P2P_CONN_STATE | usual.event.wifi.p2p.CONN_STATE_CHANGE | ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION | Indicates the common event that the Wi-Fi P2P connection state has changed. | +| COMMON_EVENT_WIFI_P2P_STATE_CHANGED | usual.event.wifi.p2p.STATE_CHANGE | ohos.permission.GET_WIFI_INFO | Indicates the common event about the Wi-Fi P2P state, such as enabled and disabled. | +| COMMON_EVENT_WIFI_P2P_PEERS_STATE_CHANGED | usual.event.wifi.p2p.DEVICES_CHANGE | ohos.permission.GET_WIFI_INFO | Indicates the common event about the status change of Wi-Fi P2P peer devices. | +| COMMON_EVENT_WIFI_P2P_PEERS_DISCOVERY_STATE_CHANGED | usual.event.wifi.p2p.PEER_DISCOVERY_STATE_CHANGE | ohos.permission.GET_WIFI_INFO | Indicates the common event about the Wi-Fi P2P discovery status change. | +| COMMON_EVENT_WIFI_P2P_CURRENT_DEVICE_STATE_CHANGED | usual.event.wifi.p2p.CURRENT_DEVICE_CHANGE | ohos.permission.GET_WIFI_INFO | Indicates the common event about the status change of the Wi-Fi P2P local device. | +| COMMON_EVENT_WIFI_P2P_GROUP_STATE_CHANGED | usual.event.wifi.p2p.GROUP_STATE_CHANGED | ohos.permission.GET_WIFI_INFO | Indicates the common event that the Wi-Fi P2P group information has changed. | +| COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_CONNECT_STATE_UPDATE | usual.event.bluetooth.handsfree.ag.CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event about the connection state of Bluetooth handsfree communication. | +| COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_CURRENT_DEVICE_UPDATE | usual.event.bluetooth.handsfree.ag.CURRENT_DEVICE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the device connected to the Bluetooth handsfree is active. | +| COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_AUDIO_STATE_UPDATE | usual.event.bluetooth.handsfree.ag.AUDIO_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the connection state of Bluetooth A2DP has changed. | +| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsource.CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event about the connection state of Bluetooth A2DP. | +| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CURRENT_DEVICE_UPDATE | usual.event.bluetooth.a2dpsource.CURRENT_DEVICE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the device connected using Bluetooth A2DP is active. | +| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_PLAYING_STATE_UPDATE | usual.event.bluetooth.a2dpsource.PLAYING_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the playing state of Bluetooth A2DP has changed. | +| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_AVRCP_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsource.AVRCP_CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the AVRCP connection state of Bluetooth A2DP has changed. | +| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CODEC_VALUE_UPDATE | usual.event.bluetooth.a2dpsource.CODEC_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the audio codec state of Bluetooth A2DP has changed. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_DISCOVERED | usual.event.bluetooth.remotedevice.DISCOVERED | ohos.permission.LOCATION and ohos.permission.USE_BLUETOOTH | Indicates the common event that a remote Bluetooth device is discovered. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CLASS_VALUE_UPDATE | usual.event.bluetooth.remotedevice.CLASS_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth class of a remote Bluetooth device has changed. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_CONNECTED | usual.event.bluetooth.remotedevice.ACL_CONNECTED | ohos.permission.USE_BLUETOOTH | Indicates the common event that a low-ACL connection has been established with a remote Bluetooth device. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_DISCONNECTED | usual.event.bluetooth.remotedevice.ACL_DISCONNECTED | ohos.permission.USE_BLUETOOTH | Indicates the common event that a low-ACL connection has been disconnected from a remote Bluetooth device. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_NAME_UPDATE | usual.event.bluetooth.remotedevice.NAME_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the friendly name of a remote Bluetooth device is retrieved for the first time or is changed since the last retrieval. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIR_STATE | usual.event.bluetooth.remotedevice.PAIR_STATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the connection state of a remote Bluetooth device has changed. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_BATTERY_VALUE_UPDATE | usual.event.bluetooth.remotedevice.BATTERY_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the battery level of a remote Bluetooth device is retrieved for the first time or is changed since the last retrieval. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_SDP_RESULT | usual.event.bluetooth.remotedevice.SDP_RESULT | - | Indicates the common event about the SDP state of a remote Bluetooth device. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_UUID_VALUE | usual.event.bluetooth.remotedevice.UUID_VALUE | ohos.permission.DISCOVER_BLUETOOTH | Indicates the common event about the UUID connection state of a remote Bluetooth device. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_REQ | usual.event.bluetooth.remotedevice.PAIRING_REQ | ohos.permission.DISCOVER_BLUETOOTH | Indicates the common event about the pairing request from a remote Bluetooth device. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_CANCEL | usual.event.bluetooth.remotedevice.PAIRING_CANCEL | - | Indicates the common event that Bluetooth pairing is canceled. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REQ | usual.event.bluetooth.remotedevice.CONNECT_REQ | - | Indicates the common event about the connection request from a remote Bluetooth device. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REPLY | usual.event.bluetooth.remotedevice.CONNECT_REPLY | - | Indicates the common event about the response to the connection request from a remote Bluetooth device. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_CANCEL | usual.event.bluetooth.remotedevice.CONNECT_CANCEL | - | Indicates the common event that the connection to a remote Bluetooth device has been canceled. | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_CONNECT_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.CONNECT_STATE_UPDATE | - | Indicates the common event that the connection state of a Bluetooth handsfree has changed. | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AUDIO_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.AUDIO_STATE_UPDATE | - | Indicates the common event that the audio state of a Bluetooth handsfree has changed. | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_COMMON_EVENT | usual.event.bluetooth.handsfreeunit.AG_COMMON_EVENT | - | Indicates the common event that the audio gateway state of a Bluetooth handsfree has changed. | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_CALL_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.AG_CALL_STATE_UPDATE | - | Indicates the common event that the calling state of a Bluetooth handsfree has changed. | +| COMMON_EVENT_BLUETOOTH_HOST_STATE_UPDATE | usual.event.bluetooth.host.STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the state of a Bluetooth adapter has been changed, for example, Bluetooth has been enabled or disabled. | +| COMMON_EVENT_BLUETOOTH_HOST_REQ_DISCOVERABLE | usual.event.bluetooth.host.REQ_DISCOVERABLE | - | Indicates the common event about the request for the user to allow Bluetooth device scanning. | +| COMMON_EVENT_BLUETOOTH_HOST_REQ_ENABLE | usual.event.bluetooth.host.REQ_ENABLE | ohos.permission.USE_BLUETOOTH | Indicates the common event about the request for the user to enable Bluetooth. | +| COMMON_EVENT_BLUETOOTH_HOST_REQ_DISABLE | usual.event.bluetooth.host.REQ_DISABLE | ohos.permission.USE_BLUETOOTH | Indicates the common event about the request for the user to disable Bluetooth. | +| COMMON_EVENT_BLUETOOTH_HOST_SCAN_MODE_UPDATE | usual.event.bluetooth.host.SCAN_MODE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth scanning mode of a device has changed. | +| COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_STARTED | usual.event.bluetooth.host.DISCOVERY_STARTED | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth scanning has been started on the device. | +| COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_FINISHED | usual.event.bluetooth.host.DISCOVERY_FINISHED | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth scanning is finished on the device. | +| COMMON_EVENT_BLUETOOTH_HOST_NAME_UPDATE | usual.event.bluetooth.host.NAME_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth adapter name of the device has changed. | +| COMMON_EVENT_BLUETOOTH_A2DPSINK_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsink.CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the connection state of Bluetooth A2DP Sink has changed. | +| COMMON_EVENT_BLUETOOTH_A2DPSINK_PLAYING_STATE_UPDATE | usual.event.bluetooth.a2dpsink.PLAYING_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the playing state of Bluetooth A2DP Sink has changed. | +| COMMON_EVENT_BLUETOOTH_A2DPSINK_AUDIO_STATE_UPDATE | usual.event.bluetooth.a2dpsink.AUDIO_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the audio state of Bluetooth A2DP Sink has changed. | +| COMMON_EVENT_NFC_ACTION_ADAPTER_STATE_CHANGED | usual.event.nfc.action.ADAPTER_STATE_CHANGED | - | Indicates the common event that the state of the device's NFC adapter has changed. | +| COMMON_EVENT_NFC_ACTION_RF_FIELD_ON_DETECTED | usual.event.nfc.action.RF_FIELD_ON_DETECTED | ohos.permission.MANAGE_SECURE_SETTINGS | Indicates the action of a common event that the NFC RF field is detected to be in the enabled state. | +| COMMON_EVENT_NFC_ACTION_RF_FIELD_OFF_DETECTED | usual.event.nfc.action.RF_FIELD_OFF_DETECTED | ohos.permission.MANAGE_SECURE_SETTINGS | Indicates the common event that the NFC RF field is detected to be in the disabled state. | +| COMMON_EVENT_DISCHARGING | usual.event.DISCHARGING | - | Indicates the common event that the system stops charging the battery. | +| COMMON_EVENT_CHARGING | usual.event.CHARGING | - | Indicates the common event that the system starts charging the battery. | +| COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED | usual.event.DEVICE_IDLE_MODE_CHANGED | - | Indicates the common event that the system idle mode has changed. | +| COMMON_EVENT_POWER_SAVE_MODE_CHANGED | usual.event.POWER_SAVE_MODE_CHANGED | - | Indicates the common event that the power saving mode of the system has changed. | +| COMMON_EVENT_USER_ADDED | usual.event.USER_ADDED | ohos.permission.MANAGE_LOCAL_ACCOUNTS | Indicates the common event that a user has been added to the system. | +| COMMON_EVENT_USER_REMOVED | usual.event.USER_REMOVED | ohos.permission.MANAGE_LOCAL_ACCOUNTS | Indicates the common event that a user has been removed from the system. | +| COMMON_EVENT_ABILITY_ADDED | usual.event.ABILITY_ADDED | ohos.permission.LISTEN_BUNDLE_CHANGE | Indicates the common event that an ability has been added. | +| COMMON_EVENT_ABILITY_REMOVED | usual.event.ABILITY_REMOVED | ohos.permission.LISTEN_BUNDLE_CHANGE | Indicates the common event that an ability has been removed. | +| COMMON_EVENT_ABILITY_UPDATED | usual.event.ABILITY_UPDATED | ohos.permission.LISTEN_BUNDLE_CHANGE | Indicates the common event that an ability has been updated. | +| COMMON_EVENT_LOCATION_MODE_STATE_CHANGED | usual.event.location.MODE_STATE_CHANGED | - | Indicates the common event that the location mode of the system has changed. | +| COMMON_EVENT_IVI_SLEEP | common.event.IVI_SLEEP | - | Indicates the common event that the in-vehicle infotainment (IVI) system of a vehicle is sleeping. | +| COMMON_EVENT_IVI_PAUSE | common.event.IVI_PAUSE | - | Indicates the common event that the IVI system of a vehicle has entered sleep mode and the playing application is instructed to stop playback. | +| COMMON_EVENT_IVI_STANDBY | common.event.IVI_STANDBY | - | Indicates the common event that a third-party application is instructed to pause the current work. | +| COMMON_EVENT_IVI_LASTMODE_SAVE | common.event.IVI_LASTMODE_SAVE | - | Indicates the common event that a third-party application is instructed to save its last mode. | +| COMMON_EVENT_IVI_VOLTAGE_ABNORMAL | common.event.IVI_VOLTAGE_ABNORMAL | - | Indicates the common event that the voltage of the vehicle's power system is abnormal. | +| COMMON_EVENT_IVI_HIGH_TEMPERATURE | common.event.IVI_HIGH_TEMPERATURE | - | Indicates the common event that the temperature of the IVI system is high. | +| COMMON_EVENT_IVI_EXTREME_TEMPERATURE | common.event.IVI_EXTREME_TEMPERATURE | - | Indicates the common event that the temperature of the IVI system is extremely high. | +| COMMON_EVENT_IVI_TEMPERATURE_ABNORMAL | common.event.IVI_TEMPERATURE_ABNORMAL | - | Indicates the common event that the IVI system has an extreme temperature. | +| COMMON_EVENT_IVI_VOLTAGE_RECOVERY | common.event.IVI_VOLTAGE_RECOVERY | - | Indicates the common event that the voltage of the vehicle's power system is restored to normal. | +| COMMON_EVENT_IVI_TEMPERATURE_RECOVERY | common.event.IVI_TEMPERATURE_RECOVERY | - | Indicates the common event that the temperature of the IVI system is restored to normal. | +| COMMON_EVENT_IVI_ACTIVE | common.event.IVI_ACTIVE | - | Indicates the common event that the battery service is active. | +|COMMON_EVENT_USB_STATE9+ | usual.event.hardware.usb.action.USB_STATE | - | Indicates a common event indicating that the USB device status changes. | +|COMMON_EVENT_USB_PORT_CHANGED9+ | usual.event.hardware.usb.action.USB_PORT_CHANGED | - | Indicates the public event that the USB port status of the user device changes. | +| COMMON_EVENT_USB_DEVICE_ATTACHED | usual.event.hardware.usb.action.USB_DEVICE_ATTACHED | - | Indicates the common event that a USB device has been attached when the user device functions as a USB host. | +| COMMON_EVENT_USB_DEVICE_DETACHED | usual.event.hardware.usb.action.USB_DEVICE_DETACHED | - | Indicates the common event that a USB device has been detached when the user device functions as a USB host. | +| COMMON_EVENT_USB_ACCESSORY_ATTACHED | usual.event.hardware.usb.action.USB_ACCESSORY_ATTACHED | - | Indicates the common event that a USB accessory was attached. | +| COMMON_EVENT_USB_ACCESSORY_DETACHED | usual.event.hardware.usb.action.USB_ACCESSORY_DETACHED | - | Indicates the common event that a USB accessory was detached. | +| COMMON_EVENT_DISK_REMOVED | usual.event.data.DISK_REMOVED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed. | +| COMMON_EVENT_DISK_UNMOUNTED | usual.event.data.DISK_UNMOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was unmounted. | +| COMMON_EVENT_DISK_MOUNTED | usual.event.data.DISK_MOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was mounted. | +| COMMON_EVENT_DISK_BAD_REMOVAL | usual.event.data.DISK_BAD_REMOVAL | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed without being unmounted. | +| COMMON_EVENT_DISK_UNMOUNTABLE | usual.event.data.DISK_UNMOUNTABLE | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device becomes unmountable. | +| COMMON_EVENT_DISK_EJECT | usual.event.data.DISK_EJECT | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was ejected. | +| COMMON_EVENT_VOLUME_REMOVED9+ | usual.event.data.VOLUME_REMOVED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed. | +| COMMON_EVENT_VOLUME_UNMOUNTED9+ | usual.event.data.VOLUME_UNMOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was unmounted. | +| COMMON_EVENT_VOLUME_MOUNTED9+ | usual.event.data.VOLUME_MOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was mounted. | +| COMMON_EVENT_VOLUME_BAD_REMOVAL9+ | usual.event.data.VOLUME_BAD_REMOVAL | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed without being unmounted. | +| COMMON_EVENT_VOLUME_EJECT9+ | usual.event.data.VOLUME_EJECT | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was ejected. | +| COMMON_EVENT_VISIBLE_ACCOUNTS_UPDATED | usual.event.data.VISIBLE_ACCOUNTS_UPDATED | ohos.permission.GET_APP_ACCOUNTS | Indicates the common event that the account visibility changed. | +| COMMON_EVENT_ACCOUNT_DELETED | usual.event.data.ACCOUNT_DELETED | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | Indicates the common event that the account was deleted. | +| COMMON_EVENT_FOUNDATION_READY | usual.event.data.FOUNDATION_READY | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the foundation is ready. | +| COMMON_EVENT_AIRPLANE_MODE_CHANGED | usual.event.AIRPLANE_MODE | - | Indicates the common event that the airplane mode of the device has changed. | +| COMMON_EVENT_SPLIT_SCREEN | usual.event.SPLIT_SCREEN | ohos.permission.RECEIVER_SPLIT_SCREEN | Indicates the common event of screen splitting. | +| COMMON_EVENT_SLOT_CHANGE9+ | usual.event.SLOT_CHANGE | ohos.permission.NOTIFICATION_CONTROLLER | Indicates the common event that the notification slot has been updated. | +| COMMON_EVENT_SPN_INFO_CHANGED 9+ | usual.event.SPN_INFO_CHANGED | - | Indicates the common event that the SPN displayed has been updated. | +| COMMON_EVENT_QUICK_FIX_APPLY_RESULT 9+ | usual.event.QUICK_FIX_APPLY_RESULT | - | Indicates the common event that a quick fix is applied to the application. | + + +## CommonEventManager.publish + +publish(event: string, callback: AsyncCallback\): void + +Publishes a common event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------- | +| event | string | Yes | Name of the common event to publish.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** +For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md). + +|ID |Error Message | +|-----------|--------------------| +|1500004 |not System services or System app| +|1500007 |message send error| +|1500008 |CEMS error| +|1500009 |system error| + +**Example** + +```ts +// Callback for common event publication +function publishCallBack(err) { + if (err) { + console.error("publish failed " + JSON.stringify(err)); + } else { + console.info("publish"); + } +} + +// Publish a common event. +try { + CommonEventManager.publish("event", publishCallBack); +} catch(err) { + console.error('publish failed, catch error' + JSON.stringify(err)); +} +``` + +## CommonEventManager.publish + +publish(event: string, options: CommonEventPublishData, callback: AsyncCallback\): void + +Publishes a common event with given attributes. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ---------------------- | +| event | string | Yes | Name of the common event to publish. | +| options | [CommonEventPublishData](#commoneventpublishdata) | Yes | Attributes of the common event to publish.| +| callback | syncCallback\ | Yes | Callback used to return the result. | + +**Error codes** +|ID |Error Message | +|-----------|--------------------| +|1500004 |not System services or System app| +|1500007 |message send error| +|1500008 |CEMS error| +|1500009 |system error| + + +**Example** + + +```ts +// Attributes of a common event. +var options = { + code: 0, // Result code of the common event. + data: "initial data";// Result data of the common event. + isOrdered: true // The common event is an ordered one. +} + +// Callback for common event publication +function publishCallBack(err) { + if (err) { + console.error("publish failed " + JSON.stringify(err)); + } else { + console.info("publish"); + } +} + +// Publish a common event. +try { + CommonEventManager.publish("event", options, publishCallBack); +} catch (err) { + console.error('publish failed, catch error' + JSON.stringify(err)); +} +``` + + + +## CommonEventManager.publishAsUser + +publishAsUser(event: string, userId: number, callback: AsyncCallback\): void + +Publishes a common event to a specific user. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------------- | +| event | string | Yes | Name of the common event to publish. | +| userId | number | Yes | User ID.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Error codes** +|ID |Error Message | +|-----------|--------------------| +|1500004 |not System services or System app| +|1500007 |message send error| +|1500008 |CEMS error| +|1500009 |system error| + +**Example** + +```ts +// Callback for common event publication +function publishAsUserCallBack(err) { + if (err) { + console.error("publishAsUser failed " + JSON.stringify(err)); + } else { + console.info("publishAsUser"); + } +} + +// Specify the user to whom the common event will be published. +var userId = 100; + +// Publish a common event. +try { + CommonEventManager.publishAsUser("event", userId, publishAsUserCallBack); +} catch (err) { + console.error('publishAsUser failed, catch error' + JSON.stringify(err)); +} +``` + + + +## CommonEventManager.publishAsUser + +publishAsUser(event: string, userId: number, options: CommonEventPublishData, callback: AsyncCallback\): void + +Publishes a common event with given attributes to a specific user. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ---------------------- | +| event | string | Yes | Name of the common event to publish. | +| userId | number | Yes| User ID.| +| options | [CommonEventPublishData](#commoneventpublishdata) | Yes | Attributes of the common event to publish.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Error codes** +|ID |Error Message | +|-----------|--------------------| +|1500004 |not System services or System app| +|1500007 |message send error| +|1500008 |CEMS error| +|1500009 |system error| + +**Example** + + +```ts +// Attributes of a common event. +var options = { + code: 0, // Result code of the common event. + data: "initial data";// Result data of the common event. +} + +// Callback for common event publication +function publishAsUserCallBack(err) { + if (err) { + console.error("publishAsUser failed " + JSON.stringify(err)); + } else { + console.info("publishAsUser"); + } +} + +// Specify the user to whom the common event will be published. +var userId = 100; + +// Publish a common event. +try { + CommonEventManager.publishAsUser("event", userId, options, publishAsUserCallBack); +} catch (err) { + console.error('publishAsUser failed, catch error' + JSON.stringify(err)); +} +``` + + + +## CommonEventManager.createSubscriber + +createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback\): void + +Creates a subscriber. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | ------------------------------------------------------------ | ---- | -------------------------- | +| subscribeInfo | [CommonEventSubscribeInfo](#commoneventsubscribeinfo) | Yes | Subscriber information. | +| callback | AsyncCallback\<[CommonEventSubscriber](#commoneventsubscriber)> | Yes | Callback used to return the result.| + +**Example** + + +```ts +var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. + +// Subscriber information. +var subscribeInfo = { + events: ["event"] +}; + +// Callback for subscriber creation. +function createSubscriberCallBack(err, commonEventSubscriber) { + if(!err) { + console.info("createSubscriber"); + subscriber = commonEventSubscriber; + } else { + console.error("createSubscriber failed " + JSON.stringify(err)); + } +} + +// Create a subscriber. +try { + CommonEventManager.createSubscriber(subscribeInfo, createSubscriberCallBack); +} catch (err) { + console.error('createSubscriber failed, catch error' + JSON.stringify(err)); +} +``` + + + +## CommonEventManager.createSubscriber + +createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise\ + +Creates a subscriber. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | ----------------------------------------------------- | ---- | -------------- | +| subscribeInfo | [CommonEventSubscribeInfo](#commoneventsubscribeinfo) | Yes | Subscriber information.| + +**Return value** +| Type | Description | +| --------------------------------------------------------- | ---------------- | +| Promise\<[CommonEventSubscriber](#commoneventsubscriber)> | Promise used to return the subscriber object.| + +**Example** + +```ts +var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. + +// Subscriber information. +var subscribeInfo = { + events: ["event"] +}; + +// Create a subscriber. +try { + CommonEventManager.createSubscriber(subscribeInfo).then((commonEventSubscriber) => { + console.info("createSubscriber"); + subscriber = commonEventSubscriber; +}).catch((err) => { + console.error("createSubscriber failed " + JSON.stringify(err)); +}); +} catch(err) { + console.error('createSubscriber failed, catch error' + JSON.stringify(err)); +} + +``` + + + +## CommonEventManager.subscribe + +subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback\): void + +Subscribes to common events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------------------------- | ---- | -------------------------------- | +| subscriber | [CommonEventSubscriber](#commoneventsubscriber) | Yes | Subscriber object. | +| callback | AsyncCallback\<[CommonEventData](#commoneventdata)> | Yes | Callback used to return the result.| + +**Example** + +```ts +// Subscriber information. +var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. + +// Subscriber information. +var subscribeInfo = { + events: ["event"] +}; + +// Callback for common event subscription. +function SubscribeCallBack(err, data) { + if (err.code) { + console.error("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribe "); + } +} + +// Callback for subscriber creation. +function createSubscriberCallBack(err, commonEventSubscriber) { + if(!err) { + console.info("createSubscriber"); + subscriber = commonEventSubscriber; + // Subscribe to a common event. + try { + CommonEventManager.subscribe(subscriber, SubscribeCallBack); + } catch (err) { + console.error("createSubscriber failed " + JSON.stringify(err)); + } + } else { + console.error("createSubscriber failed " + JSON.stringify(err)); + } +} + +// Create a subscriber. +try { + CommonEventManager.createSubscriber(subscribeInfo, createSubscriberCallBack); +} catch (err) { + console.error('createSubscriber failed, catch error' + JSON.stringify(err)); +} +``` + + + +## CommonEventManager.unsubscribe + +unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback\): void + +Unsubscribes from common events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------------------- | ---- | ------------------------ | +| subscriber | [CommonEventSubscriber](#commoneventsubscriber) | Yes | Subscriber object. | +| callback | AsyncCallback\ | No | Callback used to return the result.| + +**Example** + +```ts +var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +// Subscriber information. +var subscribeInfo = { + events: ["event"] +}; +// Callback for common event subscription. +function subscribeCallBack(err, data) { + if (err) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribe"); + } +} +// Callback for subscriber creation. +function createSubscriberCallBack(err, commonEventSubscriber) { + if (err) { + console.info("createSubscriber failed " + JSON.stringify(err)); + } else { + console.info("createSubscriber"); + subscriber = commonEventSubscriber; + // Subscribe to a common event. + try { + CommonEventManager.subscribe(subscriber, subscribeCallBack); + } catch(err) { + console.info("subscribe failed " + JSON.stringify(err)); + } + } +} +// Callback for common event unsubscription. +function unsubscribeCallBack(err) { + if (err) { + console.info("unsubscribe failed " + JSON.stringify(err)); + } else { + console.info("unsubscribe"); + } +} +// Create a subscriber. +try { + CommonEventManager.createSubscriber(subscribeInfo, createSubscriberCallBack); +} catch (err) { + console.info("createSubscriber failed " + JSON.stringify(err)); +} + +// Unsubscribe from the common event. +try { + CommonEventManager.unsubscribe(subscriber, unsubscribeCallBack); +} catch (err) { + console.info("unsubscribe failed " + JSON.stringify(err)); +} +``` + +## CommonEventSubscriber + +### getCode + +getCode(callback: AsyncCallback\): void + +Obtains the result code of this common event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for result code obtaining of an ordered common event. +function getCodeCallback(err, Code) { + if (err.code) { + console.error("getCode failed " + JSON.stringify(err)); + } else { + console.info("getCode " + JSON.stringify(Code)); + } +} +subscriber.getCode(getCodeCallback); +``` + +### getCode + +getCode(): Promise\ + +Obtains the result code of this common event. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.getCode().then((Code) => { + console.info("getCode " + JSON.stringify(Code)); +}).catch((err) => { + console.error("getCode failed " + JSON.stringify(err)); +}); +``` + +### setCode + +setCode(code: number, callback: AsyncCallback\): void + +Sets the result code for this common event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------- | +| code | number | Yes | Result code of the common event. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for result code setting of an ordered common event. +function setCodeCallback(err) { + if (err.code) { + console.error("setCode failed " + JSON.stringify(err)); + } else { + console.info("setCode"); + } +} +subscriber.setCode(1, setCodeCallback); +``` + +### setCode + +setCode(code: number): Promise\ + +Sets the result code for this common event. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| code | number | Yes | Result code of the common event.| + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.setCode(1).then(() => { + console.info("setCode"); +}).catch((err) => { + console.error("setCode failed " + JSON.stringify(err)); +}); +``` + +### getData + +getData(callback: AsyncCallback\): void + +Obtains the result data of this common event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result data.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for result data obtaining of an ordered common event. +function getDataCallback(err, Data) { + if (err.code) { + console.error("getData failed " + JSON.stringify(err)); + } else { + console.info("getData " + JSON.stringify(Data)); + } +} +subscriber.getData(getDataCallback); +``` + +### getData + +getData(): Promise\ + +Obtains the result data of this common event. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ---------------- | ------------------ | +| Promise\ | Promise used to return the result data.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.getData().then((Data) => { + console.info("getData " + JSON.stringify(Data)); +}).catch((err) => { + console.error("getData failed " + JSON.stringify(err)); +}); +``` + +### setData + +setData(data: string, callback: AsyncCallback\): void + +Sets the result data for this common event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------- | +| data | string | Yes | Result data of the common event. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for result data setting of an ordered common event +function setDataCallback(err) { + if (err.code) { + console.error("setData failed " + JSON.stringify(err)); + } else { + console.info("setData"); + } +} +subscriber.setData("publish_data_changed", setDataCallback); +``` + +### setData + +setData(data: string): Promise\ + +Sets the result data for this common event. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------- | +| data | string | Yes | Result data of the common event.| + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.setData("publish_data_changed").then(() => { + console.info("setData"); +}).catch((err) => { + console.error("setData failed " + JSON.stringify(err)); +}); +``` + +### setCodeAndData + +setCodeAndData(code: number, data: string, callback:AsyncCallback\): void + +Sets the result code and result data for this common event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------- | +| code | number | Yes | Result code of the common event. | +| data | string | Yes | Result data of the common event. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for result code and result data setting of an ordered common event. +function setCodeDataCallback(err) { + if (err.code) { + console.error("setCodeAndData failed " + JSON.stringify(err)); + } else { + console.info("setCodeDataCallback"); + } +} +subscriber.setCodeAndData(1, "publish_data_changed", setCodeDataCallback); +``` + +### setCodeAndData + +setCodeAndData(code: number, data: string): Promise\ + +Sets the result code and result data for this common event. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------- | +| code | number | Yes | Result code of the common event.| +| data | string | Yes | Result data of the common event.| + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.setCodeAndData(1, "publish_data_changed").then(() => { + console.info("setCodeAndData"); +}).catch((err) => { + console.info("setCodeAndData failed " + JSON.stringify(err)); +}); +``` + +### isOrderedCommonEvent + +isOrderedCommonEvent(callback: AsyncCallback\): void + +Checks whether this common event is an ordered one. This API uses an asynchronous callback to return the result. + + + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ---------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that the common event is an ordered one; and **false** means the opposite.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for checking whether the current common event is an ordered one. +function isOrderedCallback(err, isOrdered) { + if (err.code) { + console.error("isOrderedCommonEvent failed " + JSON.stringify(err)); + } else { + console.info("isOrdered " + JSON.stringify(isOrdered)); + } +} +subscriber.isOrderedCommonEvent(isOrderedCallback); +``` + +### isOrderedCommonEvent + +isOrderedCommonEvent(): Promise\ + +Checks whether this common event is an ordered one. This API uses a promise to return the result. + + + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ----------------- | -------------------------------- | +| Promise\ | Promise used to return the result. The value **true** means that the common event is an ordered one; and **false** means the opposite.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.isOrderedCommonEvent().then((isOrdered) => { + console.info("isOrdered " + JSON.stringify(isOrdered)); +}).catch((err) => { + console.error("isOrdered failed " + JSON.stringify(err)); +}); +``` + +### isStickyCommonEvent + +isStickyCommonEvent(callback: AsyncCallback\): void + +Checks whether this common event is a sticky one. This API uses an asynchronous callback to return the result. + + + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ---------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that the common event is a sticky one; and **false** means the opposite.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for checking whether the current common event is a sticky one. +function isStickyCallback(err, isSticky) { + if (err.code) { + console.error("isStickyCommonEvent failed " + JSON.stringify(err)); + } else { + console.info("isSticky " + JSON.stringify(isSticky)); + } +} +subscriber.isStickyCommonEvent(isStickyCallback); +``` + +### isStickyCommonEvent + +isStickyCommonEvent(): Promise\ + +Checks whether this common event is a sticky one. This API uses a promise to return the result. + + + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ----------------- | -------------------------------- | +| Promise\ | Promise used to return the result. The value **true** means that the common event is a sticky one; and **false** means the opposite.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.isStickyCommonEvent().then((isSticky) => { + console.info("isSticky " + JSON.stringify(isSticky)); +}).catch((err) => { + console.error("isSticky failed " + JSON.stringify(err)); +}); +``` + +### abortCommonEvent + +abortCommonEvent(callback: AsyncCallback\): void + +Aborts this common event. After the abort, the common event is not sent to the next subscriber. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for common event aborting. +function abortCallback(err) { + if (err.code) { + console.error("abortCommonEvent failed " + JSON.stringify(err)); + } else { + console.info("abortCommonEvent"); + } +} +subscriber.abortCommonEvent(abortCallback); +``` + +### abortCommonEvent + +abortCommonEvent(): Promise\ + +Aborts this common event. After the abort, the common event is not sent to the next subscriber. This API takes effect only for ordered common events. It uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.abortCommonEvent().then(() => { + console.info("abortCommonEvent"); +}).catch((err) => { + console.error("abortCommonEvent failed " + JSON.stringify(err)); +}); +``` + +### clearAbortCommonEvent + +clearAbortCommonEvent(callback: AsyncCallback\): void + +Clears the aborted state of this common event. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for clearing the aborted state of the current common event. +function clearAbortCallback(err) { + if (err.code) { + console.error("clearAbortCommonEvent failed " + JSON.stringify(err)); + } else { + console.info("clearAbortCommonEvent"); + } +} +subscriber.clearAbortCommonEvent(clearAbortCallback); +``` + +### clearAbortCommonEvent + +clearAbortCommonEvent(): Promise\ + +Clears the aborted state of this common event. This API takes effect only for ordered common events. It uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.clearAbortCommonEvent().then(() => { + console.info("clearAbortCommonEvent"); +}).catch((err) => { + console.error("clearAbortCommonEvent failed " + JSON.stringify(err)); +}); +``` + +### getAbortCommonEvent + +getAbortCommonEvent(callback: AsyncCallback\): void + +Checks whether this common event is in the aborted state. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ---------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that the ordered common event is in the aborted state; and **false** means the opposite.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for checking whether the current common event is in the aborted state. +function getAbortCallback(err, AbortCommonEvent) { + if (err.code) { + console.error("getAbortCommonEvent failed " + JSON.stringify(err)); + } else { + console.info("AbortCommonEvent " + AbortCommonEvent) + } +} +subscriber.getAbortCommonEvent(getAbortCallback); +``` + +### getAbortCommonEvent + +getAbortCommonEvent(): Promise\ + +Checks whether this common event is in the aborted state. This API takes effect only for ordered common events. It uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ----------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. The value **true** means that the ordered common event is in the aborted state; and **false** means the opposite.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.getAbortCommonEvent().then((AbortCommonEvent) => { + console.info("AbortCommonEvent " + JSON.stringify(AbortCommonEvent)); +}).catch((err) => { + console.error("getAbortCommonEvent failed " + JSON.stringify(err)); +}); +``` + +### getSubscribeInfo + +getSubscribeInfo(callback: AsyncCallback\): void + +Obtains the subscriber information. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ---------------------- | +| callback | AsyncCallback\<[CommonEventSubscribeInfo](#commoneventsubscribeinfo)> | Yes | Callback used to return the subscriber information.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for subscriber information obtaining. +function getSubscribeInfoCallback(err, SubscribeInfo) { + if (err.code) { + console.error("getSubscribeInfo failed " + JSON.stringify(err)); + } else { + console.info("SubscribeInfo " + JSON.stringify(SubscribeInfo)); + } +} +subscriber.getSubscribeInfo(getSubscribeInfoCallback); +``` + +### getSubscribeInfo + +getSubscribeInfo(): Promise\ + +Obtains the subscriber information. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ---------------------- | +| Promise\<[CommonEventSubscribeInfo](#commoneventsubscribeinfo)> | Promise used to return the subscriber information.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.getSubscribeInfo().then((SubscribeInfo) => { + console.info("SubscribeInfo " + JSON.stringify(SubscribeInfo)); +}).catch((err) => { + console.error("getSubscribeInfo failed " + JSON.stringify(err)); +}); +``` + +### finishCommonEvent9+ + +finishCommonEvent(callback: AsyncCallback\): void + +Finishes this ordered common event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------------------- | +| callback | AsyncCallback\ | Yes | Callback returned after the ordered common event is finished.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for ordered common event finishing. +function finishCommonEventCallback(err) { + if (err.code) { + console.error("finishCommonEvent failed " + JSON.stringify(err)); +} else { + console.info("FinishCommonEvent"); +} +} +subscriber.finishCommonEvent(finishCommonEventCallback); +``` + +### finishCommonEvent9+ + +finishCommonEvent(): Promise\ + +Finishes this ordered common event. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.finishCommonEvent().then(() => { + console.info("FinishCommonEvent"); +}).catch((err) => { + console.error("finishCommonEvent failed " + JSON.stringify(err)); +}); +``` + +## CommonEventData + +**System capability**: SystemCapability.Notification.CommonEvent + +| Name | Type | Readable| Writable| Description | +| ---------- |-------------------- | ---- | ---- | ------------------------------------------------------- | +| event | string | Yes | No | Name of the common event that is being received. | +| bundleName | string | Yes | No | Bundle name. | +| code | number | Yes | No | Result code of the common event, which is used to transfer data of the int type. | +| data | string | Yes | No | Custom result data of the common event, which is used to transfer data of the string type.| +| parameters | {[key: string]: any} | Yes | No | Additional information about the common event. | + + +## CommonEventPublishData + +**System capability**: SystemCapability.Notification.CommonEvent + +| Name | Type | Readable| Writable| Description | +| --------------------- | -------------------- | ---- | ---- | ---------------------------- | +| bundleName | string | Yes | No | Bundle name. | +| code | number | Yes | No | Result code of the common event. | +| data | string | Yes | No | Custom result data of the common event.| +| subscriberPermissions | Array\ | Yes | No | Permissions required for subscribers to receive the common event. | +| isOrdered | boolean | Yes | No | Whether the common event is an ordered one. | +| isSticky | boolean | Yes | No | Whether the common event is a sticky one. Only system applications and system services are allowed to send sticky events.| +| parameters | {[key: string]: any} | Yes | No | Additional information about the common event. | + +## CommonEventSubscribeInfo + +**System capability**: SystemCapability.Notification.CommonEvent + +| Name | Type | Readable| Writable| Description | +| ------------------- | -------------- | ---- | ---- | ------------------------------------------------------------ | +| events | Array\ | Yes | No | Name of the common event to publish. | +| publisherPermission | string | Yes | No | Permissions required for publishers to publish the common event. | +| publisherDeviceId | string | Yes | No | Device ID. The value must be the ID of an existing device on the same network. | +| userId | number | Yes | No | User ID. The default value is the ID of the current user. If this parameter is specified, the value must be an existing user ID in the system.| +| priority | number | Yes | No | Subscriber priority. The value ranges from -100 to +1000. | diff --git a/en/application-dev/reference/apis/js-apis-configPolicy.md b/en/application-dev/reference/apis/js-apis-configPolicy.md index 4e541cbfe0022219d9ebf57b0502e82984c84384..af8d2ba8f5fa0aa614d55205d176ce49132f9068 100644 --- a/en/application-dev/reference/apis/js-apis-configPolicy.md +++ b/en/application-dev/reference/apis/js-apis-configPolicy.md @@ -1,4 +1,4 @@ -# Configuration Policy +# @ohos.configPolicy (Configuration Policy) The **configPolicy** module provides APIs for obtaining the custom configuration directory and file path based on the predefined custom configuration level. @@ -24,6 +24,7 @@ For example, if the **config.xml** file is stored in **/system/etc/config.xml** **System capability**: SystemCapability.Customization.ConfigPolicy **Parameters** + | Name | Type | Mandatory | Description | | -------- | --------------------------- | ---- | --------------------- | | relPath | string | Yes | Name of the configuration file. | @@ -50,11 +51,13 @@ Obtains the path of a configuration file with the specified name and highest pri **System capability**: SystemCapability.Customization.ConfigPolicy **Parameters** + | Name | Type | Mandatory | Description | | ------- | ------ | ---- | ----- | | relPath | string | Yes | Name of the configuration file.| **Return value** + | Type | Description | | --------------------- | ------------ | | Promise<string> | Promise used to return the path of the configuration file.| @@ -79,6 +82,7 @@ For example, if the **config.xml** file is stored in **/system/etc/config.xml** **System capability**: SystemCapability.Customization.ConfigPolicy **Parameters** + | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ------------- | | relPath | string | Yes | Name of the configuration file. | @@ -105,11 +109,13 @@ Obtains a list of configuration files with the specified name, sorted in ascendi **System capability**: SystemCapability.Customization.ConfigPolicy **Parameters** + | Name | Type | Mandatory | Description | | ------- | ------ | ---- | ----- | | relPath | string | Yes | Name of the configuration file.| **Return value** + | Type | Description | | ---------------------------------- | ---- | | Promise<Array<string>> | Promise used to return the file list.| @@ -133,6 +139,7 @@ Obtains the list of configuration level directories. This API uses an asynchrono **System capability**: SystemCapability.Customization.ConfigPolicy **Parameters** + | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ----------------- | | callback | AsyncCallback<Array<string>> | Yes | Callback used to return the configuration level directory list.| @@ -158,6 +165,7 @@ Obtains the list of configuration level directories. This API uses a promise to **System capability**: SystemCapability.Customization.ConfigPolicy **Return value** + | Type | Description | | ---------------------------------- | -------- | | Promise<Array<string>> | Promise used to return the configuration level directory list.| diff --git a/en/application-dev/reference/apis/js-apis-connectedTag.md b/en/application-dev/reference/apis/js-apis-connectedTag.md index 57cf8eadb5a07bcd3038c67d4d582ab4359d2ea2..1bfb1231c3c4584fe4d608891bdf2be54458e425 100644 --- a/en/application-dev/reference/apis/js-apis-connectedTag.md +++ b/en/application-dev/reference/apis/js-apis-connectedTag.md @@ -1,18 +1,17 @@ -# Active Tag +# @ohos.connectedTag -The **connectedTag** module provides methods for using active tags. You can use the APIs provided by this module to initialize the active tag chip and read and write active tags. +The **connectedTag** module provides APIs for using active tags. You can use the APIs to initialize the active tag chip and read and write active tags. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. - ## Modules to Import -``` +```js import connectedTag from '@ohos.connectedTag'; ``` - ## connectedTag.init init(): boolean @@ -23,11 +22,11 @@ Initializes the active tag chip. **System capability**: SystemCapability.Communication.ConnectedTag -- Return value - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the initialization is successful; returns **false** otherwise.| +**Return value** +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## connectedTag.uninit @@ -39,125 +38,136 @@ Uninitializes the active tag resources. **System capability**: SystemCapability.Communication.ConnectedTag -- Return value - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Return value** +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## connectedTag.readNdefTag readNdefTag(): Promise<string> -Reads the content of this active tag. This method uses a promise to return the result. +Reads the content of this active tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.ConnectedTag -- Return value - | **Type**| **Description**| - | -------- | -------- | - | Promise<string> | Promise used to return the content of the active tag.| +**Return value** -- Example - ``` - import connectedTag from '@ohos.connectedTag'; +| **Type**| **Description**| +| -------- | -------- | +| Promise<string> | Promise used to return the content of the active tag.| - connectedTag.readNdefTag().then(result => { - console.log("promise recv ndef response: " + result); - }); - ``` +**Example** + +```js +import connectedTag from '@ohos.connectedTag'; + +connectedTag.readNdefTag().then((data) => { + console.log("connectedTag readNdefTag Promise data = " + data); +}).catch((err)=> { + console.log("connectedTag readNdefTag Promise err: " + err); +}); +``` ## connectedTag.readNdefTag readNdefTag(callback: AsyncCallback<string>): void -Reads the content of this active tag. This method uses an asynchronous callback to return the result. +Reads the content of this active tag. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.ConnectedTag -- Parameters - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<string> | Yes| Callback invoked to return the active tag content obtained.| +**Parameters** -- Example - ``` - import connectedTag from '@ohos.connectedTag'; - - connectedTag.readNdefTag(result => { - console.log("callback recv ndef response: " + result); - }); - ``` +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<string> | Yes| Callback invoked to return the active tag content obtained.| + +**Example** + +```js +import connectedTag from '@ohos.connectedTag'; + +connectedTag.readNdefTag((err, data)=> { + if (err) { + console.log("connectedTag readNdefTag AsyncCallback err: " + err); + } else { + console.log("connectedTag readNdefTag AsyncCallback data: " + data); + } +}); +``` ## connectedTag.writeNdefTag writeNdefTag(data: string): Promise<void> -Writes data to this active tag. This method uses a promise to return the result. +Writes data to this active tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.ConnectedTag -- Parameters - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | data | string | Yes| Data to write. The maximum length is 1024 bytes.| - -- Return value - | **Type**| **Description**| - | -------- | -------- | - | Promise<void> | Promise used to return the result. This method returns no value.| - -- Example - ``` - import connectedTag from '@ohos.connectedTag'; - - writeNdefTag.write("010203") - .then((value) => { - // Data is written to the tag. - console.log(`success to write event: ${value}`); - }).catch((err) => { - // Failed to write data to the tag. - console.error(`failed to write event because ${err.code}`); - }); - ``` +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| data | string | Yes| Data to write. The maximum length is 1024 bytes.| + +**Return value** + +| **Type**| **Description**| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +import connectedTag from '@ohos.connectedTag'; + +var rawData = "010203"; // change it tobe correct. +connectedTag.writeNdefTag(rawData).then(() => { + console.log("connectedTag writeNdefTag Promise success."); +}).catch((err)=> { + console.log("connectedTag writeNdefTag Promise err: " + err); +}); +``` ## connectedTag.writeNdefTag writeNdefTag(data: string, callback: AsyncCallback<void>): void -Writes data to this active tag. This method uses an asynchronous callback to return the result. +Writes data to this active tag. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.ConnectedTag -- Parameters - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | data | string | Yes| Data to write. The maximum length is 1024 bytes.| - | callback | AsyncCallback<string> | Yes| Callback invoked to return the active tag content obtained.| - -- Example - ``` - import connectedTag from '@ohos.connectedTag'; - - connectedTag.writeNdefTag("010203", (err, value) => { - if (err) { - // Failed to write data to the tag. - console.error(`failed to write event because ${err.code}`); - return; - } - - // Data is written to the tag. - console.log(`success to write event: ${value}`); - }); - ``` +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| data | string | Yes| Data to write. The maximum length is 1024 bytes.| +| callback | AsyncCallback<void> | Yes| Callback invoked to return the active tag content obtained.| + +**Example** + +```js +import connectedTag from '@ohos.connectedTag'; + +var rawData = "010203"; // change it tobe correct. +connectedTag.writeNdefTag(rawData, (err)=> { + if (err) { + console.log("connectedTag writeNdefTag AsyncCallback err: " + err); + } else { + console.log("connectedTag writeNdefTag AsyncCallback success."); + } +}); +``` ## connectedTag.on('notify') @@ -169,18 +179,12 @@ Registers the NFC field strength state events. **System capability**: SystemCapability.Communication.ConnectedTag -- Parameters - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **notify**.| - | callback | Callback<number> | Yes| Callback invoked to return the field strength state.| - -- Enumerates the field strength states. - | **Value**| **Description**| - | -------- | -------- | - | 0 | Field off.| - | 1 | Field on.| +**Parameters** +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **notify**.| +| callback | Callback<number> | Yes| Callback used to return the [NfcRfType](#nfcrftype).| ## connectedTag.off('notify') @@ -192,36 +196,54 @@ Unregisters the NFC field strength state events. **System capability**: SystemCapability.Communication.ConnectedTag -- Parameters - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **notify**.| - | callback | Callback<number> | No| Callback used to return the field strength state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| - -- Example - ``` - import connectedTag from '@ohos.connectedTag'; - - var NFC_RF_NOTIFY = "notify"; - - var recvNfcRfNotifyFunc = result => { - console.info("nfc rf receive state: " + result); - } - - // Register event notification. - connectedTag.on(NFC_RF_NOTIFY, recvNfcRfNotifyFunc); - - // Unregister event notification. - connectedTag.off(NFC_RF_NOTIFY, recvNfcRfNotifyFunc); - ``` +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **notify**.| +| callback | Callback<number> | No| Callback used to return the field strength state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + +**Example** + +```js +import connectedTag from '@ohos.connectedTag'; + +// Register the event. +connectedTag.on("notify", (err, rfState)=> { + if (err) { + console.log("connectedTag on Callback err: " + err); + } else { + console.log("connectedTag on Callback rfState: " + rfState); + } +}); + +var initStatus = connectedTag.init(); +console.log("connectedTag init status: " + initStatus); + +// Add nfc connecected tag business oprations here... +// connectedTag.writeNdefTag(rawData) +// connectedTag.readNdefTag() + +var uninitStatus = connectedTag.uninit(); +console.log("connectedTag uninit status: " + uninitStatus); + +// Unregister the event. +connectedTag.off("notify", (err, rfState)=> { + if (err) { + console.log("connectedTag off Callback err: " + err); + } else { + console.log("connectedTag off Callback rfState: " + rfState); + } +}); +``` ## NfcRfType -Enumerates the NFC states. +Enumerates the NFC field strength states. **System capability**: SystemCapability.Communication.ConnectedTag -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | -| NFC_RF_LEAVE | 0 | Field on.| +| NFC_RF_LEAVE | 0 | Field off.| | NFC_RF_ENTER | 1 | Field on.| diff --git a/en/application-dev/reference/apis/js-apis-data-ValuesBucket.md b/en/application-dev/reference/apis/js-apis-data-valuesBucket.md similarity index 97% rename from en/application-dev/reference/apis/js-apis-data-ValuesBucket.md rename to en/application-dev/reference/apis/js-apis-data-valuesBucket.md index 22ae3fc33e27b1dc0b859848fdb8e0ea6c6f2122..846f3f15481d700da9d738857bc217c64cbe6ac9 100644 --- a/en/application-dev/reference/apis/js-apis-data-ValuesBucket.md +++ b/en/application-dev/reference/apis/js-apis-data-valuesBucket.md @@ -1,4 +1,4 @@ -# Value Bucket +# @ohos.data.ValuesBucket The **ValueBucket** module holds data in key-value (KV) pairs. You can use it to insert data into a database. diff --git a/en/application-dev/reference/apis/js-apis-defaultAppManager.md b/en/application-dev/reference/apis/js-apis-defaultAppManager.md index 28830ea0737c3243e97dd2a02256b32f54616f6d..dd19bdb98680553ff3f66b3484ab95aa97b5b52d 100644 --- a/en/application-dev/reference/apis/js-apis-defaultAppManager.md +++ b/en/application-dev/reference/apis/js-apis-defaultAppManager.md @@ -1,4 +1,4 @@ -# DefaultAppManager +# @ohos.bundle.defaultAppManager (Default Application Management) The **DefaultAppManager** module provides APIs to query whether the current application is the default application of a specific type. @@ -18,25 +18,25 @@ import defaultAppMgr from '@ohos.bundle.defaultAppManager'; | --------------------------------------- | ----------- | ---------------- | | ohos.permission.GET_DEFAULT_APPLICATION | system_core | Permission related to the default application.| -For details, see in [Permission Levels](../../security/accesstoken-overview.md#permission-levels). +For details, see [Permission Levels](../../security/accesstoken-overview.md#permission-levels). ## defaultAppMgr.ApplicationType -Enumerates the application types. +Enumerates the default application types. **System capability**: SystemCapability.BundleManager.BundleFramework.DefaultApp -| Name | Type | Value | Description | -| -------- | -------- | -------------------------------------- | -------------------------------------- | -| BROWSER | string | Web Browser | Default browser. | -| IMAGE | string | Image Gallery | Default image viewer. | -| AUDIO | string | Audio Player | Default audio player. | -| VIDEO | string | Video Player | Default video player. | -| PDF | string | PDF Viewer | Default PDF reader. | -| WORD | string | Word Viewer | Default Word viewer. | -| EXCEL | string | Excel Viewer | Default Excel viewer. | -| PPT | string | PPT Viewer | Default PowerPoint viewer. | +| Name | Value| Description | +| -------- | -------------------------------------- | -------------------------------------- | +| BROWSER | "Web Browser" | Default browser. | +| IMAGE | "Image Gallery" | Default image viewer. | +| AUDIO | "Audio Player" | Default audio player. | +| VIDEO | "Video Player" | Default video player. | +| PDF | "PDF Viewer" | Default PDF reader. | +| WORD | "Word Viewer" | Default Word viewer. | +| EXCEL | "Excel Viewer" | Default Excel viewer. | +| PPT | "PPT Viewer" | Default PowerPoint viewer. | ## defaultAppMgr.isDefaultApplication @@ -58,10 +58,6 @@ Checks whether this application is the default application of a system-defined a | ------------------------- | ------------------ | | Promise\ | Promise used to return the result. If the application is the default application, `true` is returned; otherwise, `false` is returned.| -**Error codes** - -For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). - **Example** @@ -90,13 +86,9 @@ Checks whether this application is the default application of a system-defined a | type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype). | | callback | AsyncCallback\ | Yes | Callback used to return the result. If the application is the default application, `true` is returned; otherwise, `false` is returned.| -**Error codes** - -For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). - **Example** -```js +```ts import defaultAppMgr from '@ohos.bundle.defaultAppManager'; defaultAppMgr.isDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, (err, data) => { if (err) { @@ -144,7 +136,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** -```js +```ts import defaultAppMgr from '@ohos.bundle.defaultAppManager'; defaultAppMgr.getDefaultApplication(defaultAppMgr.ApplicationType.BROWSER) .then((data) => { @@ -195,7 +187,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** -```js +```ts import defaultAppMgr from '@ohos.bundle.defaultAppManager'; let userId = 100; defaultAppMgr.getDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, userId, (err, data) => { @@ -246,7 +238,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** -```js +```ts import defaultAppMgr from '@ohos.bundle.defaultAppManager'; defaultAppMgr.getDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, (err, data) => { if (err) { @@ -302,7 +294,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** -```js +```ts import defaultAppMgr from '@ohos.bundle.defaultAppManager'; defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { bundleName: "com.test.app", @@ -369,7 +361,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** -```js +```ts import defaultAppMgr from '@ohos.bundle.defaultAppManager'; let userId = 100; defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { @@ -486,7 +478,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** -```js +```ts import defaultAppMgr from '@ohos.bundle.defaultAppManager'; let userId = 100; defaultAppMgr.resetDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, userId) @@ -537,7 +529,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** -```js +```ts import defaultAppMgr from '@ohos.bundle.defaultAppManager'; let userId = 100; defaultAppMgr.resetDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, userId, (err, data) => { diff --git a/en/application-dev/reference/apis/js-apis-deque.md b/en/application-dev/reference/apis/js-apis-deque.md index 594984e1deb513a21c165c04d0d7d95a918a8766..e295a1cf9c72875727705c131b4342868daff54a 100644 --- a/en/application-dev/reference/apis/js-apis-deque.md +++ b/en/application-dev/reference/apis/js-apis-deque.md @@ -1,4 +1,4 @@ -# Linear Container Deque +# @ohos.util.Deque (Linear Container Deque) > **NOTE** > @@ -51,11 +51,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let deque = new Deque(); -try { - let deque2 = Deque(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### insertFront @@ -91,11 +86,6 @@ deque.insertFront(b); let c = {name : "Dylon", age : "13"}; deque.insertFront(c); deque.insertFront(false); -try { - deque.insertFront.bind({}, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### insertEnd @@ -131,11 +121,6 @@ deque.insertEnd(b); let c = {name : "Dylon", age : "13"}; deque.insertEnd(c); deque.insertEnd(false); -try { - deque.insertEnd.bind({}, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### has @@ -173,11 +158,6 @@ let deque = new Deque(); let result = deque.has("squirrel"); deque.insertFront("squirrel"); let result1 = deque.has("squirrel"); -try { - deque.has.bind({}, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### popFirst @@ -212,11 +192,6 @@ deque.insertEnd(5); deque.insertFront(2); deque.insertFront(4); let result = deque.popFirst(); -try { - deque.popFirst.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### popLast @@ -251,16 +226,11 @@ deque.insertFront(5); deque.insertFront(2); deque.insertFront(4); let result = deque.popLast(); -try { - deque.popLast.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value: T, index?: number, deque?: Deque<T>) => void, +forEach(callbackFn: (value: T, index?: number, deque?: Deque<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -271,7 +241,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -301,13 +271,6 @@ deque.insertEnd(4); deque.forEach((value, index) => { console.log("value:" + value, index); }); -try { - deque.forEach.bind({}, (value, index) => { - console.log("value:" + value, index); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getFirst @@ -341,11 +304,6 @@ deque.insertEnd(4); deque.insertFront(5); deque.insertFront(4); let result = deque.getFirst(); -try { - deque.getFirst.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getLast @@ -379,11 +337,6 @@ deque.insertFront(4); deque.insertFront(5); deque.insertFront(4); let result = deque.getLast(); -try { - deque.getLast.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### [Symbol.iterator] @@ -428,9 +381,4 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - deque[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md b/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md index 935211cb5ead58fd8823c87358bafc9eebafc449..f9a998f37ca17b4d4c70342bc648ed519fbe1652 100644 --- a/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md +++ b/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md @@ -1,4 +1,4 @@ -# Device Usage Statistics +# @ohos.deviceUsageStatistics (Device Usage Statistics) This module provides APIs for collecting statistics on device usage. @@ -487,7 +487,7 @@ Enumerates the interval types for querying the application usage duration. **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App -| Name | Default Value | Description | +| Name | Value | Description | | ------------ | ---- | ---------------------------------------- | | BY_OPTIMIZED | 0 | The system obtains the application usage duration statistics in the specified time frame at the interval the system deems appropriate.| | BY_DAILY | 1 | The system obtains the application usage duration statistics in the specified time frame on a daily basis. | diff --git a/en/application-dev/reference/apis/js-apis-distributed-account.md b/en/application-dev/reference/apis/js-apis-distributed-account.md index 505587d21e4cd4b792ff97282b10ae1bc4662359..5a4a93c46fbe2492cecf4569f8e4e7db63469371 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-account.md +++ b/en/application-dev/reference/apis/js-apis-distributed-account.md @@ -1,8 +1,8 @@ -# Distributed Account Management +# @ohos.account.distributedAccount -The **distributedAccount** module provides APIs for managing distributed accounts, including querying and updating account login status. +The **distributedAccount** module provides APIs for managing distributed accounts, including querying and updating account login states. -> **NOTE**
+> **NOTE** > > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -49,7 +49,7 @@ Obtains distributed account information. This API uses an asynchronous callback | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[DistributedInfo](#distributedinfo)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **undefined** and data is the distributed account information obtained. Otherwise, **err** is an error object.| + | callback | AsyncCallback<[DistributedInfo](#distributedinfo)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the distributed account information obtained. Otherwise, **err** is an error object.| **Error codes** @@ -124,7 +124,7 @@ Obtains distributed account information. This API uses an asynchronous callback | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[DistributedInfo](#distributedinfo)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **undefined** and data is the distributed account information obtained. Otherwise, **err** is an error object.| + | callback | AsyncCallback<[DistributedInfo](#distributedinfo)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the distributed account information obtained. Otherwise, **err** is an error object.| **Example** ```js @@ -181,7 +181,7 @@ Sets the distributed account information. This API uses an asynchronous callback | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | accountInfo | [DistributedInfo](#distributedinfo) | Yes| New distributed account information.| + | accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information to set.| | callback | AsyncCallback<void> | Yes| Callback invoked to return the result. If the distributed account information is set successfully, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** @@ -219,7 +219,7 @@ Sets the distributed account information. This API uses a promise to return the | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | accountInfo | [DistributedInfo](#distributedinfo) | Yes| New distributed account information.| + | accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information to set.| **Return value** @@ -322,7 +322,7 @@ Defines distributed OS account information. | -------- | -------- | -------- | -------- | | name | string | Yes| Name of the distributed account. It must be a non-null string.| | id | string | Yes| UID of the distributed account. It must be a non-null string.| -| event | string | Yes| Login state of a distributed account. The state can be login, logout, token invalid, or logoff, which correspond to the following strings respectively:
- Ohos.account.event.LOGIN
- Ohos.account.event.LOGOUT
- Ohos.account.event.TOKEN_INVALID
- Ohos.account.event.LOGOFF | +| event | string | Yes| Login state of the distributed account. The state can be login, logout, token invalid, or logoff, which correspond to the following strings respectively:
- Ohos.account.event.LOGIN
- Ohos.account.event.LOGOUT
- Ohos.account.event.TOKEN_INVALID
- Ohos.account.event.LOGOFF | | nickname9+ | string | No| Nickname of the distributed account. It must be a non-null string.| | avatar9+ | string | No| Avatar of the distributed account. It must be a non-null string.| -| scalableData | object | No| Extended information about the distributed account, passed in key-value (KV) pairs.
**NOTE**
This parameter is reserved and not used in query and update methods.| +| scalableData | object | No| Extended information about the distributed account, passed in key-value (KV) pairs.
**NOTE**
This parameter is reserved and not used in the setters and getters.| diff --git a/en/application-dev/reference/apis/js-apis-distributedBundle.md b/en/application-dev/reference/apis/js-apis-distributedBundle.md index 98a15d818444aac4bd9c57e0eb270c7a3c36fbe0..2ddd4b91388067d0b301f8d7ba26bbf748eb15cb 100644 --- a/en/application-dev/reference/apis/js-apis-distributedBundle.md +++ b/en/application-dev/reference/apis/js-apis-distributedBundle.md @@ -1,4 +1,4 @@ -# distributedBundle +# @ohos.bundle.distributedBundle The **distributedBundle** module provides APIs for managing distributed bundles. diff --git a/en/application-dev/reference/apis/js-apis-emitter.md b/en/application-dev/reference/apis/js-apis-emitter.md index 0bc6f9c6a4c156cfa2d604885572fcbe4bdc41bc..a072663e8c5cf3f667860cd72d1ef50c2bb72334 100644 --- a/en/application-dev/reference/apis/js-apis-emitter.md +++ b/en/application-dev/reference/apis/js-apis-emitter.md @@ -1,4 +1,4 @@ -# Emitter +# @ohos.events.emitter The **Emitter** module provides APIs for sending and processing in-process events, including the APIs for processing events that are subscribed to in persistent or one-shot manner, unsubscribing from events, and emitting events to the event queue. diff --git a/en/application-dev/reference/apis/js-apis-formInfo.md b/en/application-dev/reference/apis/js-apis-formInfo.md deleted file mode 100644 index 8acf0e5e3e1ccb81b2295b03c65ed8fd812efa8e..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-formInfo.md +++ /dev/null @@ -1,133 +0,0 @@ -# FormInfo - -The **FormInfo** module provides widget information and state. - -> **NOTE** -> -> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. - -## Modules to Import - -``` -import formInfo from '@ohos.application.formInfo'; -``` - -## Required Permissions - -None - -## FormInfo - -Describes widget information. - -**System capability**: SystemCapability.Ability.Form - -| Name | Readable/Writable| Type | Description | -| ----------- | -------- | -------------------- | ------------------------------------------------------------ | -| bundleName | Read only | string | Name of the bundle to which the widget belongs. | -| moduleName | Read only | string | Name of the module to which the widget belongs. | -| abilityName | Read only | string | Name of the ability to which the widget belongs. | -| name | Read only | string | Widget name. | -| description | Read only | string | Description of the widget. | -| type | Read only | [FormType](#formtype) | Widget type. Currently, only JS widgets are supported.| -| jsComponentName | Read only | string | Component name of the JS widget. | -| colorMode | Read only | [ColorMode](#colormode) | Color mode of the widget. | -| isDefault | Read only | boolean | Whether the widget is the default one. | -| updateEnabled | Read only | boolean | Whether the widget is updatable. | -| formVisibleNotify | Read only | string | Whether to send a notification when the widget is visible. | -| relatedBundleName | Read only | string | Name of the associated bundle to which the widget belongs. | -| scheduledUpdateTime | Read only | string | Time when the widget was updated. | -| formConfigAbility | Read only | string | Configuration ability of the widget. | -| updateDuration | Read only | string | Widget update period.| -| defaultDimension | Read only | number | Default dimension of the widget. | -| supportDimensions | Read only | Array<number> | Dimensions supported by the widget. | -| customizeData | Read only | {[key: string]: [value: string]} | Custom data of the widget. | - -## FormType - -Enumerates the widget types. - -**System capability**: SystemCapability.Ability.Form - -| Name | Value | Description | -| ----------- | ---- | ------------ | -| JS | 1 | JS widget. | - -## ColorMode - -Enumerates the color modes supported by the widget. - -**System capability**: SystemCapability.Ability.Form - -| Name | Value | Description | -| ----------- | ---- | ------------ | -| MODE_AUTO | -1 | Auto mode. | -| MODE_DARK | 0 | Dark mode. | -| MODE_LIGHT | 1 | Light mode. | - -## FormStateInfo - -Describes the widget state information. - -**System capability**: SystemCapability.Ability.Form - -| Name | Readable/Writable| Type | Description | -| ----------- | -------- | -------------------- | ------------------------------------------------------------ | -| formState | Read only | [FormState](#formstate) | Widget state. | -| want | Read only | Want | Want text. | - -## FormState - -Enumerates the widget states. - -**System capability**: SystemCapability.Ability.Form - -| Name | Value | Description | -| ----------- | ---- | ------------ | -| UNKNOWN | -1 | Unknown state. | -| DEFAULT | 0 | Default state. | -| READY | 1 | Ready state. | - -## FormParam - -Enumerates the widget parameters. - -**System capability**: SystemCapability.Ability.Form - -| Name | Value | Description | -| ----------- | ---- | ------------ | -| IDENTITY_KEY9+ | "ohos.extra.param.key.form_identity" | ID of a widget.
**System API**: This is a system API and cannot be called by third-party applications. | -| DIMENSION_KEY | "ohos.extra.param.key.form_dimension" | Widget dimension. | -| NAME_KEY | "ohos.extra.param.key.form_name" | Widget name. | -| MODULE_NAME_KEY | "ohos.extra.param.key.module_name" | Name of the module to which the widget belongs. | -| WIDTH_KEY | "ohos.extra.param.key.form_width" | Widget width. | -| HEIGHT_KEY | "ohos.extra.param.key.form_height" | Widget height. | -| TEMPORARY_KEY | "ohos.extra.param.key.form_temporary" | Temporary widget. | -| ABILITY_NAME_KEY9+ | "ohos.extra.param.key.ability_name" | Ability name. | -| DEVICE_ID_KEY9+ | "ohos.extra.param.key.device_id" | Device ID.
This is a system API. | -| BUNDLE_NAME_KEY9+ | "ohos.extra.param.key.bundle_name" | Key that specifies the target bundle name.| - -## FormDimension - -Enumerates the widget dimensions. - -**System capability**: SystemCapability.Ability.Form - -| Name | Value | Description | -| ----------- | ---- | ------------ | -| Dimension_1_29+ | 1 | 1 x 2. | -| Dimension_2_29+ | 2 | 2 x 2. | -| Dimension_2_49+ | 3 | 2 x 4. | -| Dimension_4_49+ | 4 | 4 x 4. | -| Dimension_2_19+ | 5 | 2 x 1. | - - -## FormInfoFilter - -Defines the widget information filter. Only the widget information that meets the filter is returned. - -**System capability**: SystemCapability.Ability.Form - -| Name | Yes | Description | -| ----------- | ---- | ------------ | -| moduleName9+ | No | Module name.| diff --git a/en/application-dev/reference/apis/js-apis-formbindingdata.md b/en/application-dev/reference/apis/js-apis-formbindingdata.md deleted file mode 100644 index 612b2dc84f23f465a844d73656954bc983c5a233..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-formbindingdata.md +++ /dev/null @@ -1,68 +0,0 @@ -# FormBindingData - -The **FormBindingData** module provides APIs for widget data binding. You can use the APIs to create a **FormBindingData** object and obtain related information. - -> **NOTE** -> -> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. - -## Modules to Import - -``` -import formBindingData from '@ohos.application.formBindingData'; -``` - -## Required Permissions - -None - -## formBindingData.createFormBindingData - -createFormBindingData(obj?: Object | string): FormBindingData - -Creates a **FormBindingData** object. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | -------------- | ---- | ------------------------------------------------------------ | -| obj | Object or string| No | Data to be displayed on the JS widget. The value can be an object containing multiple key-value pairs or a string in JSON format. The image data is identified by "formImages", and the content is multiple key-value pairs, each of which consists of an image identifier and image file descriptor. The final format is {"formImages": {"key1": fd1, "key2": fd2}}.| - - -**Return value** - -| Type | Description | -| ----------------------------------- | --------------------------------------- | -| [FormBindingData](#formbindingdata) | **FormBindingData** object created based on the passed data.| - - -**Example** - - ```js - import featureAbility from '@ohos.ability.featureAbility'; - import fileio from '@ohos.fileio'; - let context=featureAbility.getContext(); - context.getOrCreateLocalDir((err,data)=>{ - let path=data+"/xxx.jpg"; - let fd = fileio.openSync(path); - let obj = { - "temperature": "21°", - "formImages": {"image": fd} - }; - let formBindingDataObj = formBindingData.createFormBindingData(obj); - }) - - - ``` - -## Attributes - -Describes a **FormBindingData** object. - -**System capability**: SystemCapability.Ability.Form - -| Name| Readable| Writable| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -------- | -------- | -| data | Yes| No| Object | Yes| Data to be displayed on the JS widget. The value can be an object containing multiple key-value pairs or a string in JSON format.| diff --git a/en/application-dev/reference/apis/js-apis-formextension.md b/en/application-dev/reference/apis/js-apis-formextension.md deleted file mode 100644 index 1540e538e1bcc8f53165a3fd277e60f76e73a7a1..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-formextension.md +++ /dev/null @@ -1,289 +0,0 @@ -# FormExtension - -The **FormExtension** module provides APIs related to Form Extension abilities. - -> **NOTE** -> -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> The APIs of this module can be used only in the stage model. - -## Modules to Import - -``` -import FormExtension from '@ohos.application.FormExtension'; -``` - -## Required Permissions - -None - -## Attributes - -**System capability**: SystemCapability.Ability.Form - -| Name | Type | Readable| Writable| Description | -| ------- | ------------------------------------------------------- | ---- | ---- | --------------------------------------------------- | -| context | [FormExtensionContext](js-apis-formextensioncontext.md) | Yes | No | Context of the **FormExtension**. This context is inherited from **ExtensionContext**.| - -## onCreate - -onCreate(want: Want): formBindingData.FormBindingData - -Called to notify the widget provider that a **Form** instance (widget) has been created. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | -------------------------------------- | ---- | ------------------------------------------------------------ | - | want | [Want](js-apis-application-Want.md) | Yes | Information related to the extension, including the widget ID, name, and style. The information must be managed as persistent data to facilitate subsequent widget update and deletion.| - -**Return value** - - | Type | Description | - | ------------------------------------------------------------ | ----------------------------------------------------------- | - | [formBindingData.FormBindingData](js-apis-formbindingdata.md#formbindingdata) | A **formBindingData.FormBindingData** object containing the data to be displayed on the widget.| - -**Example** - - ```js - import formBindingData from '@ohos.application.formBindingData' - export default class MyFormExtension extends FormExtension { - onCreate(want) { - console.log('FormExtension onCreate, want:' + want.abilityName); - let dataObj1 = { - temperature:"11c", - "time":"11:00" - }; - let obj1 = formBindingData.createFormBindingData(dataObj1); - return obj1; - } - } - ``` - -## FormExtension.onCastToNormal - -onCastToNormal(formId: string): void - -Called to notify the widget provider that a temporary widget has been converted to a normal one. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------------------ | - | formId | string | Yes | ID of the widget that requests to be converted to a normal one.| - -**Example** - - ``` - export default class MyFormExtension extends FormExtension { - onCastToNormal(formId) { - console.log('FormExtension onCastToNormal, formId:' + formId); - } - } - ``` - -## FormExtension.onUpdate - -onUpdate(formId: string): void - -Called to notify the widget provider that a widget has been updated. After obtaining the latest data, the caller invokes **updateForm** of the [FormExtensionContext](js-apis-formextensioncontext.md) class to update the widget data. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------------ | - | formId | string | Yes | ID of the widget that requests to be updated.| - -**Example** - - ```js - import formBindingData from '@ohos.application.formBindingData' - export default class MyFormExtension extends FormExtension { - onUpdate(formId) { - console.log('FormExtension onUpdate, formId:' + formId); - let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); - this.context.updateForm(formId, obj2) - .then((data)=>{ - console.log('FormExtension context updateForm, data:' + data); - }).catch((error) => { - console.error('Operation updateForm failed. Cause: ' + error);}); - } - } - ``` - -## FormExtension.onVisibilityChange - -onVisibilityChange(newStatus: { [key: string]: number }): void - -Called to notify the widget provider of the change of visibility. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name | Type | Mandatory| Description | - | --------- | ------------------------- | ---- | ---------------------------- | - | newStatus | { [key: string]: number } | Yes | ID and visibility status of the widget to be changed.| - -**Example** - - ```js - import formBindingData from '@ohos.application.formBindingData' - export default class MyFormExtension extends FormExtension { - onVisibilityChange(newStatus) { - console.log('FormExtension onVisibilityChange, newStatus:' + newStatus); - let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); - - for (let key in newStatus) { - console.log('FormExtension onVisibilityChange, key:' + key + ", value=" + newStatus[key]); - this.context.updateForm(key, obj2) - .then((data)=>{ - console.log('FormExtension context updateForm, data:' + data); - }).catch((error) => { - console.error('Operation updateForm failed. Cause: ' + error);}); - } - } - } - ``` - -## FormExtension.onEvent - -onEvent(formId: string, message: string): void - -Called to instruct the widget provider to receive and process the widget event. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name | Type | Mandatory| Description | - | ------- | ------ | ---- | ---------------------- | - | formId | string | Yes | ID of the widget that requests the event.| - | message | string | Yes | Event message. | - -**Example** - - ```js - export default class MyFormExtension extends FormExtension { - onEvent(formId, message) { - console.log('FormExtension onEvent, formId:' + formId + ", message:" + message); - } - } - ``` - -## FormExtension.onDestroy - -onDestroy(formId: string): void - -Called to notify the widget provider that a **Form** instance (widget) has been destroyed. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------------ | - | formId | string | Yes | ID of the widget to be destroyed.| - -**Example** - - ```js - export default class MyFormExtension extends FormExtension { - onDestroy(formId) { - console.log('FormExtension onDestroy, formId:' + formId); - } - } - ``` - -## FormExtension.onConfigurationUpdated - -onConfigurationUpdated(config: Configuration): void; - -Called when the configuration of the environment where the ability is running is updated. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | [Configuration](js-apis-configuration.md) | Yes| New configuration.| - -**Example** - - ```js - class MyFormExtension extends FormExtension { - onConfigurationUpdated(config) { - console.log('onConfigurationUpdated, config:' + JSON.stringify(config)); - } - } - ``` - -## FormExtension.onAcquireFormState - -onAcquireFormState?(want: Want): formInfo.FormState; - -Called when the widget provider receives the status query result of a widget. By default, the initial state is returned. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | No| Description of the widget state, including the bundle name, ability name, module name, widget name, and widget dimension.| - -**Example** - - ```js - import formInfo from '@ohos.application.formInfo' - class MyFormExtension extends FormExtension { - onAcquireFormState(want) { - console.log('FormExtension onAcquireFormState, want:' + want); - return formInfo.FormState.UNKNOWN; - } - } - ``` - -## FormExtension.onShare - -onShare?(formId: string): {[key: string]: any}; - -Called by the widget provider to receive shared widget data. - -This is a system API. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | formId | string | Yes | ID of a widget.| - -**Return value** - - | Type | Description | - | ------------------------------------------------------------ | ----------------------------------------------------------- | - | {[key: string]: any} | Data to be shared by the widget, in the form of key-value pairs.| - -**Example** - - ```js - class MyFormExtension extends FormExtension { - onShare(formId) { - console.log('FormExtension onShare, formId:' + formId); - let wantParams = { - "temperature":"20", - "time":"2022-8-8 09:59", - }; - return wantParams; - } - } - ``` diff --git a/en/application-dev/reference/apis/js-apis-formhost.md b/en/application-dev/reference/apis/js-apis-formhost.md deleted file mode 100644 index 7ed0ff46de845198aac96bbcf7ebdeaad4055ad1..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-formhost.md +++ /dev/null @@ -1,1124 +0,0 @@ -# FormHost - -The **FormHost** module provides APIs related to the widget host, which is an application that displays the widget content and controls the position where the widget is displayed. You can use the APIs to delete, release, and update widgets, send notifications to widgets, and obtain widget information and status. - -> **NOTE** -> -> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> The APIs of this module are system APIs and cannot be called by third-party applications. - -## Modules to Import - -``` -import formHost from '@ohos.application.formHost'; -``` - -## Required Permissions - -ohos.permission.REQUIRE_FORM - -ohos.permission.GET_BUNDLE_INFO_PRIVILEGED - -## deleteForm - -deleteForm(formId: string, callback: AsyncCallback<void>): void; - -Deletes a widget. This API uses an asynchronous callback to return the result. After this API is called, the application can no longer use the widget, and the Widget Manager will not retain the widget information. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formId | string | Yes | Widget ID.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - var formId = "12400633174999288"; - formHost.deleteForm(formId, (error, data) => { - if (error.code) { - console.log('formHost deleteForm, error:' + JSON.stringify(error)); - } - }); - ``` - -## deleteForm - -deleteForm(formId: string): Promise<void>; - -Deletes a widget. This API uses a promise to return the result. After this API is called, the application can no longer use the widget, and the Widget Manager will not retain the widget information. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------- | - | formId | string | Yes | Widget ID.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - -**Parameters** - - ```js - var formId = "12400633174999288"; - formHost.deleteForm(formId).then(() => { - console.log('formHost deleteForm success'); - }).catch((error) => { - console.log('formHost deleteForm, error:' + JSON.stringify(error)); - }); - ``` - -## releaseForm - -releaseForm(formId: string, callback: AsyncCallback<void>): void; - -Releases a widget. This API uses an asynchronous callback to return the result. After this API is called, the application can no longer use the widget, but the Widget Manager still retains the widget cache and storage information. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formId | string | Yes | Widget ID.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - var formId = "12400633174999288"; - formHost.releaseForm(formId, (error, data) => { - if (error.code) { - console.log('formHost releaseForm, error:' + JSON.stringify(error)); - } - }); - ``` - -## releaseForm - -releaseForm(formId: string, isReleaseCache: boolean, callback: AsyncCallback<void>): void; - -Releases a widget. This API uses an asynchronous callback to return the result. After this API is called, the application can no longer use the widget, but the Widget Manager retains the storage information about the widget and retains or releases the cache information based on the setting. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------------- | ------ | ---- | ----------- | -| formId | string | Yes | Widget ID. | -| isReleaseCache | boolean | Yes | Whether to release the cache.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - var formId = "12400633174999288"; - formHost.releaseForm(formId, true, (error, data) => { - if (error.code) { - console.log('formHost releaseForm, error:' + JSON.stringify(error)); - } - }); - ``` - -## releaseForm - -releaseForm(formId: string, isReleaseCache?: boolean): Promise<void>; - -Releases a widget. This API uses a promise to return the result. After this API is called, the application can no longer use the widget, but the Widget Manager retains the storage information about the widget and retains or releases the cache information based on the setting. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name | Type | Mandatory| Description | - | -------------- | ------ | ---- | ----------- | - | formId | string | Yes | Widget ID. | - | isReleaseCache | boolean | No | Whether to release the cache.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - -**Example** - - ```js - var formId = "12400633174999288"; - formHost.releaseForm(formId, true).then(() => { - console.log('formHost releaseForm success'); - }).catch((error) => { - console.log('formHost releaseForm, error:' + JSON.stringify(error)); - }); - ``` - -## requestForm - -requestForm(formId: string, callback: AsyncCallback<void>): void; - -Requests a widget update. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formId | string | Yes | Widget ID.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - var formId = "12400633174999288"; - formHost.requestForm(formId, (error, data) => { - if (error.code) { - console.log('formHost requestForm, error:' + JSON.stringify(error)); - } - }); - ``` - -## requestForm - -requestForm(formId: string): Promise<void>; - -Requests a widget update. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------- | - | formId | string | Yes | Widget ID.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - -**Example** - - ```js - var formId = "12400633174999288"; - formHost.requestForm(formId).then(() => { - console.log('formHost requestForm success'); - }).catch((error) => { - console.log('formHost requestForm, error:' + JSON.stringify(error)); - }); - ``` - -## castTempForm - -castTempForm(formId: string, callback: AsyncCallback<void>): void; - -Converts a temporary widget to a normal one. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formId | string | Yes | Widget ID.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - var formId = "12400633174999288"; - formHost.castTempForm(formId, (error, data) => { - if (error.code) { - console.log('formHost castTempForm, error:' + JSON.stringify(error)); - } - }); - ``` - -## castTempForm - -castTempForm(formId: string): Promise<void>; - -Converts a temporary widget to a normal one. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------- | - | formId | string | Yes | Widget ID.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - -**Example** - - ```js - var formId = "12400633174999288"; - formHost.castTempForm(formId).then(() => { - console.log('formHost castTempForm success'); - }).catch((error) => { - console.log('formHost castTempForm, error:' + JSON.stringify(error)); - }); - ``` - -## notifyVisibleForms - -notifyVisibleForms(formIds: Array<string>, callback: AsyncCallback<void>): void; - -Instructs the widget framework to make a widget visible. This API uses an asynchronous callback to return the result. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formIds | Array<string> | Yes | List of widget IDs. | -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - var formId = ["12400633174999288"]; - formHost.notifyVisibleForms(formId, (error, data) => { - if (error.code) { - console.log('formHost notifyVisibleForms, error:' + JSON.stringify(error)); - } - }); - ``` - -## notifyVisibleForms - -notifyVisibleForms(formIds: Array<string>): Promise<void>; - -Instructs the widget framework to make a widget visible. This API uses a promise to return the result. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formIds | Array<string> | Yes | List of widget IDs.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - -**Example** - - ```js - var formId = ["12400633174999288"]; - formHost.notifyVisibleForms(formId).then(() => { - console.log('formHost notifyVisibleForms success'); - }).catch((error) => { - console.log('formHost notifyVisibleForms, error:' + JSON.stringify(error)); - }); - ``` - -## notifyInvisibleForms - -notifyInvisibleForms(formIds: Array<string>, callback: AsyncCallback<void>): void; - -Instructs the widget framework to make a widget invisible. This API uses an asynchronous callback to return the result. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formIds | Array<string> | Yes | List of widget IDs. | -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - var formId = ["12400633174999288"]; - formHost.notifyInvisibleForms(formId, (error, data) => { - if (error.code) { - console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(error)); - } - }); - ``` - -## notifyInvisibleForms - -notifyInvisibleForms(formIds: Array<string>): Promise<void>; - -Instructs the widget framework to make a widget invisible. This API uses a promise to return the result. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formIds | Array<string> | Yes | List of widget IDs.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - -**Example** - - ```js - var formId = ["12400633174999288"]; - formHost.notifyInvisibleForms(formId).then(() => { - console.log('formHost notifyInvisibleForms success'); - }).catch((error) => { - console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(error)); - }); - ``` - -## enableFormsUpdate - -enableFormsUpdate(formIds: Array<string>, callback: AsyncCallback<void>): void; - -Instructs the widget framework to make a widget updatable. This API uses an asynchronous callback to return the result. After this API is called, the widget is in the enabled state and can receive updates from the widget provider. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formIds | Array<string> | Yes | List of widget IDs. | -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - var formId = ["12400633174999288"]; - formHost.enableFormsUpdate(formId, (error, data) => { - if (error.code) { - console.log('formHost enableFormsUpdate, error:' + JSON.stringify(error)); - } - }); - ``` - -## enableFormsUpdate - -enableFormsUpdate(formIds: Array<string>): Promise<void>; - -Instructs the widget framework to make a widget updatable. This API uses a promise to return the result. After this API is called, the widget is in the enabled state and can receive updates from the widget provider. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formIds | Array<string> | Yes | List of widget IDs.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - -**Example** - - ```js - var formId = ["12400633174999288"]; - formHost.enableFormsUpdate(formId).then(() => { - console.log('formHost enableFormsUpdate success'); - }).catch((error) => { - console.log('formHost enableFormsUpdate, error:' + JSON.stringify(error)); - }); - ``` - -## disableFormsUpdate - -disableFormsUpdate(formIds: Array<string>, callback: AsyncCallback<void>): void; - -Instructs the widget framework to make a widget not updatable. This API uses an asynchronous callback to return the result. After this API is called, the widget cannot receive updates from the widget provider. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formIds | Array<string> | Yes | List of widget IDs. | -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - var formId = ["12400633174999288"]; - formHost.disableFormsUpdate(formId, (error, data) => { - if (error.code) { - console.log('formHost disableFormsUpdate, error:' + JSON.stringify(error)); - } - }); - ``` - -## disableFormsUpdate - -disableFormsUpdate(formIds: Array<string>): Promise<void>; - -Instructs the widget framework to make a widget not updatable. This API uses a promise to return the result. After this API is called, the widget cannot receive updates from the widget provider. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formIds | Array<string> | Yes | List of widget IDs.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - -**Example** - - ```js - var formId = ["12400633174999288"]; - formHost.disableFormsUpdate(formId).then(() => { - console.log('formHost disableFormsUpdate success'); - }).catch((error) => { - console.log('formHost disableFormsUpdate, error:' + JSON.stringify(error)); - }); - ``` - -## isSystemReady - -isSystemReady(callback: AsyncCallback<void>): void; - -Checks whether the system is ready. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - var formId = "12400633174999288"; - formHost.isSystemReady((error, data) => { - if (error.code) { - console.log('formHost isSystemReady, error:' + JSON.stringify(error)); - } - }); - ``` - -## isSystemReady - -isSystemReady(): Promise<void>; - -Checks whether the system is ready. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.Form - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - -**Example** - - ```js - var formId = "12400633174999288"; - formHost.isSystemReady().then(() => { - console.log('formHost isSystemReady success'); - }).catch((error) => { - console.log('formHost isSystemReady, error:' + JSON.stringify(error)); - }); - ``` - -## getAllFormsInfo - -getAllFormsInfo(callback: AsyncCallback<Array<formInfo.FormInfo>>): void; - -Obtains the widget information provided by all applications on the device. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------- | - | callback | AsyncCallback<Array<[FormInfo](./js-apis-formInfo.md#forminfo-1)>> | Yes| Callback used to return the widget information.| - -**Example** - - ```js - formHost.getAllFormsInfo((error, data) => { - if (error.code) { - console.log('formHost getAllFormsInfo, error:' + JSON.stringify(error)); - } else { - console.log('formHost getAllFormsInfo, data:' + JSON.stringify(data)); - } - }); - ``` - -## getAllFormsInfo - -getAllFormsInfo(): Promise<Array<formInfo.FormInfo>>; - - -Obtains the widget information provided by all applications on the device. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED - -**System capability**: SystemCapability.Ability.Form - -**Return value** - -| Type | Description | -| :------------ | :---------------------------------- | -| Promise<Array<[FormInfo](./js-apis-formInfo.md#forminfo-1)>> | Promise used to return the widget information.| - -**Example** - - ```js - formHost.getAllFormsInfo().then((data) => { - console.log('formHost getAllFormsInfo data:' + JSON.stringify(data)); - }).catch((error) => { - console.log('formHost getAllFormsInfo, error:' + JSON.stringify(error)); - }); - ``` - -## getFormsInfo - -getFormsInfo(bundleName: string, callback: AsyncCallback<Array<formInfo.FormInfo>>): void; - - -Obtains the widget information provided by a given application on the device. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------- | - | bundleName | string | Yes| Bundle name of the target application.| - | callback | AsyncCallback<Array<[FormInfo](./js-apis-formInfo.md#forminfo-1)>> | Yes| Callback used to return the widget information.| - -**Example** - - ```js - formHost.getFormsInfo("com.example.ohos.formjsdemo", (error, data) => { - if (error.code) { - console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); - } else { - console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); - } - }); - ``` - -## getFormsInfo - -getFormsInfo(bundleName: string, moduleName: string, callback: AsyncCallback<Array<formInfo.FormInfo>>): void; - - -Obtains the widget information provided by a given application on the device. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------- | - | bundleName | string | Yes| Bundle name of the target application.| - | moduleName | string | Yes| Module name.| - | callback | AsyncCallback<Array<[FormInfo](./js-apis-formInfo.md#forminfo-1)>> | Yes| Callback used to return the widget information.| - -**Example** - - ```js - formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry", (error, data) => { - if (error.code) { - console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); - } else { - console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); - } - }); - ``` - -## getFormsInfo - -getFormsInfo(bundleName: string, moduleName?: string): Promise<Array<formInfo.FormInfo>>; - - -Obtains the widget information provided by a given application on the device. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------- | - | bundleName | string | Yes| Bundle name of the target application.| - | moduleName | string | No| Module name.| - -**Return value** - -| Type | Description | -| :------------ | :---------------------------------- | -| Promise<Array<[FormInfo](./js-apis-formInfo.md#forminfo-1)>> | Promise used to return the widget information.| - -**Example** - - ```js - formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry").then((data) => { - console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); - }).catch((error) => { - console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); - }); - ``` - -## deleteInvalidForms - -deleteInvalidForms(formIds: Array<string>, callback: AsyncCallback<number>): void; - -Deletes invalid widgets from the list. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formIds | Array<string> | Yes | List of valid widget IDs.| -| callback | AsyncCallback<number> | Yes| Callback used to return the number of widgets deleted.| - -**Example** - - ```js - var formIds = new Array("12400633174999288", "12400633174999289"); - formHost.deleteInvalidForms(formIds, (error, data) => { - if (error.code) { - console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error)); - } else { - console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); - } - }); - ``` - -## deleteInvalidForms - -deleteInvalidForms(formIds: Array<string>): Promise<number>; - -Deletes invalid widgets from the list. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formIds | Array<string> | Yes | List of valid widget IDs.| - -**Return value** - -| Type | Description | -| :------------ | :---------------------------------- | -| Promise<number> | Promise used to return the number of widgets deleted.| - -**Example** - - ```js - var formIds = new Array("12400633174999288", "12400633174999289"); - formHost.deleteInvalidForms(formIds).then((data) => { - console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); - }).catch((error) => { - console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error)); - }); - ``` - -## acquireFormState - -acquireFormState(want: Want, callback: AsyncCallback<formInfo.FormStateInfo>): void; - -Obtains the widget state. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.REQUIRE_FORM and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| want | [Want](js-apis-application-Want.md) | Yes | **Want** information carried to query the widget state.| -| callback | AsyncCallback<[FormStateInfo](js-apis-formInfo.md#formstateinfo)> | Yes| Callback used to return the widget state.| - -**Example** - - ```js - var want = { - "deviceId": "", - "bundleName": "ohos.samples.FormApplication", - "abilityName": "FormAbility", - "parameters": { - "ohos.extra.param.key.module_name": "entry", - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.form_dimension": 2 - } - }; - formHost.acquireFormState(want, (error, data) => { - if (error.code) { - console.log('formHost acquireFormState, error:' + JSON.stringify(error)); - } else { - console.log('formHost acquireFormState, data:' + JSON.stringify(data)); - } - }); - ``` - -## acquireFormState - -acquireFormState(want: Want): Promise<formInfo.FormStateInfo>; - -Obtains the widget state. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.REQUIRE_FORM and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| want | [Want](js-apis-application-Want.md) | Yes | **Want** information carried to query the widget state.| - -**Return value** - -| Type | Description | -| :------------ | :---------------------------------- | -| Promise<[FormStateInfo](js-apis-formInfo.md#formstateinfo)> | Promise used to return the widget state.| - -**Example** - - ```js - var want = { - "deviceId": "", - "bundleName": "ohos.samples.FormApplication", - "abilityName": "FormAbility", - "parameters": { - "ohos.extra.param.key.module_name": "entry", - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.form_dimension": 2 - } - }; - formHost.acquireFormState(want).then((data) => { - console.log('formHost acquireFormState, data:' + JSON.stringify(data)); - }).catch((error) => { - console.log('formHost acquireFormState, error:' + JSON.stringify(error)); - }); - ``` - -## on("formUninstall") - -on(type: "formUninstall", callback: Callback<string>): void; - -Subscribes to widget uninstall events. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| type | string | Yes | Type of event to subscribe to. The value **formUninstall** indicates a widget uninstallation event.| -| callback | Callback<string> | Yes| Callback used for event subscription.| - -**Example** - - ```js - let callback = function(formId) { - console.log('formHost on formUninstall, formId:' + formId); - } - formHost.on("formUninstall", callback); - ``` - -## off("formUninstall") - -off(type: "formUninstall", callback?: Callback<string>): void; - -Unsubscribes from widget uninstall events. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| type | string | Yes | Type of event to subscribe to. The value **formUninstall** indicates a widget uninstallation event.| -| callback | Callback<string> | No| Callback used for event unsubscription. If it is left unspecified, it indicates the callback for all the events that have been subscribed.| - -**Example** - - ```js - let callback = function(formId) { - console.log('formHost on formUninstall, formId:' + formId); - } - formHost.off("formUninstall", callback); - ``` - -## notifyFormsVisible - -notifyFormsVisible(formIds: Array<string>, isVisible: boolean, callback: AsyncCallback<void>): void; - -Instructs the widgets to make themselves visible. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formIds | Array<string> | Yes | List of widget IDs.| -| isVisible | boolean | Yes | Whether to be visible.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - var formIds = new Array("12400633174999288", "12400633174999289"); - formHost.notifyFormsVisible(formIds, true, (error, data) => { - if (error.code) { - console.log('formHost notifyFormsVisible, error:' + JSON.stringify(error)); - } - }); - ``` - -## notifyFormsVisible - -notifyFormsVisible(formIds: Array<string>, isVisible: boolean): Promise<void>; - -Instructs the widgets to make themselves visible. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------- | - | formIds | Array<string> | Yes | List of widget IDs.| - | isVisible | boolean | Yes | Whether to be visible.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - -**Example** - - ```js - var formIds = new Array("12400633174999288", "12400633174999289"); - formHost.notifyFormsVisible(formIds, true).then(() => { - console.log('formHost notifyFormsVisible success'); - }).catch((error) => { - console.log('formHost notifyFormsVisible, error:' + JSON.stringify(error)); - }); - ``` - -## notifyFormsEnableUpdate - -notifyFormsEnableUpdate(formIds: Array<string>, isEnableUpdate: boolean, callback: AsyncCallback<void>): void; - -Instructs the widgets to enable or disable updates. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formIds | Array<string> | Yes | List of widget IDs.| -| isEnableUpdate | boolean | Yes | Whether to enable update.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - var formIds = new Array("12400633174999288", "12400633174999289"); - formHost.notifyFormsEnableUpdate(formIds, true, (error, data) => { - if (error.code) { - console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); - } - }); - ``` - -## notifyFormsEnableUpdate - -notifyFormsEnableUpdate(formIds: Array<string>, isEnableUpdate: boolean): Promise<void>; - -Instructs the widgets to enable or disable updates. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------- | - | formIds | Array<string> | Yes | List of widget IDs.| - | isEnableUpdate | boolean | Yes | Whether to enable update.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - -**Example** - - ```js - var formIds = new Array("12400633174999288", "12400633174999289"); - formHost.notifyFormsEnableUpdate(formIds, true).then(() => { - console.log('formHost notifyFormsEnableUpdate success'); - }).catch((error) => { - console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); - }); - ``` -## shareForm9+ - -shareForm(formId: string, deviceId: string, callback: AsyncCallback<void>): void; - -Shares a specified widget with a remote device. This API uses an asynchronous callback to return the result. - -This is a system API. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formId | string | Yes | Widget ID.| -| deviceId | string | Yes | Remote device ID.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - var formId = "12400633174999288"; - var deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; - formHost.shareForm(formId, deviceId, (error, data) => { - if (error.code) { - console.log('formHost shareForm, error:' + JSON.stringify(error)); - } - }); - ``` - -## shareForm9+ - -shareForm(formId: string, deviceId: string): Promise<void>; - -Shares a specified widget with a remote device. This API uses a promise to return the result. - -This is a system API. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------- | - | formId | string | Yes | Widget ID.| - | deviceId | string | Yes | Remote device ID.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - -**Parameters** - - ```js - var formId = "12400633174999288"; - var deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; - formHost.shareForm(formId, deviceId).then(() => { - console.log('formHost shareForm success'); - }).catch((error) => { - console.log('formHost shareForm, error:' + JSON.stringify(error)); - }); - ``` diff --git a/en/application-dev/reference/apis/js-apis-freeInstall.md b/en/application-dev/reference/apis/js-apis-freeInstall.md index 44ecb706ffc98b8f7937574d3ab18812b76abece..94ab3e8ac8cad4c8a41a4820741e595535f388a3 100644 --- a/en/application-dev/reference/apis/js-apis-freeInstall.md +++ b/en/application-dev/reference/apis/js-apis-freeInstall.md @@ -1,4 +1,4 @@ -# Bundle.freeInstall +# @ohos.bundle.freeInstall The **Bundle.freeInstall** module provides APIs for setting and obtaining installation-free information and APIs for obtaining **BundlePackInfo** and **DispatchInfo**. diff --git a/en/application-dev/reference/apis/js-apis-geoLocationManager.md b/en/application-dev/reference/apis/js-apis-geoLocationManager.md new file mode 100644 index 0000000000000000000000000000000000000000..9c09d174723ca769e8b712a2e874c9b3c6f4f3a8 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-geoLocationManager.md @@ -0,0 +1,2208 @@ +# Geolocation Manager + +The Geolocation Manager module provides location service management functions. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Applying for Permissions + +Before using basic location capabilities, check whether your application has been granted the permission to access the device location information. If not, your application needs to obtain the permission from the user as described below. + +The system provides the following location permissions: +- ohos.permission.LOCATION + +- ohos.permission.APPROXIMATELY_LOCATION + +- ohos.permission.LOCATION_IN_BACKGROUND + +If your application needs to access the device location information, it must first apply for required permissions. Specifically speaking: + +- API versions earlier than 9: Apply for **ohos.permission.LOCATION**. + +- API version 9 and later: Apply for **ohos.permission.APPROXIMATELY\_LOCATION**, or apply for **ohos.permission.APPROXIMATELY\_LOCATION** and **ohos.permission.LOCATION**. Note that **ohos.permission.LOCATION** cannot be applied for separately. + +| API Version| Location Permission| Permission Application Result| Location Accuracy| +| -------- | -------- | -------- | -------- | +| Earlier than 9| ohos.permission.LOCATION | Success| Location accurate to meters| +| 9 and later| ohos.permission.LOCATION | Failure| No location obtained| +| 9 and later| ohos.permission.APPROXIMATELY_LOCATION | Success| Location accurate to 5 kilometers| +| 9 and later| ohos.permission.APPROXIMATELY_LOCATION and ohos.permission.LOCATION| Success| Location accurate to meters| + +If your application needs to access the device location information when running in the background, it must be configured to be able to run in the background and be granted the **ohos.permission.LOCATION_IN_BACKGROUND** permission. In this way, the system continues to report device location information after your application moves to the background. + +You can declare the required permission in your application's configuration file. For details, see [Access Control (Permission) Development](../../security/accesstoken-guidelines.md). + + +## Modules to Import + +```ts +import geoLocationManager from '@ohos.geoLocationManager'; +``` + + +## geoLocationManager.on('locationChange') + +on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>): void + +Registers a listener for location changes with a location request initiated. The location result is reported through [LocationRequest](#locationrequest). + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **locationChange** indicates a location change event.| + | request | [LocationRequest](#locationrequest) | Yes| Location request.| + | callback | Callback<[Location](#location)> | Yes| Callback used to return the location change event.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301200 | Failed to obtain the geographical location. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; + var locationChange = (location) => { + console.log('locationChanger: data: ' + JSON.stringify(location)); + }; + try { + geoLocationManager.on('locationChange', requestInfo, locationChange); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + + ``` + + +## geoLocationManager.off('locationChange') + +off(type: 'locationChange', callback?: Callback<Location>): void + +Unregisters the listener for location changes with the corresponding location request deleted. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **locationChange** indicates a location change event.| + | callback | Callback<[Location](#location)> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301200 | Failed to obtain the geographical location. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; + var locationChange = (location) => { + console.log('locationChanger: data: ' + JSON.stringify(location)); + }; + try { + geoLocationManager.on('locationChange', requestInfo, locationChange); + geoLocationManager.off('locationChange', locationChange); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.on('locationEnabledChange') + +on(type: 'locationEnabledChange', callback: Callback<boolean>): void + +Registers a listener for location service status change events. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **locationEnabledChange** indicates a location service status change event.| + | callback | Callback<boolean> | Yes| Callback used to return the location service status change event.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var locationEnabledChange = (state) => { + console.log('locationEnabledChange: ' + JSON.stringify(state)); + } + try { + geoLocationManager.on('locationEnabledChange', locationEnabledChange); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.off('locationEnabledChange') + +off(type: 'locationEnabledChange', callback?: Callback<boolean>): void; + +Unregisters the listener for location service status change events. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **locationEnabledChange** indicates a location service status change event.| + | callback | Callback<boolean> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var locationEnabledChange = (state) => { + console.log('locationEnabledChange: state: ' + JSON.stringify(state)); + } + try { + geoLocationManager.on('locationEnabledChange', locationEnabledChange); + geoLocationManager.off('locationEnabledChange', locationEnabledChange); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.on('cachedGnssLocationsChange') + +on(type: 'cachedGnssLocationsChange', request: CachedGnssLocationsRequest, callback: Callback<Array<Location>>): void; + +Registers a listener for cached GNSS location reports. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **cachedGnssLocationsChange** indicates reporting of cached GNSS locations.| + | request | [CachedGnssLocationsRequest](#cachedgnsslocationsrequest) | Yes| Request for reporting cached GNSS location.| + | callback | Callback<boolean> | Yes| Callback used to return cached GNSS locations.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301200 | Failed to obtain the geographical location. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var cachedLocationsCb = (locations) => { + console.log('cachedGnssLocationsChange: locations: ' + JSON.stringify(locations)); + } + var requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true}; + try { + geoLocationManager.on('cachedGnssLocationsChange', requestInfo, cachedLocationsCb); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.off('cachedGnssLocationsChange') + +off(type: 'cachedGnssLocationsChange', callback?: Callback<Array<Location>>): void; + +Unregisters the listener for cached GNSS location reports. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **cachedGnssLocationsChange** indicates reporting of cached GNSS locations.| + | callback | Callback<boolean> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301200 | Failed to obtain the geographical location. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var cachedLocationsCb = (locations) => { + console.log('cachedGnssLocationsChange: locations: ' + JSON.stringify(locations)); + } + var requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true}; + try { + geoLocationManager.on('cachedGnssLocationsChange', requestInfo, cachedLocationsCb); + geoLocationManager.off('cachedGnssLocationsChange'); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.on('satelliteStatusChange') + +on(type: 'satelliteStatusChange', callback: Callback<SatelliteStatusInfo>): void; + +Registers a listener for GNSS satellite status change events. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **satelliteStatusChange** indicates a GNSS satellite status change event.| + | callback | Callback<[SatelliteStatusInfo](#satellitestatusinfo)> | Yes| Callback used to return GNSS satellite status changes.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var gnssStatusCb = (satelliteStatusInfo) => { + console.log('satelliteStatusChange: ' + JSON.stringify(satelliteStatusInfo)); + } + + try { + geoLocationManager.on('satelliteStatusChange', gnssStatusCb); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.off('satelliteStatusChange') + +off(type: 'satelliteStatusChange', callback?: Callback<SatelliteStatusInfo>): void; + +Unregisters the listener for GNSS satellite status change events. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **satelliteStatusChange** indicates a GNSS satellite status change event.| + | callback | Callback<[SatelliteStatusInfo](#satellitestatusinfo)> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | + + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var gnssStatusCb = (satelliteStatusInfo) => { + console.log('satelliteStatusChange: ' + JSON.stringify(satelliteStatusInfo)); + } + try { + geoLocationManager.on('satelliteStatusChange', gnssStatusCb); + geoLocationManager.off('satelliteStatusChange', gnssStatusCb); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.on('nmeaMessage') + +on(type: 'nmeaMessage', callback: Callback<string>): void; + +Registers a listener for GNSS NMEA message change events. + +**Permission required**: ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **nmeaMessage** indicates a GNSS NMEA message change event.| + | callback | Callback<string> | Yes| Callback used to return GNSS NMEA message changes.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | + + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var nmeaCb = (str) => { + console.log('nmeaMessage: ' + JSON.stringify(str)); + } + + try { + geoLocationManager.on('nmeaMessage', nmeaCb ); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.off('nmeaMessage') + +off(type: 'nmeaMessage', callback?: Callback<string>): void; + +Unregisters the listener for GNSS NMEA message change events. + +**Permission required**: ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **nmeaMessage** indicates a GNSS NMEA message change event.| + | callback | Callback<string> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | + + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var nmeaCb = (str) => { + console.log('nmeaMessage: ' + JSON.stringify(str)); + } + + try { + geoLocationManager.on('nmeaMessage', nmeaCb); + geoLocationManager.off('nmeaMessage', nmeaCb); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.on('gnssFenceStatusChange') + +on(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): void; + +Registers a listener for status change events of the specified geofence. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Geofence + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **gnssFenceStatusChange** indicates a geofence status change event.| + | request | [GeofenceRequest](#geofencerequest) | Yes| Geofencing request.| + | want | WantAgent | Yes| **WantAgent** used to return geofence (entrance or exit) events.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301600 | Failed to operate the geofence. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + import wantAgent from '@ohos.wantAgent'; + + let wantAgentInfo = { + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", + action: "action1", + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG], + }; + + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + var requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; + try { + geoLocationManager.on('gnssFenceStatusChange', requestInfo, wantAgentObj); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + }); + ``` + + +## geoLocationManager.off('gnssFenceStatusChange') + +off(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): void; + +Unregisters the listener for status change events of the specified geofence. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Geofence + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **gnssFenceStatusChange** indicates a geofence status change event.| + | request | [GeofenceRequest](#geofencerequest) | Yes| Geofencing request.| + | want | WantAgent | Yes| **WantAgent** used to return geofence (entrance or exit) events.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301600 | Failed to operate the geofence. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + import wantAgent from '@ohos.wantAgent'; + + let wantAgentInfo = { + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", + action: "action1", + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + var requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; + try { + geoLocationManager.on('gnssFenceStatusChange', requestInfo, wantAgentObj); + geoLocationManager.off('gnssFenceStatusChange', requestInfo, wantAgentObj); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + }); + ``` + + +## geoLocationManager.on('countryCodeChange') + +on(type: 'countryCodeChange', callback: Callback<CountryCode>): void; + +Registers a listener for country code change events. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **countryCodeChange** indicates a country code change event.| + | callback | Callback<[CountryCode](#countrycode)> | Yes| Callback used to return the country code change event.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301500 | Failed to query the area information. | + + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var callback = (code) => { + console.log('countryCodeChange: ' + JSON.stringify(code)); + } + + try { + geoLocationManager.on('countryCodeChange', callback); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.off('countryCodeChange') + +off(type: 'countryCodeChange', callback?: Callback<CountryCode>): void; + +Unregisters the listener for country code change events. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **countryCodeChange** indicates a country code change event.| + | callback | Callback<[CountryCode](#countrycode)> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301500 | Failed to query the area information. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var callback = (code) => { + console.log('countryCodeChange: ' + JSON.stringify(code)); + } + + try { + geoLocationManager.on('countryCodeChange', callback); + geoLocationManager.off('countryCodeChange', callback); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + + +## geoLocationManager.getCurrentLocation + +getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>): void + +Obtains the current location. This API uses an asynchronous callback to return the result. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | request | [CurrentLocationRequest](#currentlocationrequest) | Yes| Location request.| + | callback | AsyncCallback<[Location](#location)> | Yes| Callback used to return the current location.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301200 | Failed to obtain the geographical location. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; + var locationChange = (err, location) => { + if (err) { + console.log('locationChanger: err=' + JSON.stringify(err)); + } + if (location) { + console.log('locationChanger: location=' + JSON.stringify(location)); + } + }; + + try { + geoLocationManager.getCurrentLocation(requestInfo, locationChange); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + +## geoLocationManager.getCurrentLocation + +getCurrentLocation(callback: AsyncCallback<Location>): void; + +Obtains the current location. This API uses an asynchronous callback to return the result. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[Location](#location)> | Yes| Callback used to return the current location.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301200 | Failed to obtain the geographical location. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var locationChange = (err, location) => { + if (err) { + console.log('locationChanger: err=' + JSON.stringify(err)); + } + if (location) { + console.log('locationChanger: location=' + JSON.stringify(location)); + } + }; + + try { + geoLocationManager.getCurrentLocation(locationChange); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + +## geoLocationManager.getCurrentLocation + +getCurrentLocation(request?: CurrentLocationRequest): Promise<Location> + +Obtains the current location. This API uses a promise to return the result. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | request | [CurrentLocationRequest](#currentlocationrequest) | No| Location request.| + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<[Location](#location)> | [Location](#location) | NA | Promise used to return the current location.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301200 | Failed to obtain the geographical location. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; + try { + geoLocationManager.getCurrentLocation(requestInfo).then((result) => { + console.log('current location: ' + JSON.stringify(result)); + }) + .catch((error) => { + console.log('promise, getCurrentLocation: error=' + JSON.stringify(error)); + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.getLastLocation + +getLastLocation(): Location + +Obtains the last location. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Location | [Location](#location) | NA | Location information.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301200 |Failed to obtain the geographical location. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + var location = geoLocationManager.getLastLocation(); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.isLocationEnabled + +isLocationEnabled(): boolean + +Checks whether the location service is enabled. + +**System capability**: SystemCapability.Location.Location.Core + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | boolean | boolean | NA | Result indicating whether the location service is enabled.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + var locationEnabled = geoLocationManager.isLocationEnabled(); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.requestEnableLocation + +requestEnableLocation(callback: AsyncCallback<boolean>): void + +Requests to enable the location service. This API uses an asynchronous callback to return the result. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<boolean> | Yes| Callback used to return the result. The value **true** indicates that the user agrees to enable the location service, and the value **false** indicates the opposite.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301700 | No response to the request. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.requestEnableLocation((err, data) => { + if (err) { + console.log('requestEnableLocation: err=' + JSON.stringify(err)); + } + if (data) { + console.log('requestEnableLocation: data=' + JSON.stringify(data)); + } + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.requestEnableLocation + +requestEnableLocation(): Promise<boolean> + +Requests to enable the location service. This API uses a promise to return the result. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<boolean> | boolean | NA | Promise used to return the result. The value **true** indicates that the user agrees to enable the location service, and the value **false** indicates the opposite.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301700 | No response to the request. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.requestEnableLocation().then((result) => { + console.log('promise, requestEnableLocation: ' + JSON.stringify(result)); + }) + .catch((error) => { + console.log('promise, requestEnableLocation: error=' + JSON.stringify(error)); + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.enableLocation + +enableLocation(callback: AsyncCallback<void>): void; + +Enables the location service. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | Yes| Callback used to return the error message.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.enableLocation((err, data) => { + if (err) { + console.log('enableLocation: err=' + JSON.stringify(err)); + } + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.enableLocation + +enableLocation(): Promise<void> + +Enables the location service. This API uses a promise to return the result. + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS + +**System capability**: SystemCapability.Location.Location.Core + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<void> | void | NA | Promise used to return the error message.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.enableLocation().then((result) => { + console.log('promise, enableLocation succeed'); + }) + .catch((error) => { + console.log('promise, enableLocation: error=' + JSON.stringify(error)); + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + +## geoLocationManager.disableLocation + +disableLocation(): void; + +Disables the location service. + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS + +**System capability**: SystemCapability.Location.Location.Core + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.disableLocation(); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + + +## geoLocationManager.getAddressesFromLocation + +getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void + +Converts coordinates into geographic description through reverse geocoding. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Location.Location.Geocoder + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | request | [ReverseGeoCodeRequest](#reversegeocoderequest) | Yes| Reverse geocoding request.| + | callback | AsyncCallback<Array<[GeoAddress](#geoaddress)>> | Yes| Callback used to return the reverse geocoding result.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301300 | Reverse geocoding query failed. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; + try { + geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { + if (err) { + console.log('getAddressesFromLocation: err=' + JSON.stringify(err)); + } + if (data) { + console.log('getAddressesFromLocation: data=' + JSON.stringify(data)); + } + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.getAddressesFromLocation + +getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise<Array<GeoAddress>>; + +Converts coordinates into geographic description through reverse geocoding. This API uses a promise to return the result. + +**System capability**: SystemCapability.Location.Location.Geocoder + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | request | [ReverseGeoCodeRequest](#reversegeocoderequest) | Yes| Reverse geocoding request.| + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<Array<[GeoAddress](#geoaddress)>> | Array<[GeoAddress](#geoaddress)> | NA | Promise used to return the reverse geocoding result.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301300 | Reverse geocoding query failed. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; + try { + geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest).then((data) => { + console.log('getAddressesFromLocation: ' + JSON.stringify(data)); + }) + .catch((error) => { + console.log('promise, getAddressesFromLocation: error=' + JSON.stringify(error)); + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.getAddressesFromLocationName + +getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void + +Converts geographic description into coordinates through geocoding. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Location.Location.Geocoder + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | request | [GeoCodeRequest](#geocoderequest) | Yes| Geocoding request.| + | callback | AsyncCallback<Array<[GeoAddress](#geoaddress)>> | Yes| Callback used to return the geocoding result.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301400 | Geocoding query failed. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; + try { + geoLocationManager.getAddressesFromLocationName(geocodeRequest, (err, data) => { + if (err) { + console.log('getAddressesFromLocationName: err=' + JSON.stringify(err)); + } + if (data) { + console.log('getAddressesFromLocationName: data=' + JSON.stringify(data)); + } + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.getAddressesFromLocationName + +getAddressesFromLocationName(request: GeoCodeRequest): Promise<Array<GeoAddress>> + +Converts geographic description into coordinates through geocoding. This API uses a promise to return the result. + +**System capability**: SystemCapability.Location.Location.Geocoder + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | request | [GeoCodeRequest](#geocoderequest) | Yes| Geocoding request.| + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<Array<[GeoAddress](#geoaddress)>> | Array<[GeoAddress](#geoaddress)> | NA | Promise used to return the geocoding result.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301400 | Geocoding query failed. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; + try { + geoLocationManager.getAddressesFromLocationName(geocodeRequest).then((result) => { + console.log('getAddressesFromLocationName: ' + JSON.stringify(result)); + }) + .catch((error) => { + console.log('promise, getAddressesFromLocationName: error=' + JSON.stringify(error)); + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + +## geoLocationManager.isGeocoderAvailable + +isGeocoderAvailable(): boolean; + +Obtains the (reverse) geocoding service status. + +**System capability**: SystemCapability.Location.Location.Geocoder + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | boolean | boolean | NA | Result indicating whether the (reverse) geocoding service is available.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + var isAvailable = geoLocationManager.isGeocoderAvailable(); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.getCachedGnssLocationsSize + +getCachedGnssLocationsSize(callback: AsyncCallback<number>): void; + +Obtains the number of cached GNSS locations. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<number> | Yes| Callback used to return the number of cached GNSS locations. | + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.getCachedGnssLocationsSize((err, size) => { + if (err) { + console.log('getCachedGnssLocationsSize: err=' + JSON.stringify(err)); + } + if (size) { + console.log('getCachedGnssLocationsSize: size=' + JSON.stringify(size)); + } + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.getCachedGnssLocationsSize + +getCachedGnssLocationsSize(): Promise<number>; + +Obtains the number of cached GNSS locations. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<number> | number | NA | Promise used to return the number of cached GNSS locations.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.getCachedGnssLocationsSize().then((result) => { + console.log('promise, getCachedGnssLocationsSize: ' + JSON.stringify(result)); + }) + .catch((error) => { + console.log('promise, getCachedGnssLocationsSize: error=' + JSON.stringify(error)); + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.flushCachedGnssLocations + +flushCachedGnssLocations(callback: AsyncCallback<void>): void; + +Obtains all cached GNSS locations and clears the GNSS cache queue. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | Yes| Callback used to return the error message.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301200 | Failed to obtain the geographical location. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.flushCachedGnssLocations((err, result) => { + if (err) { + console.log('flushCachedGnssLocations: err=' + JSON.stringify(err)); + } + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.flushCachedGnssLocations + +flushCachedGnssLocations(): Promise<void>; + +Obtains all cached GNSS locations and clears the GNSS cache queue. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<void> | void | NA | Promise used to return the error code.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301200 | Failed to obtain the geographical location. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.flushCachedGnssLocations().then((result) => { + console.log('promise, flushCachedGnssLocations success'); + }) + .catch((error) => { + console.log('promise, flushCachedGnssLocations: error=' + JSON.stringify(error)); + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.sendCommand + +sendCommand(command: LocationCommand, callback: AsyncCallback<void>): void; + +Sends an extended command to the location subsystem. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | command | [LocationCommand](#locationcommand) | Yes| Extended command (string) to be sent.| + | callback | AsyncCallback<void> | Yes| Callback used to return the error code.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var requestInfo = {'scenario': 0x301, 'command': "command_1"}; + try { + geoLocationManager.sendCommand(requestInfo, (err, result) => { + if (err) { + console.log('sendCommand: err=' + JSON.stringify(err)); + } + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.sendCommand + +sendCommand(command: LocationCommand): Promise<void>; + +Sends an extended command to the location subsystem. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | command | [LocationCommand](#locationcommand) | Yes| Extended command (string) to be sent.| + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<void> | void | NA | Promise used to return the error code.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var requestInfo = {'scenario': 0x301, 'command': "command_1"}; + try { + geoLocationManager.sendCommand(requestInfo).then((result) => { + console.log('promise, sendCommand success'); + }) + .catch((error) => { + console.log('promise, sendCommand: error=' + JSON.stringify(error)); + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.getCountryCode + +getCountryCode(callback: AsyncCallback<CountryCode>): void; + +Obtains the current country code. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[CountryCode](#countrycode)> | Yes| Callback used to return the country code.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301500 | Failed to query the area information.| + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.getCountryCode((err, result) => { + if (err) { + console.log('getCountryCode: err=' + JSON.stringify(err)); + } + if (result) { + console.log('getCountryCode: result=' + JSON.stringify(result)); + } + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.getCountryCode + +getCountryCode(): Promise<CountryCode>; + +Obtains the current country code. + +**System capability**: SystemCapability.Location.Location.Core + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<[CountryCode](#countrycode)> | [CountryCode](#countrycode) | NA | Promise used to return the country code.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301500 | Failed to query the area information.| + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.getCountryCode() + .then((result) => { + console.log('promise, getCountryCode: result=' + JSON.stringify(result)); + }) + .catch((error) => { + console.log('promise, getCountryCode: error=' + JSON.stringify(error)); + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.enableLocationMock + +enableLocationMock(): void; + +Enables the mock location function. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off.| + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.enableLocationMock(); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.disableLocationMock + +disableLocationMock(): void; + +Disables the mock location function. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off.| + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.disableLocationMock(); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.setMockedLocations + +setMockedLocations(config: LocationMockConfig): void; + +Sets the mock location information. The mock locations will be reported at the interval specified in this API. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | config | [LocationMockConfig](#locationmockconfig) | Yes| Mock location information, including the interval for reporting the mock locations and the array of the mock locations.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off.| + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var locations = [ + {"latitude": 30.12, "longitude": 120.11, "altitude": 123, "accuracy": 1, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 1000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 31.13, "longitude": 121.11, "altitude": 123, "accuracy": 2, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 2000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 32.14, "longitude": 122.11, "altitude": 123, "accuracy": 3, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 3000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 33.15, "longitude": 123.11, "altitude": 123, "accuracy": 4, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 4000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 34.16, "longitude": 124.11, "altitude": 123, "accuracy": 5, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 5000000000, "additionSize": 0, "isFromMock": true} + ]; + var config = {"timeInterval": 5, "locations": locations}; + try { + geoLocationManager.setMockedLocations(config); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.enableReverseGeocodingMock + +enableReverseGeocodingMock(): void; + +Enables the mock reverse geocoding function. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.enableReverseGeocodingMock(); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.disableReverseGeocodingMock + +disableReverseGeocodingMock(): void; + +Disables the mock geocoding function. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.disableReverseGeocodingMock(); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.setReverseGeocodingMockInfo + +setReverseGeocodingMockInfo(mockInfos: Array<ReverseGeocodingMockInfo>): void; + +Sets information of the mock reverse geocoding function, including the mapping between a location and geographical name. If the location is contained in the configurations during reverse geocoding query, the corresponding geographical name will be returned. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | mockInfos | Array<[ReverseGeocodingMockInfo](#reversegeocodingmockinfo)> | Yes| Array of information of the mock reverse geocoding function, including a location and a geographical name.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var mockInfos = [ + {"location": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1, "isFromMock": true}}, + ]; + try { + geoLocationManager.setReverseGeocodingMockInfo(mockInfos); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.isLocationPrivacyConfirmed + +isLocationPrivacyConfirmed(type: LocationPrivacyType): boolean; + +Checks whether a user agrees with the privacy statement of the location service. This API can only be called by system applications. + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | [LocationPrivacyType](#locationprivacytype)| Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when the location service is enabled.| + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | boolean | boolean | NA | Callback used to return the result, which indicates whether the user agrees with the privacy statement.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + var isConfirmed = geoLocationManager.isLocationPrivacyConfirmed(1); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.setLocationPrivacyConfirmStatus + +setLocationPrivacyConfirmStatus(type: LocationPrivacyType, isConfirmed: boolean): void; + +Sets the user confirmation status for the privacy statement of the location service. This API can only be called by system applications. + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | [LocationPrivacyType](#locationprivacytype) | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when the location service is enabled.| + | isConfirmed | boolean | Yes| Callback used to return the result, which indicates whether the user agrees with the privacy statement.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.setLocationPrivacyConfirmStatus(1, true); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## LocationRequestPriority + +Sets the priority of the location request. + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Value| Description| +| -------- | -------- | -------- | +| UNSET | 0x200 | Priority unspecified.| +| ACCURACY | 0x201 | Location accuracy.| +| LOW_POWER | 0x202 | Power efficiency.| +| FIRST_FIX | 0x203 | Fast location. Use this option if you want to obtain a location as fast as possible.| + + +## LocationRequestScenario + + Sets the scenario of the location request. + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Value| Description| +| -------- | -------- | -------- | +| UNSET | 0x300 | Scenario unspecified.| +| NAVIGATION | 0x301 | Navigation.| +| TRAJECTORY_TRACKING | 0x302 | Trajectory tracking.| +| CAR_HAILING | 0x303 | Ride hailing.| +| DAILY_LIFE_SERVICE | 0x304 | Daily life services.| +| NO_POWER | 0x305 | Power efficiency. Your application does not proactively start the location service. When responding to another application requesting the same location service, the system marks a copy of the location result to your application. In this way, your application will not consume extra power for obtaining the user location.| + + +## ReverseGeoCodeRequest + +Defines a reverse geocoding request. + +**System capability**: SystemCapability.Location.Location.Geocoder + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| locale | string | Yes| Yes| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| latitude | number | Yes| Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude | number | Yes| Yes| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| +| maxItems | number | Yes| Yes| Maximum number of location records to be returned.| + + +## GeoCodeRequest + +Defines a geocoding request. + +**System capability**: SystemCapability.Location.Location.Geocoder + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| locale | string | Yes| Yes| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| description | string | Yes| Yes| Location description, for example, **No. xx, xx Road, Pudong New District, Shanghai**.| +| maxItems | number | Yes| Yes| Maximum number of location records to be returned.| +| minLatitude | number | Yes| Yes| Minimum latitude. This parameter is used with **minLongitude**, **maxLatitude**, and **maxLongitude** to specify the latitude and longitude ranges.| +| minLongitude | number | Yes| Yes| Minimum longitude.| +| maxLatitude | number | Yes| Yes| Maximum latitude.| +| maxLongitude | number | Yes| Yes| Maximum longitude.| + + +## GeoAddress + +Defines a geographic location. + +**System capability**: SystemCapability.Location.Location.Geocoder + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| latitude | number | Yes| No | Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude | number | Yes| No | Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| +| locale | string | Yes| No | Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| placeName | string | Yes| No | Landmark of the location.| +| countryCode | string | Yes| No | Country code.| +| countryName | string| Yes| No| Country name.| +| administrativeArea | string | Yes| No| Administrative region name.| +| subAdministrativeArea | string | Yes| No| Sub-administrative region name.| +| locality | string | Yes| No| Locality information.| +| subLocality | string | Yes| No| Sub-locality information.| +| roadName | string | Yes| No|Road name.| +| subRoadName | string | Yes| No| Auxiliary road information.| +| premises | string| Yes| No|House information.| +| postalCode | string | Yes| No| Postal code.| +| phoneNumber | string | Yes| No| Phone number.| +| addressUrl | string | Yes| No| Website URL.| +| descriptions | Array<string> | Yes| No| Additional descriptions.| +| descriptionsSize | number | Yes| No| Total number of additional descriptions.| +| isFromMock | Boolean | Yes| No| Whether the geographical name is from the mock reverse geocoding function.| + + +## LocationRequest + +Defines a location request. + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | Yes| Yes| Priority of the location request.| +| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes| Scenario of the location request.| +| timeInterval | number | Yes| Yes| Time interval at which location information is reported.| +| distanceInterval | number | Yes| Yes| Distance interval at which location information is reported.| +| maxAccuracy | number | Yes| Yes| Location accuracy. This parameter is valid only when the precise location function is enabled, and is invalid when the approximate location function is enabled.| + + +## CurrentLocationRequest + +Defines the current location request. + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | Yes| Yes| Priority of the location request.| +| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes| Scenario of the location request.| +| maxAccuracy | number | Yes| Yes| Location accuracy, in meters. This parameter is valid only when the precise location function is enabled, and is invalid when the approximate location function is enabled.| +| timeoutMs | number | Yes| Yes| Timeout duration, in milliseconds. The minimum value is **1000**.| + + +## SatelliteStatusInfo + +Defines the satellite status information. + +**System capability**: SystemCapability.Location.Location.Gnss + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| satellitesNumber | number | Yes| No| Number of satellites.| +| satelliteIds | Array<number> | Yes| No| Array of satellite IDs.| +| carrierToNoiseDensitys | Array<number> | Yes| No| Carrier-to-noise density ratio, that is, **cn0**.| +| altitudes | Array<number> | Yes| No| Altitude information.| +| azimuths | Array<number> | Yes| No| Azimuth information.| +| carrierFrequencies | Array<number> | Yes| No| Carrier frequency.| + + +## CachedGnssLocationsRequest + +Represents a request for reporting cached GNSS locations. + +**System capability**: SystemCapability.Location.Location.Gnss + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| reportingPeriodSec | number | Yes| Yes| Interval for reporting the cached GNSS locations, in milliseconds.| +| wakeUpCacheQueueFull | boolean | Yes| Yes | **true**: reports the cached GNSS locations to the application when the cache queue is full.
**false**: discards the cached GNSS locations when the cache queue is full.| + + +## Geofence + +Defines a GNSS geofence. Currently, only circular geofences are supported. + +**System capability**: SystemCapability.Location.Location.Geofence + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| latitude | number | Yes| Yes|Latitude information.| +| longitude | number | Yes|Yes| Longitude information.| +| radius | number | Yes|Yes| Radius of a circular geofence.| +| expiration | number | Yes|Yes| Expiration period of a geofence, in milliseconds.| + + +## GeofenceRequest + +Represents a GNSS geofencing request. + +**System capability**: SystemCapability.Location.Location.Geofence + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes | Location scenario.| +| geofence | [Geofence](#geofence)| Yes| Yes | Geofence information.| + + +## LocationPrivacyType + +Defines the privacy statement type. + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Value| Description| +| -------- | -------- | -------- | +| OTHERS | 0 | Other scenarios.| +| STARTUP | 1 | Privacy statement displayed in the startup wizard.| +| CORE_LOCATION | 2 | Privacy statement displayed when enabling the location service.| + + +## LocationCommand + +Defines an extended command. + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes | Location scenario.| +| command | string | Yes| Yes | Extended command, in the string format.| + + +## Location + +Defines a location. + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| latitude | number| Yes| No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude | number| Yes| No| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| +| altitude | number | Yes| No| Location altitude, in meters.| +| accuracy | number | Yes| No| Location accuracy, in meters.| +| speed | number | Yes| No|Speed, in m/s.| +| timeStamp | number | Yes| No| Location timestamp in the UTC format.| +| direction | number | Yes| No| Direction information.| +| timeSinceBoot | number | Yes| No| Location timestamp since boot.| +| additions | Array<string> | Yes| No| Additional description.| +| additionSize | number | Yes| No| Number of additional descriptions.| +| isFromMock | Boolean | Yes| No| Whether the location information is from the mock location function.| + + +## ReverseGeocodingMockInfo + +Represents information of the mock reverse geocoding function. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| location | [ReverseGeoCodeRequest](#reversegeocoderequest) | Yes| Yes| Latitude and longitude information.| +| geoAddress | [GeoAddress](#geoaddress) | Yes| Yes|Geographical name.| + + +## LocationMockConfig + +Represents the information of the mock location function. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| timeInterval | number | Yes| Yes| Interval at which mock locations are reported, in seconds.| +| locations | Array<Location> | Yes| Yes| Array of mocked locations.| + + +## CountryCode + +Represents country code information. + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| country | string | Yes| No| Country code.| +| type | [CountryCodeType](#countrycodetype) | Yes| No| Country code source.| + + +## CountryCodeType + +Represents the country code source type. + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Value| Description| +| -------- | -------- | -------- | +| COUNTRY_CODE_FROM_LOCALE | 1 | Country code obtained from the language configuration of the globalization module.| +| COUNTRY_CODE_FROM_SIM | 2 | Country code obtained from the SIM card.| +| COUNTRY_CODE_FROM_LOCATION | 3 | Country code obtained using the reverse geocoding function based on the user's location information.| +| COUNTRY_CODE_FROM_NETWORK | 4 | Country code obtained from the cellular network registration information.| diff --git a/en/application-dev/reference/apis/js-apis-geolocation.md b/en/application-dev/reference/apis/js-apis-geolocation.md index 92118167ad603189eac98eae73e156a794542f99..8bc027058b6d9bbda89636757219f83827029317 100644 --- a/en/application-dev/reference/apis/js-apis-geolocation.md +++ b/en/application-dev/reference/apis/js-apis-geolocation.md @@ -1,24 +1,56 @@ # Geolocation -Location services provide basic functions such as GNSS positioning, network positioning, geocoding, reverse geocoding, country code and geofencing. +The Geolocation module provides location services such as GNSS positioning, network positioning, geocoding, reverse geocoding, country code and geofencing. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> **NOTE** > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs provided by this module are no longer maintained since API version 9. You are advised to use [geoLocationManager](js-apis-geoLocationManager.md) instead. + +## Applying for Permissions + +Before using basic location capabilities, check whether your application has been granted the permission to access the device location information. If not, your application needs to obtain the permission from the user as described below. + +The system provides the following location permissions: +- ohos.permission.LOCATION + +- ohos.permission.APPROXIMATELY_LOCATION + +- ohos.permission.LOCATION_IN_BACKGROUND + +If your application needs to access the device location information, it must first apply for required permissions. Specifically speaking: + +API versions earlier than 9: Apply for **ohos.permission.LOCATION**. + +API version 9 and later: Apply for **ohos.permission.APPROXIMATELY\_LOCATION**, or apply for **ohos.permission.APPROXIMATELY\_LOCATION** and **ohos.permission.LOCATION**. Note that **ohos.permission.LOCATION** cannot be applied for separately. + +| API Version| Location Permission| Permission Application Result| Location Accuracy| +| -------- | -------- | -------- | -------- | +| Earlier than 9| ohos.permission.LOCATION | Success| Location accurate to meters| +| 9 and later| ohos.permission.LOCATION | Failure| No location obtained| +| 9 and later| ohos.permission.APPROXIMATELY_LOCATION | Success| Location accurate to 5 kilometers| +| 9 and later| ohos.permission.APPROXIMATELY_LOCATION and ohos.permission.LOCATION| Success| Location accurate to meters| + +If your application needs to access the device location information when running in the background, it must be configured to be able to run in the background and be granted the **ohos.permission.LOCATION_IN_BACKGROUND** permission. In this way, the system continues to report device location information after your application moves to the background. + +You can declare the required permission in your application's configuration file. For details, see [Access Control (Permission) Development](../../security/accesstoken-guidelines.md). ## Modules to Import -```js +```ts import geolocation from '@ohos.geolocation'; ``` -## geolocation.on('locationChange') +## geolocation.on('locationChange')(deprecated) on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>): void -Registers a listener for location changes with a location request initiated. +Registers a listener for location changes with a location request initiated. The location result is reported through [LocationRequest](#locationrequest). + +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('locationChange')](js-apis-geoLocationManager.md#geolocationmanageronlocationchange). -**Permission required**: ohos.permission.LOCATION +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core @@ -27,13 +59,14 @@ Registers a listener for location changes with a location request initiated. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **locationChange** indicates a location change event.| - | request | LocationRequest | Yes| Location request.| + | request | [LocationRequest](#locationrequest) | Yes| Location request.| | callback | Callback<[Location](#location)> | Yes| Callback used to return the location change event.| + **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; var locationChange = (location) => { @@ -43,13 +76,16 @@ Registers a listener for location changes with a location request initiated. ``` -## geolocation.off('locationChange') +## geolocation.off('locationChange')(deprecated) off(type: 'locationChange', callback?: Callback<Location>): void Unregisters the listener for location changes with the corresponding location request deleted. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('locationChange')](js-apis-geoLocationManager.md#geolocationmanagerofflocationchange). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core @@ -58,12 +94,12 @@ Unregisters the listener for location changes with the corresponding location re | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **locationChange** indicates a location change event.| - | callback | Callback<[Location](#location)> | No| Callback used to return the location change event.| + | callback | Callback<[Location](#location)> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; var locationChange = (location) => { @@ -74,13 +110,16 @@ Unregisters the listener for location changes with the corresponding location re ``` -## geolocation.on('locationServiceState') +## geolocation.on('locationServiceState')(deprecated) on(type: 'locationServiceState', callback: Callback<boolean>): void Registers a listener for location service status change events. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('locationEnabledChange')](js-apis-geoLocationManager.md#geolocationmanageronlocationenabledchange). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core @@ -93,8 +132,8 @@ Registers a listener for location service status change events. **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var locationServiceState = (state) => { console.log('locationServiceState: ' + JSON.stringify(state)); @@ -103,13 +142,16 @@ Registers a listener for location service status change events. ``` -## geolocation.off('locationServiceState') +## geolocation.off('locationServiceState')(deprecated) off(type: 'locationServiceState', callback?: Callback<boolean>): void; Unregisters the listener for location service status change events. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('locationEnabledChange')](js-apis-geoLocationManager.md#geolocationmanagerofflocationenabledchange). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core @@ -118,12 +160,12 @@ Unregisters the listener for location service status change events. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **locationServiceState** indicates a location service status change event.| - | callback | Callback<boolean> | No| Callback used to return the location service status change event.| + | callback | Callback<boolean> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var locationServiceState = (state) => { console.log('locationServiceState: state: ' + JSON.stringify(state)); @@ -133,13 +175,17 @@ Unregisters the listener for location service status change events. ``` -## geolocation.on('cachedGnssLocationsReporting')8+ +## geolocation.on('cachedGnssLocationsReporting')(deprecated) on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, callback: Callback<Array<Location>>): void; Registers a listener for cached GNSS location reports. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('cachedGnssLocationsChange')](js-apis-geoLocationManager.md#geolocationmanageroncachedgnsslocationschange). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss @@ -148,13 +194,13 @@ Registers a listener for cached GNSS location reports. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **cachedGnssLocationsReporting** indicates reporting of cached GNSS locations.| - | request | CachedGnssLocationsRequest | Yes| Request for reporting cached GNSS location.| - | callback | Callback<boolean> | Yes| Callback used to return cached GNSS locations.| + | request | [CachedGnssLocationsRequest](#cachedgnsslocationsrequest) | Yes| Request for reporting cached GNSS location.| + | callback | Callback<Array<[Location](#location)>> | Yes| Callback used to return cached GNSS locations.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var cachedLocationsCb = (locations) => { console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations)); @@ -164,13 +210,17 @@ Registers a listener for cached GNSS location reports. ``` -## geolocation.off('cachedGnssLocationsReporting')8+ +## geolocation.off('cachedGnssLocationsReporting')(deprecated) off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Location>>): void; Unregisters the listener for cached GNSS location reports. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('cachedGnssLocationsChange')](js-apis-geoLocationManager.md#geolocationmanageroffcachedgnsslocationschange). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss @@ -179,12 +229,12 @@ Unregisters the listener for cached GNSS location reports. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **cachedGnssLocationsReporting** indicates reporting of cached GNSS locations.| - | callback | Callback<boolean> | No| Callback used to return cached GNSS locations.| + | callback | Callback<Array<[Location](#location)>> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var cachedLocationsCb = (locations) => { console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations)); @@ -195,13 +245,17 @@ Unregisters the listener for cached GNSS location reports. ``` -## geolocation.on('gnssStatusChange')8+ +## geolocation.on('gnssStatusChange')(deprecated) on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>): void; Registers a listener for GNSS satellite status change events. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('satelliteStatusChange')](js-apis-geoLocationManager.md#geolocationmanageronsatellitestatuschange). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss @@ -210,12 +264,12 @@ Registers a listener for GNSS satellite status change events. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **gnssStatusChange** indicates a GNSS satellite status change.| - | callback | Callback<SatelliteStatusInfo> | Yes| Callback used to return GNSS satellite status changes.| + | callback | Callback<[SatelliteStatusInfo](#satellitestatusinfo)> | Yes| Callback used to return GNSS satellite status changes.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var gnssStatusCb = (satelliteStatusInfo) => { console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo)); @@ -224,13 +278,17 @@ Registers a listener for GNSS satellite status change events. ``` -## geolocation.off('gnssStatusChange')8+ +## geolocation.off('gnssStatusChange')(deprecated) off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>): void; Unregisters the listener for GNSS satellite status change events. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('satelliteStatusChange')](js-apis-geoLocationManager.md#geolocationmanageroffsatellitestatuschange). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss @@ -239,11 +297,11 @@ Unregisters the listener for GNSS satellite status change events. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **gnssStatusChange** indicates a GNSS satellite status change.| - | callback | Callback<SatelliteStatusInfo> | No| Callback used to return GNSS satellite status changes.| + | callback | Callback<[SatelliteStatusInfo](#satellitestatusinfo)> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var gnssStatusCb = (satelliteStatusInfo) => { console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo)); @@ -253,13 +311,17 @@ Unregisters the listener for GNSS satellite status change events. ``` -## geolocation.on('nmeaMessageChange')8+ +## geolocation.on('nmeaMessageChange')(deprecated) on(type: 'nmeaMessageChange', callback: Callback<string>): void; Registers a listener for GNSS NMEA message change events. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('nmeaMessage')](js-apis-geoLocationManager.md#geolocationmanageronnmeamessage). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss @@ -272,8 +334,8 @@ Registers a listener for GNSS NMEA message change events. **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var nmeaCb = (str) => { console.log('nmeaMessageChange: ' + JSON.stringify(str)); @@ -282,13 +344,17 @@ Registers a listener for GNSS NMEA message change events. ``` -## geolocation.off('nmeaMessageChange')8+ +## geolocation.off('nmeaMessageChange')(deprecated) off(type: 'nmeaMessageChange', callback?: Callback<string>): void; Unregisters the listener for GNSS NMEA message change events. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('nmeaMessage')](js-apis-geoLocationManager.md#geolocationmanageroffnmeamessage). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss @@ -297,12 +363,12 @@ Unregisters the listener for GNSS NMEA message change events. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **nmeaMessageChange** indicates a GNSS NMEA message change.| - | callback | Callback<string> | No| Callback used to return GNSS NMEA message changes.| + | callback | Callback<string> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var nmeaCb = (str) => { console.log('nmeaMessageChange: ' + JSON.stringify(str)); @@ -312,13 +378,17 @@ Unregisters the listener for GNSS NMEA message change events. ``` -## geolocation.on('fenceStatusChange')8+ +## geolocation.on('fenceStatusChange')(deprecated) on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; Registers a listener for status change events of the specified geofence. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('gnssFenceStatusChange')](js-apis-geoLocationManager.md#geolocationmanagerongnssfencestatuschange). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Geofence @@ -327,13 +397,13 @@ Registers a listener for status change events of the specified geofence. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **fenceStatusChange** indicates a geofence status change.| - | request | GeofenceRequest | Yes| Geofencing request.| + | request | [GeofenceRequest](#geofencerequest) | Yes| Geofencing request.| | want | WantAgent | Yes| **WantAgent** used to return geofence (entrance or exit) events.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; import wantAgent from '@ohos.wantAgent'; @@ -357,13 +427,17 @@ Registers a listener for status change events of the specified geofence. ``` -## geolocation.off('fenceStatusChange')8+ +## geolocation.off('fenceStatusChange')(deprecated) off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; Unregisters the listener for status change events of the specified geofence. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('gnssFenceStatusChange')](js-apis-geoLocationManager.md#geolocationmanageroffgnssfencestatuschange). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Geofence @@ -372,12 +446,12 @@ Unregisters the listener for status change events of the specified geofence. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **fenceStatusChange** indicates a geofence status change.| - | request | GeofenceRequest | Yes| Geofencing request.| + | request | [GeofenceRequest](#geofencerequest) | Yes| Geofencing request.| | want | WantAgent | Yes| **WantAgent** used to return geofence (entrance or exit) events.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; import wantAgent from '@ohos.wantAgent'; @@ -402,14 +476,16 @@ Unregisters the listener for status change events of the specified geofence. ``` -## geolocation.getCurrentLocation +## geolocation.getCurrentLocation(deprecated) getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>): void - Obtains the current location. This API uses an asynchronous callback to return the result. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCurrentLocation](js-apis-geoLocationManager.md#geolocationmanagergetcurrentlocation). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core @@ -417,12 +493,12 @@ Obtains the current location. This API uses an asynchronous callback to return t | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | request | [CurrentLocationRequest](#currentlocationrequest) | No| Location request.| + | request | [CurrentLocationRequest](#currentlocationrequest) | Yes| Location request.| | callback | AsyncCallback<[Location](#location)> | Yes| Callback used to return the current location.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; var locationChange = (err, location) => { @@ -434,18 +510,55 @@ Obtains the current location. This API uses an asynchronous callback to return t } }; geolocation.getCurrentLocation(requestInfo, locationChange); + ``` + + +## geolocation.getCurrentLocation(deprecated) + +getCurrentLocation(callback: AsyncCallback<Location>): void + + +Obtains the current location. This API uses an asynchronous callback to return the result. + +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCurrentLocation](js-apis-geoLocationManager.md#geolocationmanagergetcurrentlocation). + +**Required permissions**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[Location](#location)> | Yes| Callback used to return the current location.| + +**Example** + + ```ts + import geolocation from '@ohos.geolocation'; + var locationChange = (err, location) => { + if (err) { + console.log('locationChanger: err=' + JSON.stringify(err)); + } + if (location) { + console.log('locationChanger: location=' + JSON.stringify(location)); + } + }; geolocation.getCurrentLocation(locationChange); ``` -## geolocation.getCurrentLocation +## geolocation.getCurrentLocation(deprecated) getCurrentLocation(request?: CurrentLocationRequest): Promise<Location> - Obtains the current location. This API uses a promise to return the result. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCurrentLocation](js-apis-geoLocationManager.md#geolocationmanagergetcurrentlocation-2). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core @@ -457,14 +570,14 @@ Obtains the current location. This API uses a promise to return the result. **Return value** - | Name| Description| - | -------- | -------- | - | Promise<[Location](#location)> | Promise used to return the current location.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<[Location](#location)> |[Location](#location)|NA| Promise used to return the current location.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; geolocation.getCurrentLocation(requestInfo).then((result) => { @@ -473,13 +586,16 @@ Obtains the current location. This API uses a promise to return the result. ``` -## geolocation.getLastLocation +## geolocation.getLastLocation(deprecated) getLastLocation(callback: AsyncCallback<Location>): void Obtains the previous location. This API uses an asynchronous callback to return the result. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getLastLocation](js-apis-geoLocationManager.md#geolocationmanagergetlastlocation). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core @@ -491,8 +607,8 @@ Obtains the previous location. This API uses an asynchronous callback to return **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.getLastLocation((err, data) => { if (err) { @@ -505,26 +621,29 @@ Obtains the previous location. This API uses an asynchronous callback to return ``` -## geolocation.getLastLocation +## geolocation.getLastLocation(deprecated) getLastLocation(): Promise<Location> Obtains the previous location. This API uses a promise to return the result. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getLastLocation](js-apis-geoLocationManager.md#geolocationmanagergetlastlocation). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core **Return value** - | Name| Description| - | -------- | -------- | - | Promise<[Location](#location)> | Promise used to return the previous location.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<[Location](#location)> | [Location](#location)|NA|Promise used to return the previous location.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.getLastLocation().then((result) => { console.log('getLastLocation: result: ' + JSON.stringify(result)); @@ -532,14 +651,16 @@ Obtains the previous location. This API uses a promise to return the result. ``` -## geolocation.isLocationEnabled +## geolocation.isLocationEnabled(deprecated) isLocationEnabled(callback: AsyncCallback<boolean>): void - Checks whether the location service is enabled. This API uses an asynchronous callback to return the result. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.isLocationEnabled](js-apis-geoLocationManager.md#geolocationmanagerislocationenabled). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core @@ -550,8 +671,8 @@ Checks whether the location service is enabled. This API uses an asynchronous ca | callback | AsyncCallback<boolean> | Yes| Callback used to return the location service status.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.isLocationEnabled((err, data) => { if (err) { @@ -564,25 +685,28 @@ Checks whether the location service is enabled. This API uses an asynchronous ca ``` -## geolocation.isLocationEnabled +## geolocation.isLocationEnabled(deprecated) isLocationEnabled(): Promise<boolean> Checks whether the location service is enabled. This API uses a promise to return the result. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.isLocationEnabled](js-apis-geoLocationManager.md#geolocationmanagerislocationenabled). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core **Return value** - | Name| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the location service status.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<boolean> | boolean|NA|Promise used to return the location service status.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.isLocationEnabled().then((result) => { console.log('promise, isLocationEnabled: ' + JSON.stringify(result)); @@ -590,14 +714,16 @@ Checks whether the location service is enabled. This API uses a promise to retur ``` -## geolocation.requestEnableLocation +## geolocation.requestEnableLocation(deprecated) requestEnableLocation(callback: AsyncCallback<boolean>): void - Requests to enable the location service. This API uses an asynchronous callback to return the result. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.requestEnableLocation](js-apis-geoLocationManager.md#geolocationmanagerrequestenablelocation). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core @@ -608,8 +734,8 @@ Requests to enable the location service. This API uses an asynchronous callback | callback | AsyncCallback<boolean> | Yes| Callback used to return the location service status.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.requestEnableLocation((err, data) => { if (err) { @@ -622,159 +748,45 @@ Requests to enable the location service. This API uses an asynchronous callback ``` -## geolocation.requestEnableLocation +## geolocation.requestEnableLocation(deprecated) requestEnableLocation(): Promise<boolean> Requests to enable the location service. This API uses a promise to return the result. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.requestEnableLocation](js-apis-geoLocationManager.md#geolocationmanagerrequestenablelocation-1). -**System capability**: SystemCapability.Location.Location.Core - -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the location service status.| - -**Example** - - ```js - import geolocation from '@ohos.geolocation'; - geolocation.requestEnableLocation().then((result) => { - console.log('promise, requestEnableLocation: ' + JSON.stringify(result)); - }); - ``` - - -## geolocation.enableLocation - -enableLocation(callback: AsyncCallback<boolean>): void; - -Enables the location service. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API and cannot be called by third-party applications. - -**Permission required**: ohos.permission.MANAGE_SECURE_SETTINGS - -**System capability**: SystemCapability.Location.Location.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes| Callback used to return the location service status.| - -**Example** - - ```js - import geolocation from '@ohos.geolocation'; - geolocation.enableLocation((err, data) => { - if (err) { - console.log('enableLocation: err=' + JSON.stringify(err)); - } - if (data) { - console.log('enableLocation: data=' + JSON.stringify(data)); - } - }); - ``` - - -## geolocation.enableLocation - -enableLocation(): Promise<boolean> - -Enables the location service. This API uses a promise to return the result. - -**System API**: This is a system API and cannot be called by third-party applications. - -**Permission required**: ohos.permission.MANAGE_SECURE_SETTINGS +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core **Return value** - | Name| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the location service status.| - -**Example** - - ```js - import geolocation from '@ohos.geolocation'; - geolocation.enableLocation().then((result) => { - console.log('promise, enableLocation: ' + JSON.stringify(result)); - }); - ``` - -## geolocation.disableLocation - -disableLocation(callback: AsyncCallback<boolean>): void; - -Disables the location service. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API and cannot be called by third-party applications. - -**Permission required**: ohos.permission.MANAGE_SECURE_SETTINGS - -**System capability**: SystemCapability.Location.Location.Core - -**Parameters** - | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes| Callback used to return the location service status.| + | Promise<boolean> | boolean|NA|Promise used to return the location service status.| **Example** - - ```js - import geolocation from '@ohos.geolocation'; - geolocation.disableLocation((err, data) => { - if (err) { - console.log('disableLocation: err=' + JSON.stringify(err)); - } - if (data) { - console.log('disableLocation: data=' + JSON.stringify(data)); - } - }); - ``` - - -## geolocation.disableLocation - -disableLocation(): Promise<boolean> - -Disables the location service. This API uses a promise to return the result. - -**System API**: This is a system API and cannot be called by third-party applications. - -**Permission required**: ohos.permission.MANAGE_SECURE_SETTINGS - -**System capability**: SystemCapability.Location.Location.Core -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the location service status.| - -**Example** - - ```js + ```ts import geolocation from '@ohos.geolocation'; - geolocation.disableLocation().then((result) => { - console.log('promise, disableLocation: ' + JSON.stringify(result)); + geolocation.requestEnableLocation().then((result) => { + console.log('promise, requestEnableLocation: ' + JSON.stringify(result)); }); ``` -## geolocation.isGeoServiceAvailable + +## geolocation.isGeoServiceAvailable(deprecated) isGeoServiceAvailable(callback: AsyncCallback<boolean>): void Checks whether the (reverse) geocoding service is available. This API uses an asynchronous callback to return the result. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.isGeocoderAvailable](js-apis-geoLocationManager.md#geolocationmanagerisgeocoderavailable). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Geocoder @@ -785,8 +797,8 @@ Checks whether the (reverse) geocoding service is available. This API uses an as | callback | AsyncCallback<boolean> | Yes| Callback used to return the (reverse) geocoding service status.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.isGeoServiceAvailable((err, data) => { if (err) { @@ -799,25 +811,28 @@ Checks whether the (reverse) geocoding service is available. This API uses an as ``` -## geolocation.isGeoServiceAvailable +## geolocation.isGeoServiceAvailable(deprecated) isGeoServiceAvailable(): Promise<boolean> Checks whether the (reverse) geocoding service is available. This API uses a promise to return the result. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.isGeocoderAvailable](js-apis-geoLocationManager.md#geolocationmanagerisgeocoderavailable). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Geocoder **Return value** - | Name| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the (reverse) geocoding service status.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<boolean> |boolean|NA| Promise used to return the (reverse) geocoding service status.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.isGeoServiceAvailable().then((result) => { console.log('promise, isGeoServiceAvailable: ' + JSON.stringify(result)); @@ -825,13 +840,16 @@ Checks whether the (reverse) geocoding service is available. This API uses a pro ``` -## geolocation.getAddressesFromLocation +## geolocation.getAddressesFromLocation(deprecated) getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void Converts coordinates into geographic description through reverse geocoding. This API uses an asynchronous callback to return the result. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getAddressesFromLocation](js-apis-geoLocationManager.md#geolocationmanagergetaddressesfromlocation). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Geocoder @@ -843,8 +861,8 @@ Converts coordinates into geographic description through reverse geocoding. This | callback | AsyncCallback<Array<[GeoAddress](#geoaddress)>> | Yes| Callback used to return the reverse geocoding result.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; geolocation.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { @@ -858,13 +876,16 @@ Converts coordinates into geographic description through reverse geocoding. This ``` -## geolocation.getAddressesFromLocation +## geolocation.getAddressesFromLocation(deprecated) getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise<Array<GeoAddress>>; Converts coordinates into geographic description through reverse geocoding. This API uses a promise to return the result. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getAddressesFromLocation](js-apis-geoLocationManager.md#geolocationmanagergetaddressesfromlocation-1). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Geocoder @@ -876,13 +897,13 @@ Converts coordinates into geographic description through reverse geocoding. This **Return value** - | Name| Description| - | -------- | -------- | - | Promise<Array<[GeoAddress](#geoaddress)>> | Promise used to return the reverse geocoding result.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<Array<[GeoAddress](#geoaddress)>> | Array<[GeoAddress](#geoaddress)>|NA|Promise used to return the reverse geocoding result.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; geolocation.getAddressesFromLocation(reverseGeocodeRequest).then((data) => { @@ -891,13 +912,16 @@ Converts coordinates into geographic description through reverse geocoding. This ``` -## geolocation.getAddressesFromLocationName +## geolocation.getAddressesFromLocationName(deprecated) getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void Converts geographic description into coordinates through geocoding. This API uses an asynchronous callback to return the result. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getAddressesFromLocationName](js-apis-geoLocationManager.md#geolocationmanagergetaddressesfromlocationname). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Geocoder @@ -909,8 +933,8 @@ Converts geographic description into coordinates through geocoding. This API use | callback | AsyncCallback<Array<[GeoAddress](#geoaddress)>> | Yes| Callback used to return the geocoding result.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; geolocation.getAddressesFromLocationName(geocodeRequest, (err, data) => { @@ -924,13 +948,16 @@ Converts geographic description into coordinates through geocoding. This API use ``` -## geolocation.getAddressesFromLocationName +## geolocation.getAddressesFromLocationName(deprecated) getAddressesFromLocationName(request: GeoCodeRequest): Promise<Array<GeoAddress>> Converts geographic description into coordinates through geocoding. This API uses a promise to return the result. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getAddressesFromLocationName](js-apis-geoLocationManager.md#geolocationmanagergetaddressesfromlocationname-1). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Geocoder @@ -942,13 +969,13 @@ Converts geographic description into coordinates through geocoding. This API use **Return value** - | Name| Description| - | -------- | -------- | - | Promise<Array<[GeoAddress](#geoaddress)>> | Callback used to return the geocoding result.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<Array<[GeoAddress](#geoaddress)>> | Array<[GeoAddress](#geoaddress)>|NA|Callback used to return the geocoding result.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; geolocation.getAddressesFromLocationName(geocodeRequest).then((result) => { @@ -957,13 +984,17 @@ Converts geographic description into coordinates through geocoding. This API use ``` -## geolocation.getCachedGnssLocationsSize8+ +## geolocation.getCachedGnssLocationsSize(deprecated) getCachedGnssLocationsSize(callback: AsyncCallback<number>): void; Obtains the number of cached GNSS locations. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCachedGnssLocationsSize](js-apis-geoLocationManager.md#geolocationmanagergetcachedgnsslocationssize). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss @@ -974,8 +1005,8 @@ Obtains the number of cached GNSS locations. | callback | AsyncCallback<number> | Yes| Callback used to return the number of cached GNSS locations. | **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.getCachedGnssLocationsSize((err, size) => { if (err) { @@ -988,25 +1019,29 @@ Obtains the number of cached GNSS locations. ``` -## geolocation.getCachedGnssLocationsSize8+ +## geolocation.getCachedGnssLocationsSize(deprecated) getCachedGnssLocationsSize(): Promise<number>; Obtains the number of cached GNSS locations. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCachedGnssLocationsSize](js-apis-geoLocationManager.md#geolocationmanagergetcachedgnsslocationssize-1). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss **Return value** - | Name| Description| - | -------- | -------- | - | Promise<number> | Promise used to return the number of cached GNSS locations.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<number> | number|NA|Promise used to return the number of cached GNSS locations.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.getCachedGnssLocationsSize().then((result) => { console.log('promise, getCachedGnssLocationsSize: ' + JSON.stringify(result)); @@ -1014,13 +1049,17 @@ Obtains the number of cached GNSS locations. ``` -## geolocation.flushCachedGnssLocations8+ +## geolocation.flushCachedGnssLocations(deprecated) flushCachedGnssLocations(callback: AsyncCallback<boolean>): void; Obtains all cached GNSS locations and clears the GNSS cache queue. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.flushCachedGnssLocations](js-apis-geoLocationManager.md#geolocationmanagerflushcachedgnsslocations). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss @@ -1031,8 +1070,8 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. | callback | AsyncCallback<boolean> | Yes| Callback used to return the operation result.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.flushCachedGnssLocations((err, result) => { if (err) { @@ -1045,25 +1084,29 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. ``` -## geolocation.flushCachedGnssLocations8+ +## geolocation.flushCachedGnssLocations(deprecated) flushCachedGnssLocations(): Promise<boolean>; Obtains all cached GNSS locations and clears the GNSS cache queue. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.flushCachedGnssLocations](js-apis-geoLocationManager.md#geolocationmanagerflushcachedgnsslocations-1). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss **Return value** - | Name| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the operation result.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<boolean> |boolean|NA| Promise used to return the operation result.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.flushCachedGnssLocations().then((result) => { console.log('promise, flushCachedGnssLocations: ' + JSON.stringify(result)); @@ -1071,13 +1114,17 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. ``` -## geolocation.sendCommand8+ +## geolocation.sendCommand(deprecated) sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>): void; -Sends an extended command to the location subsystem. This API can only be called by system applications. +Sends an extended command to the location subsystem. + +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.sendCommand](js-apis-geoLocationManager.md#geolocationmanagersendcommand). -**Permission required**: ohos.permission.LOCATION +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core @@ -1085,12 +1132,12 @@ Sends an extended command to the location subsystem. This API can only be called | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | command | LocationCommand | Yes| Extended command (string) to be sent.| + | command | [LocationCommand](#locationcommand) | Yes| Extended command (string) to be sent.| | callback | AsyncCallback<boolean> | Yes| Callback used to return the operation result.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var requestInfo = {'scenario': 0x301, 'command': "command_1"}; geolocation.sendCommand(requestInfo, (err, result) => { @@ -1104,13 +1151,17 @@ Sends an extended command to the location subsystem. This API can only be called ``` -## geolocation.sendCommand8+ +## geolocation.sendCommand(deprecated) sendCommand(command: LocationCommand): Promise<boolean>; -Sends an extended command to the location subsystem. This API can only be called by system applications. +Sends an extended command to the location subsystem. + +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.sendCommand](js-apis-geoLocationManager.md#geolocationmanagersendcommand). -**Permission required**: ohos.permission.LOCATION +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core @@ -1118,17 +1169,17 @@ Sends an extended command to the location subsystem. This API can only be called | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | command | LocationCommand | Yes| Extended command (string) to be sent.| + | command | [LocationCommand](#locationcommand) | Yes| Extended command (string) to be sent.| **Return value** - | Name| Description| - | -------- | -------- | - | Promise<boolean> | Callback used to return the operation result.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<boolean> |boolean|NA| Callback used to return the operation result.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var requestInfo = {'scenario': 0x301, 'command': "command_1"}; geolocation.sendCommand(requestInfo).then((result) => { @@ -1137,15 +1188,18 @@ Sends an extended command to the location subsystem. This API can only be called ``` -## LocationRequestPriority +## LocationRequestPriority(deprecated) Sets the priority of the location request. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.LocationRequestPriority](js-apis-geoLocationManager.md#locationrequestpriority). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | UNSET | 0x200 | Priority unspecified.| | ACCURACY | 0x201 | Location accuracy.| @@ -1153,15 +1207,18 @@ Sets the priority of the location request. | FIRST_FIX | 0x203 | Fast location. Use this option if you want to obtain a location as fast as possible.| -## LocationRequestScenario +## LocationRequestScenario(deprecated) Sets the scenario of the location request. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.LocationRequestScenario](js-apis-geoLocationManager.md#locationrequestscenario). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | UNSET | 0x300 | Scenario unspecified.| | NAVIGATION | 0x301 | Navigation.| @@ -1171,15 +1228,18 @@ Sets the priority of the location request. | NO_POWER | 0x305 | Power efficiency. Your application does not proactively start the location service. When responding to another application requesting the same location service, the system marks a copy of the location result to your application. In this way, your application will not consume extra power for obtaining the user location.| -## GeoLocationErrorCode +## GeoLocationErrorCode(deprecated) Enumerates error codes of the location service. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | INPUT_PARAMS_ERROR7+ | 101 | Incorrect input parameters.| | REVERSE_GEOCODE_ERROR7+ | 102 | Failed to call the reverse geocoding API.| @@ -1190,213 +1250,255 @@ Enumerates error codes of the location service. | LOCATION_REQUEST_TIMEOUT_ERROR7+ | 107 | Failed to obtain the location within the specified time.| -## ReverseGeoCodeRequest +## ReverseGeoCodeRequest(deprecated) Defines a reverse geocoding request. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.ReverseGeoCodeRequest](js-apis-geoLocationManager.md#reversegeocoderequest). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Geocoder -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| locale | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| -| latitude | number | Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| -| longitude | number | Yes| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| -| maxItems | number | No| Maximum number of location records to be returned.| +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| locale | string | Yes| Yes| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| latitude | number | Yes| Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude | number | Yes| Yes| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| +| maxItems | number | Yes| Yes| Maximum number of location records to be returned.| -## GeoCodeRequest +## GeoCodeRequest(deprecated) Defines a geocoding request. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.GeoCodeRequest](js-apis-geoLocationManager.md#geocoderequest). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Geocoder -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| locale | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| -| description | number | Yes| Location description, for example, No. xx, xx Road, Pudong New District, Shanghai.| -| maxItems | number | No| Maximum number of location records to be returned.| -| minLatitude | number | No| Minimum latitude. This parameter is used with minLongitude, maxLatitude, and maxLongitude to specify the latitude and longitude ranges.| -| minLongitude | number | No| Minimum longitude.| -| maxLatitude | number | No| Maximum latitude.| -| maxLongitude | number | No| Maximum longitude.| +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| locale | string | Yes| Yes| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| description | string | Yes| Yes| Location description, for example, **No. xx, xx Road, Pudong New District, Shanghai**.| +| maxItems | number | Yes| Yes| Maximum number of location records to be returned.| +| minLatitude | number | Yes| Yes| Minimum latitude. This parameter is used with **minLongitude**, **maxLatitude**, and **maxLongitude** to specify the latitude and longitude ranges.| +| minLongitude | number | Yes| Yes| Minimum longitude.| +| maxLatitude | number | Yes| Yes| Maximum latitude.| +| maxLongitude | number | Yes| Yes| Maximum longitude.| -## GeoAddress +## GeoAddress(deprecated) Defines a geographic location. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.GeoAddress](js-apis-geoLocationManager.md#geoaddress). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Geocoder -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| latitude7+ | number | No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| -| longitude7+ | number | No| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| -| locale7+ | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| -| placeName7+ | string | No| Landmark of the location.| -| countryCode7+ | string | No| Country code.| -| countryName7+ | string | No| Country name.| -| administrativeArea7+ | string | No| Administrative region name.| -| subAdministrativeArea7+ | string | No| Sub-administrative region name.| -| locality7+ | string | No| Locality information. | -| subLocality7+ | string | No| Sub-locality information. | -| roadName7+ | string | No| Road name.| -| subRoadName7+ | string | No| Auxiliary road information.| -| premises7+ | string | No| House information.| -| postalCode7+ | string | No| Postal code.| -| phoneNumber7+ | string | No| Phone number.| -| addressUrl7+ | string | No| Website URL.| -| descriptions7+ | Array<string> | No| Additional description.| -| descriptionsSize7+ | number | No| Total number of additional descriptions.| - - -## LocationRequest +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| latitude7+ | number | Yes| No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude7+ | number | Yes| No| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| +| locale7+ | string | Yes| No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| placeName7+ | string | Yes| No| Landmark of the location.| +| countryCode7+ | string | Yes| No| Country code.| +| countryName7+ | string | Yes| No| Country name.| +| administrativeArea7+ | string | Yes| No| Administrative region name.| +| subAdministrativeArea7+ | string | Yes| No| Sub-administrative region name.| +| locality7+ | string | Yes| No| Locality information.| +| subLocality7+ | string | Yes| No| Sub-locality information.| +| roadName7+ | string | Yes| No| Road name.| +| subRoadName7+ | string | Yes| No| Auxiliary road information.| +| premises7+ | string | Yes| No| House information.| +| postalCode7+ | string | Yes| No| Postal code.| +| phoneNumber7+ | string | Yes| No| Phone number.| +| addressUrl7+ | string | Yes| No| Website URL.| +| descriptions7+ | Array<string> | Yes| No| Additional descriptions.| +| descriptionsSize7+ | number | Yes| No| Total number of additional descriptions.| + + +## LocationRequest(deprecated) Defines a location request. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.LocationRequest](js-apis-geoLocationManager.md#locationrequest). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| priority | [LocationRequestPriority](#locationrequestpriority) | No| Priority of the location request.| -| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Scenario of the location request.| -| timeInterval | number | No| Time interval at which location information is reported.| -| distanceInterval | number | No| Distance interval at which location information is reported.| -| maxAccuracy | number | No| Location accuracy.| +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | Yes| Yes| Priority of the location request.| +| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes| Scenario of the location request.| +| timeInterval | number | Yes| Yes| Time interval at which location information is reported.| +| distanceInterval | number | Yes| Yes| Distance interval at which location information is reported.| +| maxAccuracy | number | Yes| Yes| Location accuracy. This parameter is valid only when the precise location function is enabled, and is invalid when the approximate location function is enabled.| -## CurrentLocationRequest +## CurrentLocationRequest(deprecated) Defines the current location request. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.CurrentLocationRequest](js-apis-geoLocationManager.md#currentlocationrequest). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| priority | [LocationRequestPriority](#locationrequestpriority) | No| Priority of the location request.| -| scenario | [LocationRequestScenario](#locationrequestscenario) | No| Scenario of the location request.| -| maxAccuracy | number | No| Location accuracy, in meters.| -| timeoutMs | number | No| Timeout duration, in milliseconds. The minimum value is 1000.| +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | Yes| Yes| Priority of the location request.| +| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes| Scenario of the location request.| +| maxAccuracy | number | Yes| Yes| Location accuracy, in meters. This parameter is valid only when the precise location function is enabled, and is invalid when the approximate location function is enabled.| +| timeoutMs | number | Yes| Yes| Timeout duration, in milliseconds. The minimum value is **1000**.| -## SatelliteStatusInfo8+ +## SatelliteStatusInfo(deprecated) Defines the satellite status information. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.SatelliteStatusInfo](js-apis-geoLocationManager.md#satellitestatusinfo). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| satellitesNumber | number | Yes| Number of satellites.| -| satelliteIds | Array<number> | Yes| Array of satellite IDs.| -| carrierToNoiseDensitys | Array<number> | Yes| Carrier-to-noise density ratio, that is, **cn0**.| -| altitudes | Array<number> | Yes| Altitude information.| -| azimuths | Array<number> | Yes| Azimuth information.| -| carrierFrequencies | Array<number> | Yes| Carrier frequency.| +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| satellitesNumber | number | Yes| No| Number of satellites.| +| satelliteIds | Array<number> | Yes| No| Array of satellite IDs.| +| carrierToNoiseDensitys | Array<number> | Yes| No| Carrier-to-noise density ratio, that is, **cn0**.| +| altitudes | Array<number> | Yes| No| Altitude information.| +| azimuths | Array<number> | Yes| No| Azimuth information.| +| carrierFrequencies | Array<number> | Yes| No| Carrier frequency.| -## CachedGnssLocationsRequest8+ +## CachedGnssLocationsRequest(deprecated) Represents a request for reporting cached GNSS locations. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.CachedGnssLocationsRequest](js-apis-geoLocationManager.md#cachedgnsslocationsrequest). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| reportingPeriodSec | number | Yes| Interval for reporting the cached GNSS locations, in milliseconds.| -| wakeUpCacheQueueFull | boolean | Yes| **true**: reports the cached GNSS locations to the application when the cache queue is full.
**false**: discards the cached GNSS locations when the cache queue is full.| +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| reportingPeriodSec | number | Yes| Yes| Interval for reporting the cached GNSS locations, in milliseconds.| +| wakeUpCacheQueueFull | boolean | Yes| Yes | **true**: reports the cached GNSS locations to the application when the cache queue is full.
**false**: discards the cached GNSS locations when the cache queue is full.| -## Geofence8+ +## Geofence(deprecated) Defines a GNSS geofence. Currently, only circular geofences are supported. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.Geofence](js-apis-geoLocationManager.md#geofence). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Geofence -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| latitude | number | Yes| Latitude information.| -| longitude | number | Yes| Longitude information.| -| radius | number | Yes| Radius of a circular geofence.| -| expiration | number | Yes| Expiration period of a geofence, in milliseconds.| +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| latitude | number | Yes| Yes | Latitude information.| +| longitude | number | Yes| Yes | Longitude information.| +| radius | number | Yes| Yes | Radius of a circular geofence.| +| expiration | number | Yes| Yes | Expiration period of a geofence, in milliseconds.| -## GeofenceRequest8+ +## GeofenceRequest(deprecated) Represents a GNSS geofencing request. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.GeofenceRequest](js-apis-geoLocationManager.md#geofencerequest). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Geofence -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| priority | LocationRequestPriority | Yes| Priority of the location information.| -| scenario | LocationRequestScenario | Yes| Location scenario.| -| geofence | Geofence | Yes| Geofence information.| +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | Yes| Yes | Priority of the location information.| +| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes | Location scenario.| +| geofence | [Geofence](#geofence)| Yes| Yes | Geofence information.| -## LocationPrivacyType8+ +## LocationPrivacyType(deprecated) Defines the privacy statement type. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.LocationPrivacyType](js-apis-geoLocationManager.md#locationprivacytype). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | OTHERS | 0 | Other scenarios.| | STARTUP | 1 | Privacy statement displayed in the startup wizard.| | CORE_LOCATION | 2 | Privacy statement displayed when enabling the location service.| -## LocationCommand8+ +## LocationCommand(deprecated) Defines an extended command. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.LocationCommand](js-apis-geoLocationManager.md#locationcommand). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| scenario | LocationRequestScenario | Yes| Location scenario.| -| command | string | Yes| Extended command, in the string format.| +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes | Location scenario.| +| command | string | Yes| Yes | Extended command, in the string format.| -## Location +## Location(deprecated) Defines a location. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.Location](js-apis-geoLocationManager.md#location). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| latitude7+ | number | Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| -| longitude7+ | number | Yes| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| -| altitude7+ | number | Yes| Location altitude, in meters.| -| accuracy7+ | number | Yes| Location accuracy, in meters.| -| speed7+ | number | Yes| Speed, in m/s.| -| timeStamp7+ | number | Yes| Location timestamp in the UTC format.| -| direction7+ | number | Yes| Direction information.| -| timeSinceBoot7+ | number | Yes| Location timestamp since boot.| -| additions7+ | Array<string> | No| Additional information.| -| additionSize7+ | number | No| Number of additional descriptions.| +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| latitude7+ | number | Yes| No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude7+ | number | Yes| No| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| +| altitude7+ | number | Yes| No| Location altitude, in meters.| +| accuracy7+ | number | Yes| No| Location accuracy, in meters.| +| speed7+ | number | Yes| No| Speed, in m/s.| +| timeStamp7+ | number | Yes| No| Location timestamp in the UTC format.| +| direction7+ | number | Yes| No| Direction information.| +| timeSinceBoot7+ | number | Yes| No| Location timestamp since boot.| +| additions7+ | Array<string> | Yes| No| Additional description.| +| additionSize7+ | number | Yes| No| Number of additional descriptions.| diff --git a/en/application-dev/reference/apis/js-apis-hashmap.md b/en/application-dev/reference/apis/js-apis-hashmap.md index f3deddcc499cfa9cb3b32c5b3951664dfa3d44cb..d8da0f628f90a5090e9b2ccf0576b6ffb03ff69d 100644 --- a/en/application-dev/reference/apis/js-apis-hashmap.md +++ b/en/application-dev/reference/apis/js-apis-hashmap.md @@ -1,4 +1,4 @@ -# Nonlinear Container HashMap +# @ohos.util.HashMap (Nonlinear Container HashMap) > **NOTE** > @@ -53,11 +53,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let hashMap = new HashMap(); -try { - let hashMap2 = HashMap(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -88,11 +83,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts const hashMap = new HashMap(); let result = hashMap.isEmpty(); -try { - hashMap.isEmpty.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -131,11 +121,6 @@ let hashMap = new HashMap(); let result = hashMap.hasKey("squirrel"); hashMap.set("squirrel", 123); let result1 = hashMap.hasKey("squirrel"); -try { - hashMap.hasKey.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -174,11 +159,6 @@ let hashMap = new HashMap(); let result = hashMap.hasValue(123); hashMap.set("squirrel", 123); let result1 = hashMap.hasValue(123); -try { - hashMap.hasValue.bind({}, 123)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -217,11 +197,6 @@ let hashMap = new HashMap(); hashMap.set("squirrel", 123); hashMap.set("sparrow", 356); let result = hashMap.get("sparrow"); -try { - hashMap.get.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -255,11 +230,6 @@ hashMap.set("squirrel", 123); hashMap.set("sparrow", 356); let newHashMap = new HashMap(); hashMap.setAll(newHashMap); -try { - hashMap.setAll.bind({}, newHashMap)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -297,11 +267,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let hashMap = new HashMap(); let result = hashMap.set("squirrel", 123); -try { - hashMap.set.bind({}, "squirrel", 123)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -340,11 +305,6 @@ let hashMap = new HashMap(); hashMap.set("squirrel", 123); hashMap.set("sparrow", 356); let result = hashMap.remove("sparrow"); -try { - hashMap.remove.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -371,11 +331,6 @@ let hashMap = new HashMap(); hashMap.set("squirrel", 123); hashMap.set("sparrow", 356); hashMap.clear(); -try { - hashMap.clear.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -413,11 +368,6 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - hashMap.keys.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -455,11 +405,6 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - hashMap.values.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -498,17 +443,12 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er let hashMap = new HashMap(); hashMap.set("sparrow", 123); let result = hashMap.replace("sparrow", 357); -try { - hashMap.replace.bind({}, "sparrow", 357)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value?: V, key?: K, map?: HashMap) => void, thisArg?: Object): void +forEach(callbackFn: (value?: V, key?: K, map?: HashMap) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -518,7 +458,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -545,13 +485,6 @@ hashMap.set("gull", 357); hashMap.forEach((value, key) => { console.log("value:" + value, key); }); -try { - hashMap.forEach.bind({}, (value, key) => { - console.log("value:" + value, key); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -590,11 +523,6 @@ while(temp != undefined) { console.log("value:" + temp[1]); temp = iter.next().value; } -try { - hashMap.entries.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -621,6 +549,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | 10200011 | The Symbol.iterator method cannot be bound. | **Example** + ```ts let hashMap = new HashMap(); hashMap.set("squirrel", 123); @@ -640,9 +569,4 @@ while(temp != undefined) { console.log("value:" + temp[1]); temp = iter.next().value; } -try { - hashMap[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-hashset.md b/en/application-dev/reference/apis/js-apis-hashset.md index 09cd4c914ad0c512f65f7ad05c1552ef6b29f90a..2c52b1268a1ee4d61f3c89c26949823baa28e566 100644 --- a/en/application-dev/reference/apis/js-apis-hashset.md +++ b/en/application-dev/reference/apis/js-apis-hashset.md @@ -1,4 +1,4 @@ -# Nonlinear Container HashSet +# @ohos.util.HashSet (Nonlinear Container HashSet) > **NOTE** > @@ -61,11 +61,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let hashSet = new HashSet(); -try { - let hashSet2 = HashSet(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -96,11 +91,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts const hashSet = new HashSet(); let result = hashSet.isEmpty(); -try { - hashSet.isEmpty.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -139,11 +129,6 @@ let hashSet = new HashSet(); let result = hashSet.has("squirrel"); hashSet.add("squirrel"); let result1 = hashSet.has("squirrel"); -try { - hashSet.has.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -180,11 +165,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let hashSet = new HashSet(); let result = hashSet.add("squirrel"); -try { - hashSet.add.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -223,11 +203,6 @@ let hashSet = new HashSet(); hashSet.add("squirrel"); hashSet.add("sparrow"); let result = hashSet.remove("sparrow"); -try { - hashSet.remove.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -254,11 +229,6 @@ let hashSet = new HashSet(); hashSet.add("squirrel"); hashSet.add("sparrow"); hashSet.clear(); -try { - hashSet.remove.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -296,17 +266,12 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - hashSet.values.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value?: T, key?: T, set?: HashSet<T>) => void, thisArg?: Object): void +forEach(callbackFn: (value?: T, key?: T, set?: HashSet<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -316,7 +281,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -324,7 +289,7 @@ callbackfn | -------- | -------- | -------- | -------- | | value | T | No| Value of the element that is currently traversed.| | key | T | No| Key of the element that is currently traversed (same as **value**).| -| set | HashSet<T> | No| Instance that invokes the **forEach** method.| +| set | HashSet<T> | No| Instance that invokes the **forEach** API.| **Error codes** @@ -343,13 +308,6 @@ hashSet.add("squirrel"); hashSet.forEach((value, key) => { console.log("value:" + value, key); }); -try { - hashSet.forEach.bind({}, (value, key) => { - console.log("value:" + value, key); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -387,11 +345,6 @@ while(temp != undefined) { console.log("value:" + temp[1]); temp = iter.next().value; } -try { - hashSet.entries.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -436,9 +389,4 @@ while(temp != undefined) { console.log("value: " + temp); temp = iter.next().value; } -try { - hashSet[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-image.md b/en/application-dev/reference/apis/js-apis-image.md index 1bf548153ad9837dc60e7a655852a33987b22871..16b144f78ec85198dfc570336fcf021a9bc86028 100644 --- a/en/application-dev/reference/apis/js-apis-image.md +++ b/en/application-dev/reference/apis/js-apis-image.md @@ -1,4 +1,4 @@ -# Image Processing +# @ohos.multimedia.image (Image Processing) The **Image** module provides APIs for image processing. You can use the APIs to create a **PixelMap** object with specified properties or read image pixel data (even in an area). @@ -22,7 +22,7 @@ Creates a **PixelMap** object with the default BGRA_8888 format and pixel proper **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------- | ------------------------------------------------ | ---- | ---------------------------------------------------------------- | | colors | ArrayBuffer | Yes | Color array in BGRA_8888 format. | | options | [InitializationOptions](#initializationoptions8) | Yes | Pixel properties, including the alpha type, size, scale mode, pixel format, and editable.| @@ -57,7 +57,7 @@ Creates a **PixelMap** object with the default BGRA_8888 format and pixel proper **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | ------------------------------------------------ | ---- | -------------------------- | | colors | ArrayBuffer | Yes | Color array in BGRA_8888 format. | | options | [InitializationOptions](#initializationoptions8) | Yes | Pixel properties. | @@ -907,7 +907,7 @@ Releases this **PixelMap** object. This API uses an asynchronous callback to ret **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------ | | callback | AsyncCallback\ | Yes | Callback used to return the result.| @@ -1077,9 +1077,9 @@ const data = new ArrayBuffer(112); const imageSourceApi = image.createImageSource(data); ``` -## image.createIncrementalSource9+ +## image.CreateIncrementalSource9+ -createIncrementalSource(buf: ArrayBuffer): ImageSource +CreateIncrementalSource(buf: ArrayBuffer): ImageSource Creates an **ImageSource** instance in incremental mode based on the buffers. @@ -1101,12 +1101,12 @@ Creates an **ImageSource** instance in incremental mode based on the buffers. ```js const buf = new ArrayBuffer(96); // 96 is the size of the pixel map buffer to create. The value is calculated as follows: height x width x 4. -const imageSourceIncrementalSApi = image.createIncrementalSource(buf); +const imageSourceIncrementalSApi = image.CreateIncrementalSource(buf); ``` -## image.createIncrementalSource9+ +## image.CreateIncrementalSource9+ -createIncrementalSource(buf: ArrayBuffer, options?: SourceOptions): ImageSource +CreateIncrementalSource(buf: ArrayBuffer, options?: SourceOptions): ImageSource Creates an **ImageSource** instance in incremental mode based on the buffers. @@ -1129,7 +1129,7 @@ Creates an **ImageSource** instance in incremental mode based on the buffers. ```js const buf = new ArrayBuffer(96); // 96 is the size of the pixel map buffer to create. The value is calculated as follows: height x width x 4. -const imageSourceIncrementalSApi = image.createIncrementalSource(buf); +const imageSourceIncrementalSApi = image.CreateIncrementalSource(buf); ``` ## ImageSource @@ -1181,7 +1181,7 @@ Obtains information about this image. This API uses an asynchronous callback to **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | -------------------------------------- | ---- | ---------------------------------------- | | callback | AsyncCallback<[ImageInfo](#imageinfo)> | Yes | Callback used to return the image information.| @@ -1203,7 +1203,7 @@ Obtains information about an image with the specified index. This API uses a pro **Parameters** -| Name | Type | Mandatory| Description | +| Name| Type | Mandatory| Description | | ----- | ------ | ---- | ------------------------------------- | | index | number | No | Index of the image. If this parameter is not set, the default value **0** is used.| @@ -1234,7 +1234,7 @@ Obtains the value of a property with the specified index in this image. This API **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------- | ---------------------------------------------------- | ---- | ------------------------------------ | | key | string | Yes | Name of the property. | | options | [GetImagePropertyOptions](#getimagepropertyoptions7) | No | Image properties, including the image index and default property value.| @@ -1372,12 +1372,12 @@ Updates incremental data. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ---------- | ----------- | ---- | ------------ | | buf | ArrayBuffer | Yes | Incremental data. | | isFinished | boolean | Yes | Whether the update is complete.| -| value | number | No | Offset for data reading. | -| length | number | No | Array length. | +| value | number | Yes | Offset for data reading. | +| length | number | Yes | Array length. | **Return value** @@ -1405,12 +1405,12 @@ Updates incremental data. This API uses an asynchronous callback to return the r **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ---------- | ------------------- | ---- | -------------------- | | buf | ArrayBuffer | Yes | Incremental data. | | isFinished | boolean | Yes | Whether the update is complete. | -| value | number | No | Offset for data reading. | -| length | number | No | Array length. | +| value | number | Yes | Offset for data reading. | +| length | number | Yes | Array length. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1434,7 +1434,7 @@ Creates a **PixelMap** object based on image decoding parameters. This API uses **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------- | ------------------------------------ | ---- | ---------- | | options | [DecodingOptions](#decodingoptions7) | No | Image decoding parameters.| @@ -1486,7 +1486,7 @@ Creates a **PixelMap** object based on image decoding parameters. This API uses **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | -------------------------- | | options | [DecodingOptions](#decodingoptions7) | Yes | Image decoding parameters. | | callback | AsyncCallback<[PixelMap](#pixelmap7)> | Yes | Callback used to return the **PixelMap** object.| @@ -1518,7 +1518,7 @@ Releases this **ImageSource** instance. This API uses an asynchronous callback t **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------------------------------- | | callback | AsyncCallback\ | Yes | Callback invoked for instance release. If the operation fails, an error message is returned.| @@ -1768,11 +1768,11 @@ Creates an **ImageReceiver** instance by specifying the image width, height, for **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | ------ | ---- | ---------------------- | | width | number | Yes | Default image width. | | height | number | Yes | Default image height. | -| format | number | Yes | Image format, which is a constant of [ImageFormat](#imageformat9). (Currently, the value of this parameter is agreed between the user and camera. In the future, there may be other application scenarios. The receiver is used only for transfer. Currently, only **ImageFormat:JPEG** is supported.) | +| format | number | Yes | Image format, which is a constant of [ImageFormat](#imageformat9). (Only ImageFormat:JPEG and 4 are supported.) | | capacity | number | Yes | Maximum number of images that can be accessed at the same time.| **Return value** @@ -1813,7 +1813,7 @@ Obtains a surface ID for the camera or other components. This API uses an asynch **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | -------------------------- | | callback | AsyncCallback\ | Yes | Callback used to return the surface ID.| @@ -1913,7 +1913,7 @@ Reads the next image from the **ImageReceiver** instance. This API uses an async **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | ------------------------------- | ---- | -------------------------- | | callback | AsyncCallback<[Image](#image9)> | Yes | Callback used to return the next image.| @@ -1963,7 +1963,7 @@ Listens for image arrival events. **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------------------------------------ | | type | string | Yes | Type of event to listen for. The value is fixed at **imageArrival**, which is triggered when an image is received.| | callback | AsyncCallback\ | Yes | Callback invoked for the event. | @@ -1984,7 +1984,7 @@ Releases this **ImageReceiver** instance. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------ | | callback | AsyncCallback\ | Yes | Callback used to return the result.| @@ -2028,7 +2028,7 @@ Creates an **ImageCreator** instance by specifying the image width, height, form **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | ------ | ---- | ---------------------- | | width | number | Yes | Default image width. | | height | number | Yes | Default image height. | @@ -2071,7 +2071,7 @@ Obtains an image buffer from the idle queue and writes image data into it. This **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------------- | ---------------------------------------| ---- | -------------------- | | callback | AsyncCallback\ | Yes | Callback used to return the drawn image.| @@ -2080,9 +2080,9 @@ Obtains an image buffer from the idle queue and writes image data into it. This ```js creator.dequeueImage((err, img) => { if (err) { - console.info('dequeueImage succeeded.'); + console.info('dequeueImage failed.'); } - console.info('dequeueImage failed.'); + console.info('dequeueImage succeeded.'); }); ``` @@ -2120,7 +2120,7 @@ Places the drawn image in the dirty queue. This API uses an asynchronous callbac **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------------- | -------------------------| ---- | -------------------- | | interface | Image | Yes | Drawn image.| | callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| @@ -2128,12 +2128,25 @@ Places the drawn image in the dirty queue. This API uses an asynchronous callbac **Example** ```js -creator.queueImage(img, (err) => { - if (err) { - console.info('dequeueImage failed: ' + err); - } - console.info('dequeueImage succeeded'); +creator.dequeueImage().then(img => { + // Draw the image. + img.getComponent(4).then(component => { + var bufferArr = new Uint8Array(component.byteBuffer); + for (var i = 0; i < bufferArr.length; i += 4) { + bufferArr[i] = 0; //B + bufferArr[i + 1] = 0; //G + bufferArr[i + 2] = 255; //R + bufferArr[i + 3] = 255; //A + } + }) + creator.queueImage(img, (err) => { + if (err) { + console.info('queueImage failed: ' + err); + } + console.info('queueImage succeeded'); + }) }) + ``` ### queueImage9+ @@ -2159,11 +2172,24 @@ Places the drawn image in the dirty queue. This API uses a promise to return the **Example** ```js -creator.queueImage(img).then(() => { - console.info('dequeueImage succeeded.'); -}).catch(error => { - console.info('dequeueImage failed: ' + error); +creator.dequeueImage().then(img => { + // Draw the image. + img.getComponent(4).then(component => { + var bufferArr = new Uint8Array(component.byteBuffer); + for (var i = 0; i < bufferArr.length; i += 4) { + bufferArr[i] = 0; //B + bufferArr[i + 1] = 0; //G + bufferArr[i + 2] = 255; //R + bufferArr[i + 3] = 255; //A + } + }) + creator.queueImage(img).then(() => { + console.info('queueImage succeeded.'); + }).catch(error => { + console.info('queueImage failed: ' + error); + }) }) + ``` ### on9+ @@ -2176,7 +2202,7 @@ Listens for image release events. This API uses an asynchronous callback to retu **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------------- | -------------------------| ---- | -------------------- | | type | string | Yes | Type of event, which is **'imageRelease'**.| | callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| @@ -2264,7 +2290,7 @@ Obtains the component buffer from the **Image** instance based on the color comp **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------------- | --------------------------------------- | ---- | -------------------- | | componentType | [ComponentType](#componenttype9) | Yes | Color component type of the image. | | callback | AsyncCallback<[Component](#component9)> | Yes | Callback used to return the component buffer.| @@ -2291,7 +2317,7 @@ Obtains the component buffer from the **Image** instance based on the color comp **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------------- | -------------------------------- | ---- | ---------------- | | componentType | [ComponentType](#componenttype9) | Yes | Color component type of the image.| @@ -2319,7 +2345,7 @@ The corresponding resources must be released before another image arrives. **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | -------------- | | callback | AsyncCallback\ | Yes | Callback used to return the result.| @@ -2398,7 +2424,7 @@ Enumerates the pixel formats of images. **System capability**: SystemCapability.Multimedia.Image.Core -| Name | Default Value| Description | +| Name | Value | Description | | ---------------------- | ------ | ----------------- | | UNKNOWN | 0 | Unknown format. | | RGB_565 | 2 | RGB_565. | @@ -2416,7 +2442,7 @@ Enumerates the alpha types of images. **System capability**: SystemCapability.Multimedia.Image.Core -| Name | Default Value| Description | +| Name | Value | Description | | -------- | ------ | ----------------------- | | UNKNOWN | 0 | Unknown alpha type. | | OPAQUE | 1 | There is no alpha or the image is opaque.| @@ -2429,7 +2455,7 @@ Enumerates the scale modes of images. **System capability**: SystemCapability.Multimedia.Image.Core -| Name | Default Value| Description | +| Name | Value | Description | | --------------- | ------ | -------------------------------------------------- | | CENTER_CROP | 1 | Scales the image so that it fills the requested bounds of the target and crops the extra.| | FIT_TARGET_SIZE | 0 | Reduces the image size to the dimensions of the target. | @@ -2519,7 +2545,7 @@ Describes the exchangeable image file format (EXIF) information of an image. **System capability**: SystemCapability.Multimedia.Image.Core -| Name | Default Value | Description | +| Name | Value | Description | | ----------------- | ----------------------- | ------------------------ | | BITS_PER_SAMPLE | "BitsPerSample" | Number of bits per pixel. | | ORIENTATION | "Orientation" | Image orientation. | @@ -2542,7 +2568,7 @@ Enumerates the image formats. **System capability**: SystemCapability.Multimedia.Image.Core -| Name | Default Value| Description | +| Name | Value | Description | | ------------ | ------ | -------------------- | | YCBCR_422_SP | 1000 | YCBCR422 semi-planar format.| | JPEG | 2000 | JPEG encoding format. | @@ -2553,7 +2579,7 @@ Enumerates the color component types of images. **System capability**: SystemCapability.Multimedia.Image.ImageReceiver -| Name | Default Value| Description | +| Name | Value | Description | | ----- | ------ | ----------- | | YUV_Y | 1 | Luminance component. | | YUV_U | 2 | Chrominance component. | diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md b/en/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md index 62fda8be0560d4df910817a4296c7aef1aea901a..f776c56334112c2b739b5b6a85ef7153c4da1564 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md @@ -1,4 +1,4 @@ -# AbilityResult7+ +# AbilityResult The **AbilityResult** module defines the result code and data returned when an ability is started or destroyed. diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-connectOptions.md b/en/application-dev/reference/apis/js-apis-inner-ability-connectOptions.md new file mode 100644 index 0000000000000000000000000000000000000000..685329b15fe26618c4b2a3be2242d4912415a66d --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-ability-connectOptions.md @@ -0,0 +1,45 @@ +# ConnectOptions + +The **ConnectOptions** module defines the options for connection. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Type | Mandatory | Description | +| ------------ | -------- | ---- | ------------------------- | +| onConnect7+ | function | Yes | Callback invoked when the connection is successful. | +| onDisconnect7+ | function | Yes | Callback invoked when the connection fails. | +| onFailed7+ | function | Yes | Callback invoked when **connectAbility** fails to be called.| + +**Return value** + +| Type | Description | +| ------ | -------------------- | +| number | ID of the Service ability connected.| + +**Example** + +```ts +import rpc from '@ohos.rpc'; +import featureAbility from '@ohos.ability.featureAbility'; +function onConnectCallback(element, remote){ + console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); +} +function onDisconnectCallback(element){ + console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) +} +function onFailedCallback(code){ + console.log('featureAbilityTest ConnectAbility onFailed errCode : ' + code) +} +var connectId = featureAbility.connectAbility( + { + deviceId: "", + bundleName: "com.ix.ServiceAbility", + abilityName: "ServiceAbilityA", + }, + { + onConnect: onConnectCallback, + onDisconnect: onDisconnectCallback, + onFailed: onFailedCallback, + }, +); +``` diff --git a/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md similarity index 91% rename from en/application-dev/reference/apis/js-apis-dataAbilityHelper.md rename to en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md index 1d10f56aeb69e13d2f329bfc18f56127667ef930..f06df85ac59ffe3074519efd2c9aef95a5093cd7 100644 --- a/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md @@ -8,8 +8,7 @@ ## Usage Import the following modules based on the actual situation before using the current module: -``` -import featureAbility from '@ohos.ability.featureAbility' +```ts import ohos_data_ability from '@ohos.data.dataAbility' import ohos_data_rdb from '@ohos.data.rdb' ``` @@ -32,7 +31,7 @@ Opens a file with a specified URI. This API uses an asynchronous callback to ret **Example** -```javascript +```ts import featureAbility from '@ohos.ability.featureAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" @@ -69,7 +68,7 @@ Opens a file with a specified URI. This API uses a promise to return the result. **Example** -```javascript +```ts import featureAbility from '@ohos.ability.featureAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" @@ -100,7 +99,7 @@ Registers an observer to observe data specified by a given URI. This API uses an **Example** -```js +```ts import featureAbility from '@ohos.ability.featureAbility' var helper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" @@ -133,7 +132,7 @@ Deregisters the observer used to observe data specified by a given URI. This API **Example** -```js +```ts import featureAbility from '@ohos.ability.featureAbility' var helper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" @@ -169,7 +168,7 @@ Obtains the MIME type of the data specified by a given URI. This API uses an asy **Example** -```js +```ts import featureAbility from '@ohos.ability.featureAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" @@ -203,7 +202,7 @@ Obtains the MIME type of the data specified by a given URI. This API uses a prom **Example** -```js +```ts import featureAbility from '@ohos.ability.featureAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" @@ -233,7 +232,7 @@ Obtains the supported MIME types of a specified file. This API uses an asynchron **Example** -```js +```ts import featureAbility from '@ohos.ability.featureAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" @@ -271,7 +270,7 @@ Obtains the supported MIME types of a specified file. This API uses a promise to **Example** -```js +```ts import featureAbility from '@ohos.ability.featureAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" @@ -301,7 +300,7 @@ Converts the URI that refers to a Data ability into a normalized URI. This API u **Example** -```js +```ts import featureAbility from '@ohos.ability.featureAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" @@ -335,7 +334,7 @@ Converts the URI that refers to a Data ability into a normalized URI. This API u **Example** -```js +```ts import featureAbility from '@ohos.ability.featureAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" @@ -364,7 +363,7 @@ Converts a normalized URI generated by **DataAbilityHelper.normalizeUri(uri: str **Example** -```js +```ts import featureAbility from '@ohos.ability.featureAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" @@ -400,7 +399,7 @@ Converts a normalized URI generated by **DataAbilityHelper.normalizeUri(uri: str **Example** -```js +```ts import featureAbility from '@ohos.ability.featureAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" @@ -429,7 +428,7 @@ Notifies the registered observer of a change to the data specified by the URI. T **Example** -```js +```ts import featureAbility from '@ohos.ability.featureAbility' var helper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" @@ -463,7 +462,7 @@ Notifies the registered observer of a change to the data specified by the URI. T **Example** -```js +```ts import featureAbility from '@ohos.ability.featureAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" @@ -493,7 +492,7 @@ Inserts a single data record into the database. This API uses an asynchronous ca **Example** -```js +```ts import featureAbility from '@ohos.ability.featureAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" @@ -535,7 +534,7 @@ Inserts a single data record into the database. This API uses a promise to retur **Example** -```js +```ts import featureAbility from '@ohos.ability.featureAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" @@ -556,7 +555,7 @@ DAHelper.insert( ## DataAbilityHelper.batchInsert -batchInsert(uri: string, valuesBuckets: Array, callback: AsyncCallback\): void +batchInsert(uri: string, valuesBuckets: Array\, callback: AsyncCallback\): void Inserts multiple data records into the database. This API uses an asynchronous callback to return the result. @@ -567,12 +566,12 @@ Inserts multiple data records into the database. This API uses an asynchronous c | Name | Type | Mandatory| Description | | ------------ | ----------------------- | ---- | -------------------------------- | | uri | string | Yes | URI of the data to insert. | -| valuesBucket | Array | Yes | Data records to insert. | +| valuesBucket | Array\ | Yes | Data records to insert. | | callback | AsyncCallback\ | Yes | Callback used to return the number of inserted data records.| **Example** -```js +```ts import featureAbility from '@ohos.ability.featureAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" @@ -611,7 +610,7 @@ Inserts multiple data records into the database. This API uses a promise to retu **Example** -```js +```ts import featureAbility from '@ohos.ability.featureAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" @@ -640,12 +639,12 @@ Deletes one or more data records from the database. This API uses an asynchronou | Name | Type | Mandatory| Description | | ------------ | --------------------------------- | ---- | ------------------------------------------------ | | uri | string | Yes | URI of the data to delete. | -| valuesBucket | dataAbility.DataAbilityPredicates | Yes | Filter criteria. You should define the processing logic when this parameter is **null**.| +| predicates | dataAbility.DataAbilityPredicates | Yes | Filter criteria. You should define the processing logic when this parameter is **null**.| | callback | AsyncCallback\ | Yes | Callback used to return the number of deleted data records. | **Example** -```js +```ts import featureAbility from '@ohos.ability.featureAbility' import ohos_data_ability from '@ohos.data.dataAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( @@ -673,7 +672,7 @@ Deletes one or more data records from the database. This API uses a promise to r | Name | Type | Mandatory| Description | | ------------ | --------------------------------- | ---- | ------------------------------------------------ | | uri | string | Yes | URI of the data to delete. | -| valuesBucket | dataAbility.DataAbilityPredicates | Yes | Filter criteria. You should define the processing logic when this parameter is **null**.| +| predicates | dataAbility.DataAbilityPredicates | No | Filter criteria. You should define the processing logic when this parameter is **null**.| **Return value** @@ -683,7 +682,7 @@ Deletes one or more data records from the database. This API uses a promise to r **Example** -```js +```ts import featureAbility from '@ohos.ability.featureAbility' import ohos_data_ability from '@ohos.data.dataAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( @@ -717,7 +716,7 @@ Updates data records in the database. This API uses an asynchronous callback to **Example** -```js +```ts import featureAbility from '@ohos.ability.featureAbility' import ohos_data_ability from '@ohos.data.dataAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( @@ -753,7 +752,7 @@ Updates data records in the database. This API uses a promise to return the resu | ------------ | --------------------------------- | ---- | ------------------------------------------------ | | uri | string | Yes | URI of the data to update. | | valuesBucket | rdb.ValuesBucket | Yes | New values. | -| predicates | dataAbility.DataAbilityPredicates | Yes | Filter criteria. You should define the processing logic when this parameter is **null**.| +| predicates | dataAbility.DataAbilityPredicates | No | Filter criteria. You should define the processing logic when this parameter is **null**.| **Return value** @@ -763,7 +762,7 @@ Updates data records in the database. This API uses a promise to return the resu **Example** -```js +```ts import featureAbility from '@ohos.ability.featureAbility' import ohos_data_ability from '@ohos.data.dataAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( @@ -798,13 +797,13 @@ Queries data in the database. This API uses an asynchronous callback to return t | Name | Type | Mandatory| Description | | ---------- | --------------------------------- | ---- | ------------------------------------------------ | | uri | string | Yes | URI of the data to query. | -| columns | rdb.ValuesBucket | Yes | Columns to query. If this parameter is **null**, all columns will be queried. | +| columns | Array\ | Yes | Columns to query. If this parameter is **null**, all columns will be queried. | | predicates | dataAbility.DataAbilityPredicates | Yes | Filter criteria. You should define the processing logic when this parameter is **null**.| | callback | AsyncCallback\ | Yes | Callback used to return the data queried. | **Example** -```js +```ts import featureAbility from '@ohos.ability.featureAbility' import ohos_data_ability from '@ohos.data.dataAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( @@ -836,8 +835,8 @@ Queries data in the database. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ---------- | --------------------------------- | ---- | ------------------------------------------------ | | uri | string | Yes | URI of the data to query. | -| columns | rdb.ValuesBucket | Yes | Columns to query. If this parameter is **null**, all columns will be queried. | -| predicates | dataAbility.DataAbilityPredicates | Yes | Filter criteria. You should define the processing logic when this parameter is **null**.| +| columns | Array\ | No | Columns to query. If this parameter is **null**, all columns will be queried. | +| predicates | dataAbility.DataAbilityPredicates | No | Filter criteria. You should define the processing logic when this parameter is **null**.| **Return value** @@ -847,7 +846,7 @@ Queries data in the database. This API uses a promise to return the result. **Example** -```js +```ts import featureAbility from '@ohos.ability.featureAbility' import ohos_data_ability from '@ohos.data.dataAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( @@ -889,7 +888,7 @@ Calls the extended API of the Data ability. This API uses a promise to return th **Example** -```js +```ts import featureAbility from '@ohos.ability.featureAbility'; let dataAbilityHelper = featureAbility.acquireDataAbilityHelper("dataability:///com.example.jsapidemo.UserDataAbility"); @@ -920,7 +919,7 @@ Calls the extended API of the Data ability. This API uses an asynchronous callba **Example** -```js +```ts import featureAbility from '@ohos.ability.featureAbility'; let dataAbilityHelper = featureAbility.acquireDataAbilityHelper("dataability:///com.example.jsapidemo.UserDataAbility"); @@ -946,12 +945,12 @@ Operates data in the database. This API uses an asynchronous callback to return | Name | Type | Mandatory| Description | | ---------- | --------------------------------- | ---- | ------------------------------------------------ | | uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx".| -| operations | Array\<[DataAbilityOperation](#dataabilityoperation)> | Yes | A list of data operations on the database. | -| callback | AsyncCallback\> | Yes |Callback used to return the result of each operation in the **DataAbilityResult** array. | +| operations | Array\<[DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md)> | Yes | A list of data operations on the database. | +| callback | AsyncCallback\> | Yes |Callback used to return the result of each operation in the **DataAbilityResult** array. | **Example** -```js +```ts import featureAbility from '@ohos.ability.featureAbility'; // Select the operations to be performed on the database according to the DataAbilityOperation array. @@ -979,17 +978,17 @@ Operates data in the database. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ---------- | -------------------------------| ---- | ------------------------------------------------ | | uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx".| -| operations | Array\<[DataAbilityOperation](#dataabilityoperation)> | Yes | A list of data operations on the database. | +| operations | Array\<[DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md)> | Yes | A list of data operations on the database. | **Return value** | Type| Description| |------ | ------- | -|Promise\> | Promise used to return the result of each operation in the **DataAbilityResult** array.| +|Promise\> | Callback used to return the result of each operation in the **DataAbilityResult** array.| **Example** -```js +```ts import featureAbility from '@ohos.ability.featureAbility'; // Select the operations to be performed on the database according to the DataAbilityOperation array. @@ -1012,27 +1011,3 @@ dataAbilityHelper.executeBatch("dataability:///com.example.jsapidemo.UserDataAbi | Name| Type| Mandatory| Description| | ------ | ------ | ------ | ------ | | [key: string] | number \| string \| boolean \| Array\ \| null | Yes| Data stored in key-value pairs.| - -## DataAbilityOperation - -**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel - -| Name | Type | Readable | Writable | Mandatory| Description | -| -------- | -------- | -------- | -------- | --------| -------- | -| uri | string | Yes | No | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx". | -| type | featureAbility.DataAbilityOperationType | Yes | No | Yes | Operation type. | -| valuesBucket? | rdb.ValuesBucket | Yes | No | No | Data value to set. | -| valueBackReferences? | rdb.ValuesBucket | Yes | No | No | **ValuesBucket** object that contains a set of key-value pairs. | -| predicates? | dataAbility.DataAbilityPredicates | Yes | No | No | Predicates to set. If no predicate is set, all data records are displayed. | -| predicatesBackReferences? | Map\ | Yes | No | No | Back references of the predicates. | -| interrupted? | boolean | Yes | No | No | Whether batch operations can be interrupted. | -| expectedCount? | number | Yes | No | No | Expected number of rows to be updated or deleted. | - -## DataAbilityResult - -**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel - -| Name | Type | Readable | Writable | Mandatory | Description | -| -------- | -------- | -------- | -------- | -------- | -------- | -| uri? | string | Yes | No | No | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx". | -| count? | number | Yes | No | No | Number of rows affected by the operation. | diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityOperation.md b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityOperation.md new file mode 100644 index 0000000000000000000000000000000000000000..30148ab3a64188abe2aef5a8c5cf2814f297da3e --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityOperation.md @@ -0,0 +1,66 @@ +# DataAbilityOperation + +The **DataAbilityOperation** module defines the operation on Data abilities. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the FA model. + +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + +| Name | Template | Mandatory| Description | +| -------- | -------- | --------| -------- | +| uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx". | +| type | featureAbility.DataAbilityOperationType | Yes | Operation type. | +| valuesBucket? | rdb.ValuesBucket | No | Data value to set. | +| valueBackReferences? | rdb.ValuesBucket | No | **ValuesBucket** object that contains a set of key-value pairs. | +| predicates? | dataAbility.DataAbilityPredicates | No | Predicates to set. If no predicate is set, all data records are displayed. | +| predicatesBackReferences? | Map\ | No | Back references of the predicates. | +| interrupted? | boolean | No | Whether batch operations can be interrupted. | +| expectedCount? | number | No | Expected number of rows to be updated or deleted. | + +**Example** +```ts +import featureAbility from '@ohos.ability.featureAbility' + +let dataAbilityUri = ("dataability:///com.example.myapplication.TestDataAbility"); +let DAHelper; +try { + DAHelper = featureAbility.acquireDataAbilityHelper(dataAbilityUri); + if(DAHelper == null){ + console.error('DAHelper is null'); + return; + } +} catch (err) { + console.error('acquireDataAbilityHelper fail, error:' + JSON.stringify(err)); + return; +} + +let valueBucket = { + "name": "DataAbilityHelperTest", + "age": 24, + "salary": 2024.20, +}; +let dataAbilityOperation = { + uri: dataAbilityUri, + type: featureAbility.DataAbilityOperationType.TYPE_INSERT, + valuesBucket: valueBucket, + predicates: null, + expectedCount: 1, + PredicatesBackReferences: {}, + interrupted: true +} +let operations = [ + dataAbilityOperation +]; +try { + DAHelper.executeBatch(dataAbilityUri, operations, + (err, data) => { + console.log("executeBatch, data: " + JSON.stringify(data)); + } + ); +} catch (err) { + console.error('executeBatch fail: ' + JSON.stringify(err)); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md new file mode 100644 index 0000000000000000000000000000000000000000..fe602f38efcbcbb8619a29e1d05c3a6f92bf2635 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md @@ -0,0 +1,73 @@ +# DataAbilityResult + +The **DataAbilityResult** module defines the operation result on Data abilities. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the FA model. + +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| uri? | string | No | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx". | +| count? | number | No | Number of rows affected by the operation. | + +**Example** +```ts +import featureAbility from '@ohos.ability.featureAbility' + +let dataAbilityUri = ("dataability:///com.example.myapplication.TestDataAbility"); +let DAHelper; +try { + DAHelper = featureAbility.acquireDataAbilityHelper(dataAbilityUri); + if(DAHelper == null){ + console.error('DAHelper is null'); + return; + } +} catch (err) { + console.error('acquireDataAbilityHelper fail, error:' + JSON.stringify(err)); + return; +} + +let valueBucket = { + "name": "DataAbilityHelperTest", + "age": 24, + "salary": 2024.20, +}; +let operations = [ +{ + uri: dataAbilityUri, + type: featureAbility.DataAbilityOperationType.TYPE_INSERT, + valuesBucket: valueBucket, + predicates: null, + expectedCount: 1, + PredicatesBackReferences: {}, + interrupted: true, +}, +{ + uri: dataAbilityUri, + type: featureAbility.DataAbilityOperationType.TYPE_INSERT, + valuesBucket: valueBucket, + predicates: null, + expectedCount: 1, + PredicatesBackReferences: {}, + interrupted: true, +} +]; + +try { + let promise = DAHelper.executeBatch(dataAbilityUri, operations).then((data) => { + for (let i = 0; i < data.length; i++) { + let dataAbilityResult = data[i]; + console.log('dataAbilityResult.uri: ' + dataAbilityResult.uri); + console.log('dataAbilityResult.count: ' + dataAbilityResult.count); + } + }).catch(err => { + console.error('executeBatch error: ' + JSON.stringify(err)); + }); +} catch (err) { + console.error('executeBatch error: ' + JSON.stringify(err)); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-startAbilityParameter.md b/en/application-dev/reference/apis/js-apis-inner-ability-startAbilityParameter.md new file mode 100644 index 0000000000000000000000000000000000000000..bbb025920d5a49ec02cc9fc84fed7c1bee8e6fca --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-ability-startAbilityParameter.md @@ -0,0 +1,44 @@ +# StartAbilityParameter + +The **StartAbilityParameter** module defines the parameters for starting an ability. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the FA model. + +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + +| Name | Type | Mandatory | Description | +| ------------------- | -------- | ---- | -------------------------------------- | +| want | [Want](js-apis-application-want.md)| Yes | Information about the ability to start. | +| abilityStartSetting | {[key: string]: any} | No | Special attribute of the ability to start. This attribute can be passed in the method call.| + +**Example** +```ts +import featureAbility from '@ohos.ability.featureAbility' + +let Want = { + bundleName: "com.example.abilityStartSettingApp2", + abilityName: "com.example.abilityStartSettingApp.MainAbility", +} + +let abilityStartSetting ={ + [featureAbility.AbilityStartSetting.BOUNDS_KEY] : [100,200,300,400], + [featureAbility.AbilityStartSetting.WINDOW_MODE_KEY] : + featureAbility.AbilityWindowConfiguration.WINDOW_MODE_UNDEFINED, + [featureAbility.AbilityStartSetting.DISPLAY_ID_KEY] : 1, +} + +let startAbilityParameter = { + want:Want, + abilityStartSetting:abilityStartSetting +} + +featureAbility.startAbility(startAbilityParameter, (err,data)=>{ + console.log('errCode : ' + JSON.stringify(err)); + console.log('data : ' + JSON.stringify(data)); +} catch(error) { + console.log("startAbility error: " + JSON.stringify(error)); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-want.md b/en/application-dev/reference/apis/js-apis-inner-ability-want.md new file mode 100644 index 0000000000000000000000000000000000000000..4eea38a4e28c3e344a8ecdc60118af0fe93ddf19 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-ability-want.md @@ -0,0 +1,65 @@ +# Want + +Want is a carrier for information transfer between objects (application components). Want can be used as a parameter of **startAbility** to specify a startup target and information that needs to be carried during startup, for example, **bundleName** and **abilityName**, which respectively indicate the bundle name of the target ability and the ability name in the bundle. When ability A needs to start ability B and transfer some data to ability B, it can use Want a carrier to transfer the data. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +**System capability**: SystemCapability.Ability.AbilityBase + +| Name | Type | Mandatory| Description | +| ----------- | -------------------- | ---- | ------------------------------------------------------------ | +| deviceId | string | No | ID of the device running the ability. | +| bundleName | string | No | Bundle name of the application. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability.| +| abilityName | string | No | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.| +| uri | string | No | URI. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| +| type | string | No | MIME type, that is, the type of the file to open, for example, **text/xml** and **image/***. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com. | +| flags | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-ability-wantConstant.md#wantConstant.Flags).| +| action | string | No | Action to take, such as viewing and sharing application details. In implicit Want, you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data. | +| parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
**ohos.aafwk.callerPid**: PID of the caller.
**ohos.aafwk.param.callerToken**: token of the caller.
**ohos.aafwk.param.callerUid**: UID in [bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information. | +| entities | Array\ | No | Additional category information (such as browser and video player) of the target ability. It is a supplement to **action** in implicit Want and is used to filter ability types. | +| moduleName9+ | string | No | Module to which the ability belongs.| + +**Example** + +- Basic usage + + ```ts + var want = { + "deviceId": "", // An empty deviceId indicates the local device. + "bundleName": "com.extreme.test", + "abilityName": "MainAbility", + "moduleName": "entry" // moduleName is optional. + }; + this.context.startAbility(want, (error) => { + // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. + console.log("error.code = " + error.code) + }) + ``` + +- Passing a file descriptor (FD) + + ```ts + import fileio from '@ohos.fileio'; + var fd; + try { + fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); + } catch(e) { + console.log("openSync fail:" + JSON.stringify(e)); + } + var want = { + "deviceId": "", // An empty deviceId indicates the local device. + "bundleName": "com.extreme.test", + "abilityName": "MainAbility", + "moduleName": "entry", // moduleName is optional. + "parameters": { + "keyFd":{"type":"FD", "value":fd} + } + }; + this.context.startAbility(want, (error) => { + // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. + console.log("error.code = " + error.code) + }) + ``` + diff --git a/en/application-dev/reference/apis/js-apis-inner-app-appVersionInfo.md b/en/application-dev/reference/apis/js-apis-inner-app-appVersionInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..a8eb10e600ef981de57a8acc227b1b6371efde26 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-app-appVersionInfo.md @@ -0,0 +1,24 @@ +# AppVersionInfo + +The **AppVersionInfo** module defines the application version information. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Type | Readable | Writable | Description | +| ----------- | ------ | ---- | ---- | ------- | +| appName | string | Yes | No | Module name. | +| versionCode | number | Yes | No | Module description.| +| versionName | string | Yes | No | Module description ID.| + +**Example** +```ts +let appName; +let versionCode; +let versionName; +this.context.getAppVersionInfo((error, data) => { + console.info('getAppVersionInfo data is:' + JSON.stringify(data)); + appName = data.appName; + versionCode = data.versionCode; + versionName = data.versionName; +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-Context.md b/en/application-dev/reference/apis/js-apis-inner-app-context.md similarity index 78% rename from en/application-dev/reference/apis/js-apis-Context.md rename to en/application-dev/reference/apis/js-apis-inner-app-context.md index 116af9c40bdb3c13cc278a13bb7ae5b08330095f..84b46fd028782c8517e3c6aca5bad324c8eac179 100644 --- a/en/application-dev/reference/apis/js-apis-Context.md +++ b/en/application-dev/reference/apis/js-apis-inner-app-context.md @@ -4,17 +4,19 @@ The **Context** module provides context for abilities or applications. It allows > **NOTE** > -> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the FA model. ## Usage The **Context** object is created in a **featureAbility** and returned through its **getContext()** API. Therefore, you must import the **@ohos.ability.featureAbility** package before using the **Context** module. An example is as follows: -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); -context.getOrCreateLocalDir() +context.getOrCreateLocalDir().then((data) => { + console.info("getOrCreateLocalDir data: " + JSON.stringify(data)); +}); ``` ## Context.getOrCreateLocalDir7+ @@ -35,12 +37,12 @@ If this API is called for the first time, a root directory will be created. **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getOrCreateLocalDir((err, data)=>{ - console.info("data=" + data); -}) + console.info("getOrCreateLocalDir err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +}); ``` @@ -63,16 +65,14 @@ If this API is called for the first time, a root directory will be created. **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getOrCreateLocalDir().then((data) => { - console.info("data=" + data); + console.info("getOrCreateLocalDir data: " + JSON.stringify(data)); }); ``` - - ## Context.verifyPermission7+ verifyPermission(permission: string, options: PermissionOptions, callback: AsyncCallback\): void @@ -86,17 +86,19 @@ Verifies whether a specific PID and UID have the given permission. This API uses | Name | Type | Mandatory | Description | | ---------- | --------------------------------------- | ---- | -------------------- | | permission | string | Yes | Name of the permission to verify. | -| options | [PermissionOptions](#permissionoptions) | Yes | Permission options. | +| options | [PermissionOptions](#permissionoptions7) | Yes | Permission options. | | callback | AsyncCallback\ | Yes | Callback used to return the permission verification result. The value **0** means that the PID and UID have the given permission, and the value **-1** means the opposite.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' -import bundle from '@ohos.bundle' +```ts +import featureAbility from '@ohos.ability.featureAbility'; +import bundle from '@ohos.bundle'; var context = featureAbility.getContext(); -bundle.getBundleInfo('com.context.test', 1, (err,datainfo) =>{ - context.verifyPermission("com.example.permission", {uid:datainfo.uid}); +bundle.getBundleInfo('com.context.test', 1, (err, datainfo) =>{ + context.verifyPermission("com.example.permission", {uid:datainfo.uid}, (err, data) =>{ + console.info("verifyPermission err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); + }); }); ``` @@ -119,10 +121,12 @@ Verifies whether the current PID and UID have the given permission. This API use **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); -context.verifyPermission("com.example.permission") +context.verifyPermission("com.example.permission", (err, data) =>{ + console.info("verifyPermission err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +}); ``` ## Context.verifyPermission7+ @@ -148,13 +152,12 @@ Verifies whether a specific PID and UID have the given permission. This API uses **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); var Permission = {pid:1}; context.verifyPermission('com.context.permission',Permission).then((data) => { - console.info("======================>verifyPermissionCallback====================>"); - console.info("====>data====>" + JSON.stringify(data)); + console.info("verifyPermission data: " + JSON.stringify(data)); }); ``` @@ -178,8 +181,8 @@ Requests certain permissions from the system. This API uses an asynchronous call **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.requestPermissionsFromUser( ["com.example.permission1", @@ -187,11 +190,11 @@ context.requestPermissionsFromUser( "com.example.permission3", "com.example.permission4", "com.example.permission5"], - 1,(err, data)=>{ - console.info("====>requestdata====>" + JSON.stringify(data)); - console.info("====>requesterrcode====>" + JSON.stringify(err.code)); + 1, + (err, data) => { + console.info("requestPermissionsFromUser err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); } -) +); ``` @@ -218,8 +221,8 @@ Requests certain permissions from the system. This API uses a promise to return **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.requestPermissionsFromUser( ["com.example.permission1", @@ -228,8 +231,9 @@ context.requestPermissionsFromUser( "com.example.permission4", "com.example.permission5"], 1).then((data)=>{ - console.info("====>requestdata====>" + JSON.stringify(data)); - }); + console.info("requestPermissionsFromUser data: " + JSON.stringify(data)); + } +); ``` @@ -246,14 +250,16 @@ Obtains information about the current application. This API uses an asynchronous | Name | Type | Mandatory | Description | | -------- | ------------------------------- | ---- | ------------ | -| callback | AsyncCallback\ | Yes | Callback used to return the application information.| +| callback | AsyncCallback\<[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)> | Yes | Callback used to return the application information.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); -context.getApplicationInfo() +context.getApplicationInfo((err, data) => { + console.info("getApplicationInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +}); ``` @@ -270,16 +276,15 @@ Obtains information about the current application. This API uses a promise to re | Type | Description | | ------------------------- | --------- | -| Promise\ | Promise used to return the application information.| +| Promise\<[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)> | Promise used to return the application information.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getApplicationInfo().then((data) => { - console.info("=====================>getApplicationInfoCallback===================>"); - console.info("====>data====>" + JSON.stringify(data)); + console.info("getApplicationInfo data: " + JSON.stringify(data)); }); ``` @@ -301,10 +306,12 @@ Obtains the bundle name of this ability. This API uses an asynchronous callback **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); -context.getBundleName() +context.getBundleName((err, data) => { + console.info("getBundleName err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +}); ``` @@ -325,12 +332,11 @@ Obtains the bundle name of this ability. This API uses a promise to return the r **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getBundleName().then((data) => { - console.info("=======================>getBundleNameCallback====================>"); - console.info("====>data====>" + JSON.stringify(data)); + console.info("getBundleName data: " + JSON.stringify(data)); }); ``` @@ -350,10 +356,12 @@ Obtains the display orientation of this ability. This API uses an asynchronous c **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); -context.getDisplayOrientation() +context.getDisplayOrientation((err, data) => { + console.info("getDisplayOrientation err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +}); ``` ## Context.getDisplayOrientation7+ @@ -372,12 +380,11 @@ Obtains the display orientation of this ability. This API uses a promise to retu **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getDisplayOrientation().then((data) => { - console.info("=======================>getDisplayOrientationCallback====================>"); - console.info("====>data====>" + JSON.stringify(data)); + console.info("getDisplayOrientation data: " + JSON.stringify(data)); }); ``` @@ -397,10 +404,12 @@ Obtains the external cache directory of the application. This API uses an asynch **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); -context.getExternalCacheDir() +context.getExternalCacheDir((err, data) => { + console.info("getExternalCacheDir err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +}); ``` ## Context.getExternalCacheDir @@ -419,12 +428,11 @@ Obtains the external cache directory of the application. This API uses a promise **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getExternalCacheDir().then((data) => { - console.info("=======================>getExternalCacheDirCallback====================>"); - console.info("====>data====>" + JSON.stringify(data)); + console.info("getExternalCacheDir data: " + JSON.stringify(data)); }); ``` @@ -441,17 +449,17 @@ Sets the display orientation for this ability. This API uses an asynchronous cal | Name | Type | Mandatory | Description | | ----------- | ---------------------------------------- | ---- | ------------ | | orientation | [bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation) | Yes | Display orientation to set.| -| callback | AsyncCallback\<[bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation)> | Yes | Callback used to return the display orientation. | +| callback | AsyncCallback\ | Yes | Callback used to return the display orientation. | **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' -import bundle from '@ohos.bundle' +```ts +import featureAbility from '@ohos.ability.featureAbility'; +import bundle from '@ohos.bundle'; var context = featureAbility.getContext(); var orientation=bundle.DisplayOrientation.UNSPECIFIED context.setDisplayOrientation(orientation, (err) => { - console.log('---------- setDisplayOrientation fail, err: -----------', err); + console.info("setDisplayOrientation err: " + JSON.stringify(err)); }); ``` @@ -468,18 +476,17 @@ Sets the display orientation for this ability. This API uses a promise to return | Type | Description | | ---------------------------------------- | ---------------------------------------- | | orientation | [bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation) | -| Promise\<[bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation)> | Promise used to return the display orientation. | +| Promise\ | Promise used to return the display orientation. | **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' -import bundle from '@ohos.bundle' +```ts +import featureAbility from '@ohos.ability.featureAbility'; +import bundle from '@ohos.bundle'; var context = featureAbility.getContext(); var orientation=bundle.DisplayOrientation.UNSPECIFIED context.setDisplayOrientation(orientation).then((data) => { - console.info("=======================>setDisplayOrientationCallback====================>"); - console.info("====>data====>" + JSON.stringify(data)); + console.info("setDisplayOrientation data: " + JSON.stringify(data)); }); ``` @@ -500,12 +507,12 @@ Sets whether to show this feature at the top of the lock screen so that the feat **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); var show=true context.setShowOnLockScreen(show, (err) => { - console.log('---------- setShowOnLockScreen fail, err: -----------', err); + console.info("setShowOnLockScreen err: " + JSON.stringify(err)); }); ``` @@ -531,13 +538,12 @@ Sets whether to show this feature at the top of the lock screen so that the feat **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); var show=true context.setShowOnLockScreen(show).then((data) => { - console.info("=======================>setShowOnLockScreenCallback====================>"); - console.info("====>data====>" + JSON.stringify(data)); + console.info("setShowOnLockScreen data: " + JSON.stringify(data)); }); ``` @@ -558,12 +564,12 @@ Sets whether to wake up the screen when this feature is restored. This API uses **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); var wakeUp=true context.setWakeUpScreen(wakeUp, (err) => { - console.log('---------- setWakeUpScreen fail, err: -----------', err); + console.info("setWakeUpScreen err: " + JSON.stringify(err)); }); ``` @@ -589,13 +595,12 @@ Sets whether to wake up the screen when this feature is restored. This API uses **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); var wakeUp=true context.setWakeUpScreen(wakeUp).then((data) => { - console.info("=======================>setWakeUpScreenCallback====================>"); - console.info("====>data====>" + JSON.stringify(data)); + console.info("setWakeUpScreen data: " + JSON.stringify(data)); }); ``` @@ -614,14 +619,16 @@ Obtains information about the current process, including the PID and process nam | Name | Type | Mandatory | Description | | -------- | --------------------------- | ---- | ---------- | -| callback | AsyncCallback\ | Yes | Callback used to return the process information.| +| callback | AsyncCallback\<[ProcessInfo](js-apis-inner-app-processInfo.md)> | Yes | Callback used to return the process information.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); -context.getProcessInfo() +context.getProcessInfo((err, data) => { + console.info("getProcessInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +}); ``` @@ -638,16 +645,15 @@ Obtains information about the current process, including the PID and process nam | Type | Description | | --------------------- | ------- | -| Promise\ | Promise used to return the process information.| +| Promise\<[ProcessInfo](js-apis-inner-app-processInfo.md)> | Promise used to return the process information.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getProcessInfo().then((data) => { - console.info("=======================>getProcessInfoCallback====================>"); - console.info("====>data====>" + JSON.stringify(data)); + console.info("getProcessInfo data: " + JSON.stringify(data)); }); ``` @@ -667,14 +673,16 @@ This API is available only to Page abilities. | Name | Type | Mandatory | Description | | -------- | --------------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the **ohos.bundle.ElementName** object.| +| callback | AsyncCallback\<[ElementName](js-apis-bundle-ElementName.md)> | Yes | Callback used to return the **ohos.bundle.ElementName** object.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); -context.getElementName() +context.getElementName((err, data) => { + console.info("getElementName err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +}); ``` @@ -693,16 +701,15 @@ This API is available only to Page abilities. | Type | Description | | --------------------- | ------------------------------------ | -| Promise\ | Promise used to return the **ohos.bundle.ElementName** object.| +| Promise\<[ElementName](js-apis-bundle-ElementName.md)> | Promise used to return the **ohos.bundle.ElementName** object.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getElementName().then((data) => { - console.info("=======================>getElementNameCallback====================>"); - console.info("====>data====>" + JSON.stringify(data)); + console.info("getElementName data: " + JSON.stringify(data)); }); ``` @@ -722,10 +729,12 @@ Obtains the name of the current process. This API uses an asynchronous callback **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); -context.getProcessName() +context.getProcessName((err, data) => { + console.info("getProcessName err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +}); ``` @@ -746,12 +755,11 @@ Obtains the name of the current process. This API uses a promise to return the r **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getProcessName().then((data) => { - console.info("=======================>getProcessNameCallback====================>"); - console.info("====>data====>" + JSON.stringify(data)); + console.info("getProcessName data: " + JSON.stringify(data)); }); ``` @@ -773,10 +781,12 @@ Obtains the bundle name of the calling ability. This API uses an asynchronous ca **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); -context.getCallingBundle() +context.getCallingBundle((err, data) => { + console.info("getCallingBundle err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +}); ``` @@ -797,12 +807,11 @@ Obtains the bundle name of the calling ability. This API uses a promise to retur **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getCallingBundle().then((data) => { - console.info("======================>getCallingBundleCallback====================>"); - console.info("====>data====>" + JSON.stringify(data)); + console.info("getCallingBundle data: " + JSON.stringify(data)); }); ``` @@ -822,15 +831,11 @@ Obtains the cache directory of the application in the internal storage. This API **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getCacheDir((err, data) => { - if (err) { - console.error('Operation failed. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Operation successful. Data:' + JSON.stringify(data)); + console.info("getCacheDir err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -850,12 +855,11 @@ Obtains the cache directory of the application in the internal storage. This API **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getCacheDir().then((data) => { - console.info("======================>getCacheDirPromsie====================>"); - console.info("====>data====>" + JSON.stringify(data)); + console.info("getCacheDir data: " + JSON.stringify(data)); }); ``` @@ -875,15 +879,11 @@ Obtains the file directory of the application in the internal storage. This API **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getFilesDir((err, data) => { - if (err) { - console.error('Operation failed. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Operation successful. Data:' + JSON.stringify(data)); + console.info("getFilesDir err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -903,12 +903,11 @@ Obtains the file directory of the application in the internal storage. This API **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getFilesDir().then((data) => { - console.info("======================>getFilesDirPromsie====================>"); - console.info("====>data====>" + JSON.stringify(data)); + console.info("getFilesDir data: " + JSON.stringify(data)); }); ``` @@ -930,15 +929,11 @@ If the distributed file path does not exist, the system will create one and retu **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getOrCreateDistributedDir((err, data) => { - if (err) { - console.error('Operation failed. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Operation successful. Data:' + JSON.stringify(data)); + console.info("getOrCreateDistributedDir err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -960,11 +955,11 @@ If the distributed file path does not exist, the system will create one and retu **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getOrCreateDistributedDir().then((data) => { - console.info("====>data====>" + JSON.stringify(data)); + console.info("getOrCreateDistributedDir data: " + JSON.stringify(data)); }); ``` @@ -984,15 +979,11 @@ Obtains the application type. This API uses an asynchronous callback to return t **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getAppType((err, data) => { - if (err) { - console.error('Operation failed. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Operation successful. Data:' + JSON.stringify(data)); + console.info("getAppType err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -1012,11 +1003,11 @@ Obtains the application type. This API uses a promise to return the result. **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getAppType().then((data) => { - console.info("====>data====>" + JSON.stringify(data)); + console.info("getAppType data: " + JSON.stringify(data)); }); ``` @@ -1036,15 +1027,11 @@ Obtains the **ModuleInfo** object of the application. This API uses an asynchron **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getHapModuleInfo((err, data) => { - if (err) { - console.error('Operation failed. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Operation successful. Data:' + JSON.stringify(data)); + console.info("getHapModuleInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -1064,11 +1051,11 @@ Obtains the **ModuleInfo** object of the application. This API uses a promise to **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getHapModuleInfo().then((data) => { - console.info("====>data====>" + JSON.stringify(data)); + console.info("getHapModuleInfo data: " + JSON.stringify(data)); }); ``` @@ -1084,19 +1071,15 @@ Obtains the version information of the application. This API uses an asynchronou | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ------------------------------ | -| callback | AsyncCallback\<[AppVersionInfo](#appversioninfo)> | Yes | Callback used to return the version information.| +| callback | AsyncCallback\<[AppVersionInfo](js-apis-inner-app-appVersionInfo.md)> | Yes | Callback used to return the version information.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getAppVersionInfo((err, data) => { - if (err) { - console.error('Operation failed. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Operation successful. Data:' + JSON.stringify(data)); + console.info("getAppVersionInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -1112,15 +1095,15 @@ Obtains the version information of the application. This API uses a promise to r | Type | Description | | ---------------------------------------- | --------- | -| Promise\<[AppVersionInfo](#appversioninfo)> | Promise used to return the version information.| +| Promise\<[AppVersionInfo](js-apis-inner-app-appVersionInfo.md)> | Promise used to return the version information.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getAppVersionInfo().then((data) => { - console.info("====>data====>" + JSON.stringify(data)); + console.info("getAppVersionInfo data: " + JSON.stringify(data)); }); ``` @@ -1140,15 +1123,11 @@ Obtains information about this ability. This API uses an asynchronous callback t **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getAbilityInfo((err, data) => { - if (err) { - console.error('Operation failed. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Operation successful. Data:' + JSON.stringify(data)); + console.info("getAbilityInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -1168,11 +1147,11 @@ Obtains information about this ability. This API uses a promise to return the re **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getAbilityInfo().then((data) => { - console.info("====>data====>" + JSON.stringify(data)); + console.info("getAbilityInfo data: " + JSON.stringify(data)); }); ``` @@ -1192,8 +1171,8 @@ Obtains the context of the application. **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext().getApplicationContext(); ``` @@ -1213,15 +1192,11 @@ Checks whether the configuration of this ability is being updated. This API uses **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.isUpdatingConfigurations((err, data) => { - if (err) { - console.error('Operation failed. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Operation successful. Data:' + JSON.stringify(data)); + console.info("isUpdatingConfigurations err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -1241,11 +1216,11 @@ Checks whether the configuration of this ability is being updated. This API uses **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.isUpdatingConfigurations().then((data) => { - console.info("====>data====>" + JSON.stringify(data)); + console.info("isUpdatingConfigurations data: " + JSON.stringify(data)); }); ``` @@ -1265,15 +1240,11 @@ Notifies the system of the time required to draw this page function. This API us **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); -context.printDrawnCompleted((err, data) => { - if (err) { - console.error('Operation failed. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Operation successful. Data:' + JSON.stringify(data)); +context.printDrawnCompleted((err) => { + console.error('printDrawnCompleted err: ' + JSON.stringify(err)); }); ``` @@ -1293,11 +1264,11 @@ Notifies the system of the time required to draw this page function. This API us **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.printDrawnCompleted().then((data) => { - console.info("====>data====>" + JSON.stringify(data)); + console.info("printDrawnCompleted data: " + JSON.stringify(data)); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-app-processInfo.md b/en/application-dev/reference/apis/js-apis-inner-app-processInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..0da1d45efcd3ae56473a37ec28da8e056dbf3def --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-app-processInfo.md @@ -0,0 +1,22 @@ +# ProcessInfo + +The **ProcessInfo** module defines process information. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| pid | number | Yes| No| Process ID.| +| processName | string | Yes| No| Process name.| + +**Example** +```ts +import featureAbility from '@ohos.ability.featureAbility'; + +var context = featureAbility.getContext(); +context.getProcessInfo((err, data) => { + console.info("getProcessInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); + let pid = data.pid; + let processName = data.processName; +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-application-abilityDelegator.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md similarity index 84% rename from en/application-dev/reference/apis/js-apis-application-abilityDelegator.md rename to en/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md index 1a6035f15c6d68dd374d21e1953163b57d1e7648..71163a1d857e897306e1c90ed3262943fe898e98 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityDelegator.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md @@ -9,7 +9,7 @@ The **AbilityDelegator** module provides APIs for managing **AbilityMonitor** in ## Usage The ability delegator can be obtained by calling **getAbilityDelegator** in **AbilityDelegatorRegistry**. -```js +```ts import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' var abilityDelegator; @@ -22,7 +22,7 @@ abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); ### addAbilityMonitor9+ -addAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\): void +addAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\): void; Adds an **AbilityMonitor** instance. This API uses an asynchronous callback to return the result. @@ -32,12 +32,12 @@ Adds an **AbilityMonitor** instance. This API uses an asynchronous callback to r | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | -------- | ------------------------------------------------------------ | -| monitor | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) instance.| +| monitor | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) instance.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** -```js +```ts var abilityDelegator; function onAbilityCreateCallback(data) { @@ -55,11 +55,9 @@ abilityDelegator.addAbilityMonitor(monitor, (err : any) => { }); ``` - - ### addAbilityMonitor9+ -addAbilityMonitor(monitor: AbilityMonitor): Promise\ +addAbilityMonitor(monitor: AbilityMonitor): Promise\; Adds an **AbilityMonitor** instance. This API uses a promise to return the result. @@ -69,7 +67,7 @@ Adds an **AbilityMonitor** instance. This API uses a promise to return the resul | Name | Type | Mandatory| Description | | ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| monitor | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) instance.| +| monitor | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) instance.| **Return value** @@ -79,7 +77,7 @@ Adds an **AbilityMonitor** instance. This API uses a promise to return the resul **Example** -```js +```ts var abilityDelegator; function onAbilityCreateCallback(data) { @@ -101,7 +99,7 @@ abilityDelegator.addAbilityMonitor(monitor).then(() => { ### removeAbilityMonitor9+ -removeAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\): void +removeAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\): void; Removes an **AbilityMonitor** instance. This API uses an asynchronous callback to return the result. @@ -111,12 +109,12 @@ Removes an **AbilityMonitor** instance. This API uses an asynchronous callback t | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| monitor | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) instance.| +| monitor | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) instance.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** -```js +```ts var abilityDelegator; function onAbilityCreateCallback(data) { @@ -138,7 +136,7 @@ abilityDelegator.removeAbilityMonitor(monitor, (err : any) => { ### removeAbilityMonitor9+ -removeAbilityMonitor(monitor: AbilityMonitor): Promise\ +removeAbilityMonitor(monitor: AbilityMonitor): Promise\; Removes an **AbilityMonitor** instance. This API uses a promise to return the result. @@ -148,7 +146,7 @@ Removes an **AbilityMonitor** instance. This API uses a promise to return the re | Name | Type | Mandatory| Description | | ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| monitor | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) instance.| +| monitor | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) instance.| **Return value** @@ -158,7 +156,7 @@ Removes an **AbilityMonitor** instance. This API uses a promise to return the re - Example -```js +```ts var abilityDelegator; function onAbilityCreateCallback(data) { @@ -180,7 +178,7 @@ abilityDelegator.removeAbilityMonitor(monitor).then(() => { ### waitAbilityMonitor9+ -waitAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\): void +waitAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\): void; Waits for the **Ability** instance that matches the **AbilityMonitor** instance to reach the **OnCreate** lifecycle state and returns the **Ability** instance. This API uses an asynchronous callback to return the result. @@ -190,12 +188,12 @@ Waits for the **Ability** instance that matches the **AbilityMonitor** instance | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| monitor | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) instance.| -| callback | AsyncCallback\<[Ability](js-apis-application-ability.md#Ability)> | Yes | Callback used to return the result. | +| monitor | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) instance.| +| callback | AsyncCallback\<[UIAbility](js-apis-app-ability-uiAbility.md)> | Yes | Callback used to return the result. | **Example** -```js +```ts var abilityDelegator; function onAbilityCreateCallback(data) { @@ -213,11 +211,9 @@ abilityDelegator.waitAbilityMonitor(monitor, (err : any, data : any) => { }); ``` - - ### waitAbilityMonitor9+ -waitAbilityMonitor(monitor: AbilityMonitor, timeout: number, callback: AsyncCallback\): void +waitAbilityMonitor(monitor: AbilityMonitor, timeout: number, callback: AsyncCallback\): void; Waits a period of time for the **Ability** instance that matches the **AbilityMonitor** instance to reach the **OnCreate** lifecycle state and returns the **Ability** instance. This API uses an asynchronous callback to return the result. @@ -227,13 +223,13 @@ Waits a period of time for the **Ability** instance that matches the **AbilityMo | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| monitor | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) instance.| -| timeout | number | Yes | Maximum waiting time, in milliseconds. | -| callback | AsyncCallback\<[Ability](js-apis-application-ability.md#Ability)> | Yes | Callback used to return the result. | +| monitor | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) instance.| +| timeout | number | No | Maximum waiting time, in milliseconds. | +| callback | AsyncCallback\<[UIAbility](js-apis-app-ability-uiAbility.md)> | Yes | Callback used to return the result. | **Example** -```js +```ts var abilityDelegator; var timeout = 100; @@ -256,7 +252,7 @@ abilityDelegator.waitAbilityMonitor(monitor, timeout, (err : any, data : any) => ### waitAbilityMonitor9+ -waitAbilityMonitor(monitor: AbilityMonitor, timeout?: number): Promise\ +waitAbilityMonitor(monitor: AbilityMonitor, timeout?: number): Promise\; Waits a period of time for the **Ability** instance that matches the **AbilityMonitor** instance to reach the **OnCreate** lifecycle state and returns the **Ability** instance. This API uses a promise to return the result. @@ -266,18 +262,18 @@ Waits a period of time for the **Ability** instance that matches the **AbilityMo | Name | Type | Mandatory| Description | | ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| monitor | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) instance.| +| monitor | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) instance.| | timeout | number | No | Maximum waiting time, in milliseconds. | **Return value** | Type | Description | | ----------------------------------------------------------- | -------------------------- | -| Promise\<[Ability](js-apis-application-ability.md#Ability)> | Promise used to return the **Ability** instance.| +| Promise\<[UIAbility](js-apis-app-ability-uiAbility.md)> | Promise used to return the **Ability** instance.| **Example** -```js +```ts var abilityDelegator; function onAbilityCreateCallback(data) { @@ -299,7 +295,7 @@ abilityDelegator.waitAbilityMonitor(monitor).then((data : any) => { ### getAppContext9+ -getAppContext(): Context +getAppContext(): Context; Obtains the application context. @@ -309,11 +305,11 @@ Obtains the application context. | Type | Description | | ------------------------------------- | ------------------------------------------- | -| [Context](js-apis-Context.md#Context) | [Context](js-apis-Context.md#Context) of the application.| +| [Context](js-apis-inner-application-context.md) | Application [context](js-apis-inner-application-context.md).| **Example** -```js +```ts var abilityDelegator; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); @@ -324,7 +320,7 @@ var context = abilityDelegator.getAppContext(); ### getAbilityState9+ -getAbilityState(ability: Ability): number +getAbilityState(ability: UIAbility): number; Obtains the lifecycle state of an ability. @@ -334,17 +330,17 @@ Obtains the lifecycle state of an ability. | Name | Type | Mandatory| Description | | ------- | ------------------------------------------------- | ---- | --------------- | -| ability | [Ability](js-apis-application-ability.md#Ability) | Yes | Target ability.| +| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes | Target ability.| **Return value** | Type | Description | | ------ | ------------------------------------------------------------ | -| number | Lifecycle state of the ability. For details about the available enumerated values, see [AbilityLifecycleState](js-apis-abilityDelegatorRegistry.md#AbilityLifecycleState).| +| number | Lifecycle state of the ability. For details about the available enumerated values, see [AbilityLifecycleState](js-apis-application-abilityDelegatorRegistry.md#AbilityLifecycleState).| **Example** -```js +```ts var abilityDelegator; var ability; @@ -361,7 +357,7 @@ abilityDelegator.getCurrentTopAbility((err : any, data : any) => { ### getCurrentTopAbility9+ -getCurrentTopAbility(callback: AsyncCallback\): void +getCurrentTopAbility(callback: AsyncCallback\): void; Obtains the top ability of this application. This API uses an asynchronous callback to return the result. @@ -371,11 +367,11 @@ Obtains the top ability of this application. This API uses an asynchronous callb | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------ | -| callback | AsyncCallback\<[Ability](js-apis-application-ability.md#Ability)> | Yes | Callback used to return the result.| +| callback | AsyncCallback\<[UIAbility](js-apis-app-ability-uiAbility.md)> | Yes | Callback used to return the result.| **Example** -```js +```ts var abilityDelegator; var ability; @@ -390,7 +386,7 @@ abilityDelegator.getCurrentTopAbility((err : any, data : any) => { ### getCurrentTopAbility9+ -getCurrentTopAbility(): Promise\ +getCurrentTopAbility(): Promise\; Obtains the top ability of this application. This API uses a promise to return the result. @@ -400,11 +396,11 @@ Obtains the top ability of this application. This API uses a promise to return t | Type | Description | | ----------------------------------------------------------- | -------------------------------------- | -| Promise\<[Ability](js-apis-application-ability.md#Ability)> | Promise used to return the top ability.| +| Promise\<[UIAbility](js-apis-app-ability-uiAbility.md)> | Promise used to return the top ability.| **Example** -```js +```ts var abilityDelegator; var ability; @@ -419,7 +415,7 @@ abilityDelegator.getCurrentTopAbility().then((data : any) => { ### startAbility9+ -startAbility(want: Want, callback: AsyncCallback\): void +startAbility(want: Want, callback: AsyncCallback\): void; Starts an ability. This API uses an asynchronous callback to return the result. @@ -429,12 +425,12 @@ Starts an ability. This API uses an asynchronous callback to return the result. | Name | Type | Mandatory| Description | | -------- | -------------------------------------- | ---- | ------------------ | -| want | [Want](js-apis-application-Want.md) | Yes | **Want** parameter for starting the ability. | +| want | [Want](js-apis-application-want.md) | Yes | **Want** parameter for starting the ability. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** -```js +```ts var abilityDelegator; var want = { bundleName: "bundleName", @@ -451,7 +447,7 @@ abilityDelegator.startAbility(want, (err : any, data : any) => { ### startAbility9+ -startAbility(want: Want): Promise\ +startAbility(want: Want): Promise\; Starts an ability. This API uses a promise to return the result. @@ -461,7 +457,7 @@ Starts an ability. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | -------------------------------------- | ---- | --------------- | -| want | [Want](js-apis-application-Want.md) | Yes | **Want** parameter for starting the ability.| +| want | [Want](js-apis-application-want.md) | Yes | **Want** parameter for starting the ability.| **Return value** @@ -471,7 +467,7 @@ Starts an ability. This API uses a promise to return the result. **Example** -```js +```ts var abilityDelegator; var want = { bundleName: "bundleName", @@ -488,7 +484,7 @@ abilityDelegator.startAbility(want).then((data: any) => { ### doAbilityForeground9+ -doAbilityForeground(ability: Ability, callback: AsyncCallback\): void +doAbilityForeground(ability: UIAbility, callback: AsyncCallback\): void; Schedules the lifecycle state of an ability to **Foreground**. This API uses an asynchronous callback to return the result. @@ -498,12 +494,12 @@ Schedules the lifecycle state of an ability to **Foreground**. This API uses an | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | ------------------------------------------------------- | -| ability | Ability | Yes | Target ability. | -| callback | AsyncCallback\ | Yes | Callback used to return the result.
\- **true**: The operation is successful.
\- **false**: The operation failed.| +| ability | UIAbility | Yes | Target ability. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.
\- **true**: The operation is successful.
\- **false**: The operation failed.| **Example** -```js +```ts var abilityDelegator; var ability; @@ -521,7 +517,7 @@ abilityDelegator.getCurrentTopAbility((err : any, data : any) => { ### doAbilityForeground9+ -doAbilityForeground(ability: Ability): Promise\ +doAbilityForeground(ability: UIAbility): Promise\; Schedules the lifecycle state of an ability to **Foreground**. This API uses a promise to return the result. @@ -531,7 +527,7 @@ Schedules the lifecycle state of an ability to **Foreground**. This API uses a p | Name | Type | Mandatory| Description | | ------- | ------- | ---- | --------------- | -| ability | Ability | Yes | Target ability.| +| ability | UIAbility | Yes | Target ability.| **Return value** @@ -541,7 +537,7 @@ Schedules the lifecycle state of an ability to **Foreground**. This API uses a p **Example** -```js +```ts var abilityDelegator; var ability; @@ -559,7 +555,7 @@ abilityDelegator.getCurrentTopAbility((err : any, data : any) => { ### doAbilityBackground9+ -doAbilityBackground(ability: Ability, callback: AsyncCallback\): void +doAbilityBackground(ability: UIAbility, callback: AsyncCallback\): void; Schedules the lifecycle state of an ability to **Background**. This API uses an asynchronous callback to return the result. @@ -569,12 +565,12 @@ Schedules the lifecycle state of an ability to **Background**. This API uses an | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | ------------------------------------------------------- | -| ability | Ability | Yes | Target ability. | -| callback | AsyncCallback\ | Yes | Callback used to return the result.
\- **true**: The operation is successful.
\- **false**: The operation failed.| +| ability | UIAbility | Yes | Target ability. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.
\- **true**: The operation is successful.
\- **false**: The operation failed.| **Example** -```js +```ts var abilityDelegator; var ability; @@ -592,7 +588,7 @@ abilityDelegator.getCurrentTopAbility((err : any, data : any) => { ### doAbilityBackground9+ -doAbilityBackground(ability: Ability): Promise\ +doAbilityBackground(ability: UIAbility): Promise\; Schedules the lifecycle state of an ability to **Background**. This API uses a promise to return the result. @@ -602,7 +598,7 @@ Schedules the lifecycle state of an ability to **Background**. This API uses a p | Name | Type | Mandatory| Description | | ------- | ------- | ---- | --------------- | -| ability | Ability | Yes | Target ability.| +| ability | UIAbility | Yes | Target ability.| **Return value** @@ -612,7 +608,7 @@ Schedules the lifecycle state of an ability to **Background**. This API uses a p **Example** -```js +```ts var abilityDelegator; var ability; @@ -630,7 +626,7 @@ abilityDelegator.getCurrentTopAbility((err : any, data : any) => { ### printSync9+ -printSync(msg: string): void +printSync(msg: string): void; Prints log information to the unit test console. @@ -644,7 +640,7 @@ Prints log information to the unit test console. **Example** -```js +```ts var abilityDelegator; var msg = "msg"; @@ -656,7 +652,7 @@ abilityDelegator.printSync(msg); ### print -print(msg: string, callback: AsyncCallback\): void +print(msg: string, callback: AsyncCallback\): void; Prints log information to the unit test console. This API uses an asynchronous callback to return the result. @@ -671,7 +667,7 @@ Prints log information to the unit test console. This API uses an asynchronous c **Example** -```js +```ts var abilityDelegator; var msg = "msg"; @@ -685,7 +681,7 @@ abilityDelegator.print(msg, (err : any) => { ### print -print(msg: string): Promise\ +print(msg: string): Promise\; Prints log information to the unit test console. This API uses a promise to return the result. @@ -705,7 +701,7 @@ Prints log information to the unit test console. This API uses a promise to retu **Example** -```js +```ts var abilityDelegator; var msg = "msg"; @@ -719,7 +715,7 @@ abilityDelegator.print(msg).then(() => { ### executeShellCommand -executeShellCommand(cmd: string, callback: AsyncCallback\): void +executeShellCommand(cmd: string, callback: AsyncCallback\): void; Executes a shell command. This API uses an asynchronous callback to return the result. @@ -730,11 +726,11 @@ Executes a shell command. This API uses an asynchronous callback to return the r | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------ | | cmd | string | Yes | Shell command string. | -| callback | AsyncCallback\<[ShellCmdResult](js-apis-application-shellCmdResult.md#ShellCmdResult)> | Yes | Callback used to return the result.| +| callback | AsyncCallback\<[ShellCmdResult](js-apis-inner-application-shellCmdResult.md#ShellCmdResult)> | Yes | Callback used to return the result.| **Example** -```js +```ts var abilityDelegator; var cmd = "cmd"; @@ -748,7 +744,7 @@ abilityDelegator.executeShellCommand(cmd, (err : any, data : any) => { ### executeShellCommand -executeShellCommand(cmd: string, timeoutSecs: number, callback: AsyncCallback\): void +executeShellCommand(cmd: string, timeoutSecs: number, callback: AsyncCallback\): void; Executes a shell command with the timeout period specified. This API uses an asynchronous callback to return the result. @@ -759,12 +755,12 @@ Executes a shell command with the timeout period specified. This API uses an asy | Name | Type | Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | ----------------------------- | | cmd | string | Yes | Shell command string. | -| timeoutSecs | number | Yes | Command timeout period, in seconds.| -| callback | AsyncCallback\<[ShellCmdResult](js-apis-application-shellCmdResult.md#ShellCmdResult)> | Yes | Callback used to return the result. | +| timeoutSecs | number | No | Command timeout period, in seconds.| +| callback | AsyncCallback\<[ShellCmdResult](js-apis-inner-application-shellCmdResult.md#ShellCmdResult)> | Yes | Callback used to return the result. | **Example** -```js +```ts var abilityDelegator; var cmd = "cmd"; var timeout = 100; @@ -779,7 +775,7 @@ abilityDelegator.executeShellCommand(cmd, timeout, (err : any, data : any) => { ### executeShellCommand -executeShellCommand(cmd: string, timeoutSecs?: number): Promise\ +executeShellCommand(cmd: string, timeoutSecs?: number): Promise\; Executes a shell command with the timeout period specified. This API uses a promise to return the result. @@ -796,11 +792,11 @@ Executes a shell command with the timeout period specified. This API uses a prom | Type | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| Promise\<[ShellCmdResult](js-apis-application-shellCmdResult.md#ShellCmdResult)> | Promise used to return a [ShellCmdResult](js-apis-application-shellCmdResult.md#ShellCmdResult) object.| +| Promise\<[ShellCmdResult](js-apis-inner-application-shellCmdResult.md#ShellCmdResult)> | Promise used to return a [ShellCmdResult](js-apis-inner-application-shellCmdResult.md#ShellCmdResult) object.| **Example** -```js +```ts var abilityDelegator; var cmd = "cmd"; var timeout = 100; @@ -815,7 +811,7 @@ abilityDelegator.executeShellCommand(cmd, timeout).then((data : any) => { ### finishTest9+ -finishTest(msg: string, code: number, callback: AsyncCallback\): void +finishTest(msg: string, code: number, callback: AsyncCallback\): void; Finishes the test and prints log information to the unit test console. This API uses an asynchronous callback to return the result. @@ -831,7 +827,7 @@ Finishes the test and prints log information to the unit test console. This API **Example** -```js +```ts var abilityDelegator; var msg = "msg"; @@ -845,7 +841,7 @@ abilityDelegator.finishTest(msg, 0, (err : any) => { ### finishTest9+ -finishTest(msg: string, code: number): Promise\ +finishTest(msg: string, code: number): Promise\; Finishes the test and prints log information to the unit test console. This API uses a promise to return the result. @@ -866,7 +862,7 @@ Finishes the test and prints log information to the unit test console. This API **Example** -```js +```ts var abilityDelegator; var msg = "msg"; @@ -888,12 +884,12 @@ Adds an **AbilityStageMonitor** instance to monitor the lifecycle state changes | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | -------- | ------------------------------------------------------------ | -| monitor | [AbilityStageMonitor](#abilitystagemonitor) | Yes | [AbilityStageMonitor](#abilitystagemonitor) instance.| +| monitor | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) | Yes | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) instance.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** -```js +```ts var abilityDelegator; var monitor = { @@ -921,7 +917,7 @@ Adds an **AbilityStageMonitor** instance to monitor the lifecycle state changes | Name | Type | Mandatory| Description | | ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| monitor | [AbilityStageMonitor](#abilitystagemonitor) | Yes | [AbilityStageMonitor](#abilitystagemonitor) instance.| +| monitor | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) | Yes | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) instance.| **Return value** @@ -931,7 +927,7 @@ Adds an **AbilityStageMonitor** instance to monitor the lifecycle state changes **Example** -```js +```ts var abilityDelegator; var monitor = { @@ -957,12 +953,12 @@ Removes an **AbilityStageMonitor** instance from the application memory. This AP | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | -------- | ------------------------------------------------------------ | -| monitor | [AbilityStageMonitor](#abilitystagemonitor) | Yes | [AbilityStageMonitor](#abilitystagemonitor) instance.| +| monitor | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) | Yes | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) instance.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** -```js +```ts var abilityDelegator; var monitor = { @@ -990,7 +986,7 @@ Removes an **AbilityStageMonitor** object from the application memory. This API | Name | Type | Mandatory| Description | | ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| monitor | [AbilityStageMonitor](#abilitystagemonitor) | Yes | [AbilityStageMonitor](#abilitystagemonitor) instance.| +| monitor | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) | Yes | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) instance.| **Return value** @@ -1000,7 +996,7 @@ Removes an **AbilityStageMonitor** object from the application memory. This API **Example** -```js +```ts var abilityDelegator; var monitor = { @@ -1026,12 +1022,12 @@ Waits for an **AbilityStage** instance that matches the conditions set in an **A | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | -------- | ------------------------------------------------------------ | -| monitor | [AbilityStageMonitor](#abilitystagemonitor) | Yes | [AbilityStageMonitor](#abilitystagemonitor) instance.| +| monitor | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) | Yes | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) instance.| | callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, an **AbilityStage** instance is returned. Otherwise, no value is returned. | **Example** -```js +```ts var abilityDelegator; function onAbilityCreateCallback(data) { @@ -1061,7 +1057,7 @@ Waits for an **AbilityStage** instance that matches the conditions set in an **A | Name | Type | Mandatory| Description | | ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| monitor | [AbilityStageMonitor](#abilitystagemonitor) | Yes | [AbilityStageMonitor](#abilitystagemonitor) instance.| +| monitor | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) | Yes | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) instance.| | timeout | number | No | Maximum waiting time, in milliseconds.| **Return value** @@ -1072,7 +1068,7 @@ Waits for an **AbilityStage** instance that matches the conditions set in an **A **Example** -```js +```ts var abilityDelegator; function onAbilityCreateCallback(data) { @@ -1102,13 +1098,13 @@ Waits a period of time for an **AbilityStage** instance that matches the conditi | Name | Type | Mandatory| Description | | ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| monitor | [AbilityStageMonitor](#abilitystagemonitor) | Yes | [AbilityStageMonitor](#abilitystagemonitor) instance.| +| monitor | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) | Yes | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) instance.| | timeout | number | No | Maximum waiting time, in milliseconds.| | callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, an **AbilityStage** instance is returned. Otherwise, no value is returned. | **Example** -```js +```ts var abilityDelegator; var timeout = 100; @@ -1126,14 +1122,3 @@ abilityDelegator.waitAbilityStageMonitor(monitor, timeout, (err : any, data : an console.info("waitAbilityStageMonitor callback"); }); ``` - -## AbilityStageMonitor - -Provides conditions for matching **AbilityStage** instances. The most recently matched **AbilityStage** instance is saved in an **AbilityStageMonitor** instance. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name | Type | Readable| Writable| Description | -| ------------------------------------------------------------ | -------- | ---- | ---- | ------------------------------------------------------------ | -| moduleName9+ | string | Yes | Yes | Module name of the **AbilityStage** instance.| -| srcEntrance9+ | string | Yes | Yes | Source path of the **AbilityStage** instance.| diff --git a/en/application-dev/reference/apis/js-apis-application-abilityDelegatorArgs.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegatorArgs.md similarity index 88% rename from en/application-dev/reference/apis/js-apis-application-abilityDelegatorArgs.md rename to en/application-dev/reference/apis/js-apis-inner-application-abilityDelegatorArgs.md index e1b3aa3bbe5e16262db584894055c090a224b625..97ecb0ed8bf03802ac2a8e1dcab4516d45acc36d 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityDelegatorArgs.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegatorArgs.md @@ -10,12 +10,6 @@ The **AbilityDelegatorArgs** module provides a global register to store the regi The ability delegator arguments are obtained by calling **getArguments** in **AbilityDelegatorRegistry**. -```js -import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'; - -var args = AbilityDelegatorRegistry.getArguments(); -``` - ## AbilityDelegatorArgs Describes the ability delegator arguments. @@ -24,7 +18,15 @@ Describes the ability delegator arguments. | Name | Type | Readable| Writable| Description | | ------------------- | ---------------------- | ---- | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Yes | Bundle name of the application to test. | -| parameters | {[key:string]: string} | Yes | Yes | Parameters of the unit test that is started currently. | -| testCaseNames | string | Yes | Yes | Test case names. | -| testRunnerClassName | string | Yes | Yes | Names of the test case executors. | +| bundleName | string | Yes | Yes | Bundle name of the application to test.| +| parameters | {[key:string]: string} | Yes | Yes | Parameters of the unit test that is started currently.| +| testCaseNames | string | Yes | Yes | Test case names.| +| testRunnerClassName | string | Yes | Yes | Names of the test case executors.| + +**Example** + +```ts +import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'; + +var args = AbilityDelegatorRegistry.getArguments(); +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityMonitor.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityMonitor.md new file mode 100644 index 0000000000000000000000000000000000000000..7aef3303481563008a79f7f8a43be66cbbbfa7fa --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityMonitor.md @@ -0,0 +1,49 @@ +# AbilityMonitor + +The **AbilityMonitor** module provides monitors for abilities that meet specified conditions. The latest matched abilities are stored in an **AbilityMonitor** object. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Usage + +The ability monitor can be set by calling **addAbilityMonitor** in **abilityDelegator**. + +## AbilityMonitor + +Describes an ability monitor. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Type | Readable| Writable| Description | +| ------------------------------------------------------------ | -------- | ---- | ---- | ------------------------------------------------------------ | +| abilityName | string | Yes | Yes | Name of the ability bound to the ability monitor.| +| onAbilityCreate?:(data: [UIAbility](js-apis-app-ability-uiAbility.md)) | function | Yes | Yes | Called when the ability is created.
If this attribute is not set, the corresponding lifecycle callback cannot be received.| +| onAbilityForeground?:(data: [UIAbility](js-apis-app-ability-uiAbility.md)) | function | Yes | Yes | Called when the ability starts to run in the foreground.
If this attribute is not set, the corresponding lifecycle callback cannot be received.| +| onAbilityBackground?:(data: [UIAbility](js-apis-app-ability-uiAbility.md)) | function | Yes | Yes | Called when the ability starts to run in the background.
If this attribute is not set, the corresponding lifecycle callback cannot be received.| +| onAbilityDestroy?:(data: [UIAbility](js-apis-app-ability-uiAbility.md)) | function | Yes | Yes | Called when the ability is destroyed.
If this attribute is not set, the corresponding lifecycle callback cannot be received.
| +| onWindowStageCreate?:(data: [UIAbility](js-apis-app-ability-uiAbility.md)) | function | Yes | Yes | Called when the window stage is created.
If this attribute is not set, the corresponding lifecycle callback cannot be received.
| +| onWindowStageRestore?:(data: [UIAbility](js-apis-app-ability-uiAbility.md)) | function | Yes | Yes | Called when the window stage is restored.
If this attribute is not set, the corresponding lifecycle callback cannot be received.
| +| onWindowStageDestroy?:(data: [UIAbility](js-apis-app-ability-uiAbility.md)) | function | Yes | Yes | Called when the window stage is destroyed.
If this attribute is not set, the corresponding lifecycle callback cannot be received.
| + +**Example** + +```ts +import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' +var abilityDelegator; + +function onAbilityCreateCallback(data) { + console.info("onAbilityCreateCallback"); +} + +var monitor = { + abilityName: "abilityname", + onAbilityCreate: onAbilityCreateCallback +} + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.addAbilityMonitor(monitor, (err : any) => { + console.info("addAbilityMonitor callback"); +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-abilityrunninginfo.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md similarity index 56% rename from en/application-dev/reference/apis/js-apis-abilityrunninginfo.md rename to en/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md index 098f4ebba840a13d1f37d6e14256fcc9695f2a8d..4f553001c63881441b23a3ce42ba429497775b2d 100644 --- a/en/application-dev/reference/apis/js-apis-abilityrunninginfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md @@ -1,6 +1,6 @@ # AbilityRunningInfo -The **AbilityRunningInfo** module implements ability running information and ability states. +The **AbilityRunningInfo** module defines the running information and state of an ability. > **NOTE** > @@ -10,13 +10,6 @@ The **AbilityRunningInfo** module implements ability running information and abi The ability running information is obtained by using the **getAbilityRunningInfos** API in **abilityManager**. -```js -import abilitymanager from '@ohos.application.abilityManager'; -abilitymanager.getAbilityRunningInfos((err,data) => { - console.log("getAbilityRunningInfos err: " + err + " data: " + JSON.stringify(data)); -}); -``` - ## Attributes **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -30,4 +23,22 @@ abilitymanager.getAbilityRunningInfos((err,data) => { | uid | number | Yes| No| User ID. | | processName | string | Yes| No| Process name. | | startTime | number | Yes| No| Ability start time. | -| abilityState | [abilityManager.AbilityState](js-apis-application-abilityManager.md#abilitystate) | Yes| No| Ability state. | +| abilityState | [abilityManager.AbilityState](js-apis-app-ability-abilityManager.md#abilitystate) | Yes| No| Ability state. | + +**Example** + +```ts +import abilitymanager from '@ohos.application.abilityManager'; +abilitymanager.getAbilityRunningInfos((err,data) => { + console.log("getAbilityRunningInfos err: " + err + " data: " + JSON.stringify(data)); + for (let i = 0; i < data.length; i++) { + let abilityinfo = data[i]; + console.log("abilityinfo.ability: " + JSON.stringify(abilityinfo.ability)); + console.log("abilityinfo.pid: " + JSON.stringify(abilityinfo.pid)); + console.log("abilityinfo.uid: " + JSON.stringify(abilityinfo.uid)); + console.log("abilityinfo.processName: " + JSON.stringify(abilityinfo.processName)); + console.log("abilityinfo.startTime: " + JSON.stringify(abilityinfo.startTime)); + console.log("abilityinfo.abilityState: " + JSON.stringify(abilityinfo.abilityState)); + } +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-abilitystagecontext.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md similarity index 99% rename from en/application-dev/reference/apis/js-apis-abilitystagecontext.md rename to en/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md index 5475dc51466d01d8eadef472248cce237f1b6241..99a2453d84124b1eee3d7dc6a5aa7c2d8e5b8663 100644 --- a/en/application-dev/reference/apis/js-apis-abilitystagecontext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md @@ -13,7 +13,7 @@ This module provides APIs for accessing a specific ability stage. You can use th The ability stage context is obtained through an **AbilityStage** instance. -```js +```ts import AbilityStage from '@ohos.application.AbilityStage'; class MyAbilityStage extends AbilityStage { onCreate() { diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md new file mode 100644 index 0000000000000000000000000000000000000000..76a4ae2e425ce91acb0f79d22889cba231809c26 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md @@ -0,0 +1,25 @@ +# AbilityStageMonitor + +The **AbilityStageMonitor** module provides conditions for matching **AbilityStage** instances. The most recently matched **AbilityStage** instance is saved in an **AbilityStageMonitor** instance. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Type | Readable| Writable| Description | +| ------------------------------------------------------------ | -------- | ---- | ---- | ------------------------------------------------------------ | +| moduleName9+ | string | Yes | Yes | Module name of the **AbilityStage** instance.| +| srcEntrance9+ | string | Yes | Yes | Source path of the **AbilityStage** instance.| + +**Example** +```ts +import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' + +let monitor = { + moduleName: "feature_as1", + srcEntrance: "./ets/Application/MyAbilityStage.ts", +}; + +let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.waitAbilityStageMonitor(monitor, (error, data) => { + console.info("stageMonitor waitAbilityStageMonitor, abilityStage = " + JSON.stringify(data)); +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityStateData.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityStateData.md new file mode 100644 index 0000000000000000000000000000000000000000..b86ba33545181076833461e4a63650290d15be9b --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityStateData.md @@ -0,0 +1,33 @@ +# AbilityStateData + +The **AbilityStateData** module defines the ability state information. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Type | Readable| Writable| Description | +| ----------------------- | ---------| ---- | ---- | ------------------------- | +| pid8+ | number | Yes | No | Process ID. | +| bundleName8+ | string | Yes | No | Bundle name of an application. | +| abilityName8+ | string | Yes | No | Ability name. | +| uid8+ | number | Yes | No | User ID. | +| state8+ | number | Yes | No | Ability state. | +| moduleName9+ | string | Yes | No | Name of the HAP file to which the ability belongs. | +| abilityType8+ | string | Yes | No | Ability type. | + +**Example** +```ts +import appManager from "@ohos.application.appManager" + +appManager.getForegroundApplications((error, data) => { + for(let i=0; i **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The APIs of this module can be used only in the stage model. + +## Usage + +Before using the **AccessibilityExtensionContext** module, you must define a child class that inherits from **AccessibilityExtensionAbility**. + +```ts +import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtensionAbility' +let axContext; +class MainAbility extends AccessibilityExtensionAbility { + onConnect(): void { + console.log('AxExtensionAbility onConnect'); + axContext = this.context; + } +} +``` + +## FocusDirection + +Enumerates the focus directions. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +| Name | Description | +| -------- | ------- | +| up | Search for the next focusable item above the current item in focus.| +| down | Search for the next focusable item below the current item in focus.| +| left | Search for the next focusable item on the left of the current item in focus.| +| right | Search for the next focusable item on the right of the current item in focus.| +| forward | Search for the next focusable item before the current item in focus.| +| backward | Search for the next focusable item after the current item in focus.| + +## FocusType + +Enumerates the focus types. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +| Name | Description | +| ------------- | ----------- | +| accessibility | Accessibility focus.| +| normal | Normal focus. | + +## Rect + +Defines a rectangle. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +| Name | Type | Readable | Writable | Description | +| ------ | ------ | ---- | ---- | --------- | +| left | number | Yes | No | Left boundary of the rectangle.| +| top | number | Yes | No | Top boundary of the rectangle.| +| width | number | Yes | No | Width of the rectangle. | +| height | number | Yes | No | Height of the rectangle. | + +## WindowType + +Enumerates the window types. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +| Name | Description | +| ----------- | --------- | +| application | Application window.| +| system | System window.| + +## AccessibilityExtensionContext.setTargetBundleName + +setTargetBundleName(targetNames: Array\): Promise\; + +Sets the concerned target bundle. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------------------- | ---- | -------- | +| targetNames | Array<string> | Yes | Name of the target bundle.| + +**Return value** + +| Type | Description | +| ---------------------- | --------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +let targetNames = ['com.ohos.xyz']; +try { + axContext.setTargetBundleName(targetNames).then(() => { + console.info('set target bundle names success'); + }).catch((err) => { + console.error('failed to set target bundle names, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to set target bundle names, because ' + JSON.stringify(exception)); +}; +``` + +## AccessibilityExtensionContext.setTargetBundleName + +setTargetBundleName(targetNames: Array\, callback: AsyncCallback\): void; + +Sets the concerned target bundle. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------------------- | ---- | -------- | +| targetNames | Array<string> | Yes | Name of the target bundle.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation fails, **error** that contains data is returned.| + +**Example** + +```ts +let targetNames = ['com.ohos.xyz']; +try { + axContext.setTargetBundleName(targetNames, (err, data) => { + if (err) { + console.error('failed to set target bundle names, because ' + JSON.stringify(err)); + return; + } + console.info('set target bundle names success'); + }); +} catch (exception) { + console.error('failed to set target bundle names, because ' + JSON.stringify(exception)); +}; +``` + +## AccessibilityExtensionContext.getFocusElement + +getFocusElement(isAccessibilityFocus?: boolean): Promise\; + +Obtains the focus element. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------------- | ------- | ---- | ------------------- | +| isAccessibilityFocus | boolean | No | Whether the obtained focus element is an accessibility focus. The default value is **false**.| + +**Return value** + +| Type | Description | +| ----------------------------------- | ---------------------- | +| Promise<AccessibilityElement> | Promise used to return the current focus element.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + +**Example** + +```ts +let focusElement; +try { + axContext.getFocusElement().then((data) => { + focusElement = data; + console.log('get focus element success'); + }).catch((err) => { + console.error('failed to get focus element, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to get focus element, because ' + JSON.stringify(exception)); +} +``` + +## AccessibilityExtensionContext.getFocusElement + +getFocusElement(callback: AsyncCallback\): void; + +Obtains the focus element. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<AccessibilityElement> | Yes | Callback used to return the current focus element.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + +**Example** + +```ts +let focusElement; +try { + axContext.getFocusElement((err, data) => { + if (err) { + console.error('failed to get focus element, because ' + JSON.stringify(err)); + return; + } + focusElement = data; + console.info('get focus element success'); + }); +} catch (exception) { + console.error('failed to get focus element, because ' + JSON.stringify(exception)); +} +``` + +## AccessibilityExtensionContext.getFocusElement + +getFocusElement(isAccessibilityFocus: boolean, callback: AsyncCallback\): void; + +Obtains the focus element. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------------- | ------- | ---- | ------------------- | +| isAccessibilityFocus | boolean | Yes | Whether the obtained focus element is an accessibility focus.| +| callback | AsyncCallback<AccessibilityElement> | Yes | Callback used to return the current focus element.| + +**Example** + +```ts +let focusElement; +let isAccessibilityFocus = true; +try { + axContext.getFocusElement(isAccessibilityFocus, (err, data) => { + if (err) { + console.error('failed to get focus element, because ' + JSON.stringify(err)); + return; + } + focusElement = data; + console.info('get focus element success'); +}); +} catch (exception) { + console.error('failed to get focus element, because ' + JSON.stringify(exception)); +} +``` +## AccessibilityExtensionContext.getWindowRootElement + +getWindowRootElement(windowId?: number): Promise\; + +Obtains the root element of a window. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------------- | ------- | ---- | ------------------- | +| windowId | number | No | Window for which you want to obtain the root element. If this parameter is not specified, it indicates the current active window.| + +**Return value** + +| Type | Description | +| ----------------------------------- | ---------------------- | +| Promise<AccessibilityElement> | Promise used to return the root element.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + +**Example** + +```ts +let rootElement; +try { + axContext.getWindowRootElement().then((data) => { + rootElement = data; + console.log('get root element of the window success'); + }).catch((err) => { + console.error('failed to get root element of the window, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to get root element of the window, ' + JSON.stringify(exception)); +} +``` + +## AccessibilityExtensionContext.getWindowRootElement + +getWindowRootElement(callback: AsyncCallback\): void; + +Obtains the root element of a window. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<AccessibilityElement> | Yes | Callback used to return the root element.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + +**Example** + +```ts +let rootElement; +try { + axContext.getWindowRootElement((err, data) => { + if (err) { + console.error('failed to get root element of the window, because ' + JSON.stringify(err)); + return; + } + rootElement = data; + console.info('get root element of the window success'); +}); +} catch (exception) { + console.error('failed to get root element of the window, because ' + JSON.stringify(exception)); +} +``` + +## AccessibilityExtensionContext.getWindowRootElement + +getWindowRootElement(windowId: number, callback: AsyncCallback\): void; + +Obtains the root element of a window. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------------- | ------- | ---- | ------------------- | +| windowId | number | Yes | Window for which you want to obtain the root element. If this parameter is not specified, it indicates the current active window.| +| callback | AsyncCallback<AccessibilityElement> | Yes | Callback used to return the root element.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + +**Example** + +```ts +let rootElement; +let windowId = 10; +try { + axContext.getWindowRootElement(windowId, (err, data) => { + if (err) { + console.error('failed to get root element of the window, because ' + JSON.stringify(err)); + return; + } + rootElement = data; + console.info('get root element of the window success'); +}); +} catch (exception) { + console.error('failed to get root element of the window, because ' + JSON.stringify(exception)); +} +``` + +## AccessibilityExtensionContext.getWindows + +getWindows(displayId?: number): Promise\>; + +Obtains the list of windows on a display. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------------- | ------- | ---- | ------------------- | +| displayId | number | No | ID of the display from which the window information is obtained. If this parameter is not specified, it indicates the default main display.| + +**Return value** + +| Type | Description | +| ----------------------------------- | ---------------------- | +| Promise<Array<AccessibilityElement>> | Promise used to return the window list.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + +**Example** + +```ts +let windows; +try { + axContext.getWindows().then((data) => { + windows = data; + console.log('get windows success'); + }).catch((err) => { + console.error('failed to get windows, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to get windows, because ' + JSON.stringify(exception)); +} +``` + +## AccessibilityExtensionContext.getWindows + +getWindows(callback: AsyncCallback\>): void; + +Obtains the list of windows on a display. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<Array<AccessibilityElement>> | Yes | Callback used to return the window list.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + +**Example** + +```ts +let windows; +try { + axContext.getWindows((err, data) => { + if (err) { + console.error('failed to get windows, because ' + JSON.stringify(err)); + return; + } + windows = data; + console.info('get windows success'); + }); +} catch (exception) { + console.error('failed to get windows, because ' + JSON.stringify(exception)); +} +``` + +## AccessibilityExtensionContext.getWindows + +getWindows(displayId: number, callback: AsyncCallback\>): void; + +Obtains the list of windows on a display. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------------- | ------- | ---- | ------------------- | +| displayId | number | Yes | ID of the display from which the window information is obtained. If this parameter is not specified, it indicates the default main display.| +| callback | AsyncCallback<Array<AccessibilityElement>> | Yes | Callback used to return the window list.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + +**Example** + +```ts +let windows; +let displayId = 10; +try { + axContext.getWindows(displayId, (err, data) => { + if (err) { + console.error('failed to get windows, because ' + JSON.stringify(err)); + return; + } + windows = data; + console.info('get windows success'); + }); +} catch (exception) { + console.error('failed to get windows, because ' + JSON.stringify(exception)); +} +``` + +## AccessibilityExtensionContext.injectGesture + +injectGesture(gesturePath: GesturePath): Promise\; + +Inject a gesture. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| gesturePath | [GesturePath](js-apis-accessibility-GesturePath.md#gesturepath) | Yes | Path of the gesture to inject. | + +**Return value** + +| Type | Description | +| ----------------------------------- | ---------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + +**Example** + +```ts +import GesturePath from "@ohos.accessibility.GesturePath"; +import GesturePoint from '@ohos.accessibility.GesturePoint'; +let gesturePath = new GesturePath.GesturePath(100); +try { + for (let i = 0; i < 10; i++) { + let gesturePoint = new GesturePoint.GesturePoint(100, i * 200); + gesturePath.points.push(gesturePoint); + } + axContext.injectGesture(gesturePath).then(() => { + console.info('inject gesture success'); + }).catch((err) => { + console.error('failed to inject gesture, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to inject gesture, because ' + JSON.stringify(exception)); +} +``` +## AccessibilityExtensionContext.injectGesture + +injectGesture(gesturePath: GesturePath, callback: AsyncCallback\): void + +Inject a gesture. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| gesturePath | [GesturePath](js-apis-accessibility-GesturePath.md#gesturepath) | Yes | Path of the gesture to inject. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + +**Example** + +```ts +import GesturePath from "@ohos.accessibility.GesturePath"; +import GesturePoint from '@ohos.accessibility.GesturePoint'; +let gesturePath = new GesturePath.GesturePath(100); +try { + for (let i = 0; i < 10; i++) { + let gesturePoint = new GesturePoint.GesturePoint(100, i * 200); + gesturePath.points.push(gesturePoint); + } + axContext.injectGesture(gesturePath, (err, data) => { + if (err) { + console.error('failed to inject gesture, because ' + JSON.stringify(err)); + return; + } + console.info('inject gesture success'); + }); +} catch (exception) { + console.error('failed to inject gesture, because ' + JSON.stringify(exception)); +} +``` +## AccessibilityElement9+ + +Defines the accessibilityelement. Before calling APIs of **AccessibilityElement**, you must call [AccessibilityExtensionContext.getFocusElement()](#accessibilityextensioncontextgetfocuselement) or [AccessibilityExtensionContext.getWindowRootElement()](#accessibilityextensioncontextgetwindowrootelement) to obtain an **AccessibilityElement** instance. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +## attributeNames + +attributeNames\(): Promise\>; + +Obtains all attribute names of this element. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------------------------ | +| Promise<Array<T>> | Promise used to return all attribute names of the element.| + +**Example** + +```ts +let rootElement; +let attributeNames; +rootElement.attributeNames().then((data) => { + console.log('get attribute names success'); + attributeNames = data; +}).catch((err) => { + console.log('failed to get attribute names, because ' + JSON.stringify(err)); +}); +``` +## attributeNames + +attributeNames\(callback: AsyncCallback\>): void; + +Obtains all attribute names of this element. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| callback | AsyncCallback<Array<T>> | Yes | Callback used to return all attribute names of the element.| + +**Example** + +```ts +let rootElement; +let attributeNames; +rootElement.attributeNames((err, data) => { + if (err) { + console.error('failed to get attribute names, because ' + JSON.stringify(err)); + return; + } + attributeNames = data; + console.info('get attribute names success'); +}); +``` +## AccessibilityElement.attributeValue + +attributeValue\(attributeName: T): Promise\; + +Obtains the attribute value based on an attribute name. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| attributeName | T | Yes | Attribute name. | + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------------------------ | +| Promise<ElementAttributeValues[T]> | Promise used to return the attribute value.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300004 | This property does not exist. | + +**Example** + +```ts +let attributeName = 'name'; +let attributeValue; +let rootElement; +try { + rootElement.attributeValue(attributeName).then((data) => { + console.log('get attribute value by name success'); + attributeValue = data; + }).catch((err) => { + console.log('failed to get attribute value, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.log('failed to get attribute value, because ' + JSON.stringify(exception)); +} +``` +## AccessibilityElement.attributeValue + +attributeValue\(attributeName: T, + callback: AsyncCallback\): void; + +Obtains the attribute value based on an attribute name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| attributeName | T | Yes | Attribute name. | +| callback | AsyncCallback<ElementAttributeValues[T]> | Yes | Callback used to return the attribute value.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300004 | This property does not exist. | + +**Example** + +```ts +let rootElement; +let attributeValue; +let attributeName = 'name'; +try { + rootElement.attributeValue(attributeName, (err, data) => { + if (err) { + console.error('failed to get attribute value, because ' + JSON.stringify(err)); + return; + } + attributeValue = data; + console.info('get attribute value success'); + }); +} catch (exception) { + console.log('failed to get attribute value, because ' + JSON.stringify(exception)); +} +``` +## actionNames + +actionNames(): Promise\>; + +Obtains the names of all actions supported by this element. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------------------------ | +| Promise<Array<string>> | Promise used to return the names of all actions supported by the element.| + +**Example** + +```ts +let rootElement; +let actionNames; +rootElement.actionNames().then((data) => { + console.log('get action names success'); + actionNames = data; +}).catch((err) => { + console.log('failed to get action names because ' + JSON.stringify(err)); +}); +``` +## actionNames + +actionNames(callback: AsyncCallback\>): void; + +Obtains the names of all actions supported by this element. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the names of all actions supported by the element.| + +**Example** + +```ts +let rootElement; +let actionNames; +rootElement.actionNames((err, data) => { + if (err) { + console.error('failed to get action names, because ' + JSON.stringify(err)); + return; + } + actionNames = data; + console.info('get action names success'); +}); +``` +## performAction + +performAction(actionName: string, parameters?: object): Promise\; + +Performs an action based on the specified action name. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| actionName | string | Yes | Action name. | +| parameters | object | No | Parameter required for performing the target action. | + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------------------------ | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300005 | This action is not supported. | + +**Example** + +```ts +let rootElement; +try { + rootElement.performAction('action').then((data) => { + console.info('perform action success'); + }).catch((err) => { + console.log('failed to perform action, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.log('failed to perform action, because ' + JSON.stringify(exception)); +} +``` +## performAction + +performAction(actionName: string, callback: AsyncCallback\): void; + +Performs an action based on the specified action name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| actionName | string | Yes | Attribute name. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300005 | This action is not supported. | + +**Example** + +```ts +let rootElement; +try { + rootElement.performAction('action', (err, data) => { + if (err) { + console.error('failed to perform action, because ' + JSON.stringify(err)); + return; + } + console.info('perform action success'); + }); +} catch (exception) { + console.log('failed to perform action, because ' + JSON.stringify(exception)); +} +``` +## performAction + +performAction(actionName: string, parameters: object, callback: AsyncCallback\): void; + +Performs an action based on the specified action name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| actionName | string | Yes | Action name. | +| parameters | object | Yes | Parameter required for performing the target action. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300005 | This action is not supported. | + +**Example** + +```ts +let rootElement; +let actionName = 'action'; +let parameters = { + 'setText': 'test text' +}; +try { + rootElement.performAction(actionName, parameters, (err, data) => { + if (err) { + console.error('failed to perform action, because ' + JSON.stringify(err)); + return; + } + console.info('perform action success'); + }); +} catch (exception) { + console.log('failed to perform action, because ' + JSON.stringify(exception)); +} +``` +## findElement('content') + +findElement(type: 'content', condition: string): Promise\>; + +Queries the element information of the **content** type. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| type | string | Yes | Information type. The value is fixed at **'content'**. | +| condition | string | Yes | Search criteria. | + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------------------------ | +| Promise<Array<AccessibilityElement>> | Promise used to return the result.| + +**Example** + +```ts +let rootElement; +let type = 'content'; +let condition = 'keyword'; +let elements; +try { + rootElement.findElement(type, condition).then((data) => { + elements = data; + console.log('find element success'); + }).catch((err) => { + console.log('failed to find element, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.log('failed to find element, because ' + JSON.stringify(exception)); +} +``` +## findElement('content') + +findElement(type: 'content', condition: string, callback: AsyncCallback\>): void; + +Queries the element information of the **content** type. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| type | string | Yes | Information type. The value is fixed at **'content'**. | +| condition | string | Yes | Search criteria. | +| callback | AsyncCallback<Array<AccessibilityElement>> | Yes | Callback used to return the result.| + +**Example** + +```ts +let rootElement; +let type = 'content'; +let condition = 'keyword'; +let elements; +try { + rootElement.findElement(type, condition, (err, data) => { + if (err) { + console.error('failed to find element, because ' + JSON.stringify(err)); + return; + } + elements = data; + console.info('find element success'); + }); +} catch (exception) { + console.log('failed to find element, because ' + JSON.stringify(exception)); +} +``` +## findElement('focusType') + +findElement(type: 'focusType', condition: FocusType): Promise\; + +Queries the element information of the **focusType** type. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| type | string | Yes | Information type. The value is fixed at **'focusType'**. | +| condition | [FocusType](#focustype) | Yes | Enumerates the focus types. | + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------------------------ | +| Promise<AccessibilityElement> | Promise used to return the result.| + +**Example** + +```ts +let rootElement; +let type = 'focusType'; +let condition = 'normal'; +let element; +try { + rootElement.findElement(type, condition).then((data) => { + element = data; + console.log('find element success'); + }).catch((err) => { + console.log('failed to find element, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.log('failed to find element, because ' + JSON.stringify(exception)); +} +``` +## findElement('focusType') + +findElement(type: 'focusType', condition: FocusType, callback: AsyncCallback\): void; + +Queries the element information of the **focusType** type. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| type | string | Yes | Information type. The value is fixed at **'focusType'**. | +| condition | [FocusType](#focustype) | Yes | Enumerates the focus types. | +| callback | AsyncCallback<AccessibilityElement> | Yes | Callback used to return the result.| + +**Example** + +```ts +let rootElement; +let type = 'focusType'; +let condition = 'normal'; +let element; +try { + rootElement.findElement(type, condition, (err, data) => { + if (err) { + console.error('failed to find element, because ' + JSON.stringify(err)); + return; + } + element = data; + console.info('find element success'); + }); +} catch (exception) { + console.log('failed to find element, because ' + JSON.stringify(exception)); +} +``` +## findElement('focusDirection') + +findElement(type: 'focusDirection', condition: FocusDirection): Promise\; + +Queries the element information of the **focusDirection** type. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| type | string | Yes | Information type. The value is fixed at **'focusDirection'**. | +| condition | [FocusDirection](#focusdirection) | Yes | Enumerates the focus directions. | + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------------------------ | +| Promise<AccessibilityElement> | Promise used to return the result.| + +**Example** + +```ts +let rootElement; +let type = 'focusDirection'; +let condition = 'up'; +let element; +try { + rootElement.findElement(type, condition).then((data) => { + element = data; + console.log('find element success'); + }).catch((err) => { + console.log('failed to find element, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.log('failed to find element, because ' + JSON.stringify(exception)); +} +``` +## findElement('focusDirection') + +findElement(type: 'focusDirection', condition: FocusDirection, callback: AsyncCallback\): void; + +Queries the element information of the **focusDirection** type. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| type | string | Yes | Information type. The value is fixed at **'focusDirection'**. | +| condition | [FocusDirection](#focusdirection) | Yes | Direction of the next focus element. | +| callback | AsyncCallback<AccessibilityElement> | Yes | Callback used to return the result.| + +**Example** + +```ts +let rootElement; +let type = 'focusDirection'; +let condition = 'up'; +let elements; +try { + rootElement.findElement(type, condition, (err, data) => { + if (err) { + console.error('failed to find element, because ' + JSON.stringify(err)); + return; + } + elements = data; + console.info('find element success'); + }); +} catch (exception) { + console.log('failed to find element, because ' + JSON.stringify(exception)); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-appStateData.md b/en/application-dev/reference/apis/js-apis-inner-application-appStateData.md new file mode 100644 index 0000000000000000000000000000000000000000..90c03ba3418d2769a695f1bde26d1b2051279115 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-appStateData.md @@ -0,0 +1,27 @@ +# AppStateData + +The **AppStateData** module defines the application state data. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Type | Mandatory| Description | +| ----------- | -------- | ---- | ------------------------------------------------------------ | +| bundleName8+ | string | No | Bundle name of the application. | +| uid8+ | number | No | User ID.| +| state8+ | number | No | Application state.| + +**Example** +```ts +import appManager from "@ohos.application.appManager" + +appManager.getForegroundApplications((error, data) => { + for(let i=0; i { - console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error)); - }); - } } - ``` - +``` ## ApplicationContext.unregisterAbilityLifecycleCallback @@ -102,14 +104,21 @@ Deregisters the listener that monitors the ability lifecycle of the application. **Example** - ```js - let applicationContext = this.context.getApplicationContext(); - let lifecycleId = 1; - console.log("stage applicationContext: " + JSON.stringify(applicationContext)); - applicationContext.unregisterAbilityLifecycleCallback(lifecycleId, (error, data) => { - console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error)); - }); - ``` +```ts +import Ability from "@ohos.application.Ability"; + +var lifecycleId; + +export default class MyAbility extends Ability { + onDestroy() { + let applicationContext = this.context.getApplicationContext(); + console.log("stage applicationContext: " + JSON.stringify(applicationContext)); + applicationContext.unregisterAbilityLifecycleCallback(lifecycleId, (error, data) => { + console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error)); + }); + } +} +``` ## ApplicationContext.registerEnvironmentCallback @@ -123,7 +132,7 @@ Registers a listener for system environment changes. This API uses an asynchrono | Name | Type | Mandatory| Description | | ------------------------ | -------- | ---- | ------------------------------ | -| callback | [EnvironmentCallback](js-apis-application-EnvironmentCallback.md) | Yes | Callback used to return the ID of the registered listener.| +| callback | [EnvironmentCallback](js-apis-app-ability-environmentCallback.md) | Yes | Callback used to return the ID of the registered listener.| **Return value** @@ -133,14 +142,14 @@ Registers a listener for system environment changes. This API uses an asynchrono **Example** - ```js -import AbilityStage from "@ohos.application.AbilityStage"; +```ts +import Ability from "@ohos.application.Ability"; var callbackId; -export default class MyAbilityStage extends AbilityStage { +export default class MyAbility extends Ability { onCreate() { - console.log("MyAbilityStage onCreate") + console.log("MyAbility onCreate") globalThis.applicationContext = this.context.getApplicationContext(); let EnvironmentCallback = { onConfigurationUpdated(config){ @@ -153,14 +162,8 @@ export default class MyAbilityStage extends AbilityStage { callbackId = applicationContext.registerEnvironmentCallback(EnvironmentCallback); console.log("registerEnvironmentCallback number: " + JSON.stringify(callbackId)); } - onDestroy() { - let applicationContext = globalThis.applicationContext; - applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => { - console.log("unregisterEnvironmentCallback success, err: " + JSON.stringify(error)); - }); - } } - ``` +``` ## ApplicationContext.unregisterEnvironmentCallback @@ -179,10 +182,17 @@ Deregisters the listener for system environment changes. This API uses an asynch **Example** - ```js - let applicationContext = this.context.getApplicationContext(); - let callbackId = 1; - applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => { - console.log("unregisterEnvironmentCallback success, err: " + JSON.stringify(error)); - }); - ``` +```ts +import Ability from "@ohos.application.Ability"; + +var callbackId; + +export default class MyAbility extends Ability { + onDestroy() { + let applicationContext = this.context.getApplicationContext(); + applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => { + console.log("unregisterEnvironmentCallback success, err: " + JSON.stringify(error)); + }); + } +} +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md b/en/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md new file mode 100644 index 0000000000000000000000000000000000000000..15925c305ab652b9b4426c169b430af358e89331 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md @@ -0,0 +1,39 @@ +# ApplicationStateObserver + +The **ApplicationStateObserver** module defines the listener to observe the application state. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Type | Readable| Writable| Description | +| ----------------------- | ---------| ---- | ---- | ------------------------- | +| onForegroundApplicationChanged8+ | AsyncCallback\ | Yes | No | Callback invoked when the foreground or background state of an application changes. | +| onAbilityStateChanged8+ | AsyncCallback\ | Yes | No | Callback invoked when the ability state changes. | +| onProcessCreated8+ | AsyncCallback\ | Yes | No | Callback invoked when a process is created. | +| onProcessDied8+ | AsyncCallback\ | Yes | No | Callback invoked when a process is destroyed. | +| onProcessStateChanged8+ | AsyncCallback\ | Yes | No | Callback invoked when the process state is changed. | + +**Example** +```ts +import appManager from "@ohos.application.appManager" + +let applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log('onForegroundApplicationChanged appStateData: ' + JSON.stringify(appStateData)); + }, + onAbilityStateChanged(abilityStateData) { + console.log('onAbilityStateChanged onAbilityStateChanged: ' + JSON.stringify(abilityStateData)); + }, + onProcessCreated(processData) { + console.log('onProcessCreated onProcessCreated: ' + JSON.stringify(processData)); + }, + onProcessDied(processData) { + console.log('onProcessDied onProcessDied: ' + JSON.stringify(processData)); + }, + onProcessStateChanged(processData) { + console.log('onProcessStateChanged onProcessStateChanged: ' + JSON.stringify(processData)); + } +} +let observerCode = appManager.registerApplicationStateObserver(applicationStateObserver); +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-baseContext.md b/en/application-dev/reference/apis/js-apis-inner-application-baseContext.md new file mode 100644 index 0000000000000000000000000000000000000000..24b284ed85986d96e58afba9c2bc4ff75804ebca --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-baseContext.md @@ -0,0 +1,23 @@ +# BaseContext + +The abstract class **BaseContext** specifies whether its child class **Context** is used for the stage model or FA model. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Type | Readable | Writable | Description | +| -------- | ------ | ---- | ---- | ------- | +| stageMode | boolean | Yes | Yes | Whether the context is used for the stage model.| + +**Example** + + ```ts + class MyContext extends BaseContext { + constructor(stageMode) { + this.stageMode = stageMode; + } + } + ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-context.md b/en/application-dev/reference/apis/js-apis-inner-application-context.md new file mode 100644 index 0000000000000000000000000000000000000000..15e249798f9f731427b8b514b020abde8e924053 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-context.md @@ -0,0 +1,135 @@ +# Context + +The **Context** module provides context for abilities or applications. It allows access to application-specific resources, as well as permission requests and verification. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the stage model. + +## Attributes + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Type | Readable | Writable | Description | +| ----------- | ------ | ---- | ---- | ------- | +| resourceManager | resmgr.ResourceManager | Yes | No | Object for resource management. | +| applicationInfo | ApplicationInfo | Yes | No | Application information.| +| cacheDir | string | Yes | No | Cache directory.| +| tempDir | string | Yes | No | Temporary directory.| +| filesDir | string | Yes | No | File directory.| +| databaseDir | string | Yes | No | Database directory.| +| preferencesDir | string | Yes | No | Preferences directory.| +| bundleCodeDir | string | Yes | No | Bundle code directory.| +| distributedFilesDir | string | Yes | No | Distributed file directory.| +| eventHub | string | Yes | No | Event hub that implements event subscription, unsubscription, and triggering.| +| area | [AreaMode](#areamode) | Yes | No | Area in which the file to be access is located.| + + +## Context.createBundleContext + +createBundleContext(bundleName: string): Context; + +Creates the context based on the bundle name. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ------------- | +| bundleName | string | Yes | Bundle name of the application.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Context | Context created.| + +**Example** + +```ts +let bundleContext = this.context.createBundleContext("com.example.test"); +``` + +## Context.createModuleContext + +createModuleContext(moduleName: string): Context; + +Creates the context based on the module name. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ------------- | +| moduleName | string | Yes | Module name.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Context | Context created.| + +**Example** + +```ts +let moduleContext = this.context.createModuleContext("entry"); +``` + +createModuleContext(bundleName: string, moduleName: string): Context; + +Creates the context based on the bundle name and module name. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ------------- | +| bundleName | string | Yes | Bundle name of the application.| +| moduleName | string | Yes | Module name.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Context | Context created.| + +**Example** + +```ts +let moduleContext = this.context.createModuleContext("com.example.test", "entry"); +``` + +## Context.getApplicationContext + +getApplicationContext(): ApplicationContext; + +Obtains the application context. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type| Description| +| -------- | -------- | +| Context | Application context obtained.| + +**Example** + +```ts +let applicationContext = this.context.getApplicationContext(); +``` + +## AreaMode + +Enumerates the areas in which the file to be access can be located. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name| Value| Description| +| -------- | -------- | -------- | +| EL1 | 0 | Device-level encryption area.| +| EL2 | 1 | User credential encryption area.| diff --git a/en/application-dev/reference/apis/js-apis-inner-application-continueCallback.md b/en/application-dev/reference/apis/js-apis-inner-application-continueCallback.md new file mode 100644 index 0000000000000000000000000000000000000000..93d138db23255a3c312e55a423411cdb29f211e5 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-continueCallback.md @@ -0,0 +1,37 @@ +# ContinueCallback + +The **ContinueCallback** module defines the callback invoked when the mission continuation is complete. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +| Name | Type | Readable | Writable | Description | +| --------------------- | -------- | ---- | ---- | ------------------ | +| onContinueDone | function | Yes | No | Callback used to notify the user that the mission continuation is complete and return the continuation result. | + +**Example** + + ```ts + import distributedMissionManager from '@ohos.distributedMissionManager'; + + let continueDeviceInfo = { + srcDeviceId: "123", + dstDeviceId: "456", + missionId: 123, + wantParam: { + "key":"value" + } + }; + + let continueCallback = { + onContinueDone(result) { + console.log('onContinueDone, result: ' + JSON.stringify(result)); + } + } + + distributedMissionManager.continueMission(continueDeviceInfo, continueCallback, (error) => { + if (error.code != 0) { + console.error('continueMission failed, cause: ' + JSON.stringify(error)) + } + console.info('continueMission finished') + }) + ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-continueDeviceInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-continueDeviceInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..b42044ef893ebd23f97549ad378f21dcf8067c93 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-continueDeviceInfo.md @@ -0,0 +1,40 @@ +# ContinueDeviceInfo + +The **ContinueDeviceInfo** module defines the parameters required for mission continuation. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +| Name | Type | Readable | Writable | Description | +| -------- | ------ | ---- | ---- | ------- | +| srcDeviceId | string | Yes | Yes | ID of the source device.| +| dstDeviceId | string | Yes | Yes | ID of the target device.| +| missionId | number | Yes | Yes | Mission ID.| +| wantParam | {[key: string]: any} | Yes | Yes | Extended parameters.| + +**Example** + + ```ts + import distributedMissionManager from '@ohos.distributedMissionManager'; + + let continueDeviceInfo = { + srcDeviceId: "123", + dstDeviceId: "456", + missionId: 123, + wantParam: { + "key":"value" + } + }; + + let continueCallback = { + onContinueDone(result) { + console.log('onContinueDone, result: ' + JSON.stringify(result)); + } + } + + distributedMissionManager.continueMission(continueDeviceInfo, continueCallback, (error) => { + if (error.code != 0) { + console.error('continueMission failed, cause: ' + JSON.stringify(error)) + } + console.info('continueMission finished') + }) + ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-errorObserver.md b/en/application-dev/reference/apis/js-apis-inner-application-errorObserver.md new file mode 100644 index 0000000000000000000000000000000000000000..056a2313dd1aeffdcd69812c491e9e03a77f5f41 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-errorObserver.md @@ -0,0 +1,30 @@ +# ErrorObserver + +The **ErrorObserver** module defines the listener to observe errors. + +## onUnhandledException + +onUnhandledException(errMsg: string): void; + +Called when an unhandled exception occurs in the JS runtime. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| errMsg | string | No| Message and error stack trace about the exception.| + +**Example** + +```ts +import errorManager from '@ohos.application.errorManager'; + +let observer = { + onUnhandledException(errorMsg) { + console.log('onUnhandledException, errorMsg: ' + JSON.stringify(errorMsg)); + } +} +errorManager.registerErrorObserver(observer) +``` diff --git a/en/application-dev/reference/apis/js-apis-eventhub.md b/en/application-dev/reference/apis/js-apis-inner-application-eventHub.md similarity index 97% rename from en/application-dev/reference/apis/js-apis-eventhub.md rename to en/application-dev/reference/apis/js-apis-inner-application-eventHub.md index 9ae7db735cbc61fa55a764cb285801297452c5d8..9c45684cd9faaf03a8de66ba73541ae75ded9cc3 100644 --- a/en/application-dev/reference/apis/js-apis-eventhub.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-eventHub.md @@ -11,7 +11,7 @@ The **EventHub** module provides APIs to subscribe to, unsubscribe from, and tri Before using any APIs in the **EventHub**, you must obtain an **EventHub** instance through the member variable **context** of the **Ability** instance. -```js +```ts import Ability from '@ohos.application.Ability'; export default class MainAbility extends Ability { func1(){ @@ -23,7 +23,6 @@ export default class MainAbility extends Ability { } ``` - ## EventHub.on on(event: string, callback: Function): void; @@ -39,9 +38,9 @@ Subscribes to an event. | event | string | Yes| Event name.| | callback | Function | Yes| Callback invoked when the event is triggered.| -**Example** - - ```js +**Example** + + ```ts import Ability from '@ohos.application.Ability'; export default class MainAbility extends Ability { @@ -77,9 +76,9 @@ Unsubscribes from an event. If **callback** is specified, this API unsubscribes | event | string | Yes| Event name.| | callback | Function | No| Callback for the event. If **callback** is unspecified, all callbacks of the event are unsubscribed.| -**Example** - - ```js +**Example** + + ```ts import Ability from '@ohos.application.Ability'; export default class MainAbility extends Ability { @@ -115,9 +114,9 @@ Triggers an event. | event | string | Yes| Event name.| | ...args | Object[] | Yes| Variable parameters, which are passed to the callback when the event is triggered.| -**Example** - - ```js +**Example** + + ```ts import Ability from '@ohos.application.Ability'; export default class MainAbility extends Ability { diff --git a/en/application-dev/reference/apis/js-apis-extension-context.md b/en/application-dev/reference/apis/js-apis-inner-application-extensionContext.md similarity index 87% rename from en/application-dev/reference/apis/js-apis-extension-context.md rename to en/application-dev/reference/apis/js-apis-inner-application-extensionContext.md index 71d3df6c294d62f2fafa0801df0d132b88c42fe3..1ed64e2a07cc8e92a7d8310d4fb4d0c42d36ff5b 100644 --- a/en/application-dev/reference/apis/js-apis-extension-context.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-extensionContext.md @@ -2,7 +2,7 @@ The **ExtensionContext** module, inherited from **Context**, implements the context for Extension abilities. -This module provides APIs for accessing resources of a specific Extension ability. An Extension ability can use the context directly provided by **ExtensionContext** or that extended from **ExtensionContext**. For example, **ServiceExtension** uses **[ServiceExtensionContext](js-apis-service-extension-context.md)**, which extends the capabilities of starting, stopping, binding, and unbinding abilities based on **ExtensionContext**. +This module provides APIs for accessing resources of a specific Extension ability. An Extension ability can use the context directly provided by **ExtensionContext** or that extended from **ExtensionContext**. For example, **ServiceExtension** uses [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md), which extends the capabilities of starting, stopping, binding, and unbinding abilities based on **ExtensionContext**. > **NOTE** > @@ -15,8 +15,8 @@ This module provides APIs for accessing resources of a specific Extension abilit | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| currentHapModuleInfo | HapModuleInfo | Yes| No| Information about the HAP file
(See **api\bundle\hapModuleInfo.d.ts** in the **SDK** directory.) | -| config | Configuration | Yes| No| Module configuration information.
(See **api\@ohos.application.Configuration.d.ts** in the **SDK** directory.)| +| currentHapModuleInfo | [HapModuleInfo](js-apis-bundle-HapModuleInfo.md) | Yes| No| Information about the HAP file
(See **api\bundle\hapModuleInfo.d.ts** in the **SDK** directory.) | +| config | [Configuration](js-apis-app-ability-configuration.md) | Yes| No| Module configuration information.
(See **api\@ohos.app.ability.Configuration.d.ts** in the **SDK** directory.)| | extensionAbilityInfo | [ExtensionAbilityInfo](js-apis-bundleManager-extensionAbilityInfo.md) | Yes| No| Extension ability information.
(See **api\bundle\extensionAbilityInfo.d.ts** in the **SDK** directory.)| ## When to Use @@ -30,7 +30,7 @@ To adapt to devices with different performance, an application provides three mo **Example** Define a **ServiceExtension** with the same name for the three modules. -``` js +```ts import ServiceExtension from '@ohos.app.ability.ServiceExtensionAbility' import Want from '@ohos.application.Want' export default class TheServiceExtension extends ServiceExtension { @@ -60,7 +60,7 @@ export default class TheServiceExtension extends ServiceExtension { ``` Start **ServiceExtension** within the **onCreate** callback of the main ability of the entry. -``` js +```ts import Ability from '@ohos.app.ability.Ability' export default class MainAbility extends Ability { onCreate(want, launchParam) { @@ -76,7 +76,7 @@ export default class MainAbility extends Ability { ``` Create a **ServiceModule.ts** file in the entry to execute service logic. -``` js +```ts export default class ServiceModel { moduleName: string; diff --git a/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md b/en/application-dev/reference/apis/js-apis-inner-application-extensionRunningInfo.md similarity index 57% rename from en/application-dev/reference/apis/js-apis-extensionrunninginfo.md rename to en/application-dev/reference/apis/js-apis-inner-application-extensionRunningInfo.md index 841f7755273489a570865b41c63c5103c3af0c9a..9184ae6ce0f0b4b8dee355d96a4c28cf84013ef2 100644 --- a/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-extensionRunningInfo.md @@ -11,14 +11,6 @@ The **ExtensionRunningInfo** module provides running information and states for The Extension ability running information is obtained through an **abilityManager** instance. -```js -import abilityManager from '@ohos.application.abilityManager'; -let upperLimit=1 -abilityManager.getExtensionRunningInfos(upperLimit, (err,data) => { - console.log("getExtensionRunningInfos err: " + err + " data: " + JSON.stringify(data)); -}); -``` - ## Attributes **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -31,4 +23,23 @@ abilityManager.getExtensionRunningInfos(upperLimit, (err,data) => { | processName | string | Yes| No| Process name.| | startTime | number | Yes| No| Start time of the Extension ability.| | clientPackage | Array<String> | Yes| No| Names of all packages in the process.| -| type | [bundle.ExtensionAbilityType](js-apis-Bundle.md#extensionabilitytype9) | Yes| No| Extension ability type.| +| type | [bundle.ExtensionAbilityType](js-apis-Bundle.md) | Yes| No| Extension ability type.| + +**Example** +```ts +import abilityManager from '@ohos.application.abilityManager'; +let upperLimit=1; +abilityManager.getExtensionRunningInfos(upperLimit, (err,data) => { + console.log("getExtensionRunningInfos err: " + err + " data: " + JSON.stringify(data)); + for (let i=0; i { + if (error) { + console.log('FormExtensionContext startAbility, error:' + JSON.stringify(error)); + } else { + console.log(`FormExtensionContext startAbility success`); + } }) ``` -## FormExtensionContext.startAbility +## startAbility startAbility(want: Want): Promise<void> Starts an ability. This API uses a promise to return the result. -**System capability**: SystemCapability.Ability.Form +**System API**: This is a system API. -**System API**: This is a system API and cannot be called by third-party applications. +**System capability**: SystemCapability.Ability.Form **Parameters** | Name| Type | Mandatory| Description | | ------| --------------------------------- | ---- | -------------------------------------- | -| want| [Want](js-apis-application-Want.md) | Yes | Information about the ability to start, such as the ability name and bundle name.| +| want| [Want](js-apis-application-want.md) | Yes | Information about the ability to start, such as the bundle name, ability name, and custom parameters.| **Return value** | Type | Description | | ------------ | ---------------------------------- | -| Promise<void< | Promise used to return the result.| +| Promise<void< | Promise that returns no value.| **Example** -```js +```ts var want = { deviceId: "", bundleName: "com.example.formstartability", diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionCallbacks.md b/en/application-dev/reference/apis/js-apis-inner-application-missionCallbacks.md new file mode 100644 index 0000000000000000000000000000000000000000..e56a2a43e4603f1b2f8e0e2a9dfbaf303e938f7b --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionCallbacks.md @@ -0,0 +1,34 @@ +# MissionCallbacks + +The **MissionCallbacks** module defines the callbacks that can be registered as a mission status listener. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +| Name | Template | Readable | Writable | Description | +| --------------------- | -------- | ---- | ---- | ------------------ | +| notifyMissionsChanged | function | Yes | No | Callback used to notify the mission change event and return the device ID. | +| notifySnapshot | function | Yes | No | Callback used to notify the snapshot change event and return the device ID and mission ID.| +| notifyNetDisconnect | function | Yes | No | Callback used to notify the disconnection event and return the device ID and network status.| + +**Example** +```ts +import distributedMissionManager from '@ohos.distributedMissionManager'; + +let missionDeviceInfo = { + deviceId: "123456" +}; +let missionCallback = { + notifyMissionsChanged: function (deviceId) { + console.log("notifyMissionsChanged deviceId: " + JSON.stringify(deviceId)); + }, + notifySnapshot: function (mission, deviceId) { + console.log("notifySnapshot mission: " + JSON.stringify(mission)); + console.log("notifySnapshot deviceId: " + JSON.stringify(deviceId)); + }, + notifyNetDisconnect: function (mission, state) { + console.log("notifyNetDisconnect mission: " + JSON.stringify(mission)); + console.log("notifyNetDisconnect state: " + JSON.stringify(state)); + } +}; +distributedMissionManager.registerMissionListener(missionDeviceInfo, missionCallback); +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionDeviceInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-missionDeviceInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..028e5dafadb2c6b5c63486f82e08acb2e1f601c5 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionDeviceInfo.md @@ -0,0 +1,32 @@ +# MissionDeviceInfo + +The **MissionDeviceInfo** module defines the parameters required for registering a listener. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +| Name | Type | Readable | Writable | Description | +| -------- | ------ | ---- | ---- | ------- | +| deviceId | string | Yes | Yes | Device ID.| + +**Example** +```ts +import distributedMissionManager from '@ohos.distributedMissionManager'; + +let missionDeviceInfo = { + deviceId: "123456" +}; +let missionCallback = { + notifyMissionsChanged: function (deviceId) { + console.log("notifyMissionsChanged deviceId: " + JSON.stringify(deviceId)); + }, + notifySnapshot: function (mission, deviceId) { + console.log("notifySnapshot mission: " + JSON.stringify(mission)); + console.log("notifySnapshot deviceId: " + JSON.stringify(deviceId)); + }, + notifyNetDisconnect: function (mission, state) { + console.log("notifyNetDisconnect mission: " + JSON.stringify(mission)); + console.log("notifyNetDisconnect state: " + JSON.stringify(state)); + } +}; +distributedMissionManager.registerMissionListener(missionDeviceInfo, missionCallback); +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-missionInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..5240d4229fb1222c91bcbddac116b26e23e69dd9 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionInfo.md @@ -0,0 +1,34 @@ +# MissionInfo + +The **MissionInfo** module defines the mission information of an ability. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| missionId | number | Yes| Yes| Mission ID.| +| runningState | number | Yes| Yes| Running state of the mission.| +| lockedState | boolean | Yes| Yes| Locked state of the mission.| +| timestamp | string | Yes| Yes| Latest time when the mission was created or updated.| +| want | [Want](js-apis-application-want.md) | Yes| Yes| Want information of the mission.| +| label | string | Yes| Yes| Label of the mission.| +| iconPath | string | Yes| Yes| Path of the mission icon.| +| continuable | boolean | Yes| Yes| Whether the mission can be continued on another device.| + +**Example** +```ts +import missionManager from '@ohos.application.missionManager' + +missionManager.getMissionInfo("12345", 1, (error, data) => { + console.info('getMissionInfo missionId is:' + JSON.stringify(data.missionId)); + console.info('getMissionInfo runningState is:' + JSON.stringify(data.runningState)); + console.info('getMissionInfo lockedState is:' + JSON.stringify(data.lockedState)); + console.info('getMissionInfo timestamp is:' + JSON.stringify(data.timestamp)); + console.info('getMissionInfo want is:' + JSON.stringify(data.want)); + console.info('getMissionInfo label is:' + JSON.stringify(data.label)); + console.info('getMissionInfo iconPath is:' + JSON.stringify(data.iconPath)); + console.info('getMissionInfo continuable is:' + JSON.stringify(data.continuable)); +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionListener.md b/en/application-dev/reference/apis/js-apis-inner-application-missionListener.md new file mode 100644 index 0000000000000000000000000000000000000000..1070334b0107b3e3e84101a287b7966f7e16dcff --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionListener.md @@ -0,0 +1,42 @@ +# MissionListener + +The **MissionListener** module defines the listeners used to observe the mission status. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +| Name | Type | Mandatory| Description | +| ----------- | -------- | ---- | ------------------------------------------------------------ | +| onMissionCreated | function | No | Called when the system creates a mission. | +| onMissionDestroyed | function | No | Called when the system destroys the mission.| +| onMissionSnapshotChanged | function | No | Called when the system updates the mission snapshot.| +| onMissionMovedToFront | function | No | Called when the system moves the mission to the foreground.| +| onMissionLabelUpdated | function | No | Called when the system updates the mission label.| +| onMissionIconUpdated | function | No | Called when the system updates the mission icon.| +| onMissionClosed | function | No | Called when the system closes the mission.| + +**Example** +```ts +import missionManager from '@ohos.application.missionManager' + +let listener = { + onMissionCreated: function (mission) { + console.log("onMissionCreated mission: " + JSON.stringify(mission)); + }, + onMissionDestroyed: function (mission) { + console.log("onMissionDestroyed mission: " + JSON.stringify(mission)); + }, + onMissionSnapshotChanged: function (mission) { + console.log("onMissionSnapshotChanged mission: " + JSON.stringify(mission)); + }, + onMissionMovedToFront: function (mission) { + console.log("onMissionMovedToFront mission: " + JSON.stringify(mission)); + }, + onMissionIconUpdated: function (mission, icon) { + console.log("onMissionIconUpdated mission: " + JSON.stringify(mission)); + }, + onMissionClosed: function (mission) { + console.log("onMissionClosed mission: " + JSON.stringify(mission)); + } +}; +let listenerid = missionManager.registerMissionListener(listener); +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionParameter.md b/en/application-dev/reference/apis/js-apis-inner-application-missionParameter.md new file mode 100644 index 0000000000000000000000000000000000000000..5dc8a425524082102b4a554e7b911a1e7a490e8b --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionParameter.md @@ -0,0 +1,31 @@ +# MissionParameter + +The **MissionParameter** module defines the parameters required for mission synchronization. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +| Name | Type | Readable | Writable | Description | +| ----------- | ------- | ---- | ---- | ----------- | +| deviceId | string | Yes | Yes | Device ID. | +| fixConflict | boolean | Yes | Yes | Whether a version conflict occurs.| +| tag | number | Yes | Yes | Tag of the mission. | + +**Example** +```ts +import distributedMissionManager from '@ohos.distributedMissionManager'; + +let missionParameter = { + deviceId: "123456", + fixConflict: true, + tag: 123 +}; +try { + distributedMissionManager.startSyncRemoteMissions(missionParameter, + (err, data) => { + console.log("startSyncRemoteMissions, data: " + JSON.stringify(data)); + } + ); +} catch (err) { + console.error('startSyncRemoteMissions fail: ' + JSON.stringify(err)); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-application-MissionSnapshot.md b/en/application-dev/reference/apis/js-apis-inner-application-missionSnapshot.md similarity index 95% rename from en/application-dev/reference/apis/js-apis-application-MissionSnapshot.md rename to en/application-dev/reference/apis/js-apis-inner-application-missionSnapshot.md index 45024751e4460258a696e7f7e883e84fb93d73c2..bac1c9f6c38951f0ba4f5ab25a7e07d7a9441dcd 100644 --- a/en/application-dev/reference/apis/js-apis-application-MissionSnapshot.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionSnapshot.md @@ -7,11 +7,19 @@ The **MissionSnapshot** module provides the mission snapshot information of an a > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module are system APIs and cannot be called by third-party applications. -## Usage +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| ability | ElementName | Yes| Yes| Information that matches an ability.| +| snapshot | [image.PixelMap](js-apis-image.md) | Yes| Yes| Snapshot of the mission.| + +## How to Use The mission snapshot information can be obtained by using **getMissionSnapShot** in **missionManager**. -```js +**Example** +```ts import ElementName from '@ohos.bundle'; import image from '@ohos.multimedia.image'; import missionManager from '@ohos.application.missionManager'; @@ -28,13 +36,3 @@ missionManager.getMissionInfos("", 10, (error, missions) => { }) }) ``` -## MissionSnapshot - -Describes the mission snapshot. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Mission - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| ability | ElementName | Yes| Yes| Information that matches an ability.| -| snapshot | [image.PixelMap](js-apis-image.md) | Yes| Yes| Snapshot of the mission.| diff --git a/en/application-dev/reference/apis/js-apis-permissionrequestresult.md b/en/application-dev/reference/apis/js-apis-inner-application-permissionRequestResult.md similarity index 97% rename from en/application-dev/reference/apis/js-apis-permissionrequestresult.md rename to en/application-dev/reference/apis/js-apis-inner-application-permissionRequestResult.md index b397ba221d3d570e3b5eca2f551ecee228bdfc35..7a415835191f7d66bdbd7d433df150d52c3d88ac 100644 --- a/en/application-dev/reference/apis/js-apis-permissionrequestresult.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-permissionRequestResult.md @@ -7,11 +7,21 @@ The **PermissionRequestResult** module provides the result of a permission reque > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. -## Usage +## Attributes + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + + | Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| permissions | Array<string> | Yes| No| Permissions requested.| +| authResults | Array<number> | Yes| No| Whether the requested permissions are granted or denied. The value **0** means that the requests permissions are granted, and a non-zero value means the opposite. | + +## How to Use The permission request result is obtained through an **AbilityStage** instance. -```js +**Example** +```ts import Ability from '@ohos.application.Ability' export default class MainAbility extends Ability { onWindowStageCreate(windowStage) { @@ -28,13 +38,3 @@ export default class MainAbility extends Ability { } } ``` - - -## Attributes - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - - | Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| permissions | Array<string> | Yes| No| Permissions requested.| -| authResults | Array<number> | Yes| No| Whether the requested permissions are granted or denied. The value **0** means that the requests permissions are granted, and a non-zero value means the opposite. | diff --git a/en/application-dev/reference/apis/js-apis-inner-application-processData.md b/en/application-dev/reference/apis/js-apis-inner-application-processData.md new file mode 100644 index 0000000000000000000000000000000000000000..75d7312c7144f725e0d47e6aed6e3bc594ce3989 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-processData.md @@ -0,0 +1,43 @@ +# ProcessData + +The **ProcessData** module defines process data. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Type | Readable| Writable| Description | +| ----------------------- | ---------| ---- | ---- | ------------------------- | +| pid8+ | number | Yes | No | Process ID. | +| bundleName8+ | string | Yes | No | Bundle name of the application. | +| uid8+ | number | Yes | No | User ID. | +| isContinuousTask9+ | boolean | Yes | No | Whether the process is a continuous task. | +| isKeepAlive9+ | boolean | Yes | No | Whether the process remains active. | + +**Example** +```ts +import appManager from '@ohos.application.appManager' + +let applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log('onForegroundApplicationChanged appStateData: ' + JSON.stringify(appStateData)); + }, + onAbilityStateChanged(abilityStateData) { + console.log('onAbilityStateChanged onAbilityStateChanged: ' + JSON.stringify(abilityStateData)); + }, + onProcessCreated(processData) { + console.log('onProcessCreated onProcessCreated: ' + JSON.stringify(processData)); + }, + onProcessDied(processData) { + console.log('onProcessDied onProcessDied: ' + JSON.stringify(processData)); + }, + onProcessStateChanged(processData) { + console.log('onProcessStateChanged processData.pid : ' + JSON.stringify(processData.pid)); + console.log('onProcessStateChanged processData.bundleName : ' + JSON.stringify(processData.bundleName)); + console.log('onProcessStateChanged processData.uid : ' + JSON.stringify(processData.uid)); + console.log('onProcessStateChanged processData.isContinuousTask : ' + JSON.stringify(processData.isContinuousTask)); + console.log('onProcessStateChanged processData.isKeepAlive : ' + JSON.stringify(processData.isKeepAlive)); + } +} +let observerCode = appManager.registerApplicationStateObserver(applicationStateObserver); +``` diff --git a/en/application-dev/reference/apis/js-apis-processrunninginfo.md b/en/application-dev/reference/apis/js-apis-inner-application-processRunningInfo.md similarity index 55% rename from en/application-dev/reference/apis/js-apis-processrunninginfo.md rename to en/application-dev/reference/apis/js-apis-inner-application-processRunningInfo.md index dfed42e70b0c506124341952c1fa5c8b724299c1..8534ed198099f17a00769d2627349752a38aef62 100644 --- a/en/application-dev/reference/apis/js-apis-processrunninginfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-processRunningInfo.md @@ -1,16 +1,28 @@ -# ProcessRunningInfo(deprecated) +# ProcessRunningInfo The **ProcessRunningInfo** module provides process running information. > **NOTE** -> - The APIs provided by this module are deprecated since API version 9. You are advised to use [ProcessRunningInformation9+](js-apis-processrunninginformation.md) instead. +> - The APIs provided by this module are deprecated since API version 9. You are advised to use [ProcessRunningInformation9+](js-apis-inner-application-processRunningInformation.md) instead. > - The initial APIs of this module are supported since API version 8. +## Attributes + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| pid | number | Yes| No| Process ID.| +| uid | number | Yes| No| User ID.| +| processName | string | Yes| No| Process name.| +| bundleNames | Array<string> | Yes| No| Names of all running bundles in the process.| + ## Usage -The process running information is obtained by using [getProcessRunningInfos](js-apis-appmanager.md#appmanagergetprocessrunninginfosdeprecated) in **appManager**. +The process running information is obtained through [getProcessRunningInfos](js-apis-application-appManager.md##appManager.getProcessRunningInfos(deprecated)). -```js +**Example** +```ts import appManager from '@ohos.application.appManager'; app.getProcessRunningInfos().then((data) => { console.log('success:' + JSON.stringify(data)); @@ -18,14 +30,3 @@ app.getProcessRunningInfos().then((data) => { console.log('failed:' + JSON.stringify(error)); }); ``` - -## Attributes - -**System capability**: SystemCapability.Ability.AbilityRuntime.Mission - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| pid | number | Yes| No| Process ID.| -| uid | number | Yes| No| User ID.| -| processName | string | Yes| No| Process name.| -| bundleNames | Array<string> | Yes| No| Names of all bundles running in the process.| diff --git a/en/application-dev/reference/apis/js-apis-processrunninginformation.md b/en/application-dev/reference/apis/js-apis-inner-application-processRunningInformation.md similarity index 87% rename from en/application-dev/reference/apis/js-apis-processrunninginformation.md rename to en/application-dev/reference/apis/js-apis-inner-application-processRunningInformation.md index a5add77380e1a9173f9d1d1b1e44b2dfee5be38c..bae1a6f2761c1f8de4873875d0578819a43ddea2 100644 --- a/en/application-dev/reference/apis/js-apis-processrunninginformation.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-processRunningInformation.md @@ -1,4 +1,4 @@ -# ProcessRunningInformation9+ +# ProcessRunningInformation The **ProcessRunningInformation** module provides process running information. @@ -6,11 +6,11 @@ The **ProcessRunningInformation** module provides process running information. > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -## Usage Guidelines +## How to Use -The process running information is obtained through [appManager](js-apis-appmanager.md#appmanagergetprocessrunninginformation9). +The process running information is obtained through [appManager](js-apis-application-appManager.md#appmanagergetprocessrunninginformation9). -```js +```ts import appManager from '@ohos.application.appManager'; appManager.getProcessRunningInformation((error,data) => { console.log("getProcessRunningInformation error: " + error.code + " data: " + JSON.stringify(data)); diff --git a/en/application-dev/reference/apis/js-apis-service-extension-context.md b/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md similarity index 69% rename from en/application-dev/reference/apis/js-apis-service-extension-context.md rename to en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md index e2af193a5c0e62c9c5081589243d0615669a51d5..bfe660ebd6d4f0fb64a0380a3fee7b2470e9a3b3 100644 --- a/en/application-dev/reference/apis/js-apis-service-extension-context.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md @@ -38,15 +38,32 @@ Starts an ability. This API uses an asynchronous callback to return the result. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability, such as the ability name and bundle name.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + | want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability, such as the ability name and bundle name.| + | callback | AsyncCallback<void> | No| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **Example** @@ -88,8 +105,8 @@ Starts an ability. This API uses a promise to return the result. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability, such as the ability name and bundle name.| - | options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.| + | want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability, such as the ability name and bundle name.| + | options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.| **Return value** @@ -101,8 +118,25 @@ Starts an ability. This API uses a promise to return the result. | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **Example** @@ -147,16 +181,33 @@ Starts an ability with the start options specified. This API uses an asynchronou | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| -| options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Parameters used for starting the ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **Example** @@ -202,7 +253,7 @@ Starts an ability with the account ID specified. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | callback | AsyncCallback\ | Yes| Callback used to return the result.| @@ -210,8 +261,26 @@ Starts an ability with the account ID specified. This API uses an asynchronous c | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **Example** @@ -255,17 +324,35 @@ Starts an ability with the account ID and start options specified. This API uses | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Parameters used for starting the ability.| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Parameters used for starting the ability.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **Example** @@ -313,9 +400,9 @@ Starts an ability with the account ID specified. This API uses a promise to retu | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Parameters used for starting the ability.| **Return value** @@ -327,8 +414,26 @@ Starts an ability with the account ID specified. This API uses a promise to retu | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **Example** @@ -375,15 +480,25 @@ Starts a new Service Extension ability. This API uses an asynchronous callback t | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **Example** @@ -426,7 +541,7 @@ Starts a new Service Extension ability. This API uses a promise to return the re | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| **Return value** @@ -438,8 +553,18 @@ Starts a new Service Extension ability. This API uses a promise to return the re | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **Example** @@ -484,7 +609,7 @@ Starts a new Service Extension ability with the account ID specified. This API u | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | callback | AsyncCallback\ | Yes| Callback used to return the result.| @@ -492,8 +617,19 @@ Starts a new Service Extension ability with the account ID specified. This API u | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **Example** @@ -540,7 +676,7 @@ Starts a new Service Extension ability with the account ID specified. This API u | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| **Return value** @@ -553,8 +689,19 @@ Starts a new Service Extension ability with the account ID specified. This API u | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **Example** @@ -598,15 +745,22 @@ Stops a Service Extension ability in the same application. This API uses an asyn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **Example** @@ -649,7 +803,7 @@ Stops a Service Extension ability in the same application. This API uses a promi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| **Return value** @@ -661,8 +815,15 @@ Stops a Service Extension ability in the same application. This API uses a promi | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **Example** @@ -707,7 +868,7 @@ Stops a Service Extension ability in the same application with the account ID sp | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | callback | AsyncCallback\ | Yes| Callback used to return the result.| @@ -715,8 +876,16 @@ Stops a Service Extension ability in the same application with the account ID sp | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **Example** @@ -762,7 +931,7 @@ Stops a Service Extension ability in the same application with the account ID sp | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| **Return value** @@ -775,8 +944,16 @@ Stops a Service Extension ability in the same application with the account ID sp | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **Example** @@ -820,14 +997,18 @@ Terminates this ability. This API uses an asynchronous callback to return the re | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + | callback | AsyncCallback<void> | No| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | **Example** @@ -864,8 +1045,12 @@ Terminates this ability. This API uses a promise to return the result. | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | **Example** @@ -894,8 +1079,8 @@ Connects this ability to a Service ability. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability, such as the ability name and bundle name.| - | options | [ConnectOptions](js-apis-featureAbility.md#connectoptions) | Yes| Callback used to return the information indicating that the connection is successful, interrupted, or failed.| + | want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability, such as the ability name and bundle name.| + | options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes| Callback used to return the information indicating that the connection is successful, interrupted, or failed.| **Return value** @@ -907,8 +1092,13 @@ Connects this ability to a Service ability. | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | **Example** @@ -947,9 +1137,9 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| options | ConnectOptions | Yes| Remote object instance.| +| options | ConnectOptions | No| Remote object instance.| **Return value** @@ -961,8 +1151,14 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000006 | Can not cross user operations. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | **Example** @@ -1004,14 +1200,18 @@ Disconnects this ability from the Service ability. This API uses an asynchronous | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | connection | number | Yes| Number returned after **connectAbility** is called.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + | callback | AsyncCallback<void> | No| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000003 | Input error. The specified id does not exist. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | **Example** @@ -1063,8 +1263,12 @@ Disconnects this ability from the Service ability. This API uses a promise to re | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000003 | Input error. The specified id does not exist. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | **Example** @@ -1104,7 +1308,7 @@ Starts an ability in the foreground or background and obtains the caller object | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the ability to start, including **abilityName**, **moduleName**, **bundleName**, **deviceId** (optional), and **parameters** (optional). If **deviceId** is left blank or null, the local ability is started. If **parameters** is left blank or null, the ability is started in the background.| +| want | [Want](js-apis-application-want.md) | Yes| Information about the ability to start, including **abilityName**, **moduleName**, **bundleName**, **deviceId** (optional), and **parameters** (optional). If **deviceId** is left blank or null, the local ability is started. If **parameters** is left blank or null, the ability is started in the background.| **Return value** @@ -1116,8 +1320,15 @@ Starts an ability in the foreground or background and obtains the caller object | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000050 | Internal Error. | **Example** @@ -1185,4 +1396,3 @@ Starts an ability in the foreground or background and obtains the caller object ' error.message: ' + JSON.stringify(paramError.message)); } ``` - diff --git a/en/application-dev/reference/apis/js-apis-application-shellCmdResult.md b/en/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md similarity index 79% rename from en/application-dev/reference/apis/js-apis-application-shellCmdResult.md rename to en/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md index 7f9e03d201873f689838a4a53c7519ec566b990d..23c4e8d48a1b3755c829c1a9e775a1eb9bdba908 100644 --- a/en/application-dev/reference/apis/js-apis-application-shellCmdResult.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md @@ -6,11 +6,19 @@ The **ShellCmdResult** module provides the shell command execution result. > > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Type | Readable| Writable| Description | +| --------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| stdResult | string | Yes | Yes | Standard output content.| +| exitCode | number | Yes | Yes | Result code.| + ## Usage -The result is obtained by calling [executeShellCommand](js-apis-application-abilityDelegator.md#executeshellcommand) in **abilityDelegator**. +The result is obtained by calling [executeShellCommand](js-apis-inner-application-abilityDelegator.md#executeshellcommand) in **abilityDelegator**. -```js +**Example** +```ts import AbilityDelegatorRegistry from "@ohos.application.abilityDelegatorRegistry"; let abilityDelegator; let cmd = "cmd"; @@ -21,14 +29,3 @@ abilityDelegator.executeShellCommand(cmd, (err: any, data: any) => { console.info("executeShellCommand callback, success: ", data); }); ``` - -## ShellCmdResult - -Describes the shell command execution result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name | Type | Readable| Writable| Description | -| --------- | ------ | ---- | ---- | ------------------------------------------------------------ | -| stdResult | string | Yes | Yes | Standard output content. | -| exitCode | number | Yes | Yes | Result code. | diff --git a/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md b/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md new file mode 100644 index 0000000000000000000000000000000000000000..394f484144b3cf2f5fdf071ea22e2a38fe652739 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md @@ -0,0 +1,2164 @@ +# UIAbilityContext + +The **UIAbilityContext** module, inherited from **Context**, implements the context for abilities. + +This module provides APIs for accessing ability-specific resources. You can use the APIs to start and terminate an ability, obtain the caller interface, and request permissions from users by displaying a dialog box. + +> **NOTE** +> +> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs of this module can be used only in the stage model. + +## Attributes + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| abilityInfo | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | Yes| No| Ability information.| +| currentHapModuleInfo | [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) | Yes| No| Information about the current HAP.| +| config | [Configuration](js-apis-app-ability-configuration.md) | Yes| No| Configuration information.| + +## AbilityContext.startAbility + +startAbility(want: Want, callback: AsyncCallback<void>): void; + +Starts an ability. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + bundleName: "com.example.myapp", + abilityName: "MyAbility" + }; + + try { + this.context.startAbility(want, (error) => { + if (error.code) { + // Process service logic errors. + console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // Carry out normal service processing. + console.log('startAbility succeed'); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + + +## AbilityContext.startAbility + +startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void; + +Starts an ability with the start options specified. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Error codes** + +| ID| Error Message +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" + }; + var options = { + windowMode: 0 + }; + + try { + this.context.startAbility(want, options, (error) => { + if (error.code) { + // Process service logic errors. + console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // Carry out normal service processing. + console.log('startAbility succeed'); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## AbilityContext.startAbility + +startAbility(want: Want, options?: StartOptions): Promise<void>; + +Starts an ability. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Parameters used for starting the ability.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + bundleName: "com.example.myapp", + abilityName: "MyAbility" + }; + var options = { + windowMode: 0, + }; + + try { + this.context.startAbility(want, options) + .then((data) => { + // Carry out normal service processing. + console.log('startAbility succeed'); + }) + .catch((error) => { + // Process service logic errors. + console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + + +## AbilityContext.startAbilityForResult + +startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): void; + +Starts an ability. This API uses an asynchronous callback to return the result when the ability is terminated. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want |[Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| callback | AsyncCallback<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Yes| Callback used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" + }; + + try { + this.context.startAbilityForResult(want, (error, result) => { + if (error.code) { + // Process service logic errors. + console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // Carry out normal service processing. + console.log("startAbilityForResult succeed, result.resultCode = " + + result.resultCode) + }); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## AbilityContext.startAbilityForResult + +startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback<AbilityResult>): void; + +Starts an ability with the start options specified. This API uses an asynchronous callback to return the result when the ability is terminated. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want |[Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.| +| callback | AsyncCallback<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Yes| Callback used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" + }; + var options = { + windowMode: 0, + }; + + try { + this.context.startAbilityForResult(want, options, (error, result) => { + if (error.code) { + // Process service logic errors. + console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // Carry out normal service processing. + console.log("startAbilityForResult succeed, result.resultCode = " + + result.resultCode) + }); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + + +## AbilityContext.startAbilityForResult + +startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityResult>; + +Starts an ability. This API uses a promise to return the result when the ability is terminated. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Parameters used for starting the ability.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Promise used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + bundleName: "com.example.myapp", + abilityName: "MyAbility" + }; + var options = { + windowMode: 0, + }; + + try { + this.context.startAbilityForResult(want, options) + .then((result) => { + // Carry out normal service processing. + console.log("startAbilityForResult succeed, result.resultCode = " + result.resultCode); + }) + .catch((error) => { + // Process service logic errors. + console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## AbilityContext.startAbilityForResultWithAccount + +startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; + +Starts an ability. This API uses an asynchronous callback to return the result when the account of the ability is destroyed. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" + }; + var accountId = 100; + + try { + this.context.startAbilityForResultWithAccount(want, accountId, (error, result) => { + if (error.code) { + // Process service logic errors. + console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // Carry out normal service processing. + console.log("startAbilityForResultWithAccount succeed, result.resultCode = " + + result.resultCode) + }); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + + +## AbilityContext.startAbilityForResultWithAccount + +startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\): void; + +Starts an ability with the start options specified. This API uses an asynchronous callback to return the result when the account of the ability is destroyed. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" + }; + var accountId = 100; + var options = { + windowMode: 0 + }; + + try { + this.context.startAbilityForResultWithAccount(want, accountId, options, (error, result) => { + if (error.code) { + // Process service logic errors. + console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // Carry out normal service processing. + console.log("startAbilityForResultWithAccount succeed, result.resultCode = " + + result.resultCode) + }); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + + +## AbilityContext.startAbilityForResultWithAccount + +startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\; + +Starts an ability with the start options specified. This API uses a promise to return the result when the account of the ability is destroyed. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Parameters used for starting the ability.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<AbilityResult> | Promise used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" + }; + var accountId = 100; + var options = { + windowMode: 0 + }; + + try { + this.context.startAbilityForResultWithAccount(want, accountId, options) + .then((result) => { + // Carry out normal service processing. + console.log("startAbilityForResultWithAccount succeed, result.resultCode = " + + result.resultCode) + }) + .catch((error) => { + // Process service logic errors. + console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` +## AbilityContext.startServiceExtensionAbility + +startServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; + +Starts a new Service Extension ability. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" + }; + + try { + this.context.startServiceExtensionAbility(want, (error) => { + if (error.code) { + // Process service logic errors. + console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // Carry out normal service processing. + console.log('startServiceExtensionAbility succeed'); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## AbilityContext.startServiceExtensionAbility + +startServiceExtensionAbility(want: Want): Promise\; + +Starts a new Service Extension ability. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" + }; + + try { + this.context.startServiceExtensionAbility(want) + .then((data) => { + // Carry out normal service processing. + console.log('startServiceExtensionAbility succeed'); + }) + .catch((error) => { + // Process service logic errors. + console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## AbilityContext.startServiceExtensionAbilityWithAccount + +startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; + +Starts a new Service Extension ability with the account ID specified. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" + }; + var accountId = 100; + + try { + this.context.startServiceExtensionAbilityWithAccount(want, accountId, (error) => { + if (error.code) { + // Process service logic errors. + console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // Carry out normal service processing. + console.log('startServiceExtensionAbilityWithAccount succeed'); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## AbilityContext.startServiceExtensionAbilityWithAccount + +startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\; + +Starts a new Service Extension ability with the account ID specified. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" + }; + var accountId = 100; + + try { + this.context.startServiceExtensionAbilityWithAccount(want, accountId) + .then((data) => { + // Carry out normal service processing. + console.log('startServiceExtensionAbilityWithAccount succeed'); + }) + .catch((error) => { + // Process service logic errors. + console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` +## AbilityContext.stopServiceExtensionAbility + +stopServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; + +Stops a Service Extension ability in the same application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" + }; + + try { + this.context.stopServiceExtensionAbility(want, (error) => { + if (error.code) { + // Process service logic errors. + console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // Carry out normal service processing. + console.log('stopServiceExtensionAbility succeed'); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## AbilityContext.stopServiceExtensionAbility + +stopServiceExtensionAbility(want: Want): Promise\; + +Stops a Service Extension ability in the same application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" + }; + + try { + this.context.stopServiceExtensionAbility(want) + .then((data) => { + // Carry out normal service processing. + console.log('stopServiceExtensionAbility succeed'); + }) + .catch((error) => { + // Process service logic errors. + console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## AbilityContext.stopServiceExtensionAbilityWithAccount + +stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; + +Stops a Service Extension ability in the same application with the account ID specified. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" + }; + var accountId = 100; + + try { + this.context.stopServiceExtensionAbilityWithAccount(want, accountId, (error) => { + if (error.code) { + // Process service logic errors. + console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // Carry out normal service processing. + console.log('stopServiceExtensionAbilityWithAccount succeed'); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## AbilityContext.stopServiceExtensionAbilityWithAccount + +stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\; + +Stops a Service Extension ability in the same application with the account ID specified. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" + }; + var accountId = 100; + + try { + this.context.stopServiceExtensionAbilityWithAccount(want, accountId) + .then((data) => { + // Carry out normal service processing. + console.log('stopServiceExtensionAbilityWithAccount succeed'); + }) + .catch((error) => { + // Process service logic errors. + console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## AbilityContext.terminateSelf + +terminateSelf(callback: AsyncCallback<void>): void; + +Terminates this ability. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + this.context.terminateSelf((error) => { + if (error.code) { + // Process service logic errors. + console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // Carry out normal service processing. + console.log('terminateSelf succeed'); + }); + ``` + + +## AbilityContext.terminateSelf + +terminateSelf(): Promise<void>; + +Terminates this ability. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + this.context.terminateSelf().then((data) => { + // Carry out normal service processing. + console.log('terminateSelf succeed'); + }).catch((error) => { + // Process service logic errors. + console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + ``` + + +## AbilityContext.terminateSelfWithResult + +terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<void>): void; + +Terminates this ability. This API uses an asynchronous callback to return the ability result information. It is used together with **startAbilityForResult**. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes| Information returned to the caller.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + bundleName: "com.extreme.myapplication", + abilityName: "SecondAbility" + } + var resultCode = 100; + // AbilityResult information returned to the caller. + var abilityResult = { + want, + resultCode + } + + try { + this.context.terminateSelfWithResult(abilityResult, (error) => { + if (error.code) { + // Process service logic errors. + console.log('terminateSelfWithResult failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // Carry out normal service processing. + console.log('terminateSelfWithResult succeed'); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + + +## AbilityContext.terminateSelfWithResult + +terminateSelfWithResult(parameter: AbilityResult): Promise<void>; + +Terminates this ability. This API uses a promise to return the ability result information. It is used together with **startAbilityForResult**. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes| Information returned to the caller.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + + +**Example** + + ```ts + var want = { + bundleName: "com.extreme.myapplication", + abilityName: "SecondAbility" + } + var resultCode = 100; + // AbilityResult information returned to the caller. + var abilityResult = { + want, + resultCode + } + + try { + this.context.terminateSelfWithResult(abilityResult) + .then((data) => { + // Carry out normal service processing. + console.log('terminateSelfWithResult succeed'); + }) + .catch((error) => { + // Process service logic errors. + console.log('terminateSelfWithResult failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## AbilityContext.connectServiceExtensionAbility + +connectServiceExtensionAbility(want: Want, options: ConnectOptions): number; + +Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to another ability. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | No| Parameters for the connection.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Result code of the ability connection.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" + }; + var options = { + onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, + onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, + onFailed(code) { console.log('----------- onFailed -----------') } + } + + var connection = null; + try { + connection = this.context.connectServiceExtensionAbility(want, options); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + + +## AbilityContext.connectServiceExtensionAbilityWithAccount + +connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number; + +Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect this ability to another ability with the account ID specified. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | No| Parameters for the connection.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Result code of the ability connection.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000006 | Can not cross user operations. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" + }; + var accountId = 100; + var options = { + onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, + onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, + onFailed(code) { console.log('----------- onFailed -----------') } + } + + var connection = null; + try { + connection = this.context.connectServiceExtensionAbilityWithAccount(want, accountId, options); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## AbilityContext.disconnectServiceExtensionAbility + +disconnectServiceExtensionAbility(connection: number): Promise\; + +Disconnects a connection. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| connection | number | Yes| Result code of the ability connection.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000003 | Input error. The specified id does not exist. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + // connection is the return value of connectServiceExtensionAbility. + var connection = 1; + + try { + this.context.disconnectServiceExtensionAbility(connection) + .then((data) => { + // Carry out normal service processing. + console.log('disconnectServiceExtensionAbility succeed'); + }) + .catch((error) => { + // Process service logic errors. + console.log('disconnectServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## AbilityContext.disconnectServiceExtensionAbility + +disconnectServiceExtensionAbility(connection: number, callback:AsyncCallback\): void; + +Disconnects a connection. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| connection | number | Yes| Result code of the ability connection.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000003 | Input error. The specified id does not exist. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + // connection is the return value of connectServiceExtensionAbility. + var connection = 1; + + try { + this.context.disconnectServiceExtensionAbility(connection, (error) => { + if (error.code) { + // Process service logic errors. + console.log('disconnectServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // Carry out normal service processing. + console.log('disconnectServiceExtensionAbility succeed'); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## AbilityContext.startAbilityByCall + +startAbilityByCall(want: Want): Promise<Caller>; + +Starts an ability in the foreground or background and obtains the caller object for communicating with the ability. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Information about the ability to start, including **abilityName**, **moduleName**, **bundleName**, **deviceId** (optional), and **parameters** (optional). If **deviceId** is left blank or null, the local ability is started. If **parameters** is left blank or null, the ability is started in the background.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<Caller> | Promise used to return the caller object to communicate with.| + +**Example** + + Start an ability in the background. + + ```ts + var caller = undefined; + + // Start an ability in the background by not passing parameters. + var wantBackground = { + bundleName: "com.example.myservice", + moduleName: "entry", + abilityName: "MainAbility", + deviceId: "" + }; + + try { + this.context.startAbilityByCall(wantBackground) + .then((obj) => { + // Carry out normal service processing. + caller = obj; + console.log('startAbilityByCall succeed'); + }).catch((error) => { + // Process service logic errors. + console.log('startAbilityByCall failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + + Start an ability in the foreground. + + ```ts + var caller = undefined; + + // Start an ability in the foreground with ohos.aafwk.param.callAbilityToForeground in parameters set to true. + var wantForeground = { + bundleName: "com.example.myservice", + moduleName: "entry", + abilityName: "MainAbility", + deviceId: "", + parameters: { + "ohos.aafwk.param.callAbilityToForeground": true + } + }; + + try { + this.context.startAbilityByCall(wantForeground) + .then((obj) => { + // Carry out normal service processing. + caller = obj; + console.log('startAbilityByCall succeed'); + }).catch((error) => { + // Process service logic errors. + console.log('startAbilityByCall failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## AbilityContext.startAbilityWithAccount + +startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; + +Starts an ability with the account ID specified. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" + }; + var accountId = 100; + + try { + this.context.startAbilityWithAccount(want, accountId, (error) => { + if (error.code) { + // Process service logic errors. + console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // Carry out normal service processing. + console.log('startAbilityWithAccount succeed'); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + + +## AbilityContext.startAbilityWithAccount + +startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\): void; + +Starts an ability with the account ID and start options specified. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Parameters used for starting the ability.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" + }; + var accountId = 100; + var options = { + windowMode: 0 + }; + + try { + this.context.startAbilityWithAccount(want, accountId, options, (error) => { + if (error.code) { + // Process service logic errors. + console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // Carry out normal service processing. + console.log('startAbilityWithAccount succeed'); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + + +## AbilityContext.startAbilityWithAccount + +startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\; + +Starts an ability with the account ID specified. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Parameters used for starting the ability.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" + }; + var accountId = 100; + var options = { + windowMode: 0 + }; + + try { + this.context.startAbilityWithAccount(want, accountId, options) + .then((data) => { + // Carry out normal service processing. + console.log('startAbilityWithAccount succeed'); + }) + .catch((error) => { + // Process service logic errors. + console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## AbilityContext.requestPermissionsFromUser + +requestPermissionsFromUser(permissions: Array<string>, requestCallback: AsyncCallback<PermissionRequestResult>) : void; + +Requests permissions from the user by displaying a dialog box. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| permissions | Array<string> | Yes| Permissions to request.| +| callback | AsyncCallback<[PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md)> | Yes| Callback used to return the result.| + +**Example** + + ```ts + var permissions=['com.example.permission'] + this.context.requestPermissionsFromUser(permissions,(result) => { + console.log('requestPermissionsFromUserresult:' + JSON.stringify(result)); + }); + + ``` + + +## AbilityContext.requestPermissionsFromUser + +requestPermissionsFromUser(permissions: Array<string>) : Promise<PermissionRequestResult>; + +Requests permissions from the user by displaying a dialog box. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| permissions | Array<string> | Yes| Permissions to request.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<[PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md)> | Promise used to return the result.| + +**Example** + + ```ts + var permissions=['com.example.permission'] + this.context.requestPermissionsFromUser(permissions).then((data) => { + console.log('success:' + JSON.stringify(data)); + }).catch((error) => { + console.log('failed:' + JSON.stringify(error)); + }); + + ``` + + +## AbilityContext.setMissionLabel + +setMissionLabel(label: string, callback:AsyncCallback<void>): void; + +Sets a label for this ability in the mission. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| label | string | Yes| Label of the ability to set.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```ts + this.context.setMissionLabel("test",(result) => { + console.log('requestPermissionsFromUserresult:' + JSON.stringify(result)); + }); + ``` + + +## AbilityContext.setMissionLabel + +setMissionLabel(label: string): Promise<void>; + +Sets a label for this ability in the mission. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| label | string | Yes| Label of the ability to set.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| + +**Example** + + ```ts + this.context.setMissionLabel("test").then(() => { + console.log('success'); + }).catch((error) => { + console.log('failed:' + JSON.stringify(error)); + }); + ``` +## AbilityContext.setMissionIcon + +setMissionIcon(icon: image.PixelMap, callback:AsyncCallback\): void; + +Sets an icon for this ability in the mission. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| icon | image.PixelMap | Yes| Icon of the ability to set.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```ts + import image from '@ohos.multimedia.image'; + var imagePixelMap; + var color = new ArrayBuffer(0); + var initializationOptions = { + size: { + height: 100, + width: 100 + } + }; + image.createPixelMap(color, initializationOptions) + .then((data) => { + imagePixelMap = data; + }) + .catch((err) => { + console.log('--------- createPixelMap fail, err: ---------', err) + }); + this.context.setMissionIcon(imagePixelMap, (err) => { + console.log('---------- setMissionIcon fail, err: -----------', err); + }) + ``` + + +## AbilityContext.setMissionIcon + +setMissionIcon(icon: image.PixelMap): Promise\; + +Sets an icon for this ability in the mission. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| icon | image.PixelMap | Yes| Icon of the ability to set.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| + +**Example** + + ```ts + import image from '@ohos.multimedia.image'; + var imagePixelMap; + var color = new ArrayBuffer(0); + var initializationOptions = { + size: { + height: 100, + width: 100 + } + }; + image.createPixelMap(color, initializationOptions) + .then((data) => { + imagePixelMap = data; + }) + .catch((err) => { + console.log('--------- createPixelMap fail, err: ---------', err) + }); + this.context.setMissionIcon(imagePixelMap) + .then(() => { + console.log('-------------- setMissionIcon success -------------'); + }) + .catch((err) => { + console.log('-------------- setMissionIcon fail, err: -------------', err); + }); + ``` +## AbilityContext.restoreWindowStage + +restoreWindowStage(localStorage: LocalStorage) : void; + +Restores the window stage data for this ability. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| localStorage | image.LocalStorage | Yes| Storage used to store the restored window stage.| + +**Example** + + ```ts + var storage = new LocalStorage(); + this.context.restoreWindowStage(storage); + ``` + +## AbilityContext.isTerminating + +isTerminating(): boolean; + +Checks whether this ability is in the terminating state. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean| The value **true** means that the ability is in the terminating state, and **false** means the opposite.| + +**Example** + + ```ts + var isTerminating = this.context.isTerminating(); + console.log('ability state :' + isTerminating); + ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-wantAgent-triggerInfo.md b/en/application-dev/reference/apis/js-apis-inner-wantAgent-triggerInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..e659a4d80e43f59f06bfe7a8357ab6675886fad6 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-wantAgent-triggerInfo.md @@ -0,0 +1,66 @@ +# TriggerInfo + +The **TriggerInfo** module defines the information required for triggering the WantAgent. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Type | Mandatory| Description | +| ---------- | --- |-------------------- | ----------- | +| code | number | Yes | Result code.| +| want | Want | No | Want. | +| permission | string | No | Permission. | +| extraInfo | {[key: string]: any} | No | Extra information. | + +**Example** +```ts +import wantAgent from '@ohos.wantAgent'; + +let wantAgentInfo = { + wants: [ + { + deviceId: "", + bundleName: "com.example.apicoverhaptest", + abilityName: "com.example.apicoverhaptest.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true.true,false}", + parameters: { + myKey0: 2222 + } + } + ], + operationType: wantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG], + extraInfo:{ + "key": "value" + } +} + +let triggerInfo = { + code: 0, + want: { + deviceId: "", + bundleName: "com.example.apicoverhaptest", + abilityName: "com.example.apicoverhaptest.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true.true,false}", + parameters: { + myKey0: 2222 + } + }, + permission: "" + extraInfo:{ + "key": "value" + } +} + +wantAgent.trigger(wantAgentInfo, triggerInfo).then((data) =>{ + console.info("trigger data: " + JSON.stringify(data)); +}).catch((err) => { + console.error("trigger err: " + JSON.stringify(err)); +}) +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md b/en/application-dev/reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..6d93123f0ca73a7089b640f2f1cb98cc3df4308c --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md @@ -0,0 +1,46 @@ +# WantAgentInfo + +The **WantAgentInfo** module defines the information required for triggering the WantAgent. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Type | Mandatory| Description | +| -------------- | ------------------------------- | ---- | ---------------------- | +| wants | Array\ | Yes | Array of all **Want** objects. | +| operationType | wantAgent.OperationType | Yes | Operation type. | +| requestCode | number | Yes | Request code defined by the user.| +| wantAgentFlags | Array<[wantAgent.WantAgentFlags](js-apis-wantAgent.md#WantAgentFlags)> | No | Array of flags for using the **WantAgent** object. | +| extraInfo | {[key: string]: any} | No | Extra information. | + +**Example** +```ts +import wantAgent from '@ohos.wantAgent'; + +let wantAgentInfo = { + wants: [ + { + deviceId: "", + bundleName: "com.example.apicoverhaptest", + abilityName: "com.example.apicoverhaptest.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true.true,false}", + parameters: { + myKey0: 2222 + } + } + ], + operationType: wantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG], + extraInfo:{ + "key": "value" + } +} +wantAgent.getWantAgent(wantAgentInfo).then((data) =>{ + console.info("getWantAgent data: " + JSON.stringify(data)); +}).catch((err) => { + console.error("getWantAgent err: " + JSON.stringify(err)); +}) +``` diff --git a/en/application-dev/reference/apis/js-apis-installer.md b/en/application-dev/reference/apis/js-apis-installer.md index 557e655b82ab9195e2217b69ed68e8d5de0ef534..0c3651fc6add2e830f9a8e3eeb5ccabddb122e2e 100644 --- a/en/application-dev/reference/apis/js-apis-installer.md +++ b/en/application-dev/reference/apis/js-apis-installer.md @@ -1,9 +1,8 @@ -# BundleInstaller +# @ohos.bundle.installer -The **BundleInstaller** module provides APIs for you to install, uninstall, and recover bundles on devices. +The **bundle.installer** module provides APIs for you to install, uninstall, and recover bundles on devices. > **NOTE** -> > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-keycode.md b/en/application-dev/reference/apis/js-apis-keycode.md index dd4ac0b22afb7e0101579db5b6d639504f58197d..6680ea14f2ea3daa0d9144013469cf094c4904d2 100644 --- a/en/application-dev/reference/apis/js-apis-keycode.md +++ b/en/application-dev/reference/apis/js-apis-keycode.md @@ -8,7 +8,7 @@ The Keycode module provides keycodes for a key device. ## Modules to Import ```js -import {KeyCode} from '@ohos.multimodalInput.keyCode' +import {KeyCode} from '@ohos.multimodalInput.keyCode'; ``` ## KeyCode diff --git a/en/application-dev/reference/apis/js-apis-keyevent.md b/en/application-dev/reference/apis/js-apis-keyevent.md index 33d9daa72dd0c570d04d11b5eedf16f96e37dc7c..3cfb2440033aa8043801e986ade5b0bd28c475d3 100644 --- a/en/application-dev/reference/apis/js-apis-keyevent.md +++ b/en/application-dev/reference/apis/js-apis-keyevent.md @@ -1,6 +1,6 @@ # Key Event -Represents key events reported by an input device. +The Key Event module provides key events reported by an input device. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-launcherBundleManager.md b/en/application-dev/reference/apis/js-apis-launcherBundleManager.md index f149c30d7a93f9adaaa68c03edea7426a8882531..505c29ae0ef6cc18404767eaa4a4b4ac88296651 100644 --- a/en/application-dev/reference/apis/js-apis-launcherBundleManager.md +++ b/en/application-dev/reference/apis/js-apis-launcherBundleManager.md @@ -1,6 +1,6 @@ -# Bundle.launcherBundleManager +# @ohos.bundle.launcherBundleManager -The **Bundle.launcherBundleManager** module providers APIs for the **Home Screen** application to obtain the launcher ability information and shortcut information. +The **bundle.launcherBundleManager** module providers APIs for the **Home Screen** application to obtain the launcher ability information and shortcut information. > **NOTE** > @@ -27,7 +27,7 @@ Obtains the launcher ability information based on the given bundle name and user **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ---------- | ------ | ---- | -------------- | | bundleName | string | Yes | Bundle name of the application.| | userId | number | Yes | User ID.| @@ -78,7 +78,7 @@ Obtains the launcher ability information based on the given bundle name and user **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ---------- | ------ | ---- | -------------- | | bundleName | string | Yes | Bundle name of the application.| | userId | number | Yes | User ID.| @@ -128,7 +128,7 @@ Obtains the launcher ability information of all applications based on the given **Parameters** -| Name| Type | Mandatory| Description | +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------- | | userId | number | Yes | User ID.| @@ -176,7 +176,7 @@ Obtains the launcher ability information of all applications based on the given **Parameters** -| Name| Type | Mandatory| Description | +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------- | | userId | number | Yes | User ID.| @@ -222,7 +222,7 @@ Obtains the shortcut information of the current user based on the given bundle n **System capability**: SystemCapability.BundleManager.BundleFramework.Launcher -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ---------- | ------ | ---- | -------------- | | bundleName | string | Yes | Bundle name of the application.| @@ -269,13 +269,13 @@ Obtains the shortcut information of the current user based on the given bundle n **System capability**: SystemCapability.BundleManager.BundleFramework.Launcher -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ---------- | ------ | ---- | -------------- | | bundleName | string | Yes | Bundle name of the application.| **Return value** -| Template | Description | +| Type | Description | | ---------------------- | ----------------------------------------------- | | Promise\> | Promise used to return the **ShortcutInfo** object obtained.| diff --git a/en/application-dev/reference/apis/js-apis-lightweightmap.md b/en/application-dev/reference/apis/js-apis-lightweightmap.md index f2ab94b72b0538f83cd21642081172cfb19b3cb1..1e966a2b659551a35649c3c087330e7d3059e182 100644 --- a/en/application-dev/reference/apis/js-apis-lightweightmap.md +++ b/en/application-dev/reference/apis/js-apis-lightweightmap.md @@ -1,4 +1,4 @@ -# Nonlinear Container LightWeightMap +# @ohos.util.LightWeightMap (Nonlinear Container LightWeightMap) > **NOTE** > @@ -54,11 +54,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let lightWeightMap = new LightWeightMap(); -try { - let lightWeightMap2 = LightWeightMap(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -89,11 +84,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts const lightWeightMap = new LightWeightMap(); let result = lightWeightMap.isEmpty(); -try { - lightWeightMap.isEmpty.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -134,11 +124,6 @@ lightWeightMap.set("sparrow", 356); let map = new LightWeightMap(); map.set("sparrow", 356); let result = lightWeightMap.hasAll(map); -try { - lightWeightMap.hasAll.bind({}, map)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -178,11 +163,6 @@ let result = lightWeightMap.hasKey; lightWeightMap.hasKey("squirrel"); lightWeightMap.set("squirrel", 123); let result1 = lightWeightMap.hasKey("squirrel"); -try { - lightWeightMap.hasKey.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -221,11 +201,6 @@ let lightWeightMap = new LightWeightMap(); let result = lightWeightMap.hasValue(123); lightWeightMap.set("squirrel", 123); let result1 = lightWeightMap.hasValue(123); -try { - lightWeightMap.hasValue.bind({}, 123)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -256,11 +231,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let lightWeightMap = new LightWeightMap(); lightWeightMap.increaseCapacityTo(10); -try { - lightWeightMap.increaseCapacityTo.bind({}, 10)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -299,11 +269,6 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.get("sparrow"); -try { - lightWeightMap.get.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -342,11 +307,6 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.getIndexOfKey("sparrow"); -try { - lightWeightMap.getIndexOfKey.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -385,11 +345,6 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.getIndexOfValue(123); -try { - lightWeightMap.getIndexOfValue.bind({}, 123)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -420,7 +375,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The getKeyAt method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -429,16 +384,6 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.getKeyAt(1); -try { - lightWeightMap.getKeyAt.bind({}, 1)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - lightWeightMap.getKeyAt(6)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -472,11 +417,6 @@ lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let map = new LightWeightMap(); lightWeightMap.setAll(map); -try { - lightWeightMap.setAll.bind({}, map)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -513,11 +453,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let lightWeightMap = new LightWeightMap(); let result = lightWeightMap.set("squirrel", 123); -try { - lightWeightMap.set.bind({}, "squirrel", 123)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -556,11 +491,6 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); lightWeightMap.remove("sparrow"); -try { - lightWeightMap.remove.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -599,11 +529,6 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.removeAt(1); -try { - lightWeightMap.removeAt.bind({}, 1)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -635,7 +560,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The setValueAt method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -644,16 +569,6 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); lightWeightMap.setValueAt(1, 3546); -try { - lightWeightMap.setValueAt.bind({}, 1, 3546)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - lightWeightMap.setValueAt(6, 3546); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -684,7 +599,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The getValueAt method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -693,16 +608,6 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.getValueAt(1); -try { - lightWeightMap.getValueAt.bind({}, 1)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - lightWeightMap.getValueAt(6); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -729,11 +634,6 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); lightWeightMap.clear(); -try { - lightWeightMap.clear.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -771,11 +671,6 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - lightWeightMap.keys.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -813,17 +708,12 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - lightWeightMap.values.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value?: V, key?: K, map?: LightWeightMap) => void, thisArg?: Object): void +forEach(callbackFn: (value?: V, key?: K, map?: LightWeightMap) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -833,7 +723,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -860,13 +750,6 @@ lightWeightMap.set("gull", 357); lightWeightMap.forEach((value, key) => { console.log("value:" + value, key); }); -try { - lightWeightMap.forEach.bind({}, (value, key) => { - console.log("value:" + value, key); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -905,11 +788,6 @@ while(temp != undefined) { console.log("value:" + temp[1]); temp = iter.next().value; } -try { - lightWeightMap.entries.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### toString @@ -941,11 +819,6 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let iter = lightWeightMap.toString(); -try { - lightWeightMap.toString.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### [Symbol.iterator] @@ -991,9 +864,4 @@ while(temp != undefined) { console.log("value:" + temp[1]); temp = iter.next().value; } -try { - lightWeightMap[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-lightweightset.md b/en/application-dev/reference/apis/js-apis-lightweightset.md index f5cfbde6cb11daf8884e3c5cf5818fbccc9475a6..0953c12b1a012870147f5be3481de8cd28f9edd6 100644 --- a/en/application-dev/reference/apis/js-apis-lightweightset.md +++ b/en/application-dev/reference/apis/js-apis-lightweightset.md @@ -1,4 +1,4 @@ -# Nonlinear Container LightWeightSet +# @ohos.util.LightWeightSet (Nonlinear Container LightWeightSet) > **NOTE** > @@ -23,8 +23,6 @@ This topic uses the following to identify the use of generics: import LightWeightSet from '@ohos.util.LightWeightSet'; ``` - - ## LightWeightSet ### Attributes @@ -56,11 +54,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let lightWeightSet = new LightWeightSet(); -try { - let lightWeightSet2 = LightWeightSet(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -91,11 +84,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts const lightWeightSet = new LightWeightSet(); let result = lightWeightSet.isEmpty(); -try { - lightWeightSet.isEmpty.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### add @@ -131,11 +119,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let lightWeightSet = new LightWeightSet(); let result = lightWeightSet.add("squirrel"); -try { - lightWeightSet.add.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -170,11 +153,6 @@ lightWeightSet.add("sparrow"); let set = new LightWeightSet(); set.add("gull"); let result = lightWeightSet.addAll(set); -try { - lightWeightSet.addAll.bind({}, set)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -215,11 +193,6 @@ lightWeightSet.add("sparrow"); let set = new LightWeightSet(); set.add("sparrow"); let result = lightWeightSet.hasAll(set); -try { - lightWeightSet.hasAll.bind({}, set)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -258,11 +231,6 @@ let lightWeightSet = new LightWeightSet(); let result = lightWeightSet.has(123); lightWeightSet.add(123); result = lightWeightSet.has(123); -try { - lightWeightSet.has.bind({}, 123)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -302,11 +270,6 @@ lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let obj = ["squirrel", "sparrow"]; let result = lightWeightSet.equal(obj); -try { - lightWeightSet.equal.bind({}, obj)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -331,23 +294,13 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The increaseCapacityTo method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** ```ts let lightWeightSet = new LightWeightSet(); lightWeightSet.increaseCapacityTo(10); -try { - lightWeightSet.increaseCapacityTo.bind({}, 10)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - lightWeightSet.increaseCapacityTo(2); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -386,11 +339,6 @@ let lightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.getIndexOf("sparrow"); -try { - lightWeightSet.getIndexOf.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -429,11 +377,6 @@ let lightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.remove("sparrow"); -try { - lightWeightSet.remove.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -472,11 +415,6 @@ let lightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.removeAt(1); -try { - lightWeightSet.removeAt.bind({}, 1)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -515,11 +453,6 @@ let lightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.getValueAt(1); -try { - lightWeightSet.getValueAt.bind({}, 1)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -546,11 +479,6 @@ let lightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); lightWeightSet.clear(); -try { - lightWeightSet.clear.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -583,11 +511,6 @@ let lightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.toString(); -try { - lightWeightSet.toString.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -620,11 +543,6 @@ let lightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.toArray(); -try { - lightWeightSet.toArray.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -662,17 +580,12 @@ while(index < lightWeightSet.length) { console.log(JSON.stringify(iter.next().value)); index++; } -try { - lightWeightSet.values.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value?: T, key?: T, set?: LightWeightSet<T>) => void, thisArg?: Object): void +forEach(callbackFn: (value?: T, key?: T, set?: LightWeightSet<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -682,7 +595,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -709,13 +622,6 @@ lightWeightSet.add("gull"); lightWeightSet.forEach((value, key) => { console.log("value:" + value, key); }); -try { - lightWeightSet.forEach.bind({}, (value, key) => { - console.log("value:" + value, key); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -753,11 +659,6 @@ while(index < lightWeightSet.length) { console.log(JSON.stringify(iter.next().value)); index++; } -try { - lightWeightSet.entries.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -802,9 +703,4 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - lightWeightSet[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-linkedlist.md b/en/application-dev/reference/apis/js-apis-linkedlist.md index 81b7ee076547f3ac3acd72fb3267d8e84265e2b3..1eda96e1205a256960c8a03f28ee60080850d22c 100644 --- a/en/application-dev/reference/apis/js-apis-linkedlist.md +++ b/en/application-dev/reference/apis/js-apis-linkedlist.md @@ -1,4 +1,4 @@ -# Linear Container LinkedList +# @ohos.util.LinkedList (Linear Container LinkedList) > **NOTE** > @@ -21,9 +21,6 @@ This topic uses the following to identify the use of generics: import LinkedList from '@ohos.util.LinkedList'; ``` - - - ## LinkedList ### Attributes @@ -56,11 +53,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let linkedList = new LinkedList(); -try { - let linkedList2 = LinkedList(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -103,11 +95,6 @@ let result2 = linkedList.add(b); let c = {name : "Dylon", age : "13"}; let result3 = linkedList.add(c); let result4 = linkedList.add(false); -try { - linkedList.add.bind({}, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### addFirst @@ -143,11 +130,6 @@ linkedList.addFirst(b); let c = {name : "Dylon", age : "13"}; linkedList.addFirst(c); linkedList.addFirst(false); -try { - linkedList.addFirst.bind({}, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### insert @@ -172,7 +154,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The insert method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -181,16 +163,6 @@ let linkedList = new LinkedList(); linkedList.insert(0, "A"); linkedList.insert(1, 0); linkedList.insert(2, true); -try { - linkedList.insert.bind({}, 3, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - linkedList.insert(6, "b"); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### has @@ -228,11 +200,6 @@ let linkedList = new LinkedList(); let result1 = linkedList.has("squirrel"); linkedList.add("squirrel"); let result = linkedList.has("squirrel"); -try { - linkedList.has.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### get @@ -275,11 +242,6 @@ linkedList.add(1); linkedList.add(2); linkedList.add(4); let result = linkedList.get(2); -try { - linkedList.get.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getLastIndexOf @@ -322,11 +284,6 @@ linkedList.add(1); linkedList.add(2); linkedList.add(4); let result = linkedList.getLastIndexOf(2); -try { - linkedList.getLastIndexOf.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getIndexOf @@ -369,11 +326,6 @@ linkedList.add(1); linkedList.add(2); linkedList.add(4); let result = linkedList.getIndexOf(2); -try { - linkedList.getIndexOf.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### removeByIndex @@ -403,7 +355,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The removeByIndex method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -415,16 +367,6 @@ linkedList.add(5); linkedList.add(2); linkedList.add(4); let result = linkedList.removeByIndex(2); -try { - linkedList.removeByIndex.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - linkedList.removeByIndex(8); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### removeFirst @@ -448,28 +390,18 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The removeFirst method cannot be bound. | -| 10200010 | Container is empty. | +| 10200010 | The container is empty. | **Example** ```ts let linkedList = new LinkedList(); -try { - linkedList.removeFirst(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} linkedList.add(2); linkedList.add(4); linkedList.add(5); linkedList.add(2); linkedList.add(4); let result = linkedList.removeFirst(); -try { - linkedList.removeFirst.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### removeLast @@ -493,28 +425,18 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The removeLast method cannot be bound. | -| 10200010 | Container is empty. | +| 10200010 | The container is empty. | **Example** ```ts let linkedList = new LinkedList(); -try { - linkedList.removeLast(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} linkedList.add(2); linkedList.add(4); linkedList.add(5); linkedList.add(2); linkedList.add(4); let result = linkedList.removeLast(); -try { - linkedList.removeLast.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### remove @@ -554,11 +476,6 @@ linkedList.add(4); linkedList.add(5); linkedList.add(4); let result = linkedList.remove(2); -try { - linkedList.remove.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### removeFirstFound @@ -588,27 +505,17 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The removeFirstFound method cannot be bound. | -| 10200010 | Container is empty. | +| 10200010 | The container is empty. | **Example** ```ts let linkedList = new LinkedList(); -try { - linkedList.removeFirstFound(4); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} linkedList.add(2); linkedList.add(4); linkedList.add(5); linkedList.add(4); let result = linkedList.removeFirstFound(4); -try { - linkedList.removeFirstFound.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### removeLastFound @@ -638,27 +545,17 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The removeLastFound method cannot be bound. | -| 10200010 | Container is empty. | +| 10200010 | The container is empty. | **Example** ```ts let linkedList = new LinkedList(); -try { - linkedList.removeLastFound(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} linkedList.add(2); linkedList.add(4); linkedList.add(5); linkedList.add(4); let result = linkedList.removeLastFound(4); -try { - linkedList.removeLastFound.bind({}, 4)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### clone @@ -692,16 +589,11 @@ linkedList.add(4); linkedList.add(5); linkedList.add(4); let result = linkedList.clone(); -try { - linkedList.clone.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value: T, index?: number, LinkedList?: LinkedList<T>) => void, +forEach(callbackFn: (value: T, index?: number, LinkedList?: LinkedList<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -712,7 +604,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -742,13 +634,6 @@ linkedList.add(4); linkedList.forEach((value, index) => { console.log("value:" + value, index); }); -try { - linkedList.forEach.bind({}, (value, index) => { - console.log("value:" + value, index); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### clear @@ -776,11 +661,6 @@ linkedList.add(4); linkedList.add(5); linkedList.add(4); linkedList.clear(); -try { - linkedList.clear.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### set @@ -811,7 +691,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The set method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -822,16 +702,6 @@ linkedList.add(4); linkedList.add(5); linkedList.add(4); let result = linkedList.set(2, "b"); -try { - linkedList.set.bind({}, 2, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - linkedList.set(8, "b"); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### convertToArray @@ -864,11 +734,6 @@ linkedList.add(4); linkedList.add(5); linkedList.add(4); let result = linkedList.convertToArray(); -try { - linkedList.convertToArray.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getFirst @@ -902,11 +767,6 @@ linkedList.add(4); linkedList.add(5); linkedList.add(4); let result = linkedList.getFirst(); -try { - linkedList.getFirst.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getLast @@ -940,11 +800,6 @@ linkedList.add(4); linkedList.add(5); linkedList.add(4); linkedList.getLast(); -try { - linkedList.getLast.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### [Symbol.iterator] @@ -990,9 +845,4 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - linkedList[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-list.md b/en/application-dev/reference/apis/js-apis-list.md index 181febf4ebe037fe37ec061efe832bd4f9a387cd..2c657bc20289e50af9edda35a739f8fd8c3b0896 100644 --- a/en/application-dev/reference/apis/js-apis-list.md +++ b/en/application-dev/reference/apis/js-apis-list.md @@ -1,4 +1,4 @@ -# Linear Container List +# @ohos.util.List (Linear Container List) > **NOTE** > @@ -51,11 +51,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let list = new List(); -try { - let list2 = List(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -98,11 +93,6 @@ let result3 = list.add(b); let c = {name : "Dylon", age : "13"}; let result4 = list.add(c); let result5 = list.add(false); -try { - list.add.bind({}, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### insert @@ -127,7 +117,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The insert method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -136,16 +126,6 @@ let list = new List(); list.insert("A", 0); list.insert(0, 1); list.insert(true, 2); -try { - list.insert.bind({}, "b", 3)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - list.insert("b", 6); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### has @@ -183,11 +163,6 @@ let list = new List(); let result = list.has("squirrel"); list.add("squirrel"); let result1 = list.has("squirrel"); -try { - list.has.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### get @@ -230,11 +205,6 @@ list.add(1); list.add(2); list.add(4); let result = list.get(2); -try { - list.get.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getLastIndexOf @@ -277,11 +247,6 @@ list.add(1); list.add(2); list.add(4); let result = list.getLastIndexOf(2); -try { - list.getLastIndexOf.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getIndexOf @@ -325,11 +290,6 @@ list.add(2); list.add(4); list.getIndexOf(2); let result = list.getIndexOf(2); -try { - list.getIndexOf.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### equal @@ -375,11 +335,6 @@ obj1.add(5); list.equal(obj1); let obj2 = {name : "Dylon", age : "13"}; let result = list.equal(obj2); -try { - list.equal.bind({}, obj2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### removeByIndex @@ -409,7 +364,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The removeByIndex method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -421,16 +376,6 @@ list.add(5); list.add(2); list.add(4); let result = list.removeByIndex(2); -try { - list.removeByIndex.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - list.removeByIndex(8); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### remove @@ -470,16 +415,11 @@ list.add(4); list.add(5); list.add(4); let result = list.remove(2); -try { - list.remove.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### replaceAllElements -replaceAllElements(callbackfn: (value: T, index?: number, list?: List<T>) => T, +replaceAllElements(callbackFn: (value: T, index?: number, list?: List<T>) => T, thisArg?: Object): void Replaces all elements in this container with new elements, and returns the new ones. @@ -490,7 +430,7 @@ Replaces all elements in this container with new elements, and returns the new o | Name| Value Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked for the replacement.| +| callbackFn | function | Yes| Callback invoked for the replacement.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -523,18 +463,11 @@ list.replaceAllElements((value: number, index: number) => { list.replaceAllElements((value: number, index: number) => { return value = value - 2; }); -try { - list.replaceAllElements.bind({}, (value: number, index: number) => { - return value = 2 * value; - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value: T, index?: number, List?: List<T>) => void, +forEach(callbackFn: (value: T, index?: number, List?: List<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -545,7 +478,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Value Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -575,14 +508,6 @@ list.add(4); list.forEach((value, index) => { console.log("value: " + value, index); }); -try { - list.forEach.bind({}, (value, index) => { - console.log("value: " + value, index); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} - ``` ### sort @@ -624,11 +549,6 @@ list.add(5); list.add(4); list.sort((a: number, b: number) => a - b); list.sort((a: number, b: number) => b - a); -try { - list.sort.bind({}, (a: number, b: number) => b - a)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getSubList @@ -659,7 +579,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The getSubList method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -672,16 +592,6 @@ list.add(4); let result = list.getSubList(2, 4); let result1 = list.getSubList(4, 3); let result2 = list.getSubList(2, 6); -try { - list.getSubList.bind({}, 2, 4)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - list.getSubList(2, 10); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### clear @@ -709,11 +619,6 @@ list.add(4); list.add(5); list.add(4); list.clear(); -try { - list.clear.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### set @@ -744,7 +649,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The set method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -755,16 +660,6 @@ list.add(4); list.add(5); list.add(4); list.set(2, "b"); -try { - list.set.bind({}, 3, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - list.set(8, "b"); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### convertToArray @@ -798,11 +693,6 @@ list.add(4); list.add(5); list.add(4); let result = list.convertToArray(); -try { - list.convertToArray.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### isEmpty @@ -836,11 +726,6 @@ list.add(4); list.add(5); list.add(4); let result = list.isEmpty(); -try { - list.isEmpty.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getFirst @@ -874,11 +759,6 @@ list.add(4); list.add(5); list.add(4); let result = list.getFirst(); -try { - list.getFirst.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getLast @@ -912,11 +792,6 @@ list.add(4); list.add(5); list.add(4); let result = list.getLast(); -try { - list.getLast.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### [Symbol.iterator] @@ -962,9 +837,4 @@ while(temp != undefined) { console.log("value: " + temp); temp = iter.next().value; } -try { - list[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-media.md b/en/application-dev/reference/apis/js-apis-media.md index 8c4dd734fbdbe5d2a3d2bbd621f04f54ed20d883..94034c60a39513e8bafa13724c7665f9c1620202 100644 --- a/en/application-dev/reference/apis/js-apis-media.md +++ b/en/application-dev/reference/apis/js-apis-media.md @@ -1,6 +1,7 @@ # Media > **NOTE** +> > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. The multimedia subsystem provides a set of simple and easy-to-use APIs for you to access the system and use media resources. @@ -52,7 +53,7 @@ Creates a **VideoPlayer** instance. This API uses an asynchronous callback to re | Name | Type | Mandatory| Description | | -------- | ------------------------------------------- | ---- | ------------------------------ | -| callback | AsyncCallback<[VideoPlayer](#videoplayer8)> | Yes | Callback used to return the result. If the operation is successful, the **VideoPlayer** instance is returned; otherwise, **null** is returned. The instance can be used to manage and play video media.| +| callback | AsyncCallback<[VideoPlayer](#videoplayer8)> | Yes | Callback used to return the result. If the operation is successful, the **VideoPlayer** instance is returned; otherwise, **null** is returned. The instance can be used to manage and play video.| **Example** @@ -81,7 +82,7 @@ Creates a **VideoPlayer** instance. This API uses a promise to return the result | Type | Description | | ------------------------------------- | ------------------------------------------------------------ | -| Promise<[VideoPlayer](#videoplayer8)> | Promise used to return the result. If the operation is successful, the **VideoPlayer** instance is returned; otherwise, **null** is returned. The instance can be used to manage and play video media.| +| Promise<[VideoPlayer](#videoplayer8)> | Promise used to return the result. If the operation is successful, the **VideoPlayer** instance is returned; otherwise, **null** is returned. The instance can be used to manage and play video.| **Example** @@ -113,7 +114,7 @@ Only one **AudioRecorder** instance can be created per device. | Type | Description | | ------------------------------- | ------------------------------------------------------------ | -| [AudioRecorder](#audiorecorder) | Returns the **AudioRecorder** instance if the operation is successful; returns **null** otherwise. The instance can be used to record audio media.| +| [AudioRecorder](#audiorecorder) | Returns the **AudioRecorder** instance if the operation is successful; returns **null** otherwise. The instance can be used to record audio.| **Example** @@ -130,11 +131,21 @@ Only one **AudioRecorder** instance can be created per device. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------- | ---- | ------------------------------ | -| callback | AsyncCallback<[VideoRecorder](#videorecorder9)> | Yes | Callback used to return the result. If the operation is successful, the **VideoRecorder** instance is returned; otherwise, **null** is returned. The instance can be used to record video media.| +| callback | AsyncCallback<[VideoRecorder](#videorecorder9)> | Yes | Callback used to return the result. If the operation is successful, the **VideoRecorder** instance is returned; otherwise, **null** is returned. The instance can be used to record video.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ------------------------------ | +| 5400101 | No memory. Return by callback. | **Example** @@ -160,11 +171,21 @@ Only one **AudioRecorder** instance can be created per device. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Return value** | Type | Description | | ----------------------------------------- | ------------------------------------------------------------ | -| Promise<[VideoRecorder](#videorecorder9)> | Promise used to return the result. If the operation is successful, the **VideoRecorder** instance is returned; otherwise, **null** is returned. The instance can be used to record video media.| +| Promise<[VideoRecorder](#videorecorder9)> | Promise used to return the result. If the operation is successful, the **VideoRecorder** instance is returned; otherwise, **null** is returned. The instance can be used to record video.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ----------------------------- | +| 5400101 | No memory. Return by promise. | **Example** @@ -277,7 +298,7 @@ For details about the audio playback demo, see [Audio Playback Development](../. | Name | Type | Readable| Writable| Description | | ------------------------------- | ------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | | src | string | Yes | Yes | Audio file URI. The mainstream audio formats (M4A, AAC, MPEG-3, OGG, and WAV) are supported.
**Examples of supported URI schemes**:
1. FD: fd://xx
![](figures/en-us_image_url.png)
2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx
**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.INTERNET| -| fdSrc9+ | [AVFileDescriptor](#avfiledescriptor9) | Yes | Yes | Description of the audio file. This attribute is required when audio resources of an application are continuously stored in a file.
**Example:**
Assume that a music file that stores continuous music resources consists of the following:
Music 1 (address offset: 0, byte length: 100)
Music 2 (address offset: 101; byte length: 50)
Music 3 (address offset: 151, byte length: 150)
1. To play music 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }
2. To play music 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }
3. To play music 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }
If the file is an independent music file, use **src=fd://xx**.
| +| fdSrc9+ | [AVFileDescriptor](#avfiledescriptor9) | Yes | Yes | Description of the audio file. This attribute is required when audio resources of an application are continuously stored in a file.
**Example:**
Assume that a music file that stores continuous music resources consists of the following:
Music 1 (address offset: 0, byte length: 100)
Music 2 (address offset: 101; byte length: 50)
Music 3 (address offset: 151, byte length: 150)
1. To play music 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }
2. To play music 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }
3. To play music 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }
To play an independent music file, use **src=fd://xx**.
| | loop | boolean | Yes | Yes | Whether to loop audio playback. The value **true** means to loop audio playback, and **false** means the opposite. | | audioInterruptMode9+ | [audio.InterruptMode](js-apis-audio.md#interruptmode9) | Yes | Yes | Audio interruption mode. | | currentTime | number | Yes | No | Current audio playback position, in ms. | @@ -338,7 +359,7 @@ audioPlayer.stop(); reset(): void -Switches the audio resource to be played. +Resets the audio asset to be played. **System capability**: SystemCapability.Multimedia.Media.AudioPlayer @@ -496,7 +517,7 @@ for (let i = 0; i < arrayDescription.length; i++) { on(type: 'bufferingUpdate', callback: (infoType: [BufferingInfoType](#bufferinginfotype8), value: number) => void): void -Subscribes to the audio buffering update event. Only network playback supports this subscription. +Subscribes to the audio buffering update event. This API works only under online playback. **System capability**: SystemCapability.Multimedia.Media.AudioPlayer @@ -669,7 +690,7 @@ Describes audio and video file resources. It is used to specify a particular res ## VideoPlayer8+ -Provides APIs to manage and play video. Before calling an API of **VideoPlayer**, you must call [createVideoPlayer()](#mediacreatevideoplayer8) to create a [VideoPlayer](#videoplayer8) instance. +Provides APIs to manage and play video. Before calling an API of **VideoPlayer**, you must use [createVideoPlayer()](#mediacreatevideoplayer8) to create a [VideoPlayer](#videoplayer8) instance. For details about the video playback demo, see [Video Playback Development](../../media/video-playback.md). @@ -679,7 +700,7 @@ For details about the video playback demo, see [Video Playback Development](../. | Name | Type | Readable| Writable| Description | | ------------------------ | ---------------------------------- | ---- | ---- | ------------------------------------------------------------ | -| url8+ | string | Yes | Yes | Video media URL. The mainstream video formats (MPEG-4, MPEG-TS, WebM, and MKV) are supported.
**Example of supported URIs**:
1. FD: fd://xx
![](figures/en-us_image_url.png)
2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx
| +| url8+ | string | Yes | Yes | Video URL. The mainstream video formats (MPEG-4, MPEG-TS, WebM, and MKV) are supported.
**Example of supported URIs**:
1. FD: fd://xx
![](figures/en-us_image_url.png)
2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx
| | fdSrc9+ | [AVFileDescriptor](#avfiledescriptor9) | Yes| Yes| Description of a video file. This attribute is required when video resources of an application are continuously stored in a file.
**Example:**
Assume that a music file that stores continuous music resources consists of the following:
Video 1 (address offset: 0, byte length: 100)
Video 2 (address offset: 101; byte length: 50)
Video 3 (address offset: 151, byte length: 150)
1. To play video 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }
2. To play video 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }
3. To play video 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }
To play an independent video file, use **src=fd://xx**.
| | loop8+ | boolean | Yes | Yes | Whether to loop video playback. The value **true** means to loop video playback, and **false** means the opposite. | | videoScaleType9+ | [VideoScaleType](#videoscaletype9) | Yes | Yes | Video scale type. | @@ -702,10 +723,10 @@ Sets **SurfaceId**. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| --------- | -------- | ---- | ------------------------- | -| surfaceId | string | Yes | Surface ID to set. | -| callback | function | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| --------- | -------------------- | ---- | ------------------------- | +| surfaceId | string | Yes | Surface ID to set. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -763,9 +784,9 @@ Prepares for video playback. This API uses an asynchronous callback to return th **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------- | ---- | ------------------------ | -| callback | function | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -813,9 +834,9 @@ Starts to play video resources. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------- | ---- | ------------------------ | -| callback | function | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -863,9 +884,9 @@ Pauses video playback. This API uses an asynchronous callback to return the resu **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------- | ---- | ------------------------ | -| callback | function | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -913,9 +934,9 @@ Stops video playback. This API uses an asynchronous callback to return the resul **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------- | ---- | ------------------------ | -| callback | function | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -957,15 +978,15 @@ videoPlayer.stop().then(() => { reset(callback: AsyncCallback\): void -Switches the video resource to be played. This API uses an asynchronous callback to return the result. +Resets the video asset to be played. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Media.VideoPlayer **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------- | ---- | ------------------------ | -| callback | function | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -983,7 +1004,7 @@ videoPlayer.reset((err) => { reset(): Promise\ -Switches the video resource to be played. This API uses a promise to return the result. +Resets the video asset to be played. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Media.VideoPlayer @@ -1013,10 +1034,10 @@ Seeks to the specified playback position. The next key frame at the specified po **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------- | ---- | ------------------------------------------------------------ | -| timeMs | number | Yes | Position to seek to, in ms. The value range is [0, duration].| -| callback | function | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------------------------------------------ | +| timeMs | number | Yes | Position to seek to, in ms. The value range is [0, duration].| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -1045,7 +1066,7 @@ Seeks to the specified playback position. This API uses an asynchronous callback | -------- | ---------------------- | ---- | ------------------------------------------------------------ | | timeMs | number | Yes | Position to seek to, in ms. The value range is [0, duration].| | mode | [SeekMode](#seekmode8) | Yes | Seek mode. | -| callback | function | Yes | Callback used to return the result. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -1080,7 +1101,7 @@ Seeks to the specified playback position. If **mode** is not specified, the next | Type | Description | | -------------- | ------------------------------------------- | -| Promise\ | Promise used to return the playback position, in ms.| +| Promise\| Promise used to return the playback position, in ms.| **Example** @@ -1110,10 +1131,10 @@ Sets the volume. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------- | ---- | ------------------------------------------------------------ | -| vol | number | Yes | Relative volume. The value ranges from 0.00 to 1.00. The value **1** indicates the maximum volume (100%).| -| callback | function | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------------------------------------------ | +| vol | number | Yes | Relative volume. The value ranges from 0.00 to 1.00. The value **1** indicates the maximum volume (100%).| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -1169,9 +1190,9 @@ Releases the video playback resource. This API uses an asynchronous callback to **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------- | ---- | ------------------------ | -| callback | function | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1295,10 +1316,10 @@ Sets the video playback speed. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------- | ---- | ---------------------------------------------------------- | -| speed | number | Yes | Video playback speed. For details, see [PlaybackSpeed](#playbackspeed8).| -| callback | function | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ---------------------------------------------------------- | +| speed | number | Yes | Video playback speed. For details, see [PlaybackSpeed](#playbackspeed8).| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -1333,7 +1354,7 @@ Sets the video playback speed. This API uses a promise to return the result. | Type | Description | | ---------------- | ------------------------------------------------------------ | -| Promise\ | Promise used to return playback speed. For details, see [PlaybackSpeed](#playbackspeed8).| +| Promise\| Promise used to return playback speed. For details, see [PlaybackSpeed](#playbackspeed8).| **Example** @@ -1348,65 +1369,6 @@ videoPlayer.setSpeed(speed).then(() => { }); ``` -### selectBitrate9+ - -selectBitrate(bitrate:number, callback: AsyncCallback\): void - -Selects a bit rate from available ones, which can be obtained by calling [availableBitratesCollect](#onavailablebitratescollect9). This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ---------------------------------------------------------- | -| bitrate | number | Yes | Bit rate to select, which is used in the HLS multi-bit rate scenario. The unit is bit/s. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. If the set value is returned, the operation is successful; otherwise, the operation fails.| - -**Example** - -```js -let bitrate = 1024000; -videoPlayer.selectBitrate(bitrate, (err, result) => { - if (err == null) { - console.info('selectBitrate success!'); - } else { - console.info('selectBitrate fail!'); - } -}); -``` - -### selectBitrate9+ - -selectBitrate(bitrate:number): Promise\ - -Selects a bit rate from available ones, which can be obtained by calling [availableBitratesCollect](#onavailablebitratescollect9). This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer - -**Parameters** - -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | -------------------------------------------- | -| bitrate | number | Yes | Bit rate, which is used in the HLS multi-bit rate scenario. The unit is bit/s.| - -**Return value** - -| Type | Description | -| ---------------- | --------------------------- | -| Promise\ | Promise used to return the bit rate.| - -**Example** - -```js -let bitrate = 1024000; -videoPlayer.selectBitrate(bitrate).then(() => { - console.info('selectBitrate success'); -}).catch((error) => { - console.info(`video catchCallback, error:${error}`); -}); -``` - ### on('playbackCompleted')8+ on(type: 'playbackCompleted', callback: Callback\): void @@ -1596,7 +1558,7 @@ Enumerates the video scale modes. **System capability**: SystemCapability.Multimedia.Media.VideoPlayer -| Name | Default Value| Description | +| Name | Value| Description | | ---------------------------- | ------ | ---------- | | VIDEO_SCALE_TYPE_FIT | 0 | The video will be stretched to fit the window.| | VIDEO_SCALE_TYPE_FIT_CROP| 1 | The video will be stretched to fit the window, without changing its aspect ratio. The content may be cropped. | @@ -1630,7 +1592,7 @@ audioPlayer.getTrackDescription((error, arrList) => { ## AudioRecorder -Implements audio recording. Before calling an API of **AudioRecorder**, you must call [createAudioRecorder()](#mediacreateaudiorecorder) to create an [AudioRecorder](#audiorecorder) instance. +Implements audio recording. Before calling an API of **AudioRecorder**, you must use [createAudioRecorder()](#mediacreateaudiorecorder) to create an [AudioRecorder](#audiorecorder) instance. For details about the audio recording demo, see [Audio Recording Development](../../media/audio-recorder.md). @@ -1890,13 +1852,13 @@ Enumerates the audio encoding formats. **System capability**: SystemCapability.Multimedia.Media.AudioRecorder -| Name | Default Value| Description | -| ------- | ------ | ------------------------------------------------------------ | -| DEFAULT | 0 | Default encoding format.
This API is defined but not implemented yet.| -| AMR_NB | 1 | AMR-NB.
This API is defined but not implemented yet.| -| AMR_WB | 2 | Adaptive Multi Rate-Wide Band Speech Codec (AMR-WB).
This API is defined but not implemented yet.| -| AAC_LC | 3 | Advanced Audio Coding Low Complexity (AAC-LC).| -| HE_AAC | 4 | High-Efficiency Advanced Audio Coding (HE_AAC).
This API is defined but not implemented yet.| +| Name | Value | Description | +| ------- | ---- | ------------------------------------------------------------ | +| DEFAULT | 0 | Default encoding format.
This API is defined but not implemented yet. | +| AMR_NB | 1 | AMR-NB.
This API is defined but not implemented yet.| +| AMR_WB | 2 | Adaptive Multi Rate-Wide Band Speech Codec (AMR-WB).
This API is defined but not implemented yet.| +| AAC_LC | 3 | Advanced Audio Coding Low Complexity (AAC-LC).| +| HE_AAC | 4 | High-Efficiency Advanced Audio Coding (HE_AAC).
This API is defined but not implemented yet.| ## AudioOutputFormat(deprecated) @@ -1908,13 +1870,13 @@ Enumerates the audio output formats. **System capability**: SystemCapability.Multimedia.Media.AudioRecorder -| Name | Default Value| Description | -| -------- | ------ | ------------------------------------------------------------ | -| DEFAULT | 0 | Default encapsulation format.
This API is defined but not implemented yet.| -| MPEG_4 | 2 | MPEG-4. | -| AMR_NB | 3 | AMR_NB.
This API is defined but not implemented yet.| -| AMR_WB | 4 | AMR_WB.
This API is defined but not implemented yet.| -| AAC_ADTS | 6 | Audio Data Transport Stream (ADTS), which is a transport stream format of AAC-based audio.| +| Name | Value | Description | +| -------- | ---- | ------------------------------------------------------------ | +| DEFAULT | 0 | Default encapsulation format.
This API is defined but not implemented yet. | +| MPEG_4 | 2 | MPEG-4. | +| AMR_NB | 3 | AMR_NB.
This API is defined but not implemented yet. | +| AMR_WB | 4 | AMR_WB.
This API is defined but not implemented yet. | +| AAC_ADTS | 6 | Audio Data Transport Stream (ADTS), which is a transport stream format of AAC-based audio.| ## VideoRecorder9+ @@ -1926,6 +1888,8 @@ For details about the video recording demo, see [Video Recording Development](.. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + | Name | Type | Readable| Writable| Description | | ------------------ | -------------------------------------- | ---- | ---- | ---------------- | | state9+ | [VideoRecordState](#videorecordstate9) | Yes | No | Video recording state.| @@ -1940,6 +1904,8 @@ Sets video recording parameters. This API uses an asynchronous callback to retur **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -1947,6 +1913,17 @@ Sets video recording parameters. This API uses an asynchronous callback to retur | config | [VideoRecorderConfig](#videorecorderconfig9) | Yes | Video recording parameters to set. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | --------------------------------------- | +| 201 | Permission denied. Return by callback. | +| 401 | Parameter error. Return by callback. | +| 5400102 | Operate not permit. Return by callback. | +| 5400105 | Service died. Return by callback. | + **Example** ```js @@ -1992,6 +1969,8 @@ Sets video recording parameters. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Parameters** | Name| Type | Mandatory| Description | @@ -2004,6 +1983,17 @@ Sets video recording parameters. This API uses a promise to return the result. | -------------- | ---------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | -------------------------------------- | +| 201 | Permission denied. Return by promise. | +| 401 | Parameter error. Return by promise. | +| 5400102 | Operate not permit. Return by promise. | +| 5400105 | Service died. Return by promise. | + **Example** ```js @@ -2049,12 +2039,24 @@ This API can be called only after [prepare()](#videorecorder_prepare1) is called **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | --------------------------- | | callback | AsyncCallback\ | Yes | Callback used to obtain the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | --------------------------------------- | +| 5400102 | Operate not permit. Return by callback. | +| 5400103 | IO error. Return by callback. | +| 5400105 | Service died. Return by callback. | + **Example** ```js @@ -2082,12 +2084,24 @@ This API can be called only after [prepare()](#videorecorder_prepare1) is called **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Return value** | Type | Description | | ---------------- | -------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | -------------------------------------- | +| 5400102 | Operate not permit. Return by promise. | +| 5400103 | IO error. Return by promise. | +| 5400105 | Service died. Return by promise. | + **Example** ```js @@ -2111,12 +2125,24 @@ This API can be called only after [prepare()](#videorecorder_prepare1) and [getI **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------------------------- | | callback | AsyncCallback\ | Yes | Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | --------------------------------------- | +| 5400102 | Operate not permit. Return by callback. | +| 5400103 | IO error. Return by callback. | +| 5400105 | Service died. Return by callback. | + **Example** ```js @@ -2140,12 +2166,24 @@ This API can be called only after [prepare()](#videorecorder_prepare1) and [getI **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Return value** | Type | Description | | -------------- | ------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | -------------------------------------- | +| 5400102 | Operate not permit. Return by promise. | +| 5400103 | IO error. Return by promise. | +| 5400105 | Service died. Return by promise. | + **Example** ```js @@ -2167,12 +2205,24 @@ This API can be called only after [start()](#videorecorder_start1) is called. Yo **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------------------------- | | callback | AsyncCallback\ | Yes | Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | --------------------------------------- | +| 5400102 | Operate not permit. Return by callback. | +| 5400103 | IO error. Return by callback. | +| 5400105 | Service died. Return by callback. | + **Example** ```js @@ -2196,12 +2246,24 @@ This API can be called only after [start()](#videorecorder_start1) is called. Yo **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Return value** | Type | Description | | -------------- | ------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | -------------------------------------- | +| 5400102 | Operate not permit. Return by promise. | +| 5400103 | IO error. Return by promise. | +| 5400105 | Service died. Return by promise. | + **Example** ```js @@ -2221,12 +2283,24 @@ Resumes video recording. This API uses an asynchronous callback to return the re **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------------------------- | | callback | AsyncCallback\ | Yes | Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | --------------------------------------- | +| 5400102 | Operate not permit. Return by callback. | +| 5400103 | IO error. Return by callback. | +| 5400105 | Service died. Return by callback. | + **Example** ```js @@ -2248,12 +2322,24 @@ Resumes video recording. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Return value** | Type | Description | | -------------- | ------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | -------------------------------------- | +| 5400102 | Operate not permit. Return by promise. | +| 5400103 | IO error. Return by promise. | +| 5400105 | Service died. Return by promise. | + **Example** ```js @@ -2275,12 +2361,24 @@ To start another recording, you must call [prepare()](#videorecorder_prepare1) a **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------------------------- | | callback | AsyncCallback\ | Yes | Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | --------------------------------------- | +| 5400102 | Operate not permit. Return by callback. | +| 5400103 | IO error. Return by callback. | +| 5400105 | Service died. Return by callback. | + **Example** ```js @@ -2304,12 +2402,24 @@ To start another recording, you must call [prepare()](#videorecorder_prepare1) a **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Return value** | Type | Description | | -------------- | ------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | -------------------------------------- | +| 5400102 | Operate not permit. Return by promise. | +| 5400103 | IO error. Return by promise. | +| 5400105 | Service died. Return by promise. | + **Example** ```js @@ -2329,12 +2439,22 @@ Releases the video recording resource. This API uses an asynchronous callback to **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | -------------------------------- | | callback | AsyncCallback\ | Yes | Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | --------------------------------- | +| 5400105 | Service died. Return by callback. | + **Example** ```js @@ -2356,12 +2476,22 @@ Releases the video recording resource. This API uses a promise to return the res **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Return value** | Type | Description | | -------------- | ----------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | --------------------------------- | +| 5400105 | Service died. Return by callback. | + **Example** ```js @@ -2383,12 +2513,23 @@ To start another recording, you must call [prepare()](#videorecorder_prepare1) a **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------------------------- | | callback | AsyncCallback\ | Yes | Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | --------------------------------- | +| 5400103 | IO error. Return by callback. | +| 5400105 | Service died. Return by callback. | + **Example** ```js @@ -2412,12 +2553,23 @@ To start another recording, you must call [prepare()](#videorecorder_prepare1) a **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Return value** | Type | Description | | -------------- | ------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | -------------------------------- | +| 5400103 | IO error. Return by promise. | +| 5400105 | Service died. Return by promise. | + **Example** ```js @@ -2444,6 +2596,15 @@ Subscribes to video recording error events. After an error event is reported, yo | type | string | Yes | Event type, which is **'error'** in this case.
The **'error'** event is triggered when an error occurs during video recording.| | callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | --------------------------------- | +| 5400103 | IO error. Return by callback. | +| 5400105 | Service died. Return by callback. | + **Example** ```js @@ -2459,6 +2620,8 @@ Enumerates the video recording states. You can obtain the state through the **st **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + | Name | Type | Description | | -------- | ------ | ---------------------- | | idle | string | The video recorder is idle. | @@ -2474,7 +2637,9 @@ Describes the video recording parameters. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder -| Name | Type | Mandatory| Description | +**System API**: This is a system API. + +| Name | Type | Mandatory| Description | | --------------- | ---------------------------------------------- | ---- | ------------------------------------------------------------ | | audioSourceType | [AudioSourceType](#audiosourcetype9) | Yes | Type of the audio source for video recording. | | videoSourceType | [VideoSourceType](#videosourcetype9) | Yes | Type of the video source for video recording. | @@ -2489,6 +2654,8 @@ Enumerates the audio source types for video recording. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + | Name | Value | Description | | ------------------------- | ---- | ---------------------- | | AUDIO_SOURCE_TYPE_DEFAULT | 0 | Default audio input source.| @@ -2500,6 +2667,8 @@ Enumerates the video source types for video recording. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + | Name | Value | Description | | ----------------------------- | ---- | ------------------------------- | | VIDEO_SOURCE_TYPE_SURFACE_YUV | 0 | The input surface carries raw data.| @@ -2511,7 +2680,9 @@ Describes the video recording profile. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder -| Name | Type | Mandatory| Description | +**System API**: This is a system API. + +| Name | Type | Mandatory| Description | | ---------------- | -------------------------------------------- | ---- | ---------------- | | audioBitrate | number | Yes | Audio encoding bit rate.| | audioChannels | number | Yes | Number of audio channels.| @@ -2541,7 +2712,7 @@ Describes the geographical location of the recorded video. **System capability**: SystemCapability.Multimedia.Media.Core -| Name | Type| Mandatory| Description | -| --------- | -------- | ---- | ---------------- | -| latitude | number | Yes | Latitude of the geographical location.| -| longitude | number | Yes | Longitude of the geographical location.| +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ---------------- | +| latitude | number | Yes | Latitude of the geographical location.| +| longitude | number | Yes | Longitude of the geographical location.| diff --git a/en/application-dev/reference/apis/js-apis-nfcTag.md b/en/application-dev/reference/apis/js-apis-nfcTag.md index 2f3a208fe1f95b2c4f936709d047fa4c9581f8b6..91ef73c07db34721d0cc0f964bb992ce37669ae3 100644 --- a/en/application-dev/reference/apis/js-apis-nfcTag.md +++ b/en/application-dev/reference/apis/js-apis-nfcTag.md @@ -1,8 +1,9 @@ -# NFC Tags +# @ohos.nfc.tag The **nfcTag** module provides APIs for managing Near-Field Communication (NFC) tags. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## **Declaration** @@ -47,12 +48,10 @@ Before developing applications related to tag read and write, you must declare N } ``` > **CAUTION**
-> -> - The **actions** field is mandatory. It must be **ohos.nfc.tag.action.TAG_FOUND** and cannot be changed. -> - The **name** field of **metadata** is mandatory. It must be **tag-tech** and cannot be changed. -> - The **value** field of **metadata** is mandatory. It can be **NfcA**, **NfcB**, **NfcF**, **NfcV**, **IsoDep**, **Ndef**, **MifareClassic**, **MifareUL**, **NdefFormatable** or their combinations. Incorrect setting of this field will cause a parsing failure. -> - The **name** field of **requestPermissions** is mandatory. It must be **ohos.permission.NFC_TAG** and cannot be changed. - +1. The **actions** field is mandatory. It must be **ohos.nfc.tag.action.TAG_FOUND** and cannot be changed. +2. The **name** field under **metadata** is mandatory. It must be **tag-tech** and cannot be changed. +3. The **value** field under **metadata** is mandatory. It can be **NfcA**, **NfcB**, **NfcF**, **NfcV**, **IsoDep**, **Ndef**, **MifareClassic**, **MifareUL**, **NdefFormatable** or any of their combinations. Incorrect settings of this field will cause a parsing failure. +4. The **name** field under **requestPermissions** is mandatory. It must be **ohos.permission.NFC_TAG** and cannot be changed. ## **Modules to Import** @@ -61,34 +60,63 @@ import tag from '@ohos.nfc.tag'; ``` ## **tag.TagInfo** -Before reading or writing data to a card with tags, the application must obtain **TagInfo** to determine the tag technologies supported by the card. Then, the application can invoke the correct API to communicate with the card. + +Before a card with tags is read or written, **TagInfo** must be obtained to determine the tag technologies supported by the card. In this way, the application can invoke the correct API to communicate with the card. ```js import tag from '@ohos.nfc.tag'; onCreate(want, launchParam) { // Add other code here. - // want is initialized by the NFC service and contains taginfo. - var tagInfo = tag.getTagInfo(want); - if (tagInfo == undefined) { + // want is initialized by the NFC service and contains tagInfo. + var tagInfo; + try { + tagInfo = tag.getTagInfo(want); + } catch (error) { + console.log("tag.getTagInfo catched error: " + error); + } + if (tagInfo == null || tagInfo == undefined) { console.log("no TagInfo to be created, ignore it."); return; } + + // get the supported technologies for this found tag. var isNfcATag = false; + var isIsoDepTag = false; for (var i = 0; i < tagInfo.technology.length; i++) { if (tagInfo.technology[i] == tag.NFC_A) { isNfcATag = true; - break; + } + + if (tagInfo.technology[i] == tag.ISO_DEP) { + isIsoDepTag = true; } // Also check for technology tag.NFC_B, NFC_F, NFC_V, ISO_DEP, NDEF, MIFARE_CLASSIC, MIFARE_ULTRALIGHT, and NDEF_FORMATABLE. } + + // use NfcA APIs to access the found tag. if (isNfcATag) { - var nfcA = tag.getNfcATag(taginfo); + var nfcA; + try { + nfcA = tag.getNfcATag(taginfo); + } catch (error) { + console.log("tag.getNfcATag catched error: " + error); + } + // Other code to read or write this tag. + } + + // use getIsoDep APIs to access the found tag. + if (isIsoDepTag) { + var isoDep; + try { + isoDep = tag.getIsoDep(taginfo); + } catch (error) { + console.log("tag.getIsoDep catched error: " + error); + } // Other code to read or write this tag. } - // use the same code to handle "NfcA/NfcB/NfcF/NfcV/IsoDep/Ndef/MifareClassic/MifareUL/NdefFormatable", such as, - // var isoDep = tag.getIsoDepTag(taginfo); + // Use the same code to handle "NfcA/NfcB/NfcF/NfcV/Ndef/MifareClassic/MifareUL/NdefFormatable". } ``` @@ -156,78 +184,122 @@ Obtains an **NfcVTag** object, which allows access to the tags that use the NFC- | -------- | ---------------- | | [NfcVTag](js-apis-nfctech.md#nfcvtag) | **NfcVTag** object obtained.| -## tag.getIsoDepTag9+ +## tag.getIsoDep9+ -getIsoDepTag(tagInfo: [TagInfo](#taginfo)): [IsoDepTag](js-apis-nfctech.md#isoDepTag9 ) +getIsoDep(tagInfo: [TagInfo](#taginfo)): [IsoDepTag](js-apis-nfctech.md#isoDepTag9 ) Obtains an **IsoDepTag** object, which allows access to the tags that use the ISO-DEP technology. -**Required permissions**: ohos.permission.NFC_TAG - **System capability**: SystemCapability.Communication.NFC.Core +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. | + **Return value** | **Type**| **Description** | | ---------- | ------------------| | [IsoDepTag](js-apis-nfctech.md#isodeptag9) | **IsoDepTag** object obtained.| -## tag.getNdefTag9+ +**Error codes** -getNdefTag(tagInfo: [TagInfo](#taginfo)): [NdefTag](js-apis-nfctech.md#ndeftag9) +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). -Obtains an **NdefTag** object, which allows access to the tags in the NFC Data Exchange Format (NDEF). +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +## tag.getNdef9+ -**Required permissions**: ohos.permission.NFC_TAG +getNdef(tagInfo: [TagInfo](#taginfo)): [NdefTag](js-apis-nfctech.md#ndeftag9) + +Obtains an **NdefTag** object, which allows access to the tags in the NFC Data Exchange Format (NDEF). **System capability**: SystemCapability.Communication.NFC.Core +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. | + **Return value** | **Type**| **Description** | | ---------| -------------- | | [NdefTag](js-apis-nfctech.md#ndeftag9) | **NdefTag** object obtained.| -## tag.getMifareClassicTag9+ +**Error codes** -getMifareClassicTag(tagInfo: [TagInfo](#taginfo)): [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). -Obtains a **MifareClassicTag** object, which allows access to the tags that use MIFARE Classic. +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | -**Required permissions**: ohos.permission.NFC_TAG +## tag.getMifareClassic9+ + +getMifareClassic(tagInfo: [TagInfo](#taginfo)): [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) + +Obtains a **MifareClassicTag** object, which allows access to the tags that use MIFARE Classic. **System capability**: SystemCapability.Communication.NFC.Core +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. | + **Return value** | **Type**| **Description** | | ----------------- | ------------------------| | [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) | **MifareClassicTag** object obtained.| -## tag.getMifareUltralightTag9+ +**Error codes** -getMifareUltralightTag(tagInfo: [TagInfo](#taginfo)): [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9) +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). -Obtains a **MifareUltralightTag** object, which allows access to the tags that use MIFARE Ultralight. +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | -**Required permissions**: ohos.permission.NFC_TAG +## tag.getMifareUltralight9+ + +getMifareUltralight(tagInfo: [TagInfo](#taginfo)): [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9) + +Obtains a **MifareUltralightTag** object, which allows access to the tags that use MIFARE Ultralight. **System capability**: SystemCapability.Communication.NFC.Core +**Parameters** +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. | + **Return value** | **Type**| **Description** | | -------------------- | ---------------------------| | [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9) | **MifareUltralightTag** object obtained.| -## tag.getNdefFormatableTag9+ +**Error codes** -getNdefFormatableTag(tagInfo: [TagInfo](#taginfo)): [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag9) +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). -Obtains an **NdefFormatableTag** object, which allows access to the tags that are NDEF formattable. +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | -**Required permissions**: ohos.permission.NFC_TAG +## tag.getNdefFormatable9+ + +getNdefFormatable(tagInfo: [TagInfo](#taginfo)): [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag9) + +Obtains an **NdefFormatableTag** object, which allows access to the tags that are NDEF formattable. **System capability**: SystemCapability.Communication.NFC.Core @@ -237,89 +309,376 @@ Obtains an **NdefFormatableTag** object, which allows access to the tags that ar | ------------------ | --------------------------| | [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag) | **NdefFormatableTag** object obtained.| +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + ## tag.getTagInfo9+ -getTagInfo(want: Want): [TagInfo](#taginfo) +getTagInfo(want: [Want](js-apis-app-ability-want.md#Want)): [TagInfo](#taginfo) Obtains **TagInfo** from **Want**, which is initialized by the NFC service and contains the attributes required by **TagInfo**. -**Required permissions**: ohos.permission.NFC_TAG - **System capability**: SystemCapability.Communication.NFC.Core +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| want | [Want](js-apis-app-ability-want.md#Want) | Yes | Data obtained from the parameters of the **onCreate** entry function when an ability is dispatched. | + **Return value** | **Type**| **Description** | | ------------------ | --------------------------| | [TagInfo](#taginfo) | **TagInfo** object obtained.| -## TagInfo -Defines the **TagInfo** object, which provides information about the tag technologies supported by a card. +## tag.ndef.makeUriRecord9+ -**Required permissions**: ohos.permission.NFC_TAG +makeUriRecord(uri: string): [NdefRecord](#ndefrecord9); + +Creates an NDEF record based on the specified URI. **System capability**: SystemCapability.Communication.NFC.Core -| **Name**| **Type**| **Description**| -| -------- | -------- | -------- | -| uid9+ | number[] | Tag unique identifier (UID). Each number of the UID is a hexadecimal number ranging from **0x00** to **0xFF**.| -| technology9+ | number[] | Supported technologies. Each number is a constant indicating the supported technology.| -| supportedProfiles | number[] | Supported technologies. This parameter is not supported since API version 9 and is replaced by **technology**.| +**Parameters** -## NdefRecord9+ -Defines an NDEF tag record. For details, see *NFCForum-TS-NDEF_1.0*. +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| uri | string | Yes| Data to write to the NDEF record.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefRecord](#ndefrecord9) | NDEF record created. For details, see *NFCForum-TS-NDEF_1.0*.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +try { + let uri = "https://gitee.com/openharmony"; // change it to be correct. + let ndefRecord = tag.ndef.makeUriRecord(uri); + if (ndefRecord != undefined) { + console.log("ndefMessage makeUriRecord rtdType: " + ndefRecord.rtdType); + console.log("ndefMessage makeUriRecord payload: " + ndefRecord.payload); + } else { + console.log("ndefMessage makeUriRecord ndefRecord: " + ndefRecord); + } +} catch (busiError) { + console.log("ndefMessage makeUriRecord catched busiError: " + busiError); +} +``` + +## tag.ndef.makeTextRecord9+ + +makeTextRecord(text: string, locale: string): [NdefRecord](#ndefrecord9); + +Creates an NDEF record based on the specified text data and encoding type. + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| text | string | Yes | Text to write to the NDEF record.| +| locale | string | Yes | Encoding mode of the text.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefRecord](#ndefrecord9) | NDEF record created. For details, see *NFCForum-TS-NDEF_1.0*.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +try { + let text = "Hello World"; // change it to be correct. + let locale = "en"; // change it to be correct. + let ndefRecord = tag.ndef.makeTextRecord(text, locale); + if (ndefRecord != undefined) { + console.log("ndefMessage makeTextRecord rtdType: " + ndefRecord.rtdType); + console.log("ndefMessage makeTextRecord payload: " + ndefRecord.payload); + } else { + console.log("ndefMessage makeTextRecord ndefRecord: " + ndefRecord); + } +} catch (busiError) { + console.log("ndefMessage makeTextRecord catched busiError: " + busiError); +} +``` + + +## tag.ndef.makeMimeRecord9+ + +makeMimeRecord(mimeType: string, mimeData: number[]): [NdefRecord](#ndefrecord9); + +Creates an NDEF record based on the specified MIME data and type. + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| mimeType | string | Yes | MIME type that complies with RFC rules, for example, **text/plain** or **image/jpeg**.| +| mimeData | number[] | Yes | MIME data, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefRecord](#ndefrecord9) | NDEF record created. For details, see *NFCForum-TS-NDEF_1.0*.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +try { + let mimeType = "text/plain"; // change it to be correct. + let mimeData = [0x01, 0x02, 0x03, 0x04]; // change it to be correct. + let ndefRecord = tag.ndef.makeMimeRecord(mimeType, mimeData); + if (ndefRecord != undefined) { + console.log("ndefMessage makeMimeRecord rtdType: " + ndefRecord.rtdType); + console.log("ndefMessage makeMimeRecord payload: " + ndefRecord.payload); + } else { + console.log("ndefMessage makeMimeRecord ndefRecord: " + ndefRecord); + } +} catch (busiError) { + console.log("ndefMessage makeMimeRecord catched busiError: " + busiError); +} +``` +## tag.ndef.makeExternalRecord9+ + +makeExternalRecord(domainName: string, type: string, externalData: number[]): [NdefRecord](#ndefrecord9); + +Creates an NDEF record based on application-specific data. + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| domainName | string | Yes | Bundle name of the application or domain name of the organization that releases the applications.| +| type | string | Yes | Type of the application data.| +| externalData | number[] | Yes | Application data, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefRecord](#ndefrecord9) | NDEF record created. For details, see *NFCForum-TS-NDEF_1.0*.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +try { + let domainName = "ohos.nfc.application"; // change it to be correct. + let type = "test"; // change it to be correct. + let externalData = [0x01, 0x02, 0x03, 0x04]; // change it to be correct. + let ndefRecord = tag.ndef.makeExternalRecord(domainName, type, externalData); + if (ndefRecord != undefined) { + console.log("ndefMessage makeExternalRecord rtdType: " + ndefRecord.rtdType); + console.log("ndefMessage makeExternalRecord payload: " + ndefRecord.payload); + } else { + console.log("ndefMessage makeExternalRecord ndefRecord: " + ndefRecord); + } +} catch (busiError) { + console.log("ndefMessage makeExternalRecord catched busiError: " + busiError); +} +``` + +## tag.ndef.messageToBytes9+ + +messageToBytes(ndefMessage: [NdefMessage](js-apis-nfctech.md#ndefmessage9)): number[]; + +Converts an NDEF message to bytes. + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| ndefMessage | [NdefMessage](js-apis-nfctech.md#ndefmessage9) | Yes | NDEF message to convert.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number[] | NDEF message in bytes, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +let rawData = [0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]; // MUST can be parsed as NDEF Record. +let ndefMessage; +try { + ndefMessage = tag.ndef.createNdefMessage(rawData); + console.log("ndef createNdefMessage, ndefMessage: " + ndefMessage); +} catch (busiError) { + console.log("ndef createNdefMessage busiError: " + busiError); +} + +try { + let rawData2 = tag.ndef.messageToBytes(ndefMessage); + console.log("ndefMessage messageToBytes rawData2: " + rawData2); +} catch (busiError) { + console.log("ndefMessage messageToBytes catched busiError: " + busiError); +} +``` +## tag.ndef.createNdefMessage9+ + +createNdefMessage(data: number[]): [NdefMessage](js-apis-nfctech.md#ndefmessage9) + +Creates an NDEF message from raw byte data. The data must comply with the NDEF record format. Otherwise, the NDE record list contained in the **NdefMessage** object will be empty. + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| data | number[] | Yes| Raw byte data, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**. The data must comply with the NDEF record format.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefMessage](js-apis-nfctech.md#ndefmessage9) | NDEF message created. For details, see *NFCForum-TS-NDEF_1.0*.| + +**Example** +```js +import tag from '@ohos.nfc.tag'; + +let rawData = [0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]; // MUST can be parsed as NDEF Record. +let ndefMessage; +try { + ndefMessage = tag.ndef.createNdefMessage(rawData); + console.log("ndef createNdefMessage, ndefMessage: " + ndefMessage); +} catch (busiError) { + console.log("ndef createNdefMessage busiError: " + busiError); +} +``` + +## tag.ndef.createNdefMessage9+ + +createNdefMessage(ndefRecords: NdefRecord[]): [NdefMessage](js-apis-nfctech.md#ndefmessage9) + +Creates an NDEF message from the NDEF records list. + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| ndefRecords | [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] | Yes| NDEF record list used to create the NDEF message. For details, see *NFCForum-TS-NDEF_1.0*.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefMessage](js-apis-nfctech.md#ndefmessage9) | NDEF message created. For details, see *NFCForum-TS-NDEF_1.0*.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +let uriRecord = tag.ndef.makeUriRecord("https://gitee.com/openharmony"); +let textRecord = tag.ndef.makeTextRecord("Hello World", "en"); +let ndefRecords = [uriRecord, textRecord]; +let ndefMessage; +try { + ndefMessage = tag.ndef.createNdefMessage(ndefRecords); + console.log("ndef createNdefMessage ndefMessage: " + ndefMessage); +} catch (busiError) { + console.log("ndef createNdefMessage busiError: " + busiError); +} +``` + +## TagInfo + +Defines the **TagInfo** object, which provides information about the tag technologies supported by a card. + +**System capability**: SystemCapability.Communication.NFC.Core **Required permissions**: ohos.permission.NFC_TAG +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| uid9+ | number[] | Yes| No| Tag unique identifier (UID), which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| +| technology9+ | number[] | Yes| No| Supported technologies. Each number is a constant indicating the supported technology.| +| supportedProfiles | number[] | Yes| No| Supported profiles. This parameter is not supported since API version 9. Use [tag.TagInfo#technology](#taginfo) instead.| +| extrasData9+ | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap)[] | Yes| No| Extended attribute value of the tag technology.
**System API**: This is a system API.| +| tagRfDiscId9+ | number | Yes| No| ID allocated when the tag is discovered.
**System API**: This is a system API.| +| remoteTagService9+ | [rpc.RemoteObject](js-apis-rpc.md#remoteobject) | Yes| No| Remote object of the NFC service process used for interface communication between the client and the service.
**System API**: This is a system API.| +## NdefRecord9+ +Defines an NDEF record. For details, see *NFCForum-TS-NDEF_1.0*. + **System capability**: SystemCapability.Communication.NFC.Core -| **Name**| **Type**| **Description**| -| -------- | -------- | -------- | -| tnf | number | Type name field (TNF) of an NDEF record.| -| rtdType| number[] | Record type definition (RTD) of an NDEF record. Each number is a hexadecimal number ranging from **0x00** to **0xFF**.| -| id | number[] | ID of an NDEF record. Each number is a hexadecimal number ranging from **0x00** to **0xFF**.| -| payload | number[] | Payload of an NDEF record. Each number is a hexadecimal number ranging from **0x00** to **0xFF**.| + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| tnf | number | Yes| No| Type name field (TNF) of the NDEF record.| +| rtdType| number[] | Yes| No| Record type definition (RTD) of the NDEF record. It consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| +| id | number[] | Yes| No| NDEF record ID, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| +| payload | number[] | Yes| No| NDEF payload, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| ## Technology Type Definition Enumerates the tag technology types. -**Required permissions**: ohos.permission.NFC_TAG - **System capability**: SystemCapability.Communication.NFC.Core + | **Name**| **Value**| **Description**| | -------- | -------- | -------- | | NFC_A | 1 | NFC-A (ISO 14443-3A).| -| NFC_B | 2 | NFC-A (ISO 14443-3B).| +| NFC_B | 2 | NFC-B (ISO 14443-3B).| | ISO_DEP | 3 | ISO-DEP (ISO 14443-4).| | NFC_F | 4 | NFC-F (JIS 6319-4).| | NFC_V | 5 | NFC-V (ISO 15693).| | NDEF | 6 | NDEF.| +| NDEF_FORMATABLE9+ | 7 | NDEF formattable.| | MIFARE_CLASSIC | 8 | MIFARE Classic.| | MIFARE_ULTRALIGHT | 9 | MIFARE Ultralight.| -| NDEF_FORMATABLE9+ | 10 | NDEF formattable.| ## TnfType9+ Enumerates the TNF types. For details, see *NFCForum-TS-NDEF_1.0*. -**Required permissions**: ohos.permission.NFC_TAG - **System capability**: SystemCapability.Communication.NFC.Core + | **Name**| **Value**| **Description**| | -------- | -------- | -------- | | TNF_EMPTY | 0x0 | Empty.| -| TNF_WELL_KNOWN | 0x01 | NFC Forum Well Known Type [NFC RTD].| -| TNF_MEDIA | 0x02 | Media-type as defined in RFC 2046 [RFC 2046].| -| TNF_ABSOLUTE_URI | 0x03 | Absolute URI as defined in RFC 3986 [RFC 3986].| -| TNF_EXT_APP | 0x04 | NFC Forum external type [NFC RTD].| -| TNF_UNKNOWN | 0x05 | Unknown.| -| TNF_UNCHANGED | 0x06 | Unchanged (see section 2.3.3).| +| TNF_WELL_KNOWN | 0x1 | NFC Forum Well Known Type [NFC RTD].| +| TNF_MEDIA | 0x2 | Media-type as defined in RFC 2046 [RFC 2046].| +| TNF_ABSOLUTE_URI | 0x3 | Absolute URI as defined in RFC 3986 [RFC 3986].| +| TNF_EXT_APP | 0x4 | NFC Forum external type [NFC RTD].| +| TNF_UNKNOWN | 0x5 | Unknown.| +| TNF_UNCHANGED | 0x6 | Unchanged (see section 2.3.3 in *NFCForum-TS-NDEF_1.0*).| ## NDEF Record RTD Enumerates the NDEF record types. For details about the RTD, see *NFCForum-TS-NDEF_1.0*. -**Required permissions**: ohos.permission.NFC_TAG - **System capability**: SystemCapability.Communication.NFC.Core + | **Name**| **Value**| **Description**| | -------- | -------- | -------- | | RTD_TEXT9+ | [0x54] | NDEF record of the text type.| @@ -328,36 +687,33 @@ Enumerates the NDEF record types. For details about the RTD, see *NFCForum-TS-ND ## NfcForumType9+ Enumerates the NFC Forum tag types. -**Required permissions**: ohos.permission.NFC_TAG - **System capability**: SystemCapability.Communication.NFC.Core + | **Name**| **Value**| **Description**| | -------- | -------- | -------- | | NFC_FORUM_TYPE_1 | 1 | NFC Forum tag type 1.| | NFC_FORUM_TYPE_2 | 2 | NFC Forum tag type 2.| | NFC_FORUM_TYPE_3 | 3 | NFC Forum tag type 3.| | NFC_FORUM_TYPE_4 | 4 | NFC Forum tag type 4.| -| MIFARE_CLASSIC | 101 | MIFARE Classic type.| +| MIFARE_CLASSIC | 101 | MIFARE Classic.| ## MifareClassicType9+ Enumerates the MIFARE Classic tag types. -**Required permissions**: ohos.permission.NFC_TAG - **System capability**: SystemCapability.Communication.NFC.Core + | **Name**| **Value**| **Description**| | -------- | -------- | -------- | -| TYPE_UNKNOWN | -1 | Unknown type.| -| TYPE_CLASSIC | 0 | MIFARE Classic.| -| TYPE_PLUS | 1 | MIFARE Plus.| -| TYPE_PRO | 2 | MIFARE Pro.| +| TYPE_UNKNOWN | 0 | Unknown type.| +| TYPE_CLASSIC | 1 | MIFARE Classic.| +| TYPE_PLUS | 2 | MIFARE Plus.| +| TYPE_PRO | 3 | MIFARE Pro.| ## MifareClassicSize9+ -Enumerates the storage sizes of MIFARE Classic tags. - -**Required permissions**: ohos.permission.NFC_TAG +Enumerates the sizes of MIFARE Classic tags. **System capability**: SystemCapability.Communication.NFC.Core + | **Name**| **Value**| **Description**| | -------- | -------- | -------- | | MC_SIZE_MINI | 320 | Each tag has 5 sectors, and each sector has 4 blocks.| @@ -365,15 +721,14 @@ Enumerates the storage sizes of MIFARE Classic tags. | MC_SIZE_2K | 2048 | Each tag has 32 sectors, and each sector has 4 blocks.| | MC_SIZE_4K | 4096 | Each tag has 40 sectors, and each sector has 4 blocks.| -### MifareUltralightType9+ +## MifareUltralightType9+ Enumerates the MIFARE Ultralight tag types. -**Required permissions**: ohos.permission.NFC_TAG - **System capability**: SystemCapability.Communication.NFC.Core + | **Name**| **Value**| **Description**| | -------- | -------- | -------- | -| TYPE_UNKOWN | -1 | Unknown type.| +| TYPE_UNKNOWN | 0 | Unknown type.| | TYPE_ULTRALIGHT | 1 | MIFARE Ultralight.| | TYPE_ULTRALIGHT_C | 2 | MIFARE Ultralight C.| diff --git a/en/application-dev/reference/apis/js-apis-nfctech.md b/en/application-dev/reference/apis/js-apis-nfctech.md index 9817e5fd5c1f2a7f797f2c20fa7b6eff18dc25a5..e28864fc7bd2002838b7ae982bcb7b5269e2c086 100644 --- a/en/application-dev/reference/apis/js-apis-nfctech.md +++ b/en/application-dev/reference/apis/js-apis-nfctech.md @@ -1,11 +1,12 @@ -# NFC Tag Technologies +# nfctech The **nfctech** module provides APIs for reading and writing tags that use different Near-Field Communication (NFC) technologies. > **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -## **Modules to Import** +## Modules to Import ```js import tag from '@ohos.nfc.tag'; @@ -13,11 +14,11 @@ import tag from '@ohos.nfc.tag'; ## NfcATag -Provides access to NFC-A (ISO 14443-3A) properties and I/O operations. This class inherits from **TagSession**. +Provides APIs to access NFC-A (ISO 14443-3A) properties and perform I/O operations on a tag. This class inherits from **[TagSession](js-apis-tagSession.md)**. **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **NfcATag**. +The following describes the unique APIs of **NfcATag**. ### NfcATag.getSak @@ -40,8 +41,7 @@ Obtains the SAK value of this NFC-A tag. ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcA' correctly. - +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcA' correctly. let sak = nfcA.getSak(); console.log("nfcA sak: " + sak); ``` @@ -67,18 +67,18 @@ Obtains the ATQA value of this NFC-A tag. ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcA' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcA' correctly. let atqa = nfcA.getAtqa(); console.log("nfcA atqa: " + atqa); ``` ## NfcBTag -Provides access to NFC-B (ISO 14443-3B) properties and I/O operations. This class inherits from **TagSession**. +Provides APIs to access NFC-B (ISO 14443-3B) properties and perform I/O operations on a tag. This class inherits from **TagSession**. **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **NfcBTag**. +The following describes the unique APIs of **NfcBTag**. ### NfcBTag.getRespAppData @@ -94,14 +94,14 @@ Obtains the application data of this NFC-B tag. | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | Application data obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number[] | Application data obtained, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcB' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcB' correctly. let respAppData = nfcB.getRespAppData(); console.log("nfcB respAppData: " + respAppData); ``` @@ -120,25 +120,25 @@ Obtains the protocol information of this NFC-B tag. | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | Protocol information obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number[] | Protocol information obtained, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcB' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcB' correctly. let respProtocol = nfcB.getRespProtocol(); console.log("nfcB respProtocol: " + respProtocol); ``` ## NfcFTag -Provides access to NFC-F (JIS 6319-4) properties and I/O operations. This class inherits from **TagSession**. +Provides APIs to access NFC-F (JIS 6319-4) properties and perform I/O operations on a tag. This class inherits from **TagSession**. **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **NfcFTag**. +The following describes the unique APIs of **NfcFTag**. ### NfcFTag.getSystemCode @@ -154,14 +154,14 @@ Obtains the system code from this NFC-F tag. | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | System code obtained. Each number in the system code is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number[] | System code obtained, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcF' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcF' correctly. let systemCode = nfcF.getSystemCode(); console.log("nfcF systemCode: " + systemCode); ``` @@ -174,31 +174,31 @@ Obtains the PMm (consisting of the IC code and manufacturer parameters) informat **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | PMm information obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number[] | PMm information obtained, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcF' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcF' correctly. let pmm = nfcF.getPmm(); console.log("nfcF pmm: " + pmm); ``` ## NfcVTag -Provides access to NFC-V (ISO 15693) properties and I/O operations. This class inherits from **TagSession**. +Provides APIs to access NFC-V (ISO 15693) properties and perform I/O operations on a tag. This class inherits from **TagSession**. **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **NfcVTag**. +The following describes the unique APIs of **NfcVTag**. ### NfcvTag.getResponseFlags @@ -208,20 +208,20 @@ Obtains the response flags from this NFC-V tag. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| number | Response flags obtained. The value is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number | Response flags obtained, which consist of hexadecimal numbers ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcV' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcV' correctly. let responseFlags = nfcV.getResponseFlags(); console.log("nfcV responseFlags: " + responseFlags); ``` @@ -234,54 +234,52 @@ Obtains the data storage format identifier (DSFID) from this NFC-V tag. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| number | DSFID obtained. The value is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number | DSFID obtained, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcV' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcV' correctly. let dsfId = nfcV.getDsfId(); console.log("nfcV dsfId: " + dsfId); ``` ## IsoDepTag9+ -Provides access to ISO-DEP (ISO 14443-4) properties and I/O operations. This class inherits from **TagSession**. +Provides APIs to access ISO-DEP (ISO 14443-4) properties and I/O operations on a tag. This class inherits from **TagSession**. **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **IsoDepTag**. +The following describes the unique APIs of **IsoDepTag**. ### IsoDepTag.getHistoricalBytes9+ getHistoricalBytes(): number[] -Obtains the historical bytes of this tag. - -**Required permissions**: ohos.permission.NFC_TAG +Obtains the historical bytes for the given tag. This API applies only to the IsoDep cards that use the NFC-A technology. -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | Historical bytes obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number[] | Historical bytes obtained, which consist of hexadecimal numbers ranging from **0x00** to **0xFF**. If the IsoDep tag uses the NFC-B technology, **null** will be returned.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'isoDep' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'isoDep' correctly. let historicalBytes = isoDep.getHistoricalBytes(); console.log("isoDep historicalBytes: " + historicalBytes); ``` @@ -290,24 +288,22 @@ console.log("isoDep historicalBytes: " + historicalBytes); getHiLayerResponse(): number[] -Obtains the HiLayer response of this tag. - -**Required permissions**: ohos.permission.NFC_TAG +Obtains the higher-layer response bytes for the given tag. This API applies only to the IsoDep cards that use the NFC-B technology. -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | HiLayer response obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number[] | Higher-layer response bytes obtained, which consist of hexadecimal numbers ranging from **0x00** to **0xFF**. If the IsoDep tag uses the NFC-A technology, **null** will be returned.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'isoDep' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'isoDep' correctly. let hiLayerResponse = isoDep.getHiLayerResponse(); console.log("isoDep hiLayerResponse: " + hiLayerResponse); ``` @@ -320,7 +316,7 @@ Checks whether an extended application protocol data unit (APDU) is supported. T **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** @@ -328,18 +324,39 @@ Checks whether an extended application protocol data unit (APDU) is supported. T | ------------------ | --------------------------| | Promise<boolean> | Promise used to return the result. If the extended APDU is supported, **true** is returned; otherwise, **false** is returned.| +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'isoDep' correctly. -isoDep.isExtendedApduSupported() - .then((data) => { - console.log("isoDep isExtendedApduSupported data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'isoDep' correctly. + +// Connect to the tag if it is not connected. +if (!isoDep.isTagConnected()) { + if (!isoDep.connectTag()) { + console.log("isoDep connectTag failed."); + return; + } +} + +try { + isoDep.isExtendedApduSupported().then((response) => { + console.log("isoDep isExtendedApduSupported Promise response: " + response); }).catch((err)=> { - console.log("isoDep isExtendedApduSupported err: " + err); + console.log("isoDep isExtendedApduSupported Promise err: " + err); }); +} catch (busiError) { + console.log("isoDep isExtendedApduSupported Promise busiError: " + busiError); +} + ``` ### IsoDepTag.isExtendedApduSupported9+ @@ -350,7 +367,7 @@ Checks whether an extended APDU is supported. This API uses an asynchronous call **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** @@ -358,251 +375,159 @@ Checks whether an extended APDU is supported. This API uses an asynchronous call | -------- | ----------------------- | ---- | -------------------------------------- | | callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the extended APDU is supported, **true** is returned; otherwise, **false** is returned.| -```js -import tag from '@ohos.nfc.tag'; - -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'isoDep' correctly. -isoDep.isExtendedApduSupported((err, data)=> { - if (err) { - console.log("isoDep isExtendedApduSupported err: " + err); - } else { - console.log("isoDep isExtendedApduSupported data: " + data); - } -}); -``` - -## NdefTag9+ - -Provides access to the tags in the NFC Data Exchange Format (NDEF). This class inherits from **TagSession**. - -**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). - -The following describes the unique interfaces of **NdefTag**. - -### NdefTag.createNdefMessage9+ - -createNdefMessage(data: number[]): [NdefMessage](#ndefmessage9) +**Error codes** -Creates an NDEF message using raw bytes. +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC - -**Parameters** - -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| data | number[] | Yes| Raw bytes used to create the message. Each number is a hexadecimal number ranging from **0x00** to **0xFF**.| - -**Return value** - -| **Type**| **Description** | -| ------------------ | --------------------------| -| [NdefMessage](#ndefmessage9) | NDEF message created. For details, see *NFCForum-TS-NDEF_1.0*.| +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let rawData = [0x00, 0xa4, 0x04, ......]; // change the raw data bytes tobe correct. -let ndefMessage = ndef.createNdefMessage(rawData); -console.log("ndef ndefMessage: " + ndefMessage); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'isoDep' correctly. + +// Connect to the tag if it is not connected. +if (!isoDep.isTagConnected()) { + if (!isoDep.connectTag()) { + console.log("isoDep connectTag failed."); + return; + } +} + +try { + isoDep.isExtendedApduSupported((err, response)=> { + if (err) { + console.log("isoDep isExtendedApduSupported AsyncCallback err: " + err); + } else { + console.log("isoDep isExtendedApduSupported AsyncCallback response: " + response); + } + }); +} catch (busiError) { + console.log("isoDep isExtendedApduSupported AsyncCallback busiError: " + busiError); +} ``` ## NdefMessage9+ ### NdefMessage.getNdefRecords9+ -getNdefRecords(): [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[ ] +getNdefRecords(): [tag.NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] Obtains all NDEF records. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[ ] | List of NDEF records obtained. For details, see *NFCForum-TS-NDEF_1.0*.| +| [tag.NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] | List of NDEF records obtained. For details, see *NFCForum-TS-NDEF_1.0*.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let ndefRecords = ndef.getNdefRecords(); +// Obtain ndefMessage from tag.ndef.createNdefMessage or ndefTag.getNdefMessage. +// var ndefMessage = tag.ndef.createNdefMessage(...); +// var ndefMessage = ndefTag.getNdefMessage(); + +let ndefRecords = ndefMessage.getNdefRecords(); console.log("ndef ndefRecords number: " + ndefRecords.length); ``` -### NdefTag.createNdefMessage9+ - -createNdefMessage(ndefRecords: NdefRecord[]): [NdefMessage](#ndefmessage9) - -Creates an NDEF message using the NDEF records. - -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC - -**Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| ndefRecords | [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] | Yes| NDEF records used to create the NDEF message. For details, see *NFCForum-TS-NDEF_1.0*.| - -**Return value** - -| **Type**| **Description** | -| ------------------ | --------------------------| -| [NdefMessage](#ndefmessage9) | NDEF message created. For details, see *NFCForum-TS-NDEF_1.0*.| - -**Example** +## NdefTag9+ -```js -import tag from '@ohos.nfc.tag'; +Provides APIs to access the tags in the NFC Data Exchange Format (NDEF). This class inherits from **TagSession**. -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let ndefRecords = [ - // record format: tnf, rtdType, id, payload - // 1st record: - {tnf: 0x01, rtdType: [0x54], id: [0x01, 0x02, ...], payload: [0x00, 0xa4, 0x04, ...]}, +**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). - // 2nd record: - {tnf: 0x02, rtdType: [0x55], id: [0x03, 0x04, ...], payload: [0x00, 0xa4, 0x04, ...]}, - - // other record if has one ... -]; -let ndefMessage = ndef.createNdefMessage(ndefRecords); -console.log("ndef ndefMessage: " + ndefMessage); -``` +The following describes the unique APIs of **NdefTag**. ### NdefTag.getNdefTagType9+ -getNdefTagType(): NfcForumType +getNdefTagType(): [tag.NfcForumType](js-apis-nfcTag.md#nfcforumtype9) -Obtains the type of this NDEF tag. +Obtains the NDEF tag type. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| [NfcForumType](js-apis-nfcTag.md#nfcforumtype9) | NDEF tag type obtained. It can be NFC FORUM TYPE 1, 2, 3, or 4.| +| [tag.NfcForumType](js-apis-nfcTag.md#nfcforumtype9) | NDEF tag type obtained. It can be NFC FORUM TYPE 1, 2, 3, or 4.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let ndefTagType = ndef.getNdefTagType(); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. +let ndefTagType = ndefTag.getNdefTagType(); console.log("ndef ndefTagType: " + ndefTagType); ``` ### NdefTag.getNdefMessage9+ -getNdefMessage(): NdefMessage +getNdefMessage(): [NdefMessage](#ndefmessage9) -Obtains the NDEF message. +Obtains the NDEF message from this NDEF tag. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| [NdefMessage](#ndefmessage9) | NDEF message obtained. For details, see *NFCForum-TS-NDEF_1.0*.| +| [NdefMessage](#ndefmessage9) | NDEF message created. For details, see *NFCForum-TS-NDEF_1.0*.| **Example** - ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let ndefMessage = ndef.getNdefMessage(); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. +let ndefMessage = ndefTag.getNdefMessage(); console.log("ndef ndefMessage: " + ndefMessage); ``` ### NdefTag.isNdefWritable9+ -isNdefWritable(): Promise<boolean> - -Checks whether the NDEF tag is writable. This API uses a promise to return the result. +isNdefWritable(): boolean; -**Required permissions**: ohos.permission.NFC_TAG +Check whether this NDEF tag is writable. Before calling the data write API, check whether the write operation is supported. -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| Promise<boolean> | Promise used to return the result. If the tag is writable, **true** is returned; otherwise, **false** is returned.| - -**Example** - -```js -import tag from '@ohos.nfc.tag'; - -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -ndef.isNdefWritable() - .then((data) => { - console.log("ndef isNdefWritable data: " + data); - }).catch((err)=> { - console.log("ndef isNdefWritable err: " + err); - }); -``` - -### NdefTag.isNdefWritable9+ - -isNdefWritable(callback: AsyncCallback<boolean>): void; - -Checks whether the NDEF tag is writable. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the tag is writable, **true** is returned; otherwise, **false** is returned.| +| boolean | Promise used to return the result. If the tag is writable, **true** is returned; otherwise, **false** is returned.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -ndef.isNdefWritable((err, data)=> { - if (err) { - console.log("ndef isNdefWritable err: " + err); - } else { - console.log("ndef isNdefWritable data: " + data); - } -}); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. +var isWritable = ndefTag.isNdefWritable(); +console.log("ndef isNdefWritable: " + isWritable); ``` ### NdefTag.readNdef9+ -readNdef(): Promise\ +readNdef(): Promise\<[NdefMessage](#ndefmessage9)> Reads the NDEF message from this tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** @@ -610,18 +535,38 @@ Reads the NDEF message from this tag. This API uses a promise to return the resu | ------------------ | --------------------------| | Promise\<[NdefMessage](#ndefmessage9)> | Promise used to return the message read.| +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -ndef.readNdef() - .then((data) => { - console.log("ndef readNdef data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. + +// Connect to the tag if it is not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; + } +} + +try { + ndefTag.readNdef().then((ndefmessage) => { + console.log("ndef readNdef Promise ndefmessage: " + ndefmessage); }).catch((err)=> { - console.log("ndef readNdef err: " + err); + console.log("ndef readNdef Promise err: " + err); }); +} catch (busiError) { + console.log("ndef readNdef Promise catched busiError: " + busiError); +} ``` ### NdefTag.readNdef9+ @@ -632,38 +577,59 @@ Reads the NDEF message from this tag. This API uses an asynchronous callback to **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback\<[NdefMessage](#ndefmessage9)> | Yes | Callback invoked to return the result.| +| callback | AsyncCallback\<[NdefMessage](#ndefmessage9)> | Yes | Callback invoked to return the NDEF message read.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -ndef.readNdef((err, data)=> { - if (err) { - console.log("ndef readNdef err: " + err); - } else { - console.log("ndef readNdef data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. + +// Connect to the tag if it is not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; } -}); +} + +try { + ndefTag.readNdef((err, ndefmessage)=> { + if (err) { + console.log("ndef readNdef AsyncCallback err: " + err); + } else { + console.log("ndef readNdef AsyncCallback ndefmessage: " + ndefmessage); + } + }); +} catch (busiError) { + console.log("ndef readNdef AsyncCallback catched busiError: " + busiError); +} ``` ### NdefTag.writeNdef9+ -writeNdef(msg: NdefMessage): Promise\; +writeNdef(msg: NdefMessage): Promise\; Writes an NDEF message to this tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** @@ -671,59 +637,97 @@ Writes an NDEF message to this tag. This API uses a promise to return the result | -------- | ----------------------- | ---- | -------------------------------------- | | msg | NdefMessage | Yes | NDEF message to write.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let ndefMessage = ndef.createNdefMessage([0x01, 0x02, ...]); // change the raw data to be correct. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. +// NDEF message created from raw data, such as: +let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // It must be parsed as NDEF Record. +// or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[]) -ndef.writeNdef(ndefMessage) - .then((data) => { - console.log("ndef writeNdef data: " + data); +// Connect to the tag if it is not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; + } +} + +try { + ndefTag.writeNdef(ndefMessage).then(() => { + console.log("ndef writeNdef Promise success."); }).catch((err)=> { console.log("ndef writeNdef err: " + err); }); +} catch (busiError) { + console.log("ndef writeNdef Promise catch busiError: " + busiError); +} ``` ### NdefTag.writeNdef9+ -writeNdef(msg: NdefMessage, callback: AsyncCallback\): void +writeNdef(msg: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void Writes an NDEF message to this tag. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| msg | NdefMessage | Yes | NDEF message to write.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| msg | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let ndefMessage = ndef.createNdefMessage([0x01, 0x02, ...]); // change the raw data to be correct. -ndef.writeNdef(ndefMessage, (err, data)=> { - if (err) { - console.log("ndef writeNdef err: " + err); - } else { - console.log("ndef writeNdef data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. +// NDEF message created from raw data, such as: +let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // It must be parsed as NDEF Record. +// or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[]) + +// Connect to the tag if it is not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; } -}); +} + +try { + ndefTag.writeNdef(ndefMessage, (err)=> { + if (err) { + console.log("ndef writeNdef AsyncCallback err: " + err); + } else { + console.log("ndef writeNdef AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("ndef writeNdef AsyncCallback catch busiError: " + busiError); +} ``` ### NdefTag.canSetReadOnly9+ @@ -734,7 +738,7 @@ Checks whether this NDEF tag can be set to read-only. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** @@ -742,92 +746,133 @@ Checks whether this NDEF tag can be set to read-only. | ------------------ | --------------------------| | boolean| Returns **true** if the tag can be set to read-only; returns **false** otherwise.| +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -var canSetReadOnly = ndef.canSetReadOnly(); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. +var canSetReadOnly = ndefTag.canSetReadOnly(); console.log("ndef canSetReadOnly: " + canSetReadOnly); ``` ### NdefTag.setReadOnly9+ -setReadOnly(): Promise\ +setReadOnly(): Promise\ Sets this NDEF tag to read-only. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise<number> | Promise used to return the result. If the operation is successful, **0** is returned; otherwise, an error code is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -ndef.setReadOnly() - .then((data) => { - console.log("ndef setReadOnly data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. + +// Connect to the tag if it is not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; + } +} + +try { + ndefTag.setReadOnly().then(() => { + console.log("ndef setReadOnly Promise success."); }).catch((err)=> { - console.log("ndef setReadOnly err: " + err); + console.log("ndef setReadOnly Promise err: " + err); }); +} catch (busiError) { + console.log("ndef setReadOnly Promise catch busiError: " + busiError); +} ``` ### NdefTag.setReadOnly9+ -setReadOnly(callback: AsyncCallback\): void +setReadOnly(callback: AsyncCallback\): void Sets this NDEF tag to read-only. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -ndef.setReadOnly((err, data)=> { - if (err) { - console.log("ndef setReadOnly err: " + err); - } else { - console.log("ndef setReadOnly data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. + +// Connect to the tag if it is not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; } -}); +} + +try { + ndefTag.setReadOnly((err)=> { + if (err) { + console.log("ndef setReadOnly AsyncCallback err: " + err); + } else { + console.log("ndef setReadOnly AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("ndef setReadOnly AsyncCallback catch busiError: " + busiError); +} ``` ### NdefTag.getNdefTagTypeString9+ -getNdefTagTypeString(type: [NfcForumType](js-apis-nfcTag.md#nfcforumtype9)): string - -Converts an NFC Forum Type tag to a byte array defined in the NFC Forum. +getNdefTagTypeString(type: [tag.NfcForumType](js-apis-nfcTag.md#nfcforumtype9)): string -**Required permissions**: ohos.permission.NFC_TAG +Converts an NFC Forum Type tag to a string defined in the NFC Forum. -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| type | [NfcForumType](js-apis-nfcTag.md#nfcforumtype9) | Yes | NDEF tag type. It can be NFC FORUM type 1, 2, 3, or 4.| +| type | [tag.NfcForumType](js-apis-nfcTag.md#nfcforumtype9) | Yes | NDEF tag type. It can be NFC FORUM type 1, 2, 3, or 4.| **Return value** @@ -840,110 +885,149 @@ Converts an NFC Forum Type tag to a byte array defined in the NFC Forum. ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let ndefTypeString = ndef.getNdefTagTypeString(tag.NFC_FORUM_TYPE_1); -console.log("ndef ndefTypeString: " + ndefTypeString); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. + +try { + let ndefTypeString = ndefTag.getNdefTagTypeString(tag.NFC_FORUM_TYPE_1); + console.log("ndef ndefTypeString: " + ndefTypeString); +} catch (busiError) { + console.log("ndef getNdefTagTypeString catch busiError: " + busiError); +} ``` ## MifareClassicTag9+ -Provides access to MIFARE Classic properties and I/O operations. This class inherits from **TagSession**. +Provides APIs to access MIFARE Classic properties and perform I/O operations on a tag. This class inherits from [TagSession](js-apis-tagSession.md). **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **MifareClassicTag**. +The following describes the unique APIs of **MifareClassicTag**. ### MifareClassicTag.authenticateSector9+ -authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean): Promise\ +authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean): Promise\ -Authenticates a sector using the key. The sector can be accessed only after the authentication is successful. This API uses a promise to return the result. +Authenticates a sector using a key. The sector can be accessed only after the authentication is successful. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| sectorIndex | number | Yes | Index of the sector to authenticate.| -| key | number[]| Yes | Key (6 bytes) used for authentication.| +| sectorIndex | number | Yes | Index of the sector to authenticate. The sector indexes start from **0**.| +| key | number[]| Yes | Key (6 bytes) used for sector authentication.| | isKeyA | boolean | Yes | Whether the key is key A. The value **true** indicates key A, and **false** indicates key B.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If the authentication is successful, **true** is returned. Otherwise, **false** is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let sectorIndex = 1; // change it to be correct index. -let key = [0x04, 0x05, ....]; // change it to be correct key. -mifareClassic.authenticateSector(sectorIndex, key, true); - .then((data) => { - console.log("mifareClassic authenticateSector data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; + } +} + +try { + let sectorIndex = 1; // Change it as required. + let key = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06] // The key must be of 6 bytes. + mifareClassic.authenticateSector(sectorIndex, key, true).then(() => { + console.log("mifareClassic authenticateSector Promise success."); }).catch((err)=> { - console.log("mifareClassic authenticateSector err: " + err); + console.log("mifareClassic authenticateSector Promise err: " + err); }); +} catch (busiError) { + console.log("mifareClassic authenticateSector Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.authenticateSector9+ -authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean, callback: AsyncCallback\): void +authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean, callback: AsyncCallback\): void -Authenticates a sector using the key. The sector can be accessed only after the authentication is successful. This API uses an asynchronous callback to return the result. +Authenticates a sector using a key. The sector can be accessed only after the authentication is successful. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| sectorIndex | number | Yes | Index of the sector to authenticate.| -| key | number[]| Yes | Key (6 bytes) used for authentication.| +| sectorIndex | number | Yes | Index of the sector to authenticate. The sector indexes start from **0**.| +| key | number[]| Yes | Key (6 bytes) used for sector authentication.| | isKeyA | boolean | Yes | Whether the key is key A. The value **true** indicates key A, and **false** indicates key B.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| -**Example** +**Error codes** +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + +**Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let sectorIndex = 1; // change it to be correct index. -let key = [0x04, 0x05, ....]; // change it to be correct key. -mifareClassic.authenticateSector(sectorIndex, key, true, (err, data)=> { - if (err) { - console.log("mifareClassic authenticateSector err: " + err); - } else { - console.log("mifareClassic authenticateSector data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let sectorIndex = 1; // Change it as required. + let key = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06] // The key must be of 6 bytes. + mifareClassic.authenticateSector(sectorIndex, key, true, (err)=> { + if (err) { + console.log("mifareClassic authenticateSector AsyncCallback err: " + err); + } else { + console.log("mifareClassic authenticateSector AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic authenticateSector AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.readSingleBlock9+ readSingleBlock(blockIndex: number): Promise\ -Reads a block (16 bytes) on the tag. This API uses a promise to return the result. +Reads a block (16 bytes) on this tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the block to read.| +| blockIndex | number | Yes | Index of the block to read. The block indexes start from **0**.| **Return value** @@ -951,421 +1035,632 @@ Reads a block (16 bytes) on the tag. This API uses a promise to return the resul | ------------------ | --------------------------| | Promise\ | Promise used to return the block data read.| +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -mifareClassic.readSingleBlock(blockIndex, (err, data)=> { - if (err) { - console.log("mifareClassic readSingleBlock err: " + err); - } else { - console.log("mifareClassic readSingleBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + mifareClassic.readSingleBlock(blockIndex).then((data) => { + console.log("mifareClassic readSingleBlock Promise data: " + data); + }).catch((err)=> { + console.log("mifareClassic readSingleBlock Promise err: " + err); + }); +} catch (busiError) { + console.log("mifareClassic readSingleBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.readSingleBlock9+ readSingleBlock(blockIndex: number, callback: AsyncCallback\): void -Reads a block (16 bytes) on the tag. This API uses an asynchronous callback to return the result. +Reads a block (16 bytes) on this tag. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the block to read.| +| blockIndex | number | Yes | Index of the block to read. The block indexes start from **0**.| | callback | AsyncCallback\ | Yes | Callback invoked to return the block read.| +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -mifareClassic.readSingleBlock(blockIndex, (err, data)=> { - if (err) { - console.log("mifareClassic readSingleBlock err: " + err); - } else { - console.log("mifareClassic readSingleBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + mifareClassic.readSingleBlock(blockIndex, (err, data)=> { + if (err) { + console.log("mifareClassic readSingleBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic readSingleBlock AsyncCallback data: " + data); + } + }); +} catch (busiError) { + console.log("mifareClassic readSingleBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.writeSingleBlock9+ -writeSingleBlock(blockIndex: number, data: number[]): Promise\ +writeSingleBlock(blockIndex: number, data: number[]): Promise\ -Writes data to a block on the tag. This API uses a promise to return the result. +Writes data to a block on this tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the target block.| -| data | number[] | Yes | Data to write.| +| blockIndex | number | Yes | Index of the target block. The block indexes start from **0**.| +| data | number[] | Yes | 16-byte data to write.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let rawData = [0x0a, 0x14, ...]; // change it to be correct data. -mifareClassic.writeSingleBlock(blockIndex, rawData, (err, data)=> { - if (err) { - console.log("mifareClassic writeSingleBlock err: " + err); - } else { - console.log("mifareClassic writeSingleBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + let rawData = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, + 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10]; // MUST be 16 bytes, change it to be correct data. + mifareClassic.writeSingleBlock(blockIndex, rawData).then(() => { + console.log("mifareClassic writeSingleBlock Promise success."); + }).catch((err)=> { + console.log("mifareClassic writeSingleBlock Promise err: " + err); + }); +} catch (busiError) { + console.log("mifareClassic writeSingleBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.writeSingleBlock9+ -writeSingleBlock(blockIndex: number, data: number[], callback: AsyncCallback\): void +writeSingleBlock(blockIndex: number, data: number[], callback: AsyncCallback\): void -Writes data to a block on the tag. This API uses an asynchronous callback to return the result. +Writes data to a block on this tag. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the target block.| -| data | number[] | Yes | Data to write.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| blockIndex | number | Yes | Index of the target block. The block indexes start from **0**.| +| data | number[] | Yes | 16-byte data to write.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let rawData = [0x0a, 0x14, ...]; // change it to be correct data. -mifareClassic.writeSingleBlock(blockIndex, rawData, (err, data)=> { - if (err) { - console.log("mifareClassic writeSingleBlock err: " + err); - } else { - console.log("mifareClassic writeSingleBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + let rawData = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, + 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10]; // MUST be 16 bytes, change it to be correct data. + mifareClassic.writeSingleBlock(blockIndex, rawData, (err)=> { + if (err) { + console.log("mifareClassic writeSingleBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic writeSingleBlock AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic writeSingleBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.incrementBlock9+ -incrementBlock(blockIndex: number, value: number): Promise\ +incrementBlock(blockIndex: number, value: number): Promise\ Increments a block with data. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the block to increment.| -| value | number | Yes | Block data to increment. The value is a non-negative number.| +| blockIndex | number | Yes | Index of the block to increment. The block indexes start from **0**.| +| value | number | Yes | Block data to increment. The value cannot be a negative number.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let value = 0x20; // change it to be correct data. -mifareClassic.incrementBlock(blockIndex, value, (err, data)=> { - if (err) { - console.log("mifareClassic incrementBlock err: " + err); - } else { - console.log("mifareClassic incrementBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + let value = 0x20; // Change it as required. + mifareClassic.incrementBlock(blockIndex, value).then(() => { + console.log("mifareClassic incrementBlock Promise success."); + }).catch((err)=> { + console.log("mifareClassic incrementBlock Promise err: " + err); + }); +} catch (busiError) { + console.log("mifareClassic incrementBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.incrementBlock9+ -incrementBlock(blockIndex: number, value: number, callback: AsyncCallback\): void +incrementBlock(blockIndex: number, value: number, callback: AsyncCallback\): void Increments a block with data. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the block to increment.| -| value | number | Yes | Block data to increment. The value is a non-negative number.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| blockIndex | number | Yes | Index of the block to increment. The block indexes start from **0**.| +| value | number | Yes | Block data to increment. The value cannot be a negative number.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let value = 0x20; // change it to be correct data. -mifareClassic.incrementBlock(blockIndex, value, (err, data)=> { - if (err) { - console.log("mifareClassic incrementBlock err: " + err); - } else { - console.log("mifareClassic incrementBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + let value = 0x20; // Change it as required. + mifareClassic.incrementBlock(blockIndex, value, (err)=> { + if (err) { + console.log("mifareClassic incrementBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic incrementBlock AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic incrementBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.decrementBlock9+ -decrementBlock(blockIndex: number, value: number): Promise\ +decrementBlock(blockIndex: number, value: number): Promise\ -Decrements a block with data. This API uses a promise to return the result. +Decrements a block. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the block to decrement.| -| value | number | Yes | Block data to decrement. The value is a non-negative number.| +| blockIndex | number | Yes | Index of the block to decrement. The block indexes start from **0**.| +| value | number | Yes | Block data to decrement. The value cannot be a negative number.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let value = 0x20; // change it to be correct data. -mifareClassic.decrementBlock(blockIndex, value, (err, data)=> { - if (err) { - console.log("mifareClassic decrementBlock err: " + err); - } else { - console.log("mifareClassic decrementBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + let value = 0x20; // Change it as required. + mifareClassic.decrementBlock(blockIndex, value).then(() => { + console.log("mifareClassic decrementBlock Promise success."); + }).catch((err)=> { + console.log("mifareClassic decrementBlock Promise err: " + err); + }); +} catch (busiError) { + console.log("mifareClassic decrementBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.decrementBlock9+ -decrementBlock(blockIndex: number, value: number, callback: AsyncCallback\): void +decrementBlock(blockIndex: number, value: number, callback: AsyncCallback\): void -Decrements a block with data. This API uses an asynchronous callback to return the result. +Decrements a block. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the block to decrement.| -| value | number | Yes | Block data to decrement. The value is a non-negative number.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| blockIndex | number | Yes | Index of the block to decrement. The block indexes start from **0**.| +| value | number | Yes | Block data to decrement. The value cannot be a negative number.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let value = 0x20; // change it to be correct data. -mifareClassic.decrementBlock(blockIndex, value, (err, data)=> { - if (err) { - console.log("mifareClassic decrementBlock err: " + err); - } else { - console.log("mifareClassic decrementBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + let value = 0x20; // Change it as required. + mifareClassic.decrementBlock(blockIndex, value, (err)=> { + if (err) { + console.log("mifareClassic decrementBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic decrementBlock AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic decrementBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.transferToBlock9+ -transferToBlock(blockIndex: number): Promise\ +transferToBlock(blockIndex: number): Promise\ -Copies data from the register to a block. This API uses a promise to return the result. +Transfers data from the temporary register to a block. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the destination block.| +| blockIndex | number | Yes | Index of the destination block. The value starts form **0**.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js - import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -mifareClassic.transferToBlock(blockIndex, (err, data)=> { - if (err) { - console.log("mifareClassic transferToBlock err: " + err); - } else { - console.log("mifareClassic transferToBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + mifareClassic.transferToBlock(blockIndex).then(() => { + console.log("mifareClassic transferToBlock Promise success."); + }).catch((err)=> { + console.log("mifareClassic transferToBlock Promise err: " + err); + }); +} catch (busiError) { + console.log("mifareClassic transferToBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.transferToBlock9+ -transferToBlock(blockIndex: number, callback: AsyncCallback\): void +transferToBlock(blockIndex: number, callback: AsyncCallback\): void -Copies data from the register to a block. This API uses an asynchronous callback to return the result. +Transfers data from the temporary register to a block. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the destination block.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| blockIndex | number | Yes | Index of the destination block. The value starts form **0**.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -mifareClassic.transferToBlock(blockIndex, (err, data)=> { - if (err) { - console.log("mifareClassic transferToBlock err: " + err); - } else { - console.log("mifareClassic transferToBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + mifareClassic.transferToBlock(blockIndex, (err)=> { + if (err) { + console.log("mifareClassic transferToBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic transferToBlock AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic transferToBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.restoreFromBlock9+ -restoreFromBlock(blockIndex: number): Promise\ +restoreFromBlock(blockIndex: number): Promise\ -Copies data from a block to the register. This API uses a promise to return the result. +Restores data in the temporary register from a block. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the source block.| +| blockIndex | number | Yes | Index of the target block. The value starts form **0**.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js - import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -mifareClassic.restoreFromBlock(blockIndex) - .then((data) => { - console.log("mifareClassic restoreFromBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; + } +} + +try { + let blockIndex = 1; // Change it as required. + mifareClassic.restoreFromBlock(blockIndex).then(() => { + console.log("mifareClassic restoreFromBlock Promise success."); }).catch((err)=> { - console.log("mifareClassic isExtendrestoreFromBlockedApduSupported err: " + err); + console.log("mifareClassic restoreFromBlock Promise err: " + err); }); +} catch (busiError) { + console.log("mifareClassic restoreFromBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.restoreFromBlock9+ -restoreFromBlock(blockIndex: number, callback: AsyncCallback\): void +restoreFromBlock(blockIndex: number, callback: AsyncCallback\): void -Copies data from a block to the register. This API uses an asynchronous callback to return the result. +Restores data in the temporary register from a block. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the source block.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| blockIndex | number | Yes | Index of the target block. The value starts form **0**.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -mifareClassic.restoreFromBlock(blockIndex, (err, data)=> { - if (err) { - console.log("mifareClassic restoreFromBlock err: " + err); - } else { - console.log("mifareClassic restoreFromBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + mifareClassic.restoreFromBlock(blockIndex, (err)=> { + if (err) { + console.log("mifareClassic restoreFromBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic restoreFromBlock AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic restoreFromBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.getSectorCount9+ @@ -1374,9 +1669,7 @@ getSectorCount(): number Obtains the number of sectors in this MIFARE Classic tag. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** @@ -1389,7 +1682,7 @@ Obtains the number of sectors in this MIFARE Classic tag. ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. let sectorCount = mifareClassic.getSectorCount(); console.log("mifareClassic sectorCount: " + sectorCount); ``` @@ -1400,15 +1693,13 @@ getBlockCountInSector(sectorIndex: number): number Obtains the number of blocks in a sector. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| sectorIndex | number | Yes | Index of the sector.| +| sectorIndex | number | Yes | Index of the target sector. The sector indexes start from **0**.| **Return value** @@ -1421,33 +1712,37 @@ Obtains the number of blocks in a sector. ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockCountInSector = mifareClassic.getBlockCountInSector(); -console.log("mifareClassic blockCountInSector: " + blockCountInSector); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +try { + let sectorIndex = 1; // Change it as required. + let blockCnt = mifareClassic.getBlockCountInSector(sectorIndex); + console.log("mifareClassic blockCnt: " + blockCnt); +} catch (busiError) { + console.log("mifareClassic getBlockCountInSector catch busiError: " + busiError); +} ``` ### MifareClassicTag.getType9+ -getType(): [MifareClassicType](js-apis-nfcTag.md#mifareclassictype9) +getType(): [tag.MifareClassicType](js-apis-nfcTag.md#mifareclassictype9) Obtains the type of this MIFARE Classic tag. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| [MifareClassicType](js-apis-nfcTag.md#mifareclassictype9) | Type of the MIFARE Classic tag obtained.| +| [tag.MifareClassicType](js-apis-nfcTag.md#mifareclassictype9) | Type of the MIFARE Classic tag obtained.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. let getType = mifareClassic.getType(); console.log("mifareClassic getType: " + getType); ``` @@ -1456,11 +1751,9 @@ console.log("mifareClassic getType: " + getType); getTagSize(): number -Obtains the tag size (in bytes). For details, see [MifareClassicSize](js-apis-nfcTag.md#mifareclassicsize9). - -**Required permissions**: ohos.permission.NFC_TAG +Obtains the size of this tag. For details, see [MifareClassicSize](js-apis-nfcTag.md#mifareclassicsize9). -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** @@ -1473,7 +1766,7 @@ Obtains the tag size (in bytes). For details, see [MifareClassicSize](js-apis-nf ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. let tagSize = mifareClassic.getTagSize(); console.log("mifareClassic tagSize: " + tagSize); ``` @@ -1482,11 +1775,9 @@ console.log("mifareClassic tagSize: " + tagSize); isEmulatedTag(): boolean -Checks whether the tag is an emulated tag. +Checks whether it is an emulated tag. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** @@ -1499,7 +1790,7 @@ Checks whether the tag is an emulated tag. ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. let isEmulatedTag = mifareClassic.isEmulatedTag(); console.log("mifareClassic isEmulatedTag: " + isEmulatedTag); ``` @@ -1508,17 +1799,15 @@ console.log("mifareClassic isEmulatedTag: " + isEmulatedTag); getBlockIndex(sectorIndex: number): number -Obtains the first block of a sector. +Obtains the index of the first block in a sector. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| sectorIndex | number | Yes | Index of the sector.| +| sectorIndex | number | Yes | Index of the target sector. The sector indexes start from **0**.| **Return value** @@ -1531,27 +1820,30 @@ Obtains the first block of a sector. ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let sectorIndex = 1; // change it to be correct index. -let blockIndex = mifareClassic.getBlockIndex(sectorIndex); -console.log("mifareClassic blockIndex: " + blockIndex); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +try { + let sectorIndex = 1; // Change it as required. + let blockIndex = mifareClassic.getBlockIndex(sectorIndex); + console.log("mifareClassic blockIndex: " + blockIndex); +} catch (busiError) { + console.log("mifareClassic getBlockIndex catch busiError: " + busiError); +} ``` ### MifareClassicTag.getSectorIndex9+ getSectorIndex(blockIndex: number): number -Obtains the index of a sector that contains the specified block. - -**Required permissions**: ohos.permission.NFC_TAG +Obtains the index of a sector that holds the specified block. -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the block contained in the sector.| +| blockIndex | number | Yes| Index of the block. The block indexes start from **0**.| **Return value** @@ -1564,41 +1856,54 @@ Obtains the index of a sector that contains the specified block. ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let sectorIndex = mifareClassic.getSectorIndex(blockIndex); -console.log("mifareClassic sectorIndex: " + sectorIndex); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +try { + let blockIndex = 1; // Change it as required. + let sectorIndex = mifareClassic.getSectorIndex(blockIndex); + console.log("mifareClassic sectorIndex: " + sectorIndex); +} catch (busiError) { + console.log("mifareClassic getSectorIndex catch busiError: " + busiError); +} ``` ## MifareUltralightTag9+ -Provides access to MIFARE Ultralight properties and I/O operations. This class inherits from **TagSession**. +Provides APIs to access MIFARE Ultralight properties and perform I/O operations on a tag. This class inherits from **TagSession**. **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **MifareUltralightTag**. +The following describes the unique APIs of **MifareUltralightTag**. ### MifareUltralightTag.readMultiplePages9+ readMultiplePages(pageIndex: number): Promise\ -Reads multiple pages (4 bytes per page). This API uses a promise to return the result. +Reads four pages (4 bytes per page) from this tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | ------------------------------ | -| pageIndex | number | Yes | Indexes of the pages to read.| +| pageIndex | number | Yes | Index of the first page to read. The page indexes start from **0**.| **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| Promise\ | Promise used to return the data read.| +| Promise\ | Promise used to return the data read, which is 16 bytes in total.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** @@ -1606,207 +1911,286 @@ Reads multiple pages (4 bytes per page). This API uses a promise to return the r import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareUltralight' correctly. -let pageIndex = 1; // change it to be correct index. -mifareUltralight.readMultiplePages(pageIndex) - .then((data) => { - console.log("mifareUltralight readMultiplePages data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareUltralight' correctly. + +// Connect to the tag if it is not connected. +if (!mifareUltralight.isTagConnected()) { + if (!mifareUltralight.connectTag()) { + console.log("mifareUltralight connectTag failed."); + return; + } +} + +try { + let pageIndex = 1; // Change it as required. + mifareUltralight.readMultiplePages(pageIndex).then((data) => { + console.log("mifareUltralight readMultiplePages Promise data = " + data); }).catch((err)=> { - console.log("mifareUltralight readMultiplePages err: " + err); + console.log("mifareUltralight readMultiplePages Promise err: " + err); }); +} catch (busiError) { + console.log("mifareUltralight readMultiplePages Promise catch busiError: " + busiError); +} ``` ### MifareUltralightTag.readMultiplePages9+ readMultiplePages(pageIndex: number, callback: AsyncCallback\): void -Reads multiple pages (4 bytes per page). This API uses an asynchronous callback to return the result. +Reads four pages (4 bytes per page) from this tag. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| pageIndex | number | Yes | Indexes of the pages to read.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| pageIndex | number | Yes | Index of the first page to read. The page indexes start from **0**.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the data read, which is 16 bytes in total.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareUltralight' correctly. -let pageIndex = 1; // change it to be correct index. -mifareUltralight.readMultiplePages(pageIndex, (err, data)=> { - if (err) { - console.log("mifareUltralight readMultiplePages err: " + err); - } else { - console.log("mifareUltralight readMultiplePages data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareUltralight' correctly. + +// Connect to the tag if it is not connected. +if (!mifareUltralight.isTagConnected()) { + if (!mifareUltralight.connectTag()) { + console.log("mifareUltralight connectTag failed."); + return; } -}); +} + +try { + let pageIndex = 1; // Change it as required. + mifareUltralight.readMultiplePages(pageIndex, (err, data)=> { + if (err) { + console.log("mifareUltralight readMultiplePages AsyncCallback err: " + err); + } else { + console.log("mifareUltralight readMultiplePages AsyncCallback data: " + data); + } + }); +} catch (busiError) { + console.log("mifareUltralight readMultiplePages AsyncCallback catch busiError: " + busiError); +} ``` -### MifareUltralightTag.writeSinglePages9+ +### MifareUltralightTag.writeSinglePage9+ -writeSinglePages(pageIndex: number, data: number[]): Promise\ +writeSinglePage(pageIndex: number, data: number[]): Promise\ -Writes a page of data. This API uses a promise to return the result. +Writes one page (4 bytes) of data to this tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| pageIndex | number | Yes | Index of the page.| -| data | number[] | Yes | Data to write.| +| pageIndex | number | Yes | Index of the page to write. The page indexes start from **0**.| +| data | number[] | Yes | 4-byte data to write.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareUltralight' correctly. -let pageIndex = 1; // change it to be correct index. -let data = [0x01, 0x02, ...]; // change it to be correct raw data. -mifareUltralight.writeSinglePages(pageIndex, data) - .then((data) => { - console.log("mifareUltralight writeSinglePages data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareUltralight' correctly. + +// Connect to the tag if it is not connected. +if (!mifareUltralight.isTagConnected()) { + if (!mifareUltralight.connectTag()) { + console.log("mifareUltralight connectTag failed."); + return; + } +} + +try { + let pageIndex = 1; // Change it as required. + let rawData = [0x01, 0x02, 0x03, 0x04]; // MUST be 4 bytes, change it to be correct raw data. + mifareUltralight.writeSinglePage(pageIndex, rawData).then(() => { + console.log("mifareUltralight writeSinglePage Promise success."); }).catch((err)=> { - console.log("mifareUltralight writeSinglePages err: " + err); + console.log("mifareUltralight writeSinglePage Promise err: " + err); }); +} catch (busiError) { + console.log("mifareUltralight writeSinglePage Promise catch busiError: " + busiError); +} ``` -### MifareUltralightTag.writeSinglePages9+ +### MifareUltralightTag.writeSinglePage9+ -writeSinglePages(pageIndex: number, data: number[], callback: AsyncCallback\): void +writeSinglePage(pageIndex: number, data: number[], callback: AsyncCallback\): void -Writes a page of data. This API uses an asynchronous callback to return the result. +Writes one page (4 bytes) of data to this tag. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | ------------------------ | -| pageIndex | number | Yes | Index of the page.| -| data | number[] | Yes | Data to write.| -| callback|AsyncCallback\ |Yes| Callback invoked to return the result.| +| pageIndex | number | Yes | Index of the page to write. The page indexes start from **0**.| +| data | number[] | Yes | 4-byte data to write.| +| callback|AsyncCallback\ |Yes| Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareUltralight' correctly. -let pageIndex = 1; // change it to be correct index. -let data = [0x01, 0x02, ...]; // change it to be correct raw data. -mifareUltralight.writeSinglePages(pageIndex, data, (err, data)=> { - if (err) { - console.log("mifareUltralight writeSinglePages err: " + err); - } else { - console.log("mifareUltralight writeSinglePages data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareUltralight' correctly. + +// Connect to the tag if it is not connected. +if (!mifareUltralight.isTagConnected()) { + if (!mifareUltralight.connectTag()) { + console.log("mifareUltralight connectTag failed."); + return; } -}); +} + +try { + let pageIndex = 1; // Change it as required. + let rawData = [0x01, 0x02, 0x03, 0x04]; // MUST be 4 bytes, change it to be correct raw data. + mifareUltralight.writeSinglePage(pageIndex, rawData, (err)=> { + if (err) { + console.log("mifareUltralight writeSinglePage AsyncCallback err: " + err); + } else { + console.log("mifareUltralight writeSinglePage AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareUltralight writeSinglePage AsyncCallback catch busiError: " + busiError); +} ``` ### MifareUltralightTag.getType9+ -getType(): MifareUltralightType +getType(): [tag.MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9) -Obtains the MIFARE Ultralight tag type, in bytes. For details, see [MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9). - -**Required permissions**: ohos.permission.NFC_TAG +Obtains the type of this MIFARE Ultralight tag. -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| MifareUltralightType | MIFARE Ultralight tag type obtained. For details, see [MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9).| +| [tag.MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9) | Type of the MIFARE Ultralight tag obtained.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareUltralight' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareUltralight' correctly. let getType = mifareClassic.getType(); console.log("mifareUltralight getType: " + getType); ``` ## NdefFormatableTag9+ -Provides APIs for operating NDEF formattable tags. This class inherits from **TagSession**. +Provides APIs for formatting NDEF formattable tags. This class inherits from **TagSession**. **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **NdefFormatableTag**. +The following describes the unique APIs of **NdefFormatableTag**. ### NdefFormatableTag.format9+ -format(message: [NdefMessage](#ndefmessage9)): Promise\ +format(message: [NdefMessage](#ndefmessage9)): Promise\ -Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API uses a promise to return the result. +Formats this tag as an NDEF tag, and writes an NDEF message to it. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If this parameter is **null**, the tag is formatted only (no data will be written).| +| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write. If this parameter is **null**, the tag is formatted only (no data will be written).| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let data = [0x01, 0x02, ...]; // change it to be correct raw data. -let ndefmessage = ndef.createNdefMessage(data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefFormatable' correctly. -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndefFormatable' correctly. -ndefFormatable.format(ndefmessage, (err, data)=> { - if (err) { - console.log("ndefFormatable format err: " + err); - } else { - console.log("ndefFormatable format data: " + data); +// Connect to the tag if it is not connected. +if (!ndefFormatable.isTagConnected()) { + if (!ndefFormatable.connectTag()) { + console.log("ndefFormatable connectTag failed."); + return; } -}); +} + +try { + // NDEF message created from raw data, such as: + let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // It must be parsed as NDEF Record. + // or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[]) + + ndefFormatable.format(ndefMessage).then(() => { + console.log("ndefFormatable format Promise success."); + }).catch((err)=> { + console.log("ndefFormatable format Promise err: " + err); + }); +} catch (busiError) { + console.log("ndefFormatable format Promise catch busiError: " + busiError); +} ``` ### NdefFormatableTag.format9+ -format(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void +format(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void -Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API uses an asynchronous callback to return the result. +Formats this tag as an NDEF tag, and writes an NDEF message to it. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** @@ -1818,7 +2202,7 @@ Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API | **Type**| **Description** | | ------------------ | --------------------------| -| callback: AsyncCallback\ | Callback invoked to return the result.| +| callback: AsyncCallback\ | Callback invoked to return the result.| **Example** @@ -1826,82 +2210,108 @@ Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let data = [0x01, 0x02, ...]; // change it to be correct raw data. -let ndefmessage = ndef.createNdefMessage(data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefFormatable' correctly. -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndefFormatable' correctly. -ndefFormatable.format(ndefmessage, (err, data)=> { - if (err) { - console.log("ndefFormatable format err: " + err); - } else { - console.log("ndefFormatable format data: " + data); +// Connect to the tag if it is not connected. +if (!ndefFormatable.isTagConnected()) { + if (!ndefFormatable.connectTag()) { + console.log("ndefFormatable connectTag failed."); + return; } -}); +} + +try { + // NDEF message created from raw data, such as: + let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // It must be parsed as NDEF Record. + // or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[]) + + ndefFormatable.format(ndefMessage, (err)=> { + if (err) { + console.log("ndefFormatable format AsyncCallback err: " + err); + } else { + console.log("ndefFormatable format AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("ndefFormatable format AsyncCallback catch busiError: " + busiError); +} ``` ### NdefFormatableTag.formatReadOnly9+ -formatReadOnly(message: [NdefMessage](#ndefmessage9)): Promise\ +formatReadOnly(message: [NdefMessage](#ndefmessage9)): Promise\ -Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and then sets the tag to read-only. This API uses a promise to return the result. +Formats this tag as an NDEF tag, writes an NDEF message to it, and then sets the tag to read-only. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If this parameter is **null**, the tag is formatted only (no data will be written).| +| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write. If this parameter is **null**, the tag is formatted only (no data will be written).| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let data = [0x01, 0x02, ...]; // change it to be correct raw data. -let ndefmessage = ndef.createNdefMessage(data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefFormatable' correctly. -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndefFormatable' correctly. -ndefFormatable.formatReadOnly(ndefmessage, (err, data)=> { - if (err) { - console.log("ndefFormatable formatReadOnly err: " + err); - } else { - console.log("ndefFormatable formatReadOnly data: " + data); +// Connect to the tag if it is not connected. +if (!ndefFormatable.isTagConnected()) { + if (!ndefFormatable.connectTag()) { + console.log("ndefFormatable connectTag failed."); + return; } -}); +} + +try { + // NDEF message created from raw data, such as: + let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // It must be parsed as NDEF Record. + // or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[]) + + ndefFormatable.formatReadOnly(ndefMessage).then(() => { + console.log("ndefFormatable formatReadOnly Promise success."); + }).catch((err)=> { + console.log("ndefFormatable formatReadOnly Promise err: " + err); + }); +} catch (busiError) { + console.log("ndefFormatable formatReadOnly Promise catch busiError: " + busiError); +} ``` ### NdefFormatableTag.formatReadOnly9+ -formatReadOnly(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void +formatReadOnly(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and then sets the tag to read-only. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If this parameter is **null**, the tag is formatted only (no data will be written).| +| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write. If this parameter is **null**, the tag is formatted only (no data will be written).| **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| callback: AsyncCallback\ | Callback invoked to return the result.| +| callback: AsyncCallback\ | Callback invoked to return the result.| **Example** @@ -1909,16 +2319,29 @@ Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and the ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let data = [0x01, 0x02, ...]; // change it to be correct raw data. -let ndefmessage = ndef.createNdefMessage(data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefFormatable' correctly. -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndefFormatable' correctly. -ndefFormatable.formatReadOnly(ndefmessage, (err, data)=> { - if (err) { - console.log("ndefFormatable formatReadOnly err: " + err); - } else { - console.log("ndefFormatable formatReadOnly data: " + data); +// Connect to the tag if it is not connected. +if (!ndefFormatable.isTagConnected()) { + if (!ndefFormatable.connectTag()) { + console.log("ndefFormatable connectTag failed."); + return; } -}); +} + +try { + // NDEF message created from raw data, such as: + let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // It must be parsed as NDEF Record. + // or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[]) + + ndefFormatable.formatReadOnly(ndefMessage, (err)=> { + if (err) { + console.log("ndefFormatable formatReadOnly AsyncCallback err: " + err); + } else { + console.log("ndefFormatable formatReadOnly AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("ndefFormatable formatReadOnly AsyncCallback catch busiError: " + busiError); +} ``` diff --git a/en/application-dev/reference/apis/js-apis-notification.md b/en/application-dev/reference/apis/js-apis-notification.md index ff80fc8564758868ec979ff6bf033b7084fea561..99dd6551d098ddf0d6f58a69bde92191e38d083d 100644 --- a/en/application-dev/reference/apis/js-apis-notification.md +++ b/en/application-dev/reference/apis/js-apis-notification.md @@ -1,4 +1,4 @@ -# Notification +# @ohos.notification The **Notification** module provides notification management capabilities, covering notifications, notification slots, notification subscription, notification enabled status, and notification badge status. @@ -852,11 +852,7 @@ Subscribes to a notification with the subscription information specified. This A ```js function onConsumeCallback(data) { - if (err.code) { - console.info("subscribe failed " + JSON.stringify(err)); - } else { - console.info("subscribe success"); - } + console.info("Consume callback: " + JSON.stringify(data)); } var subscriber = { onConsume: onConsumeCallback @@ -1621,7 +1617,7 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | -------------------- | | hashCode | string | Yes | Unique notification ID. | -| reason | [RemoveReason](#removereason9) | Yes | Reason for removing the notification. | +| reason | [RemoveReason](#removereason9) | Yes | Indicates the reason for deleting a notification. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1659,7 +1655,7 @@ Removes a notification for a specified bundle. This API uses a promise to return | Name | Type | Mandatory| Description | | -------- | ---------- | ---- | ---------- | | hashCode | string | Yes | Unique notification ID.| -| reason | [RemoveReason](#removereason9) | Yes | Reason for removing the notification. | +| reason | [RemoveReason](#removereason9) | Yes | Reason for deleting the notification. | **Example** @@ -2567,11 +2563,11 @@ Requests notification to be enabled for this application. This API uses an async **Example** ```javascript -function requestEnableNotificationCallback() { +function requestEnableNotificationCallback(err) { if (err.code) { console.info("requestEnableNotification failed " + JSON.stringify(err)); } else { - console.info("requestEnableNotification success"); + } }; @@ -2620,7 +2616,7 @@ Sets whether this device supports distributed notifications. This API uses an as **Example** ```javascript -function enabledNotificationCallback() { +function enabledNotificationCallback(err) { if (err.code) { console.info("enableDistributed failed " + JSON.stringify(err)); } else { @@ -2682,11 +2678,11 @@ Obtains whether this device supports distributed notifications. This API uses an **Example** ```javascript -function isDistributedEnabledCallback() { +function isDistributedEnabledCallback(err, data) { if (err.code) { console.info("isDistributedEnabled failed " + JSON.stringify(err)); } else { - console.info("isDistributedEnabled success"); + console.info("isDistributedEnabled success " + JSON.stringify(data)); } }; @@ -2742,7 +2738,7 @@ Sets whether an application supports distributed notifications based on the bund **Example** ```javascript -function enableDistributedByBundleCallback() { +function enableDistributedByBundleCallback(err) { if (err.code) { console.info("enableDistributedByBundle failed " + JSON.stringify(err)); } else { @@ -2817,11 +2813,11 @@ Obtains whether an application supports distributed notifications based on the b **Example** ```javascript -function isDistributedEnabledByBundleCallback(data) { +function isDistributedEnabledByBundleCallback(err, data) { if (err.code) { console.info("isDistributedEnabledByBundle failed " + JSON.stringify(err)); } else { - console.info("isDistributedEnabledByBundle success"); + console.info("isDistributedEnabledByBundle success" + JSON.stringify(data)); } }; @@ -2893,7 +2889,7 @@ Obtains the notification reminder type. This API uses an asynchronous callback t **Example** ```javascript -function getDeviceRemindTypeCallback(data) { +function getDeviceRemindTypeCallback(err,data) { if (err.code) { console.info("getDeviceRemindType failed " + JSON.stringify(err)); } else { @@ -3414,6 +3410,8 @@ Notification.getSyncNotificationEnabledWithoutApp(userId) ## NotificationSubscriber +Provides callbacks for receiving or removing notifications. + **System API**: This is a system API and cannot be called by third-party applications. ### onConsume @@ -3430,7 +3428,7 @@ Callback for receiving notifications. | Name| Type| Mandatory| Description| | ------------ | ------------------------ | ---- | -------------------------- | -| data | AsyncCallback\<[SubscribeCallbackData](#subscribecallbackdata)\> | Yes| Notification information returned.| +| data | [SubscribeCallbackData](#subscribecallbackdata) | Yes| Notification information returned.| **Example** @@ -3447,15 +3445,6 @@ function onConsumeCallback(data) { console.info('===> onConsume in test'); let req = data.request; console.info('===> onConsume callback req.id:' + req.id); - let wantAgent = data.wantAgent; - wantAgent .getWant(wantAgent) - .then((data1) => { - console.info('===> getWant success want:' + JSON.stringify(data1)); - }) - .catch((err) => { - console.error('===> getWant failed because' + JSON.stringify(err)); - }); - console.info('===> onConsume callback req.wantAgent:' + JSON.stringify(req.wantAgent)); }; var subscriber = { @@ -3479,7 +3468,7 @@ Callback for removing notifications. | Name| Type| Mandatory| Description| | ------------ | ------------------------ | ---- | -------------------------- | -| data | AsyncCallback\<[SubscribeCallbackData](#subscribecallbackdata)\> | Yes| Notification information returned.| +| data | [SubscribeCallbackData](#subscribecallbackdata) | Yes| Notification information returned.| **Example** @@ -3723,13 +3712,13 @@ Notification.subscribe(subscriber, subscribeCallback); **System API**: This is a system API and cannot be called by third-party applications. -| Name | Readable| Writable| Type | Description | -| --------------- | ---- | --- | ------------------------------------------------- | -------- | -| request | Yes | No | [NotificationRequest](#notificationrequest) | Notification content.| -| sortingMap | Yes | No | [NotificationSortingMap](#notificationsortingmap) | Notification sorting information.| -| reason | Yes | No | number | Reason for deletion.| -| sound | Yes | No | string | Sound used for notification.| -| vibrationValues | Yes | No | Array\ | Vibration used for notification.| +| Name | Type | Readable| Writable| Description | +| --------------- | ------------------------------------------------- | ---- | --- | -------- | +| request | [NotificationRequest](#notificationrequest) | Yes | No | Notification content.| +| sortingMap | [NotificationSortingMap](#notificationsortingmap) | Yes | No | Notification sorting information.| +| reason | number | Yes | No | Reason for deletion.| +| sound | string | Yes | No | Sound used for notification.| +| vibrationValues | Array\ | Yes | No | Vibration used for notification.| ## EnabledNotificationCallbackData8+ @@ -3738,11 +3727,11 @@ Notification.subscribe(subscriber, subscribeCallback); **System API**: This is a system API and cannot be called by third-party applications. -| Name | Readable| Writable| Type | Description | -| ------ | ---- | --- | ------- | ---------------- | -| bundle | Yes | No | string | Bundle name of the application. | -| uid | Yes | No | number | UID of the application. | -| enable | Yes | No | boolean | Notification enabled status of the application.| +| Name | Type | Readable| Writable| Description | +| ------ | ------- | ---- | --- | ---------------- | +| bundle | string | Yes | No | Bundle name of the application. | +| uid | number | Yes | No | UID of the application. | +| enable | boolean | Yes | No | Notification enabled status of the application.| ## DoNotDisturbDate8+ @@ -3751,11 +3740,11 @@ Notification.subscribe(subscriber, subscribeCallback); **System API**: This is a system API and cannot be called by third-party applications. -| Name | Readable| Writable| Type | Description | -| ----- | ---- | --- | ------------------------------------- | ------------------------ | -| type | Yes | No | [DoNotDisturbType](#donotdisturbtype8) | DND time type.| -| begin | Yes | No | Date | DND start time.| -| end | Yes | No | Date | DND end time.| +| Name | Type | Readable| Writable| Description | +| ----- ------------------------------------- || ---- | --- | ------------------------ | +| type | [DoNotDisturbType](#donotdisturbtype8) | Yes | No | DND time type.| +| begin | Date | Yes | No | DND start time.| +| end | Date | Yes | No | DND end time.| @@ -3802,10 +3791,10 @@ Notification.subscribe(subscriber, subscribeCallback); **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| ------ | ---- | --- | ------ | ------ | -| bundle | Yes | Yes | string | Bundle name. | -| uid | Yes | Yes | number | User ID.| +| Name | Type | Readable| Writable| Description | +| ------ | ------ |---- | --- | ------ | +| bundle | string | Yes | Yes | Bundle name. | +| uid | number | Yes | Yes | User ID.| @@ -3813,10 +3802,10 @@ Notification.subscribe(subscriber, subscribeCallback); **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| ----- | ---- | --- | ------ | -------- | -| id | Yes | Yes | number | Notification ID. | -| label | Yes | Yes | string | Notification label.| +| Name | Type | Readable| Writable| Description | +| ----- | ------ | ---- | --- | -------- | +| id | number | Yes | Yes | Notification ID. | +| label | string | Yes | Yes | Notification label.| ## SlotType @@ -3834,84 +3823,98 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationActionButton +Enumerates the buttons in the notification. + **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| --------- | --- | ---- | ----------------------------------------------- | ------------------------- | -| title | Yes | Yes | string | Button title. | -| wantAgent | Yes | Yes | WantAgent | **WantAgent** of the button.| -| extras | Yes | Yes | { [key: string]: any } | Extra information of the button. | -| userInput8+ | Yes | Yes | [NotificationUserInput](#notificationuserinput8) | User input object. | +| Name | Type | Readable| Writable| Description | +| --------- | ----------------------------------------------- | --- | ---- | ------------------------- | +| title | string | Yes | Yes | Button title. | +| wantAgent | WantAgent | Yes | Yes | **WantAgent** of the button.| +| extras | { [key: string]: any } | Yes | Yes | Extra information of the button. | +| userInput8+ | [NotificationUserInput](#notificationuserinput8) | Yes | Yes | User input object. | ## NotificationBasicContent +Describes the normal text notification. + **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| -------------- | ---- | ---- | ------ | ---------------------------------- | -| title | Yes | Yes | string | Notification title. | -| text | Yes | Yes | string | Notification content. | -| additionalText | Yes | Yes | string | Additional information of the notification.| +| Name | Type | Readable| Writable| Description | +| -------------- | ------ | ---- | ---- | ---------------------------------- | +| title | string | Yes | Yes | Notification title. | +| text | string | Yes | Yes | Notification content. | +| additionalText | string | Yes | Yes | Additional information of the notification.| ## NotificationLongTextContent +Describes the long text notification. + **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| -------------- | ---- | --- | ------ | -------------------------------- | -| title | Yes | Yes | string | Notification title. | -| text | Yes | Yes | string | Notification content. | -| additionalText | Yes | Yes | string | Additional information of the notification.| -| longText | Yes | Yes | string | Long text of the notification. | -| briefText | Yes | Yes | string | Brief text of the notification.| -| expandedTitle | Yes | Yes | string | Title of the notification in the expanded state. | +| Name | Type | Readable| Writable| Description | +| -------------- | ------ | ---- | --- | -------------------------------- | +| title | string | Yes | Yes | Notification title. | +| text | string | Yes | Yes | Notification content. | +| additionalText | string | Yes | Yes | Additional information of the notification.| +| longText | string | Yes | Yes | Long text of the notification. | +| briefText | string | Yes | Yes | Brief text of the notification.| +| expandedTitle | string | Yes | Yes | Title of the notification in the expanded state. | ## NotificationMultiLineContent +Describes the multi-line text notification. + **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| -------------- | --- | --- | --------------- | -------------------------------- | -| title | Yes | Yes | string | Notification title. | -| text | Yes | Yes | string | Notification content. | -| additionalText | Yes | Yes | string | Additional information of the notification.| -| briefText | Yes | Yes | string | Brief text of the notification.| -| longTitle | Yes | Yes | string | Title of the notification in the expanded state. | -| lines | Yes | Yes | Array\ | Multi-line text of the notification. | +| Name | Type | Readable| Writable| Description | +| -------------- | --------------- | --- | --- | -------------------------------- | +| title | string | Yes | Yes | Notification title. | +| text | string | Yes | Yes | Notification content. | +| additionalText | string | Yes | Yes | Additional information of the notification.| +| briefText | string | Yes | Yes | Brief text of the notification.| +| longTitle | string | Yes | Yes | Title of the notification in the expanded state. | +| lines | Array\ | Yes | Yes | Multi-line text of the notification. | ## NotificationPictureContent +Describes the picture-attached notification. + **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| -------------- | ---- | --- | -------------- | -------------------------------- | -| title | Yes | Yes | string | Notification title. | -| text | Yes | Yes | string | Notification content. | -| additionalText | Yes | Yes | string | Additional information of the notification.| -| briefText | Yes | Yes | string | Brief text of the notification.| -| expandedTitle | Yes | Yes | string | Title of the notification in the expanded state. | -| picture | Yes | Yes | image.PixelMap | Picture attached to the notification. | +| Name | Type | Readable| Writable| Description | +| -------------- | -------------- | ---- | --- | -------------------------------- | +| title | string | Yes | Yes | Notification title. | +| text | string | Yes | Yes | Notification content. | +| additionalText | string | Yes | Yes | Additional information of the notification.| +| briefText | string | Yes | Yes | Brief text of the notification.| +| expandedTitle | string | Yes | Yes | Title of the notification in the expanded state. | +| picture | image.PixelMap | Yes | Yes | Picture attached to the notification. | ## NotificationContent +Describes the notification content. + **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| ----------- | ---- | --- | ------------------------------------------------------------ | ------------------ | -| contentType | Yes | Yes | [ContentType](#contenttype) | Notification content type. | -| normal | Yes | Yes | [NotificationBasicContent](#notificationbasiccontent) | Normal text. | -| longText | Yes | Yes | [NotificationLongTextContent](#notificationlongtextcontent) | Long text.| -| multiLine | Yes | Yes | [NotificationMultiLineContent](#notificationmultilinecontent) | Multi-line text. | -| picture | Yes | Yes | [NotificationPictureContent](#notificationpicturecontent) | Picture-attached. | +| Name | Type | Readable| Writable| Description | +| ----------- | ------------------------------------------------------------ | ---- | --- | ------------------ | +| contentType | [ContentType](#contenttype) | Yes | Yes | Notification content type. | +| normal | [NotificationBasicContent](#notificationbasiccontent) | Yes | Yes | Normal text. | +| longText | [NotificationLongTextContent](#notificationlongtextcontent) | Yes | Yes | Long text.| +| multiLine | [NotificationMultiLineContent](#notificationmultilinecontent) | Yes | Yes | Multi-line text. | +| picture | [NotificationPictureContent](#notificationpicturecontent) | Yes | Yes | Picture-attached. | ## NotificationFlagStatus8+ +Describes the notification flag status. + **System capability**: SystemCapability.Notification.Notification **System API**: This is a system API and cannot be called by third-party applications. @@ -3925,133 +3928,149 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationFlags8+ +Enumerates notification flags. + **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| ---------------- | ---- | ---- | ---------------------- | --------------------------------- | -| soundEnabled | Yes | No | NotificationFlagStatus | Whether to enable the sound alert for the notification. | -| vibrationEnabled | Yes | No | NotificationFlagStatus | Whether to enable vibration for the notification. | +| Name | Type | Readable| Writable| Description | +| ---------------- | ---------------------- | ---- | ---- | --------------------------------- | +| soundEnabled | NotificationFlagStatus | Yes | No | Whether to enable the sound alert for the notification. | +| vibrationEnabled | NotificationFlagStatus | Yes | No | Whether to enable vibration for the notification. | ## NotificationRequest -**System capability**: SystemCapability.Notification.Notification - -| Name | Readable| Writable| Type | Description | -| --------------------- | ---- | --- | --------------------------------------------- | -------------------------- | -| content | Yes | Yes | [NotificationContent](#notificationcontent) | Notification content. | -| id | Yes | Yes | number | Notification ID. | -| slotType | Yes | Yes | [SlotType](#slottype) | Slot type. | -| isOngoing | Yes | Yes | boolean | Whether the notification is an ongoing notification. | -| isUnremovable | Yes | Yes | boolean | Whether the notification can be removed. | -| deliveryTime | Yes | Yes | number | Time when the notification is sent. | -| tapDismissed | Yes | Yes | boolean | Whether the notification is automatically cleared. | -| autoDeletedTime | Yes | Yes | number | Time when the notification is automatically cleared. | -| wantAgent | Yes | Yes | WantAgent | **WantAgent** instance to which the notification will be redirected after being clicked. | -| extraInfo | Yes | Yes | {[key: string]: any} | Extended parameters. | -| color | Yes | Yes | number | Background color of the notification. | -| colorEnabled | Yes | Yes | boolean | Whether the notification background color is enabled. | -| isAlertOnce | Yes | Yes | boolean | Whether the notification triggers an alert only once.| -| isStopwatch | Yes | Yes | boolean | Whether to display the stopwatch. | -| isCountDown | Yes | Yes | boolean | Whether to display the countdown time. | -| isFloatingIcon | Yes | Yes | boolean | Whether the notification is displayed as a floating icon. | -| label | Yes | Yes | string | Notification label. | -| badgeIconStyle | Yes | Yes | number | Notification badge type. | -| showDeliveryTime | Yes | Yes | boolean | Whether to display the time when the notification is delivered. | -| actionButtons | Yes | Yes | Array\<[NotificationActionButton](#notificationactionbutton)\> | Buttons in the notification. Up to two buttons are allowed. | -| smallIcon | Yes | Yes | PixelMap | Small notification icon. | -| largeIcon | Yes | Yes | PixelMap | Large notification icon. | -| creatorBundleName | Yes | No | string | Name of the bundle that creates the notification. | -| creatorUid | Yes | No | number | UID used for creating the notification. | -| creatorPid | Yes | No | number | PID used for creating the notification. | -| creatorUserId8+| Yes | No | number | ID of the user who creates the notification. | -| hashCode | Yes | No | string | Unique ID of the notification. | -| classification | Yes | Yes | string | Notification category.
**System API**: This is a system API and cannot be called by third-party applications. | -| groupName8+| Yes | Yes | string | Group notification name. | -| template8+ | Yes | Yes | [NotificationTemplate](#notificationtemplate8) | Notification template. | -| isRemoveAllowed8+ | Yes | No | boolean | Whether the notification can be removed.
**System API**: This is a system API and cannot be called by third-party applications. | -| source8+ | Yes | No | number | Notification source.
**System API**: This is a system API and cannot be called by third-party applications. | -| distributedOption8+ | Yes | Yes | [DistributedOptions](#distributedoptions8) | Option of distributed notification. | -| deviceId8+ | Yes | No | string | Device ID of the notification source.
**System API**: This is a system API and cannot be called by third-party applications. | -| notificationFlags8+ | Yes | No | [NotificationFlags](#notificationflags8) | Notification flags. | -| removalWantAgent9+ | Yes | Yes | WantAgent | **WantAgent** instance to which the notification will be redirected when it is removed. | -| badgeNumber9+ | Yes | Yes | number | Number of notifications displayed on the application icon. | +Describes the notification request. + +**System capability**: SystemCapability.Notification.Notification + +| Name | Type | Readable| Writable| Description | +| --------------------- | --------------------------------------------- | ---- | --- | -------------------------- | +| content | [NotificationContent](#notificationcontent) | Yes | Yes | Notification content. | +| id | number | Yes | Yes | Notification ID. | +| slotType | [SlotType](#slottype) | Yes | Yes | Slot type. | +| isOngoing | boolean | Yes | Yes | Whether the notification is an ongoing notification. | +| isUnremovable | boolean | Yes | Yes | Whether the notification can be removed. | +| deliveryTime | number | Yes | Yes | Time when the notification is sent. | +| tapDismissed | boolean | Yes | Yes | Whether the notification is automatically cleared. | +| autoDeletedTime | number | Yes | Yes | Time when the notification is automatically cleared. | +| wantAgent | WantAgent | Yes | Yes | **WantAgent** instance to which the notification will be redirected after being clicked. | +| extraInfo | {[key: string]: any} | Yes | Yes | Extended parameters. | +| color | number | Yes | Yes | Background color of the notification. Not supported currently. | +| colorEnabled | boolean | Yes | Yes | Whether the notification background color is enabled. Not supported currently. | +| isAlertOnce | boolean | Yes | Yes | Whether the notification triggers an alert only once.| +| isStopwatch | boolean | Yes | Yes | Whether to display the stopwatch. | +| isCountDown | boolean | Yes | Yes | Whether to display the countdown time. | +| isFloatingIcon | boolean | Yes | Yes | Whether the notification is displayed as a floating icon. | +| label | string | Yes | Yes | Notification label. | +| badgeIconStyle | number | Yes | Yes | Notification badge type. | +| showDeliveryTime | boolean | Yes | Yes | Whether to display the time when the notification is delivered. | +| actionButtons | Array\<[NotificationActionButton](#notificationactionbutton)\> | Yes | Yes | Buttons in the notification. Up to two buttons are allowed. | +| smallIcon | PixelMap | Yes | Yes | Small notification icon. | +| largeIcon | PixelMap | Yes | Yes | Large notification icon. | +| creatorBundleName | string | Yes | No | Name of the bundle that creates the notification. | +| creatorUid | number | Yes | No | UID used for creating the notification. | +| creatorPid | number | Yes | No | PID used for creating the notification. | +| creatorUserId8+| number | Yes | No | ID of the user who creates the notification. | +| hashCode | string | Yes | No | Unique ID of the notification. | +| classification | string | Yes | Yes | Notification category.
**System API**: This is a system API and cannot be called by third-party applications. | +| groupName8+| string | Yes | Yes | Group notification name. | +| template8+ | [NotificationTemplate](#notificationtemplate8) | Yes | Yes | Notification template. | +| isRemoveAllowed8+ | boolean | Yes | No | Whether the notification can be removed.
**System API**: This is a system API and cannot be called by third-party applications. | +| source8+ | number | Yes | No | Notification source.
**System API**: This is a system API and cannot be called by third-party applications. | +| distributedOption8+ | [DistributedOptions](#distributedoptions8) | Yes | Yes | Option of distributed notification. | +| deviceId8+ | string | Yes | No | Device ID of the notification source.
**System API**: This is a system API and cannot be called by third-party applications. | +| notificationFlags8+ | [NotificationFlags](#notificationflags8) | Yes | No | Notification flags. | +| removalWantAgent9+ | WantAgent | Yes | Yes | **WantAgent** instance to which the notification will be redirected when it is removed. | +| badgeNumber9+ | number | Yes | Yes | Number of notifications displayed on the application icon. | ## DistributedOptions8+ +Describes distributed options. + **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| ---------------------- | ---- | ---- | -------------- | ---------------------------------- | -| isDistributed | Yes | Yes | boolean | Whether the notification is a distributed notification. | -| supportDisplayDevices | Yes | Yes | Array\ | Types of the devices to which the notification can be synchronized. | -| supportOperateDevices | Yes | Yes | Array\ | Devices on which notification can be enabled. | -| remindType | Yes | No | number | Notification reminder type.
**System API**: This is a system API and cannot be called by third-party applications. | +| Name | Type | Readable| Writable| Description | +| ---------------------- | -------------- | ---- | ---- | ---------------------------------- | +| isDistributed | boolean | Yes | Yes | Whether the notification is a distributed notification. | +| supportDisplayDevices | Array\ | Yes | Yes | Types of the devices to which the notification can be synchronized. | +| supportOperateDevices | Array\ | Yes | Yes | Devices on which notification can be enabled. | +| remindType | number | Yes | No | Notification reminder type.
**System API**: This is a system API and cannot be called by third-party applications. | ## NotificationSlot +Describes the notification slot. + **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| -------------------- | ---- | --- | --------------------- | ------------------------------------------ | -| type | Yes | Yes | [SlotType](#slottype) | Slot type. | -| level | Yes | Yes | number | Notification level. If this parameter is not set, the default value is used based on the notification slot type.| -| desc | Yes | Yes | string | Notification slot description. | -| badgeFlag | Yes | Yes | boolean | Whether to display the badge. | -| bypassDnd | Yes | Yes | boolean | Whether to bypass the DND mode in the system. | -| lockscreenVisibility | Yes | Yes | number | Mode for displaying the notification on the lock screen. | -| vibrationEnabled | Yes | Yes | boolean | Whether vibration is supported for the notification. | -| sound | Yes | Yes | string | Notification alert tone. | -| lightEnabled | Yes | Yes | boolean | Whether the indicator blinks for the notification. | -| lightColor | Yes | Yes | number | Indicator color of the notification. | -| vibrationValues | Yes | Yes | Array\ | Vibration mode of the notification. | -| enabled9+ | Yes | No | boolean | Enabled status of the notification slot. | +| Name | Type | Readable| Writable| Description | +| -------------------- | --------------------- | ---- | --- | ------------------------------------------ | +| type | [SlotType](#slottype) | Yes | Yes | Slot type. | +| level | number | Yes | Yes | Notification level. If this parameter is not set, the default value is used based on the notification slot type.| +| desc | string | Yes | Yes | Notification slot description. | +| badgeFlag | boolean | Yes | Yes | Whether to display the badge. | +| bypassDnd | boolean | Yes | Yes | Whether to bypass the DND mode in the system. | +| lockscreenVisibility | number | Yes | Yes | Mode for displaying the notification on the lock screen. | +| vibrationEnabled | boolean | Yes | Yes | Whether vibration is supported for the notification. | +| sound | string | Yes | Yes | Notification alert tone. | +| lightEnabled | boolean | Yes | Yes | Whether the indicator blinks for the notification. | +| lightColor | number | Yes | Yes | Indicator color of the notification. | +| vibrationValues | Array\ | Yes | Yes | Vibration mode of the notification. | +| enabled9+ | boolean | Yes | No | Enabled status of the notification slot. | ## NotificationSorting +Provides sorting information of active notifications. + **System capability**: SystemCapability.Notification.Notification **System API**: This is a system API and cannot be called by third-party applications. -| Name | Readable| Writable| Type | Description | -| -------- | ---- | --- | ------------------------------------- | ------------ | -| slot | Yes | No | [NotificationSlot](#notificationslot) | Notification slot content.| -| hashCode | Yes | No | string | Unique ID of the notification.| -| ranking | Yes | No | number | Notification sequence number.| +| Name | Type | Readable| Writable| Description | +| -------- | ------------------------------------- | ---- | --- | ------------ | +| slot | [NotificationSlot](#notificationslot) | Yes | No | Notification slot content.| +| hashCode | string | Yes | No | Unique ID of the notification.| +| ranking | number | Yes | No | Notification sequence number.| ## NotificationSortingMap +Provides sorting information of active notifications in all subscribed notifications. + **System capability**: SystemCapability.Notification.Notification **System API**: This is a system API and cannot be called by third-party applications. -| Name | Readable| Writable| Type | Description | -| -------------- | ---- | --- | ------------------------------------------------------------ | ---------------- | -| sortings | Yes | No | {[key: string]: [NotificationSorting](#notificationsorting)} | Array of notification sorting information.| -| sortedHashCode | Yes | No | Array\ | Array of unique notification IDs.| +| Name | Type | Readable| Writable| Description | +| -------------- | ------------------------------------------------------------ | ---- | --- | ---------------- | +| sortings | {[key: string]: [NotificationSorting](#notificationsorting)} | Yes | No | Array of notification sorting information.| +| sortedHashCode | Array\ | Yes | No | Array of unique notification IDs.| ## NotificationSubscribeInfo +Provides the information about the publisher for notification subscription. + **System capability**: SystemCapability.Notification.Notification **System API**: This is a system API and cannot be called by third-party applications. -| Name | Readable| Writable| Type | Description | -| ----------- | --- | ---- | --------------- | ------------------------------- | -| bundleNames | Yes | Yes | Array\ | Bundle names of the applications whose notifications are to be subscribed to.| -| userId | Yes | Yes | number | User whose notifications are to be subscribed to. | +| Name | Type | Readable| Writable| Description | +| ----------- | --------------- | --- | ---- | ------------------------------- | +| bundleNames | Array\ | Yes | Yes | Bundle names of the applications whose notifications are to be subscribed to.| +| userId | number | Yes | Yes | User whose notifications are to be subscribed to. | ## NotificationTemplate8+ +Notification template. + **System capability**: SystemCapability.Notification.Notification -| Name| Type | Readable| Writable| Description | +| Name| Type | Readable| Writable| Description | | ---- | ---------------------- | ---- | ---- | ---------- | | name | string | Yes | Yes | Template name.| | data | {[key:string]: Object} | Yes | Yes | Template data.| @@ -4059,11 +4078,13 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationUserInput8+ +Provides the notification user input. + **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| -------- | --- | ---- | ------ | ----------------------------- | -| inputKey | Yes | Yes | string | Key to identify the user input.| +| Name | Type | Readable| Writable| Description | +| -------- | ------ | --- | ---- | ----------------------------- | +| inputKey | string | Yes | Yes | Key to identify the user input.| ## DeviceRemindType8+ diff --git a/en/application-dev/reference/apis/js-apis-osAccount.md b/en/application-dev/reference/apis/js-apis-osAccount.md index 068e2a1ca6c4c01c2e69144354bd90b86302619a..f903401701e9f68ae6277a687215310f59afc34c 100644 --- a/en/application-dev/reference/apis/js-apis-osAccount.md +++ b/en/application-dev/reference/apis/js-apis-osAccount.md @@ -1,8 +1,9 @@ -# OS Account Management +# @ohos.account.osAccount The **osAccount** module provides basic capabilities for managing OS accounts, including adding, deleting, querying, setting, subscribing to, and enabling an OS account. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -2708,7 +2709,6 @@ Obtains the constraint source information of an OS account. This API uses a prom console.info('queryOsAccountConstraintSourceType exception:' + JSON.stringify(e)); } ``` - ### isMultiOsAccountEnable(deprecated) isMultiOsAccountEnable(callback: AsyncCallback<boolean>): void @@ -4280,17 +4280,12 @@ Register a PIN inputer. | ----------| ----------------------- | --- | -------------------------- | | inputer | [IInputer](#iinputer8) | Yes | PIN inputer, which is used to obtain the PIN.| -**Return value** - -| Type | Description | -| :------ | :-------------------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - **Error codes** | ID| Error Message | | -------- | --------------------------- | | 12300001 | System service exception. | +| 12300102 | Invalid inputer. | | 12300103 | Inputer already registered. | **Example** @@ -4299,8 +4294,8 @@ Register a PIN inputer. let password = new Uint8Array([0, 0, 0, 0, 0]); try { let result = pinAuth.registerInputer({ - onGetData: (pinSubType, callback) => { - callback.onSetData(pinSubType, password); + onGetData: (authSubType, callback) => { + callback.onSetData(authSubType, password); } }); console.log('registerInputer result = ' + result); @@ -4327,6 +4322,91 @@ Unregisters this PIN inputer. pinAuth.unregisterInputer(); ``` +### InputerManager 10+ + +Provides APIs for managing credential inputers. + +### registerInputer10+ + +registerInputer(authType: AuthType, inputer: IInputer): void; + +Register a credential inputer. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_USER_AUTH_INTERNAL or ohos.permission.MANAGE_USER_IDM + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------| ----------------------- | --- | -------------------------- | +| authType | [AuthType](#authtype8) | Yes | Authentication credential type.| +| inputer | [IInputer](#iinputer8) | Yes | Credential inputer to register.| + +**Error codes** + +| ID| Error Message | +| -------- | --------------------------- | +| 12300001 | System service exception. | +| 12300102 | Invalid authType or inputer. | +| 12300103 | The credential inputer has been registered. | +| 12300106 | Unsupported authType. | + +**Example** + ```js + let inputerMgr = new account_osAccount.InputerManager(); + let authType = account_osAccount.AuthType.DOMAIN; + let password = new Uint8Array([0, 0, 0, 0, 0]); + try { + InputerMgr.registerInputer(authType, { + onGetData: (authSubType, callback) => { + callback.onSetData(authSubType, password); + } + }); + console.log('registerInputer success.'); + } catch (e) { + console.log('registerInputer exception = ' + JSON.stringify(e)); + } + ``` + +### unregisterInputer10+ + +unregisterInputer(authType: AuthType): void; + +Unregisters this credential inputer. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_USER_AUTH_INTERNAL or ohos.permission.MANAGE_USER_IDM + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------| ----------------------- | --- | -------------------------- | +| authType | [AuthType](#authtype8) | Yes | Authentication credential type.| + +**Error codes** + +| ID| Error Message | +| -------- | --------------------------- | +| 12300002 | Invalid authType. | + +**Example** + ```js + let inputerMgr = new account_osAccount.InputerManager(); + let authType = account_osAccount.AuthType.DOMAIN; + try { + inputerMgr.unregisterInputer(authType); + console.log('unregisterInputer success.'); + } catch(err) { + console.log("unregisterInputer err:" + JSON.stringify(err)); + } + ``` + ## UserIdentityManager8+ Provides APIs for user identity management (IDM). @@ -4456,8 +4536,8 @@ Adds credential information, including the credential type, subtype, and token ( let password = new Uint8Array([0, 0, 0, 0, 0, 0]); let pinAuth = new account_osAccount.PINAuth(); pinAuth.registerInputer({ - onGetData: (pinSubType, callback) => { - callback.onSetData(pinSubType, password); + onGetData: (authSubType, callback) => { + callback.onSetData(authSubType, password); } }); let credentialInfo = { @@ -4470,12 +4550,12 @@ Adds credential information, including the credential type, subtype, and token ( try { userIDM.addCredential(credentialInfo, { onResult: (result, extraInfo) => { - console.log('updateCredential result = ' + result); - console.log('updateCredential extraInfo = ' + extraInfo); + console.log('addCredential result = ' + result); + console.log('addCredential extraInfo = ' + extraInfo); } }); } catch (e) { - console.log('updateCredential exception = ' + JSON.stringify(e)); + console.log('addCredential exception = ' + JSON.stringify(e)); } }); ``` @@ -4520,8 +4600,8 @@ Updates credential information. This API uses a callback to return the result. token: null }; pinAuth.registerInputer({ - onGetData: (pinSubType, callback) => { - callback.onSetData(pinSubType, password); + onGetData: (authSubType, callback) => { + callback.onSetData(authSubType, password); } }); userIDM.openSession((err, challenge) => { @@ -4820,7 +4900,7 @@ Provides callbacks for PIN operations. ### onSetData8+ -onSetData: (pinSubType: AuthSubType, data: Uint8Array) => void; +onSetData: (authSubType: AuthSubType, data: Uint8Array) => void; **System API**: This is a system API. @@ -4832,7 +4912,7 @@ Called to set data in a PIN operation. | Name | Type | Mandatory| Description | | ---------- | ---------------------------------------- | ---- | ----------------------------------------------- | -| pinSubType | [AuthSubType](#authsubtype8) | Yes | Credential subtype. | +| authSubType | [AuthSubType](#authsubtype8) | Yes | Credential subtype. | | data | Uint8Array | Yes | Data (credential) to set. The data is used for authentication and operations for adding and modifying credentials.| **Example** @@ -4840,11 +4920,11 @@ Called to set data in a PIN operation. let password = new Uint8Array([0, 0, 0, 0, 0, 0]); let passwordNumber = new Uint8Array([1, 2, 3, 4]); let inputer = { - onGetData: (pinSubType, callback) => { - if (pinSubType == account_osAccount.AuthSubType.PIN_NUMBER) { - callback.onSetData(pinSubType, passwordNumber); + onGetData: (authSubType, callback) => { + if (authSubType == account_osAccount.AuthSubType.PIN_NUMBER) { + callback.onSetData(authSubType, passwordNumber); } else { - callback.onSetData(pinSubType, password); + callback.onSetData(authSubType, password); } } }; @@ -4852,13 +4932,13 @@ Called to set data in a PIN operation. ## IInputer8+ -Provides callbacks for the PIN input box. +Provides callbacks for credential inputers. **System API**: This is a system API. ### onGetData8+ -onGetData: (pinSubType: AuthSubType, callback: IInputData) => void; +onGetData: (authSubType: AuthSubType, callback: IInputData) => void; Called to obtain data. @@ -4877,11 +4957,11 @@ Called to obtain data. let password = new Uint8Array([0, 0, 0, 0, 0, 0]); let passwordNumber = new Uint8Array([1, 2, 3, 4]); let inputer = { - onGetData: (pinSubType, callback) => { - if (pinSubType == account_osAccount.AuthSubType.PIN_NUMBER) { - callback.onSetData(pinSubType, passwordNumber); + onGetData: (authSubType, callback) => { + if (authSubType == account_osAccount.AuthSubType.PIN_NUMBER) { + callback.onSetData(authSubType, passwordNumber); } else { - callback.onSetData(pinSubType, password); + callback.onSetData(authSubType, password); } } }; @@ -5157,6 +5237,8 @@ Enumerates the authentication credential types. | ----- | ----- | ---------------- | | PIN | 1 | PIN authentication.| | FACE | 2 | Facial authentication.| +| FINGERPRINT10+ | 4 | Fingerprint authentication.| +| DOMAIN10+ | 1024 | Domain authentication.| ## AuthSubType8+ @@ -5170,9 +5252,10 @@ Enumerates the authentication credential subtypes. | ---------- | ----- | ------------------ | | PIN_SIX | 10000 | Six-digit PIN. | | PIN_NUMBER | 10001 | Custom PIN.| -| PIN_MIXED | 10002 | Custom mixed credential.| +| PIN_MIXED | 10002 | Custom mixed credentials.| | FACE_2D | 20000 | 2D face credential. | | FACE_3D | 20001 | 3D face credential. | +| DOMAIN_MIXED10+ | 10240001 | Mixed domain authentication credentials. | ## AuthTrustLevel8+ diff --git a/en/application-dev/reference/apis/js-apis-plainarray.md b/en/application-dev/reference/apis/js-apis-plainarray.md index 79ede0ce7a1aac37d64fe0a848e4bb5948cd877b..dfc05166987a87d07bc1499fbcb980b45f08f2e8 100644 --- a/en/application-dev/reference/apis/js-apis-plainarray.md +++ b/en/application-dev/reference/apis/js-apis-plainarray.md @@ -1,4 +1,4 @@ -# Nonlinear Container PlainArray +# @ohos.util.PlainArray (Nonlinear Container PlainArray) > **NOTE** > @@ -21,8 +21,6 @@ This topic uses the following to identify the use of generics: import PlainArray from '@ohos.util.PlainArray'; ``` - - ## PlainArray ### Attributes @@ -54,11 +52,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let plainArray = new PlainArray(); -try { - let plainArray2 = PlainArray(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -89,11 +82,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts const plainArray = new PlainArray(); let result = plainArray.isEmpty(); -try { - plainArray.isEmpty.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -132,11 +120,6 @@ let plainArray = new PlainArray(); plainArray.has(1); plainArray.add(1, "squirrel"); let result1 = plainArray.has(1); -try { - plainArray.has.bind({}, 1)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -175,11 +158,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.get(1); -try { - plainArray.get.bind({}, 1)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -218,11 +196,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.getIndexOfKey(2); -try { - plainArray.getIndexOfKey.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -261,11 +234,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.getIndexOfValue("squirrel"); -try { - plainArray.getIndexOfValue.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -304,11 +272,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.getKeyAt(1); -try { - plainArray.getKeyAt.bind({}, 1)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getValueAt @@ -338,7 +301,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The getValueAt method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -347,16 +310,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.getValueAt(1); -try { - plainArray.getValueAt.bind({}, 1)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - plainArray.getValueAt(10); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### clone @@ -388,11 +341,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let newPlainArray = plainArray.clone(); -try { - plainArray.clone.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -424,11 +372,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); -try { - plainArray.add.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -467,11 +410,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.remove(2); -try { - plainArray.remove.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -510,11 +448,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.removeAt(1); -try { - plainArray.removeAt.bind({}, 1)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -546,7 +479,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The removeRangeFrom method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -555,16 +488,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.removeRangeFrom(1, 3); -try { - plainArray.removeRangeFrom.bind({}, 1, 3)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - plainArray.removeRangeFrom(10, 3); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -590,7 +513,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The setValueAt method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -599,16 +522,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); plainArray.setValueAt(1, 3546); -try { - plainArray.setValueAt.bind({}, 1, 3546)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - plainArray.setValueAt(10, 3); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -641,11 +554,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.toString(); -try { - plainArray.toString.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -672,17 +580,12 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); plainArray.clear(); -try { - plainArray.clear.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value: T, index?: number, PlainArray?: PlainArray<T>) => void, thisArg?: Object): void +forEach(callbackFn: (value: T, index?: number, PlainArray?: PlainArray<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -692,7 +595,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -719,13 +622,6 @@ plainArray.add(2, "sparrow"); plainArray.forEach((value, index) => { console.log("value:" + value, index); }); -try { - plainArray.forEach.bind({}, (value, index) => { - console.log("value:" + value, index); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -772,9 +668,4 @@ while(temp != undefined) { console.log("value:" + temp[1]); temp = iter.next().value; } -try { - plainArray[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-power.md b/en/application-dev/reference/apis/js-apis-power.md index ad6e437f09767e362b2787f5ee78dd58d1a65165..1c78452681d08db91a4aa3ee4cf2aea785072191 100644 --- a/en/application-dev/reference/apis/js-apis-power.md +++ b/en/application-dev/reference/apis/js-apis-power.md @@ -1,10 +1,9 @@ # Power Manager -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. - The Power Manager module provides APIs for rebooting and shutting down the system, as well as querying the screen status. +> **NOTE** +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -12,42 +11,294 @@ The Power Manager module provides APIs for rebooting and shutting down the syste import power from '@ohos.power'; ``` -## System Capability - -SystemCapability.PowerManager.PowerManager.Core - +## power.shutdown -## power.shutdownDevice - -shutdownDevice(reason: string): void +shutdown(reason: string): void Shuts down the system. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Required permission**: ohos.permission.REBOOT +**System capability:** SystemCapability.PowerManager.PowerManager.Core + **Parameters** | Name | Type | Mandatory | Description | | ------ | ------ | ---- | ----- | | reason | string | Yes | Reason for system shutdown.| +**Error codes** + +For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md). + +| Code | Error Message | +|---------|---------| +| 4900101 | Operation failed. Cannot connect to service.| + **Example** ```js -power.shutdownDevice("shutdown_test"); -console.info('power_shutdown_device_test success') +try { + power.shutdown('shutdown_test'); +} catch(err) { + console.error('shutdown failed, err: ' + err); +} ``` +## power.reboot9+ + +reboot(reason: string): void + +Reboots the system. + +**System API**: This is a system API. + +**Required permission**: ohos.permission.REBOOT + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------- | +| reason | string | Yes | Reason for system reboot.| + +**Error codes** + +For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md). + +| Code | Error Message | +|---------|---------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + power.reboot('reboot_test'); +} catch(err) { + console.error('reboot failed, err: ' + err); +} +``` + +## power.isActive9+ + +isActive(): boolean + +Checks whether the current device is active. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Error codes** + +For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md). + +| Code | Error Message | +|---------|---------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + var isActive = power.isActive(); + console.info('power is active: ' + isActive); +} catch(err) { + console.error('check active status failed, err: ' + err); +} +``` + +## power.wakeup9+ + +wakeup(detail: string): void + +Wakes up a device. + +**System API**: This is a system API. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------- | +| detail | string | Yes | Reason for wakeup.| + +**Error codes** + +For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md). + +| Code | Error Message | +|---------|---------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + power.wakeup('wakeup_test'); +} catch(err) { + console.error('wakeup failed, err: ' + err); +} +``` + +## power.suspend9+ + +suspend(): void + +Hibernates a device. + +**System API**: This is a system API. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Error codes** + +For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md). + +| Code | Error Message | +|---------|---------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + power.suspend(); +} catch(err) { + console.error('suspend failed, err: ' + err); +} +``` -## power.rebootDevice +## power.getPowerMode9+ + +getPowerMode(): DevicePowerMode + +Obtains the power mode of this device. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Return value** + +| Type | Description | +| ------------------------------------ | ---------- | +| [DevicePowerMode](#devicepowermode9) | Power mode.| + +**Error codes** + +For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md). + +| Code | Error Message | +|---------|---------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + var mode = power.getPowerMode(); + console.info('power mode: ' + mode); +} catch(err) { + console.error('get power mode failed, err: ' + err); +} +``` + +## power.setPowerMode9+ + +setPowerMode(mode: DevicePowerMode, callback: AsyncCallback<void>): void + +Sets the power mode of this device. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permission**: ohos.permission.POWER_OPTIMIZATION + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | +| mode | [DevicePowerMode](#devicepowermode9) | Yes | Power mode. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the power mode is successfully set, **err** is **undefined**; otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md). + +| Code | Error Message | +|---------|---------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +power.setPowerMode(power.DevicePowerMode.MODE_PERFORMANCE, err => { + if (typeof err === 'undefined') { + console.info('set power mode to MODE_PERFORMANCE'); + } else { + console.error('set power mode failed, err: ' + err); + } +}); +``` + +## power.setPowerMode9+ + +setPowerMode(mode: DevicePowerMode): Promise<void> + +Sets the power mode of this device. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permission**: ohos.permission.POWER_OPTIMIZATION + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------ | ---- | ---------- | +| mode | [DevicePowerMode](#devicepowermode9) | Yes | Power mode.| + +**Return value** + +| Type | Description | +| ------------------- | -------------------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md). + +| Code | Error Message | +|---------|---------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +power.setPowerMode(power.DevicePowerMode.MODE_PERFORMANCE) +.then(() => { + console.info('set power mode to MODE_PERFORMANCE'); +}) +.catch(err => { + console.error('set power mode failed, err: ' + err); +}); +``` + +## power.rebootDevice(deprecated) rebootDevice(reason: string): void +> This API is deprecated since API version 9. You are advised to use [power.reboot](#powerreboot9) instead. + Reboots the system. -**Required permission**: ohos.permission.REBOOT (to reboot) or ohos.permission.REBOOT_RECOVERY (to reboot and enter the recovery or updater mode) +**Required permission**: ohos.permission.REBOOT + +**System capability:** SystemCapability.PowerManager.PowerManager.Core **Parameters** @@ -58,55 +309,73 @@ Reboots the system. **Example** ```js -power.rebootDevice("reboot_test"); -console.info('power_reboot_device_test success') +power.rebootDevice('reboot_test'); ``` - -## power.isScreenOn +## power.isScreenOn(deprecated) isScreenOn(callback: AsyncCallback<boolean>): void -Checks the screen status of the current device. +> This API is deprecated since API version 9. You are advised to use [power.isActive](#powerisactive9) instead. + +Checks the screen status of the current device. This API uses an asynchronous callback to return the result. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------- | ---- | ---------------------------------------- | -| callback | AsyncCallback<boolean> | Yes | Callback used to obtain the return value.
Return value: The value **true** indicates that the screen is on, and the value **false** indicates the opposite.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the screen status obtained, where the value **true** indicates on and the value **false** indicates the opposite. Otherwise, **err** is an error object.| **Example** ```js -power.isScreenOn((error, screenOn) => { - if (typeof error === "undefined") { - console.info('screenOn status is ' + screenOn); +power.isScreenOn((err, data) => { + if (typeof err === 'undefined') { + console.info('screen on status is ' + data); } else { - console.log('error: ' + error); + console.error('check screen status failed, err: ' + err); } }) ``` - -## power.isScreenOn +## power.isScreenOn(deprecated) isScreenOn(): Promise<boolean> -Checks the screen status of the current device. +> This API is deprecated since API version 9. You are advised to use [power.isActive](#powerisactive9) instead. + +Checks the screen status of the current device. This API uses a promise to return the result. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core **Return value** -| Type | Description | -| ---------------------- | --------------------------------------- | -| Promise<boolean> | Promise used to obtain the return value.
Return value: The value **true** indicates that the screen is on, and the value **false** indicates the opposite.| +| Type | Description | +| ---------------------- | -------------------------------------------------- | +| Promise<boolean> | Promise used to return the result. The value **true** indicates that the screen is on, and the value **false** indicates the opposite.| **Example** ```js power.isScreenOn() -.then(screenOn => { - console.info('screenOn status is ' + screenOn); +.then(data => { + console.info('screen on status is ' + data); }) -.catch(error => { - console.log('error: ' + error); +.catch(err => { + console.error('check screen status failed, err: ' + err); }) ``` + +## DevicePowerMode9+ + +Enumerates power modes. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +| Name | Value | Description | +| ----------------------- | ---- | ---------------------- | +| MODE_NORMAL | 600 | Standard mode. It is the default value.| +| MODE_POWER_SAVE | 601 | Power saving mode. | +| MODE_PERFORMANCE | 602 | Performance mode. | +| MODE_EXTREME_POWER_SAVE | 603 | Ultra power saving mode. | diff --git a/en/application-dev/reference/apis/js-apis-process.md b/en/application-dev/reference/apis/js-apis-process.md index 59727e8c039dd23adc71b3a0b314e5664e8c9b34..318ba307995a44950461ae3b9a43e92743c37364 100755 --- a/en/application-dev/reference/apis/js-apis-process.md +++ b/en/application-dev/reference/apis/js-apis-process.md @@ -1,4 +1,4 @@ -# Obtaining Process Information +# @ohos.process (Obtaining Process Information) > **NOTE** > @@ -18,13 +18,13 @@ import process from '@ohos.process'; | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| egid | number | Yes| No| Effective group identifier (EGID) of a process. This is a system API and cannot be called by third-party applications.| -| euid | number | Yes| No| Effective user identifier (EUID) of a process. This is a system API and cannot be called by third-party applications.| -| gid | number | Yes| No| Group identifier (GID) of a process. This is a system API and cannot be called by third-party applications.| +| egid | number | Yes| No| Effective group identifier (EGID) of a process.
**System API**: This is a system API.
It is used only to test applications.| +| euid | number | Yes| No| Effective user identifier (EUID) of a process.
**System API**: This is a system API.
It is used only to test applications.| +| gid | number | Yes| No| Group identifier (GID) of a process.
**System API**: This is a system API.
It is used only to test applications.| | uid | number | Yes| No| User identifier (UID) of a process.| -| groups | number[] | Yes| No| Array with supplementary group IDs. This is a system API and cannot be called by third-party applications.| +| groups | number[] | Yes| No| Array with supplementary group IDs.
**System API**: This is a system API.
It is used only to test applications.| | pid | number | Yes| No| Process ID (PID) of a process.| -| ppid | number | Yes| No| Parent process ID (PPID) of a process. This is a system API and cannot be called by third-party applications.| +| ppid | number | Yes| No| Parent process ID (PPID) of a process.
**System API**: This is a system API.
It is used only to test applications.| | tid8+ | number | Yes| No| Thread ID (TID) of a process.| @@ -32,7 +32,7 @@ import process from '@ohos.process'; Provides APIs for throwing exceptions during the addition of a process. -### process.isAppUid9+ +### isAppUid9+ isAppUid(v: number): boolean @@ -60,7 +60,7 @@ let result = pro.isAppUid(688); ``` -### process.getUidForName9+ +### getUidForName9+ getUidForName(v: string): number @@ -88,7 +88,7 @@ let pres = pro .getUidForName("tool"); ``` -### process.getThreadPriority9+ +### getThreadPriority9+ getThreadPriority(v: number): number @@ -117,7 +117,7 @@ let pres = pro.getThreadPriority(tid); ``` -### process.getSystemConfig9+ +### getSystemConfig9+ getSystemConfig(name: number): number @@ -146,7 +146,7 @@ let pres = pro.getSystemConfig(_SC_ARG_MAX); ``` -### process.getEnvironmentVar9+ +### getEnvironmentVar9+ getEnvironmentVar(name: string): string @@ -174,7 +174,7 @@ let pres = pro.getEnvironmentVar("PATH"); ``` -### process.exit9+ +### exit9+ exit(code: number): void @@ -198,7 +198,7 @@ pro.exit(0); ``` -### process.kill9+ +### kill9+ kill(signal: number, pid: number): boolean @@ -238,10 +238,10 @@ Allows a process to obtain the standard input and output of its child processes, | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| pid | number | Yes| No| PID of the child process. This is a system API and cannot be called by third-party applications.| -| ppid | number | Yes| No| PPID of the child process. This is a system API and cannot be called by third-party applications.| -| exitCode | number | Yes| No| Exit code of the child process. This is a system API and cannot be called by third-party applications.| -| killed | boolean | Yes| No| Whether the parent process successfully sends a signal to the child process to terminate it. This is a system API and cannot be called by third-party applications.| +| pid | number | Yes| No| PID of the child process.
**System API**: This is a system API.
It is used only to test applications.| +| ppid | number | Yes| No| PPID of the child process.
**System API**: This is a system API.
It is used only to test applications.| +| exitCode | number | Yes| No| Exit code of the child process.
**System API**: This is a system API.
It is used only to test applications.| +| killed | boolean | Yes| No| Whether the parent process successfully sends a signal to the child process to terminate it.
**System API**: This is a system API.
It is used only to test applications.| ### wait @@ -250,7 +250,9 @@ wait(): Promise<number> Waits until the child process ends. This method uses a promise to return the exit code of the child process. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +It is used only to test applications. **System capability**: SystemCapability.Utils.Lang @@ -277,7 +279,9 @@ getOutput(): Promise<Uint8Array> Obtains the standard output of the child process. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +It is used only to test applications. **System capability**: SystemCapability.Utils.Lang @@ -304,7 +308,9 @@ getErrorOutput(): Promise<Uint8Array> Obtains the standard error output of the child process. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +It is used only to test applications. **System capability**: SystemCapability.Utils.Lang @@ -331,7 +337,9 @@ close(): void Closes the child process in running. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +It is used only to test applications. **System capability**: SystemCapability.Utils.Lang @@ -349,7 +357,9 @@ kill(signal: number | string): void Sends a signal to the specified child process to terminate it. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +It is used only to test applications. **System capability**: SystemCapability.Utils.Lang @@ -593,7 +603,9 @@ runCmd(command: string, options?: { timeout?: number, killSignal?: number | stri Forks a new process to run a shell command and returns the **ChildProcess** object. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +It is used only to test applications. **System capability**: SystemCapability.Utils.Lang @@ -609,7 +621,7 @@ This is a system API and cannot be called by third-party applications. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | timeout | number | No| Maximum running time (in ms) of the child process. When the running time of the child process exceeds the value of this parameter, the parent process sends a **killSignal** to the child process to terminate it. The default value is **0**.| -| killSignal | number \| string | No| Signal sent to the child process when the running time of a child process exceeds the timeout period. The default value is **SIGTERM**.| +| killSignal | number \| string | No| Signal sent to the child process when the running time of a child process exceeds the timeout period. The default value is **SIGTERM**.| | maxBuffer | number | No| Maximum buffer size for the standard input and output of the child process. When the size is exceeded, the child process will be terminated. The default value is **1024 \* 1024**.| **Return value** @@ -650,7 +662,9 @@ on(type: string, listener: EventListener): void Stores the events triggered by the user. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +It is used only to test applications. **System capability**: SystemCapability.Utils.Lang @@ -682,7 +696,9 @@ off(type: string): boolean Deletes the event stored by the user. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +It is used only to test applications. **System capability**: SystemCapability.Utils.Lang @@ -737,7 +753,9 @@ cwd(): string Obtains the working directory of this process. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +It is used only to test applications. **System capability**: SystemCapability.Utils.Lang @@ -754,7 +772,9 @@ chdir(dir: string): void Changes the working directory of this process. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +It is used only to test applications. **System capability**: SystemCapability.Utils.Lang diff --git a/en/application-dev/reference/apis/js-apis-queue.md b/en/application-dev/reference/apis/js-apis-queue.md index 11ca91994e98310961e657db1a4c5e2554798c99..57ce3f7b301c42167b6af3830e39949afd76f719 100644 --- a/en/application-dev/reference/apis/js-apis-queue.md +++ b/en/application-dev/reference/apis/js-apis-queue.md @@ -1,4 +1,4 @@ -# Linear Container Queue +# @ohos.util.Queue (Linear Container Queue) > **NOTE** > @@ -51,11 +51,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let queue = new Queue(); -try { - let queue2 = Queue(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -97,11 +92,6 @@ let b = [1, 2, 3]; let result2 = queue.add(b); let c = {name : "Dylon", age : "13"}; let result3 = queue.add(c); -try { - queue.add.bind({}, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### pop @@ -136,11 +126,6 @@ queue.add(5); queue.add(2); queue.add(4); let result = queue.pop(); -try { - queue.pop.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getFirst @@ -151,7 +136,7 @@ Obtains the first element of this container. **System capability**: SystemCapability.Utils.Lang -**Parameters** +**Return value** | Type| Description| | -------- | -------- | @@ -174,16 +159,11 @@ queue.add(4); queue.add(5); queue.add(2); let result = queue.getFirst(); -try { - queue.getFirst.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value: T, index?: number, Queue?: Queue<T>) => void, +forEach(callbackFn: (value: T, index?: number, Queue?: Queue<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -194,7 +174,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -224,13 +204,6 @@ queue.add(4); queue.forEach((value, index) => { console.log("value:" + value, index); }); -try { - queue.forEach.bind({}, (value, index) => { - console.log("value:" + value, index); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### [Symbol.iterator] @@ -275,9 +248,4 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - queue[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-request.md b/en/application-dev/reference/apis/js-apis-request.md index 65e8c2708c98748ba55a734e8095228233d90b9a..2220b4bbc02bd9a68fa900138869b6d3f6620675 100644 --- a/en/application-dev/reference/apis/js-apis-request.md +++ b/en/application-dev/reference/apis/js-apis-request.md @@ -1,9 +1,9 @@ -# Upload and Download +# @ohos.request The **request** module provides applications with basic upload, download, and background transmission agent capabilities. > **NOTE** -> +> > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -34,8 +34,9 @@ var config = { The **cleartextTraffic** attribute is not involved during application development in the stage model. -The download server must support the HTTP HEAD method so that the size of the data to download can be obtained through **content-length**. Otherwise, the download task fails. If this is the case, you can check the failure cause through [on('fail')7+)](#onfail7). +The download server must support the HTTP HEAD method so that the size of the data to download can be obtained through **Content-length**. Otherwise, the download task fails. If this is the case, you can check the failure cause through [on('fail')7+](#onfail7). +Only HTTP requests are supported. HTTPS requests are not supported. ## Constants @@ -69,86 +70,93 @@ The download server must support the HTTP HEAD method so that the size of the da | SESSION_SUCCESSFUL7+ | number | Yes| No| Successful download.| -## request.upload +## request.uploadFile9+ -upload(config: UploadConfig): Promise<UploadTask> +uploadFile(context: BaseContext, config: UploadConfig): Promise<UploadTask> Uploads files. This API uses a promise to return the result. -This API can be used only in the FA model. - -> **NOTE**
This API is deprecated since API version 9. You are advised to use [request.uploadFile9+](#requestuploadfile9). - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| +| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| + **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[UploadTask](#uploadtask)> | Promise used to return the **UploadTask** object.| +| Type| Description| +| -------- | -------- | +| Promise<[UploadTask](#uploadtask)> | Promise used to return the **UploadTask** object.| + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400002 | Bad file path. | **Example** - + ```js let uploadTask; let uploadConfig = { - url: 'https://patch', + url: 'http://patch', header: { key1: "value1", key2: "value2" }, method: "POST", files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], data: [{ name: "name123", value: "123" }], }; - request.upload(uploadConfig).then((data) => { + request.uploadFile(globalThis.abilityContext, uploadConfig).then((data) => { uploadTask = data; }).catch((err) => { console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); - }) + }); ``` -## request.upload +## request.uploadFile9+ -upload(config: UploadConfig, callback: AsyncCallback<UploadTask>): void +uploadFile(context: BaseContext, config: UploadConfig, callback: AsyncCallback<UploadTask>): void Uploads files. This API uses an asynchronous callback to return the result. -This API can be used only in the FA model. - -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [request.uploadFile9+](#requestuploadfile9-1). - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| - | callback | AsyncCallback<[UploadTask](#uploadtask)> | Yes| Callback used to return the **UploadTask** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| +| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| +| callback | AsyncCallback<[UploadTask](#uploadtask)> | Yes| Callback used to return the **UploadTask** object.| + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400002 | Bad file path. | **Example** - + ```js let uploadTask; let uploadConfig = { - url: 'https://patch', + url: 'http://patch', header: { key1: "value1", key2: "value2" }, method: "POST", files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], data: [{ name: "name123", value: "123" }], }; - request.upload(uploadConfig, (err, data) => { + request.uploadFile(globalThis.abilityContext, uploadConfig, (err, data) => { if (err) { console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); return; @@ -156,15 +164,18 @@ This API can be used only in the FA model. uploadTask = data; }); ``` -## request.upload9+ -upload(context: BaseContext, config: UploadConfig): Promise<UploadTask> +## request.upload(deprecated) + +upload(config: UploadConfig): Promise<UploadTask> Uploads files. This API uses a promise to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [request.uploadFile9+](#requestuploadfile9). +**Model restriction**: This API can be used only in the FA model. + +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [request.uploadFile9+](#requestuploadfile9). **Required permissions**: ohos.permission.INTERNET @@ -172,46 +183,46 @@ Uploads files. This API uses a promise to return the result. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | BaseContext | Yes| Application-based context.| - | config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| - +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[UploadTask](#uploadtask)> | Promise used to return the **UploadTask** object.| +| Type| Description| +| -------- | -------- | +| Promise<[UploadTask](#uploadtask)> | Promise used to return the **UploadTask** object.| **Example** - + ```js let uploadTask; let uploadConfig = { - url: 'https://patch', + url: 'http://patch', header: { key1: "value1", key2: "value2" }, method: "POST", files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], data: [{ name: "name123", value: "123" }], }; - request.upload(globalThis.abilityContext, uploadConfig).then((data) => { + request.upload(uploadConfig).then((data) => { uploadTask = data; }).catch((err) => { console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); - }); + }) ``` -## request.upload9+ +## request.upload(deprecated) -upload(context: BaseContext, config: UploadConfig, callback: AsyncCallback<UploadTask>): void +upload(config: UploadConfig, callback: AsyncCallback<UploadTask>): void Uploads files. This API uses an asynchronous callback to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [request.uploadFile9+](#requestuploadfile9-1). +**Model restriction**: This API can be used only in the FA model. + +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [request.uploadFile9+](#requestuploadfile9-1). **Required permissions**: ohos.permission.INTERNET @@ -219,24 +230,23 @@ Uploads files. This API uses an asynchronous callback to return the result. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | BaseContext | Yes| Application-based context.| - | config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| - | callback | AsyncCallback<[UploadTask](#uploadtask)> | Yes| Callback used to return the **UploadTask** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| +| callback | AsyncCallback<[UploadTask](#uploadtask)> | Yes| Callback used to return the **UploadTask** object.| **Example** - + ```js let uploadTask; let uploadConfig = { - url: 'https://patch', + url: 'http://patch', header: { key1: "value1", key2: "value2" }, method: "POST", files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], data: [{ name: "name123", value: "123" }], }; - request.upload(globalThis.abilityContext, uploadConfig, (err, data) => { + request.upload(uploadConfig, (err, data) => { if (err) { console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); return; @@ -245,13 +255,16 @@ Uploads files. This API uses an asynchronous callback to return the result. }); ``` +## request.upload(deprecated) -## request.uploadFile9+ - -uploadFile(context: BaseContext, config: UploadConfig): Promise<UploadTask> +upload(context: BaseContext, config: UploadConfig): Promise<UploadTask> Uploads files. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 9 and is deprecated since API version 9. You are advised to use [request.uploadFile9+](#requestuploadfile9). + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload @@ -259,36 +272,29 @@ Uploads files. This API uses a promise to return the result. **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | -| context | BaseContext | Yes| Application-based context.| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| | config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| **Return value** | Type| Description| - | -------- | -------- | -| Promise<[UploadTask](#uploadtask)> | Promise used to return the **UploadTask** object.| - -**Error codes** -For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). - -| ID| Error Message| | -------- | -------- | -| 13400002 | Bad file path. | +| Promise<[UploadTask](#uploadtask)> | Promise used to return the **UploadTask** object.| **Example** ```js let uploadTask; let uploadConfig = { - url: 'https://patch', + url: 'http://patch', header: { key1: "value1", key2: "value2" }, method: "POST", files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], data: [{ name: "name123", value: "123" }], }; - request.uploadFile(globalThis.abilityContext, uploadConfig).then((data) => { + request.upload(globalThis.abilityContext, uploadConfig).then((data) => { uploadTask = data; }).catch((err) => { console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); @@ -296,12 +302,16 @@ For details about the error codes, see [Upload and Download Error Codes](../erro ``` -## request.uploadFile9+ +## request.upload(deprecated) -uploadFile(context: BaseContext, config: UploadConfig, callback: AsyncCallback<UploadTask>): void +upload(context: BaseContext, config: UploadConfig, callback: AsyncCallback<UploadTask>): void Uploads files. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [request.uploadFile9+](#requestuploadfile9-1). + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload @@ -309,30 +319,23 @@ Uploads files. This API uses an asynchronous callback to return the result. **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | -| context | BaseContext | Yes| Application-based context.| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| | config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| | callback | AsyncCallback<[UploadTask](#uploadtask)> | Yes| Callback used to return the **UploadTask** object.| -**Error codes** -For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). - -| ID| Error Message| -| -------- | -------- | -| 13400002 | Bad file path. | - **Example** ```js let uploadTask; let uploadConfig = { - url: 'https://patch', + url: 'http://patch', header: { key1: "value1", key2: "value2" }, method: "POST", files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], data: [{ name: "name123", value: "123" }], }; - request.uploadFile(globalThis.abilityContext, uploadConfig, (err, data) => { + request.upload(globalThis.abilityContext, uploadConfig, (err, data) => { if (err) { console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); return; @@ -341,10 +344,10 @@ For details about the error codes, see [Upload and Download Error Codes](../erro }); ``` - ## UploadTask -Implements file uploads. Before using any APIs of this class, you must obtain an **UploadTask** object. +Implements file uploads. Before using any APIs of this class, you must obtain an **UploadTask** object through [request.uploadFile9+](#requestuploadfile9) in promise mode or [request.uploadFile9+](#requestuploadfile9-1) in callback mode. + ### on('progress') @@ -359,10 +362,10 @@ Subscribes to an upload event. This API uses an asynchronous callback to return **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (upload progress).| - | callback | function | Yes| Callback for the upload progress event.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (upload progress).| +| callback | function | Yes| Callback for the upload progress event.| Parameters of the callback function @@ -372,9 +375,8 @@ Subscribes to an upload event. This API uses an asynchronous callback to return | totalSize | number | Yes| Total size of the files to upload, in KB.| **Example** - + ```js - let uploadTask; uploadTask.on('progress', function callback(uploadedSize, totalSize) { console.info("upload totalSize:" + totalSize + " uploadedSize:" + uploadedSize); } @@ -394,10 +396,10 @@ Subscribes to an upload event. This API uses an asynchronous callback to return **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to subscribe to. The value is **'headerReceive'** (response header).| - | callback | function | Yes| Callback for the HTTP Response Header event.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value is **'headerReceive'** (response header).| +| callback | function | Yes| Callback for the HTTP Response Header event.| Parameters of the callback function @@ -406,9 +408,8 @@ Subscribes to an upload event. This API uses an asynchronous callback to return | header | object | Yes| HTTP Response Header.| **Example** - + ```js - let uploadTask; uploadTask.on('headerReceive', function callback(headers){ console.info("upOnHeader headers:" + JSON.stringify(headers)); } @@ -428,10 +429,10 @@ Subscribes to an upload event. This API uses an asynchronous callback to return **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to subscribe to. The value **'complete'** means the upload completion event, and **'fail'** means the upload failure event.| - | callback | Callback<Array<TaskState>> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value **'complete'** means the upload completion event, and **'fail'** means the upload failure event.| +| callback | Callback<Array<TaskState>> | Yes| Callback used to return the result.| Parameters of the callback function @@ -440,9 +441,8 @@ Subscribes to an upload event. This API uses an asynchronous callback to return | taskstates | Array<[TaskState](#taskstate9)> | Yes| Upload result.| **Example** - + ```js - let uploadTask; uploadTask.on('complete', function callback(taskStates) { for (let i = 0; i < taskStates.length; i++ ) { console.info("upOnComplete taskState:" + JSON.stringify(taskStates[i])); @@ -471,10 +471,10 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (upload progress).| - | callback | function | No| Callback for the upload progress event.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (upload progress).| +| callback | function | No| Callback for the upload progress event.| Parameters of the callback function @@ -484,9 +484,8 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret | totalSize | number | Yes| Total size of the files to upload, in KB.| **Example** - + ```js - let uploadTask; uploadTask.off('progress', function callback(uploadedSize, totalSize) { console.info('uploadedSize: ' + uploadedSize, 'totalSize: ' + totalSize); } @@ -506,10 +505,10 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to unsubscribe from. The value is **'headerReceive'** (response header).| - | callback | function | No| Callback for the HTTP Response Header event.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to unsubscribe from. The value is **'headerReceive'** (response header).| +| callback | function | No| Callback for the HTTP Response Header event.| Parameters of the callback function @@ -518,9 +517,8 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret | header | object | Yes| HTTP Response Header.| **Example** - + ```js - let uploadTask; uploadTask.off('headerReceive', function callback(headers) { console.info("upOnHeader headers:" + JSON.stringify(headers)); } @@ -539,10 +537,10 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to subscribe to. The value **'complete'** means the upload completion event, and **'fail'** means the upload failure event.| - | callback | Callback<Array<TaskState>> | No| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value **'complete'** means the upload completion event, and **'fail'** means the upload failure event.| +| callback | Callback<Array<TaskState>> | No| Callback used to return the result.| Parameters of the callback function @@ -551,9 +549,8 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret | taskstates | Array<[TaskState](#taskstate9)> | Yes| Upload result.| **Example** - + ```js - let uploadTask; uploadTask.off('complete', function callback(taskStates) { for (let i = 0; i < taskStates.length; i++ ) { console.info("upOnComplete taskState:" + JSON.stringify(taskStates[i])); @@ -569,16 +566,10 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret ); ``` +### delete9+ +delete(): Promise<boolean> -### remove - -remove(): Promise<boolean> - -Removes this upload task. This API uses a promise to return the result. - -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [delete9+](#delete9). +Deletes this upload task. This API uses a promise to return the result. **Required permissions**: ohos.permission.INTERNET @@ -586,15 +577,14 @@ Removes this upload task. This API uses a promise to return the result. **Return value** - | Type| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the result. It returns **true** if the operation is successful and returns **false** otherwise.| +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the task removal result. It returns **true** if the operation is successful and returns **false** otherwise.| **Example** - + ```js - let uploadTask; - uploadTask.remove().then((result) => { + uploadTask.delete().then((result) => { if (result) { console.info('Upload task removed successfully. '); } else { @@ -606,31 +596,26 @@ Removes this upload task. This API uses a promise to return the result. ``` -### remove +### delete9+ -remove(callback: AsyncCallback<boolean>): void +delete(callback: AsyncCallback<boolean>): void Removes this upload task. This API uses an asynchronous callback to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [delete9+](#delete9-1). - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| **Example** - + ```js - let uploadTask; - uploadTask.remove((err, result) => { + uploadTask.delete((err, result) => { if (err) { console.error('Failed to remove the upload task. Cause: ' + JSON.stringify(err)); return; @@ -644,11 +629,15 @@ Removes this upload task. This API uses an asynchronous callback to return the r ``` -### delete9+ +### remove(deprecated) -delete(): Promise<boolean> +remove(): Promise<boolean> -Deletes this upload task. This API uses a promise to return the result. +Removes this upload task. This API uses a promise to return the result. + +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [delete9+](#delete9). **Required permissions**: ohos.permission.INTERNET @@ -657,14 +646,13 @@ Deletes this upload task. This API uses a promise to return the result. **Return value** | Type| Description| - | -------- | -------- | -| Promise<boolean> | Promise used to return the task deletion result. It returns **true** if the operation is successful and returns **false** otherwise.| +| -------- | -------- | +| Promise<boolean> | Promise used to return the task removal result. It returns **true** if the operation is successful and returns **false** otherwise.| **Example** ```js - let uploadTask; - uploadTask.delete().then((result) => { + uploadTask.remove().then((result) => { if (result) { console.info('Upload task removed successfully. '); } else { @@ -676,11 +664,15 @@ Deletes this upload task. This API uses a promise to return the result. ``` -### delete9+ +### remove(deprecated) -delete(callback: AsyncCallback<boolean>): void +remove(callback: AsyncCallback<boolean>): void + +Removes this upload task. This API uses an asynchronous callback to return the result. -Deletes this upload task. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [delete9+](#delete9-1). **Required permissions**: ohos.permission.INTERNET @@ -689,14 +681,13 @@ Deletes this upload task. This API uses an asynchronous callback to return the r **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | +| -------- | -------- | -------- | -------- | | callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| **Example** ```js - let uploadTask; - uploadTask.delete((err, result) => { + uploadTask.remove((err, result) => { if (err) { console.error('Failed to remove the upload task. Cause: ' + JSON.stringify(err)); return; @@ -709,7 +700,6 @@ Deletes this upload task. This API uses an asynchronous callback to return the r }); ``` - ## UploadConfig **Required permissions**: ohos.permission.INTERNET @@ -746,7 +736,7 @@ Deletes this upload task. This API uses an asynchronous callback to return the r | -------- | -------- | -------- | -------- | | filename | string | Yes| File name in the header when **multipart** is used.| | name | string | Yes| Name of a form item when **multipart** is used. The default value is **file**.| -| uri | string | Yes| Local path for storing files.
The **dataability** and **internal** protocol types are supported. However, the **internal** protocol type supports only temporary directories. Below are examples:
dataability:///com.domainname.dataability.persondata/person/10/file.txt
internal://cache/path/to/file.txt | +| uri | string | Yes| Local path for storing files.
The **dataability** and **internal** protocol types are supported. However, the **internal** protocol type supports only temporary directories. Below are examples:
dataability:///com.domainname.dataability.persondata/person/10/file.txt

internal://cache/path/to/file.txt | | type | string | Yes| Type of the file content. By default, the type is obtained based on the extension of the file name or URI.| @@ -761,40 +751,43 @@ Deletes this upload task. This API uses an asynchronous callback to return the r | name | string | Yes| Name of a form element.| | value | string | Yes| Value of a form element.| +## request.downloadFile9+ -## request.download - -download(config: DownloadConfig): Promise<DownloadTask> +downloadFile(context: BaseContext, config: DownloadConfig): Promise<DownloadTask> Downloads files. This API uses a promise to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [request.downloadFile9+](#requestdownloadfile9). - -This API can be used only in the FA model. - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| +| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[DownloadTask](#downloadtask)> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<[DownloadTask](#downloadtask)> | Promise used to return the result.| + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400001 | File operation error. | +| 13400002 | Bad file path. | +| 13400003 | Task manager service error. | **Example** - + ```js let downloadTask; - request.download({ url: 'https://xxxx/xxxx.hap' }).then((data) => { + request.downloadFile(globalThis.abilityContext, { url: 'https://xxxx/xxxx.hap' }).then((data) => { downloadTask = data; }).catch((err) => { console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); @@ -802,34 +795,38 @@ This API can be used only in the FA model. ``` -## request.download +## request.downloadFile9+ -download(config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void +downloadFile(context: BaseContext, config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void; Downloads files. This API uses an asynchronous callback to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [request.downloadFile9+](#requestdownloadfile9-1). - -This API can be used only in the FA model. - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| - | callback | AsyncCallback<[DownloadTask](#downloadtask)> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| +| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| +| callback | AsyncCallback<[DownloadTask](#downloadtask)> | Yes| Callback used to return the result.| + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400001 | File operation error. | +| 13400002 | Bad file path. | +| 13400003 | Task manager service error. | **Example** - + ```js let downloadTask; - request.download({ url: 'https://xxxx/xxxxx.hap', + request.downloadFile(globalThis.abilityContext, { url: 'https://xxxx/xxxxx.hap', filePath: 'xxx/xxxxx.hap'}, (err, data) => { if (err) { console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); @@ -839,15 +836,17 @@ This API can be used only in the FA model. }); ``` -## request.download9+ +## request.download(deprecated) -download(context: BaseContext, config: DownloadConfig): Promise<DownloadTask> +download(config: DownloadConfig): Promise<DownloadTask> Downloads files. This API uses a promise to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [request.downloadFile9+](#requestdownloadfile9). +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [request.downloadFile9+](#requestdownloadfile9). + +**Model restriction**: This API can be used only in the FA model. **Required permissions**: ohos.permission.INTERNET @@ -855,22 +854,21 @@ Downloads files. This API uses a promise to return the result. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | BaseContext | Yes| Application-based context.| - | config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[DownloadTask](#downloadtask)> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<[DownloadTask](#downloadtask)> | Promise used to return the result.| **Example** - + ```js let downloadTask; - request.download(globalThis.abilityContext, { url: 'https://xxxx/xxxx.hap' }).then((data) => { + request.download({ url: 'https://xxxx/xxxx.hap' }).then((data) => { downloadTask = data; }).catch((err) => { console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); @@ -878,15 +876,17 @@ Downloads files. This API uses a promise to return the result. ``` -## request.download9+ +## request.download(deprecated) -download(context: BaseContext, config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void; +download(config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void Downloads files. This API uses an asynchronous callback to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [request.downloadFile9+](#requestdownloadfile9-1). +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [request.downloadFile9+](#requestdownloadfile9-1). + +**Model restriction**: This API can be used only in the FA model. **Required permissions**: ohos.permission.INTERNET @@ -894,17 +894,16 @@ Downloads files. This API uses an asynchronous callback to return the result. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | BaseContext | Yes| Application-based context.| - | config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| - | callback | AsyncCallback<[DownloadTask](#downloadtask)> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| +| callback | AsyncCallback<[DownloadTask](#downloadtask)> | Yes| Callback used to return the result.| **Example** - + ```js let downloadTask; - request.download(globalThis.abilityContext, { url: 'https://xxxx/xxxxx.hap', + request.download({ url: 'https://xxxx/xxxxx.hap', filePath: 'xxx/xxxxx.hap'}, (err, data) => { if (err) { console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); @@ -914,13 +913,16 @@ Downloads files. This API uses an asynchronous callback to return the result. }); ``` +## request.download(deprecated) -## request.downloadFile9+ - -downloadFile(context: BaseContext, config: DownloadConfig): Promise<DownloadTask> +download(context: BaseContext, config: DownloadConfig): Promise<DownloadTask> Downloads files. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 9 and is deprecated since API version 9. You are advised to use [request.downloadFile9+](#requestdownloadfile9). + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -928,30 +930,21 @@ Downloads files. This API uses a promise to return the result. **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | -| context | BaseContext | Yes| Application-based context.| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| | config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| **Return value** | Type| Description| - | -------- | -------- | -| Promise<[DownloadTask](#downloadtask)> | Promise used to return the result.| - -**Error codes** -For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). - -| ID| Error Message| | -------- | -------- | -| 13400001 | File operation error. | -| 13400002 | Bad file path. | -| 13400003 | Task manager service error. | +| Promise<[DownloadTask](#downloadtask)> | Promise used to return the result.| **Example** ```js let downloadTask; - request.downloadFile(globalThis.abilityContext, { url: 'https://xxxx/xxxx.hap' }).then((data) => { + request.download(globalThis.abilityContext, { url: 'https://xxxx/xxxx.hap' }).then((data) => { downloadTask = data; }).catch((err) => { console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); @@ -959,12 +952,16 @@ For details about the error codes, see [Upload and Download Error Codes](../erro ``` -## request.downloadFile9+ +## request.download(deprecated) -downloadFile(context: BaseContext, config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void; +download(context: BaseContext, config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void; Downloads files. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [request.downloadFile9+](#requestdownloadfile9-1). + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -972,25 +969,16 @@ Downloads files. This API uses an asynchronous callback to return the result. **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | -| context | BaseContext | Yes| Application-based context.| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| | config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| | callback | AsyncCallback<[DownloadTask](#downloadtask)> | Yes| Callback used to return the result.| -**Error codes** -For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). - -| ID| Error Message| -| -------- | -------- | -| 13400001 | File operation error. | -| 13400002 | Bad file path. | -| 13400003 | Task manager service error. | - **Example** ```js let downloadTask; - request.downloadFile(globalThis.abilityContext, { url: 'https://xxxx/xxxxx.hap', + request.download(globalThis.abilityContext, { url: 'https://xxxx/xxxxx.hap', filePath: 'xxx/xxxxx.hap'}, (err, data) => { if (err) { console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); @@ -1003,7 +991,7 @@ For details about the error codes, see [Upload and Download Error Codes](../erro ## DownloadTask -Implements file downloads. +Implements file downloads. Before using any APIs of this class, you must obtain a **DownloadTask** object through [request.downloadFile9+](#requestdownloadfile9) in promise mode or [request.downloadFile9+](#requestdownloadfile9-1) in callback mode. ### on('progress') @@ -1018,10 +1006,10 @@ Subscribes to a download event. This API uses an asynchronous callback to return **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (download progress).| - | callback | function | Yes| Callback for the download progress event.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (download progress).| +| callback | function | Yes| Callback for the download progress event.| Parameters of the callback function @@ -1031,9 +1019,8 @@ Subscribes to a download event. This API uses an asynchronous callback to return | totalSize | number | Yes| Total size of the files to download, in KB.| **Example** - + ```js - let downloadTask; downloadTask.on('progress', function download_callback(receivedSize, totalSize) { console.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize); } @@ -1053,10 +1040,10 @@ Unsubscribes from a download event. This API uses an asynchronous callback to re **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (download progress).| - | callback | function | No| Callback for the download progress event.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (download progress).| +| callback | function | No| Callback for the download progress event.| Parameters of the callback function @@ -1066,7 +1053,7 @@ Unsubscribes from a download event. This API uses an asynchronous callback to re | totalSize | number | Yes| Total size of the files to download.| **Example** - + ```js downloadTask .off('progress', function download_callback(receivedSize, totalSize) { console.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize); @@ -1087,15 +1074,14 @@ Subscribes to a download event. This API uses an asynchronous callback to return **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to subscribe to.
- **'complete'**: download task completion event.
- **'pause'**: download task pause event.
- **'remove'**: download task removal event.| - | callback | function | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to.
- **'complete'**: download task completion event.
- **'pause'**: download task pause event.
- **'remove'**: download task removal event.| +| callback | function | Yes| Callback used to return the result.| **Example** - + ```js - let downloadTask; downloadTask.on('complete', function callback() { console.info('Download task completed.'); } @@ -1115,15 +1101,14 @@ Unsubscribes from a download event. This API uses an asynchronous callback to re **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to unsubscribe from.
- **'complete'**: download task completion event.
- **'pause'**: download task pause event.
- **'remove'**: download task removal event.| - | callback | function | No| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to unsubscribe from.
- **'complete'**: download task completion event.
- **'pause'**: download task pause event.
- **'remove'**: download task removal event.| +| callback | function | No| Callback used to return the result.| **Example** - + ```js - let downloadTask; downloadTask.off('complete', function callback() { console.info('Download task completed.'); } @@ -1143,10 +1128,10 @@ Subscribes to the download task failure event. This API uses an asynchronous cal **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to subscribe to. The value is **'fail'** (download failure).| - | callback | function | Yes| Callback for the download task failure event.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value is **'fail'** (download failure).| +| callback | function | Yes| Callback for the download task failure event.| Parameters of the callback function @@ -1155,9 +1140,8 @@ Subscribes to the download task failure event. This API uses an asynchronous cal | err | number | Yes| Error code of the download failure. For details about the error codes, see [ERROR_*](#constants).| **Example** - + ```js - let downloadTask; downloadTask.on('fail', function callBack(err) { console.info('Download task failed. Cause:' + err); } @@ -1177,10 +1161,10 @@ Unsubscribes from the download task failure event. This API uses an asynchronous **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to unsubscribe from. The value is **'fail'** (download failure).| - | callback | function | No| Callback for the download task failure event.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to unsubscribe from. The value is **'fail'** (download failure).| +| callback | function | No| Callback for the download task failure event.| Parameters of the callback function @@ -1189,41 +1173,34 @@ Unsubscribes from the download task failure event. This API uses an asynchronous | err | number | Yes| Error code of the download failure. For details about the error codes, see [ERROR_*](#constants).| **Example** - + ```js - let downloadTask; downloadTask.off('fail', function callBack(err) { console.info('Download task failed. Cause:' + err); } ); ``` + ### delete9+ -### remove - -remove(): Promise<boolean> +delete(): Promise<boolean> Removes this download task. This API uses a promise to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [delete9+](#delete9-2). - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download **Return value** - | Type| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the task removal result.| +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the task removal result.| **Example** - + ```js - let downloadTask; - downloadTask.remove().then((result) => { + downloadTask.delete().then((result) => { if (result) { console.info('Download task removed.'); } else { @@ -1235,31 +1212,26 @@ Removes this download task. This API uses a promise to return the result. ``` -### remove +### delete9+ -remove(callback: AsyncCallback<boolean>): void +delete(callback: AsyncCallback<boolean>): void Removes this download task. This API uses an asynchronous callback to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [delete9+](#delete9-3). - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes| Callback used to return the task removal result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the task removal result.| **Example** - + ```js - let downloadTask; - downloadTask.remove((err, result)=>{ + downloadTask.delete((err, result)=>{ if(err) { console.error('Failed to remove the download task.'); return; @@ -1273,31 +1245,26 @@ Removes this download task. This API uses an asynchronous callback to return the ``` -### query7+ +### getTaskInfo9+ -query(): Promise<DownloadInfo> +getTaskInfo(): Promise<DownloadInfo> Queries this download task. This API uses a promise to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getTaskInfo9+](#gettaskinfo9). - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[DownloadInfo](#downloadinfo7)> | Promise used to return the download task information.| +| Type| Description| +| -------- | -------- | +| Promise<[DownloadInfo](#downloadinfo7)> | Promise used to return the download task information.| **Example** - + ```js - let downloadTask; - downloadTask.query().then((downloadInfo) => { + downloadTask.getTaskInfo().then((downloadInfo) => { console.info('Download task queried. Data:' + JSON.stringify(downloadInfo)) }) .catch((err) => { console.error('Failed to query the download task. Cause:' + err) @@ -1305,31 +1272,26 @@ Queries this download task. This API uses a promise to return the result. ``` -### query7+ +### getTaskInfo9+ -query(callback: AsyncCallback<DownloadInfo>): void +getTaskInfo(callback: AsyncCallback<DownloadInfo>): void Queries this download task. This API uses an asynchronous callback to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getTaskInfo9+](#gettaskinfo9-1). - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[DownloadInfo](#downloadinfo7)> | Yes| Callback used to return the download task information.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[DownloadInfo](#downloadinfo7)> | Yes| Callback used to return the download task information.| **Example** - + ```js - let downloadTask; - downloadTask.query((err, downloadInfo)=>{ + downloadTask.getTaskInfo((err, downloadInfo)=>{ if(err) { console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err)); } else { @@ -1339,15 +1301,11 @@ Queries this download task. This API uses an asynchronous callback to return the ``` -### queryMimeType7+ - -queryMimeType(): Promise<string> +### getTaskMimeType9+ -Queries the **MimeType** of this download task. This API uses a promise to return the result. +getTaskMimeType(): Promise<string> -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getTaskMimeType9+](#gettaskmimetype9). +Obtains the **MimeType** of this download task. This API uses a promise to return the result. **Required permissions**: ohos.permission.INTERNET @@ -1355,15 +1313,14 @@ Queries the **MimeType** of this download task. This API uses a promise to retur **Return value** - | Type| Description| - | -------- | -------- | - | Promise<string> | Promise used to return the **MimeType** of the download task.| +| Type| Description| +| -------- | -------- | +| Promise<string> | Promise used to return the **MimeType** of the download task.| **Example** - + ```js - let downloadTask; - downloadTask.queryMimeType().then((data) => { + downloadTask.getTaskMimeType().then((data) => { console.info('Download task queried. Data:' + JSON.stringify(data)); }).catch((err) => { console.error('Failed to query the download MimeType. Cause:' + JSON.stringify(err)) @@ -1371,15 +1328,11 @@ Queries the **MimeType** of this download task. This API uses a promise to retur ``` -### queryMimeType7+ - -queryMimeType(callback: AsyncCallback<string>): void; +### getTaskMimeType9+ -Queries the **MimeType** of this download task. This API uses an asynchronous callback to return the result. +getTaskMimeType(callback: AsyncCallback<string>): void; -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getTaskMimeType9+](#gettaskmimetype9-1). +Obtains the **MimeType** of this download task. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.INTERNET @@ -1387,15 +1340,14 @@ Queries the **MimeType** of this download task. This API uses an asynchronous ca **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<string> | Yes| Callback used to return the **MimeType** of the download task.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<string> | Yes| Callback used to return the **MimeType** of the download task.| **Example** - + ```js - let downloadTask; - downloadTask.queryMimeType((err, data)=>{ + downloadTask.getTaskMimeType((err, data)=>{ if(err) { console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err)); } else { @@ -1405,31 +1357,26 @@ Queries the **MimeType** of this download task. This API uses an asynchronous ca ``` -### pause7+ +### suspend9+ -pause(): Promise<void> +suspend(): Promise<boolean> Pauses this download task. This API uses a promise to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [suspend9+](#suspend9). - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the download task pause result.| +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the download task pause result.| **Example** - + ```js - let downloadTask; - downloadTask.pause().then((result) => { + downloadTask.suspend().then((result) => { if (result) { console.info('Download task paused. '); } else { @@ -1441,13 +1388,9 @@ Pauses this download task. This API uses a promise to return the result. ``` -### pause7+ - -pause(callback: AsyncCallback<void>): void +### suspend9+ -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [suspend9+](#suspend9-1). +suspend(callback: AsyncCallback<boolean>): void Pauses this download task. This API uses an asynchronous callback to return the result. @@ -1457,15 +1400,14 @@ Pauses this download task. This API uses an asynchronous callback to return the **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| **Example** - + ```js - let downloadTask; - downloadTask.pause((err, result)=>{ + downloadTask.suspend((err, result)=>{ if(err) { console.error('Failed to pause the download task. Cause:' + JSON.stringify(err)); return; @@ -1479,31 +1421,26 @@ Pauses this download task. This API uses an asynchronous callback to return the ``` -### resume7+ +### restore9+ -resume(): Promise<void> +restore(): Promise<boolean> Resumes this download task. This API uses a promise to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [restore9+](#restore9). - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the result.| **Example** - + ```js - let downloadTask; - downloadTask.resume().then((result) => { + downloadTask.restore().then((result) => { if (result) { console.info('Download task resumed.') } else { @@ -1516,13 +1453,9 @@ Resumes this download task. This API uses a promise to return the result. ``` -### resume7+ - -resume(callback: AsyncCallback<void>): void +### restore9+ -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [restore9+](#restore9-1). +restore(callback: AsyncCallback<boolean>): void Resumes this download task. This API uses an asynchronous callback to return the result. @@ -1532,15 +1465,14 @@ Resumes this download task. This API uses an asynchronous callback to return the **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| **Example** - + ```js - let downloadTask; - downloadTask.resume((err, result)=>{ + downloadTask.restore((err, result)=>{ if (err) { console.error('Failed to resume the download task. Cause:' + err); return; @@ -1554,11 +1486,16 @@ Resumes this download task. This API uses an asynchronous callback to return the ``` -### delete9+ -delete(): Promise<boolean> +### remove(deprecated) -Deletes this download task. This API uses a promise to return the result. +remove(): Promise<boolean> + +Removes this download task. This API uses a promise to return the result. + +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [delete9+](#delete9-2). **Required permissions**: ohos.permission.INTERNET @@ -1567,14 +1504,13 @@ Deletes this download task. This API uses a promise to return the result. **Return value** | Type| Description| - | -------- | -------- | -| Promise<boolean> | Promise used to return the result.| +| -------- | -------- | +| Promise<boolean> | Promise used to return the task removal result.| **Example** ```js - let downloadTask; - downloadTask.delete().then((result) => { + downloadTask.remove().then((result) => { if (result) { console.info('Download task removed.'); } else { @@ -1586,11 +1522,15 @@ Deletes this download task. This API uses a promise to return the result. ``` -### delete9+ +### remove(deprecated) -delete(callback: AsyncCallback<boolean>): void +remove(callback: AsyncCallback<boolean>): void -Deletes this download task. This API uses an asynchronous callback to return the result. +Removes this download task. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [delete9+](#delete9-3). **Required permissions**: ohos.permission.INTERNET @@ -1599,14 +1539,13 @@ Deletes this download task. This API uses an asynchronous callback to return the **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the task removal result.| **Example** ```js - let downloadTask; - downloadTask.delete((err, result)=>{ + downloadTask.remove((err, result)=>{ if(err) { console.error('Failed to remove the download task.'); return; @@ -1620,12 +1559,16 @@ Deletes this download task. This API uses an asynchronous callback to return the ``` -### getTaskInfo9+ +### query(deprecated) -getTaskInfo(): Promise<DownloadInfo> +query(): Promise<DownloadInfo> Queries this download task. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [getTaskInfo9+](#gettaskinfo9). + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -1639,8 +1582,7 @@ Queries this download task. This API uses a promise to return the result. **Example** ```js - let downloadTask; - downloadTask.getTaskInfo().then((downloadInfo) => { + downloadTask.query().then((downloadInfo) => { console.info('Download task queried. Data:' + JSON.stringify(downloadInfo)) }) .catch((err) => { console.error('Failed to query the download task. Cause:' + err) @@ -1648,12 +1590,16 @@ Queries this download task. This API uses a promise to return the result. ``` -### getTaskInfo9+ +### query(deprecated) query(callback: AsyncCallback<DownloadInfo>): void Queries this download task. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [getTaskInfo9+](#gettaskinfo9-1). + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -1661,14 +1607,13 @@ Queries this download task. This API uses an asynchronous callback to return the **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | +| -------- | -------- | -------- | -------- | | callback | AsyncCallback<[DownloadInfo](#downloadinfo7)> | Yes| Callback used to return the download task information.| **Example** ```js - let downloadTask; - downloadTask.getTaskInfo((err, downloadInfo)=>{ + downloadTask.query((err, downloadInfo)=>{ if(err) { console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err)); } else { @@ -1678,11 +1623,15 @@ Queries this download task. This API uses an asynchronous callback to return the ``` -### getTaskMimeType9+ +### queryMimeType(deprecated) -getTaskMimeType(): Promise<string> +queryMimeType(): Promise<string> -Obtains the **MimeType** of this download task. This API uses a promise to return the result. +Queries the **MimeType** of this download task. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [getTaskMimeType9+](#gettaskmimetype9). **Required permissions**: ohos.permission.INTERNET @@ -1691,14 +1640,13 @@ Obtains the **MimeType** of this download task. This API uses a promise to retur **Return value** | Type| Description| - | -------- | -------- | +| -------- | -------- | | Promise<string> | Promise used to return the **MimeType** of the download task.| **Example** ```js - let downloadTask; - downloadTask.getTaskMimeType().then((data) => { + downloadTask.queryMimeType().then((data) => { console.info('Download task queried. Data:' + JSON.stringify(data)); }).catch((err) => { console.error('Failed to query the download MimeType. Cause:' + JSON.stringify(err)) @@ -1706,11 +1654,15 @@ Obtains the **MimeType** of this download task. This API uses a promise to retur ``` -### getTaskMimeType9+ +### queryMimeType(deprecated) -getTaskMimeType(callback: AsyncCallback<string>): void; +queryMimeType(callback: AsyncCallback<string>): void; -Obtains the **MimeType** of this download task. This API uses an asynchronous callback to return the result. +Queries the **MimeType** of this download task. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [getTaskMimeType9+](#gettaskmimetype9-1). **Required permissions**: ohos.permission.INTERNET @@ -1719,14 +1671,13 @@ Obtains the **MimeType** of this download task. This API uses an asynchronous ca **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | +| -------- | -------- | -------- | -------- | | callback | AsyncCallback<string> | Yes| Callback used to return the **MimeType** of the download task.| **Example** ```js - let downloadTask; - downloadTask.getTaskMimeType((err, data)=>{ + downloadTask.queryMimeType((err, data)=>{ if(err) { console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err)); } else { @@ -1736,12 +1687,16 @@ Obtains the **MimeType** of this download task. This API uses an asynchronous ca ``` -### suspend9+ +### pause(deprecated) -suspend(): Promise<boolean> +pause(): Promise<void> Pauses this download task. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [suspend9+](#suspend9). + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -1749,14 +1704,13 @@ Pauses this download task. This API uses a promise to return the result. **Return value** | Type| Description| - | -------- | -------- | -| Promise<boolean> | Promise used to return the download task pause result.| +| -------- | -------- | +| Promise<void> | Promise used to return the download task pause result.| **Example** ```js - let downloadTask; - downloadTask.suspend().then((result) => { + downloadTask.pause().then((result) => { if (result) { console.info('Download task paused. '); } else { @@ -1768,9 +1722,13 @@ Pauses this download task. This API uses a promise to return the result. ``` -### suspend9+ +### pause(deprecated) -suspend(callback: AsyncCallback<boolean>): void +pause(callback: AsyncCallback<void>): void + +> **NOTE** +> +> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [suspend9+](#suspend9-1). Pauses this download task. This API uses an asynchronous callback to return the result. @@ -1781,14 +1739,13 @@ Pauses this download task. This API uses an asynchronous callback to return the **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** ```js - let downloadTask; - downloadTask.suspend((err, result)=>{ + downloadTask.pause((err, result)=>{ if(err) { console.error('Failed to pause the download task. Cause:' + JSON.stringify(err)); return; @@ -1802,12 +1759,16 @@ Pauses this download task. This API uses an asynchronous callback to return the ``` -### restore9+ +### resume(deprecated) -restore(): Promise<boolean> +resume(): Promise<void> Resumes this download task. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [restore9+](#restore9). + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -1815,14 +1776,13 @@ Resumes this download task. This API uses a promise to return the result. **Return value** | Type| Description| - | -------- | -------- | -| Promise<boolean> | Promise used to return the result.| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Example** ```js - let downloadTask; - downloadTask.restore().then((result) => { + downloadTask.resume().then((result) => { if (result) { console.info('Download task resumed.') } else { @@ -1835,9 +1795,13 @@ Resumes this download task. This API uses a promise to return the result. ``` -### restore9+ +### resume(deprecated) -restore(callback: AsyncCallback<boolean>): void +resume(callback: AsyncCallback<void>): void + +> **NOTE** +> +> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [restore9+](#restore9-1). Resumes this download task. This API uses an asynchronous callback to return the result. @@ -1848,14 +1812,13 @@ Resumes this download task. This API uses an asynchronous callback to return the **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** ```js - let downloadTask; - downloadTask.restore((err, result)=>{ + downloadTask.resume((err, result)=>{ if (err) { console.error('Failed to resume the download task. Cause:' + err); return; diff --git a/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md b/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md index 8944052b4fed8899733d3cf924479ddc4359fc7e..03645ac62b8ec51c616fbfd6e923aef203a52ad6 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @@ -1,4 +1,4 @@ -# Background Task Management +# @ohos.resourceschedule.backgroundTaskManager (Background Task Management) The **BackgroundTaskManager** module provides APIs to manage background tasks. @@ -234,7 +234,7 @@ Requests a continuous task from the system. This API uses an asynchronous callba | Name | Type | Mandatory | Description | | --------- | ---------------------------------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| | bgMode | [BackgroundMode](#backgroundmode) | Yes | Background mode requested. | | wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. | @@ -308,7 +308,7 @@ Requests a continuous task from the system. This API uses a promise to return th | Name | Type | Mandatory | Description | | --------- | ---------------------------------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| | bgMode | [BackgroundMode](#backgroundmode) | Yes | Background mode requested. | | wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | @@ -381,7 +381,7 @@ Requests to cancel a continuous task. This API uses an asynchronous callback to | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** @@ -437,7 +437,7 @@ Requests to cancel a continuous task. This API uses a promise to return the resu | Name | Type | Mandatory | Description | | ------- | ------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| **Return value** @@ -618,12 +618,12 @@ Enumerates the efficiency resource types. **System API**: This is a system API. -| Name | Description | -| ----------------------- | --------------------- | -| CPU | CPU resources, which prevent the application from being suspended. | -| COMMON_EVENT | A type of software resources, which prevent common events from being proxied when the application is suspended. | -| TIMER | A type of software resources, which prevent timers from being proxied when the application is suspended. | -| WORK_SCHEDULER | WORK_SCHEDULER resources, which ensure that the application has more time to execute the task. | -| BLUETOOTH | A type of hardware resources, which prevent Bluetooth resources from being proxied when the application is suspended. | -| GPS | A type of hardware resources, which prevent GPS resources from being proxied when the application is suspended. | -| AUDIO | A type of hardware resources, which prevent audio resources from being proxied when the application is suspended.| +| Name | Value | Description | +| ----------------------- | ---- | --------------------- | +| CPU | 1 | CPU resources, which prevent the application from being suspended. | +| COMMON_EVENT | 2 | A type of software resources, which prevent common events from being proxied when the application is suspended. | +| TIMER | 4 | A type of software resources, which prevent timers from being proxied when the application is suspended. | +| WORK_SCHEDULER | 8 | WORK_SCHEDULER resources, which ensure that the application has more time to execute the task. | +| BLUETOOTH | 16 | A type of hardware resources, which prevent Bluetooth resources from being proxied when the application is suspended. | +| GPS | 32 | A type of hardware resources, which prevent GPS resources from being proxied when the application is suspended. | +| AUDIO | 64 | A type of hardware resources, which prevent audio resources from being proxied when the application is suspended.| diff --git a/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md b/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md index f83329d727dd9c95d076415717d1e765665326b8..b423c712999053c8a00d0b8503525cd03ce1cdf8 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md @@ -1,4 +1,4 @@ -# Device Usage Statistics +# @ohos.resourceschedule.usageStatistics (Device Usage Statistics) This module provides APIs for collecting statistics on device usage. @@ -703,7 +703,7 @@ Queries FA usage records. This API uses an asynchronous callback to return a max | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ----------------------------------- | -| callback | AsyncCallback<Array<[HapModuleInfo](#hapmoduleinfo)>> | Yes | Callback used to return a maximum of 1000 FA usage records.| +| callback | AsyncCallback<Array<[HapModuleInfo](#hapmoduleinfo)>> | Yes | Callback used to return a maximum of **maxNum** FA usage records.| **Error codes** diff --git a/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md b/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md index e62f6ca72f897772a8c98f21d14aaf18e398f575..77638dbfe38acf986f1b632349253c9ceb9496ed 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md @@ -1,4 +1,4 @@ -# Work Scheduler +# @ohos.resourceschedule.workScheduler The **workScheduler** module provides the APIs for registering, canceling, and querying Work Scheduler tasks, which do not have real-time constraints. @@ -437,45 +437,45 @@ Enumerates the network types that can trigger the task. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler -| Name | Description | -| ---------------------- | ----------------------- | -| NETWORK_TYPE_ANY | Any network type. | -| NETWORK_TYPE_MOBILE | Mobile network. | -| NETWORK_TYPE_WIFI | Wi-Fi network. | -| NETWORK_TYPE_BLUETOOTH | Bluetooth network.| -| NETWORK_TYPE_WIFI_P2P | Wi-Fi P2P network. | -| NETWORK_TYPE_ETHERNET | Ethernet. | +| Name | Value | Description | +| ---------------------- | ---- | ----------------------- | +| NETWORK_TYPE_ANY | 0 | Any network type. | +| NETWORK_TYPE_MOBILE | 1 | Mobile network. | +| NETWORK_TYPE_WIFI | 2 | Wi-Fi network. | +| NETWORK_TYPE_BLUETOOTH | 3 | Bluetooth network.| +| NETWORK_TYPE_WIFI_P2P | 4 | Wi-Fi P2P network. | +| NETWORK_TYPE_ETHERNET | 5 | Ethernet. | ## ChargingType Enumerates the charging types that can trigger the task. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler -| Name | Description | -| ------------------------- | -------------------- | -| CHARGING_PLUGGED_ANY | Any charging type.| -| CHARGING_PLUGGED_AC | DC charging. | -| CHARGING_PLUGGED_USB | USB charging. | -| CHARGING_PLUGGED_WIRELESS | Wireless charging. | +| Name | Value | Description | +| ------------------------- | ---- | -------------------- | +| CHARGING_PLUGGED_ANY | 0 | Any charging type.| +| CHARGING_PLUGGED_AC | 1 | DC charging. | +| CHARGING_PLUGGED_USB | 2 | USB charging. | +| CHARGING_PLUGGED_WIRELESS | 3 | Wireless charging. | ## BatteryStatus Enumerates the battery states that can trigger the task. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler -| Name | Description | -| -------------------------- | -------------------------- | -| BATTERY_STATUS_LOW | A low battery alert is displayed. | -| BATTERY_STATUS_OKAY | The battery level is restored from low to normal. | -| BATTERY_STATUS_LOW_OR_OKAY | The battery level is restored from low to normal, or a low battery alert is displayed.| +| Name | Value | Description | +| -------------------------- | ---- | -------------------------- | +| BATTERY_STATUS_LOW | 0 | A low battery alert is displayed. | +| BATTERY_STATUS_OKAY | 1 | The battery level is restored from low to normal. | +| BATTERY_STATUS_LOW_OR_OKAY | 2 | The battery level is restored from low to normal, or a low battery alert is displayed.| ## StorageRequest Enumerates the storage states that can trigger the task. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler -| Name | Description | -| ------------------------- | ------------------------------ | -| STORAGE_LEVEL_LOW | The storage space is insufficient. | -| STORAGE_LEVEL_OKAY | The storage space is restored from insufficient to normal. | -| STORAGE_LEVEL_LOW_OR_OKAY | The storage space is restored from insufficient to normal, or the storage space is insufficient.| +| Name | Value | Description | +| ------------------------- | ---- | ------------------------------ | +| STORAGE_LEVEL_LOW | 0 | The storage space is insufficient. | +| STORAGE_LEVEL_OKAY | 1 | The storage space is restored from insufficient to normal. | +| STORAGE_LEVEL_LOW_OR_OKAY | 2 | The storage space is restored from insufficient to normal, or the storage space is insufficient.| diff --git a/en/application-dev/reference/apis/js-apis-rpc.md b/en/application-dev/reference/apis/js-apis-rpc.md index 50e5cfe7cc8bdb66fc5fddce209a47e684d8bc11..94757432a9c16fa471fb98629b63387594542e65 100644 --- a/en/application-dev/reference/apis/js-apis-rpc.md +++ b/en/application-dev/reference/apis/js-apis-rpc.md @@ -1,9 +1,11 @@ -# RPC +# @ohos.rpc The **RPC** module implements communication between processes, including inter-process communication (IPC) on a single device and remote procedure call (RPC) between processes on difference devices. IPC is implemented based on the Binder driver, and RPC is based on the DSoftBus driver. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> > This module supports return of error codes since API version 9. @@ -24,7 +26,7 @@ The APIs of this module return exceptions since API version 9. The following tab | ------------------------------------- | ------- | --------------------------------------------- | | CHECK_PARAM_ERROR | 401 | Parameter check failed. | | OS_MMAP_ERROR | 1900001 | Failed to call mmap. | - | OS_IOCTL_ERROR | 1900002 | Failed to execute **ioctl** with the shared memory file descriptor.| + | OS_IOCTL_ERROR | 1900002 | Failed to call **ioctl** with the shared memory file descriptor.| | WRITE_TO_ASHMEM_ERROR | 1900003 | Failed to write data to the shared memory. | | READ_FROM_ASHMEM_ERROR | 1900004 | Failed to read data from the shared memory. | | ONLY_PROXY_OBJECT_PERMITTED_ERROR | 1900005 | This operation is allowed only on the proxy object. | @@ -123,7 +125,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode readRemoteObject(): IRemoteObject -Reads a remote object from **MessageSequence**. You can use this API to deserialize the **MessageSequence** object to generate an **IRemoteObject**. The remote object is read in the order in which it is written to this **MessageSequence** object. +Reads the remote object from **MessageSequence**. You can use this API to deserialize the **MessageSequence** object to generate an **IRemoteObject**. The remote object is read in the order in which it is written to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core @@ -405,7 +407,7 @@ Obtains the read position of this **MessageSequence** object. | Type| Description| | ------ | ------ | - | number | Current read position of the **MessageSequence** object.| + | number | Read position obtained.| **Example** @@ -427,7 +429,7 @@ Obtains the write position of this **MessageSequence** object. | Type| Description| | ------ | ----- | - | number | Current write position of the **MessageSequence** object.| + | number | Write position obtained.| **Example** @@ -504,7 +506,7 @@ Moves the write pointer to the specified position. writeByte(val: number): void -Writes a Byte value to this **MessageSequence** object. +Writes a byte value to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core @@ -538,7 +540,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode readByte(): number -Reads the Byte value from this **MessageSequence** object. +Reads the byte value from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core @@ -2856,7 +2858,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode readFileDescriptor(): number -Reads a file descriptor from this **MessageSequence** object. +Reads the file descriptor from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core @@ -4017,7 +4019,7 @@ Writes a string to this **MessageParcel** object. readString(): string -Reads a string from this **MessageParcel** object. +Reads the string from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core diff --git a/en/application-dev/reference/apis/js-apis-runninglock.md b/en/application-dev/reference/apis/js-apis-runninglock.md index 1b25989357a2e101b5b6e95d05b5ca60dab2fb6f..e3718c5878ccae3e63f8bdfae8b37061599fffda 100644 --- a/en/application-dev/reference/apis/js-apis-runninglock.md +++ b/en/application-dev/reference/apis/js-apis-runninglock.md @@ -1,95 +1,205 @@ -# Running Lock +# RunningLock -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+The RunningLock module provides APIs for creating, querying, holding, and releasing running locks. + +> **NOTE** > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -The Running Lock module provides APIs for creating, querying, holding, and releasing running locks. +## Modules to Import +```js +import runningLock from '@ohos.runningLock'; +``` -## Modules to Import +## runningLock.isSupported9+ + +isSupported(type: RunningLockType): boolean; + +Checks whether a specified type of **RunningLock** is supported. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------- | ---- | -------------------- | +| type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object.| + +**Return value** + +| Type | Description | +| ------- | --------------------------------------- | +| boolean | The value **true** indicates that the specified type of **RunningLock** is supported, and the value **false** indicates the opposite.| + +**Error codes** + +For details about the error codes, see [RunningLock Error Codes](../errorcodes/errorcode-runninglock.md). + +| Code | Error Message | +|---------|---------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** +```js +try { + var isSupported = runningLock.isSupported(runningLock.RunningLockType.BACKGROUND); + console.info('BACKGROUND type supported: ' + isSupported); +} catch(err) { + console.error('check supported failed, err: ' + err); +} ``` -import runningLock from '@ohos.runningLock'; + +## runningLock.create9+ + +create(name: string, type: RunningLockType, callback: AsyncCallback<RunningLock>): void + +Creates a **RunningLock** object. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Required permission:** ohos.permission.RUNNING_LOCK + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | +| name | string | Yes | Name of the **RunningLock** object. | +| type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object to be created. | +| callback | AsyncCallback<[RunningLock](#runninglock)> | Yes | Callback used to return the result. If a lock is successfully created, **err** is **undefined** and **data** is the created **RunningLock**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [RunningLock Error Codes](../errorcodes/errorcode-runninglock.md). + +| Code | Error Message | +|---------|----------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +runningLock.create('running_lock_test', runningLock.RunningLockType.BACKGROUND, (err, lock) => { + if (typeof err === 'undefined') { + console.info('created running lock: ' + lock); + } else { + console.error('create running lock failed, err: ' + err); + } +}); ``` +## runningLock.create9+ -## RunningLockType +create(name: string, type: RunningLockType): Promise<RunningLock> -Enumerates the types of **RunningLock** objects. +Creates a **RunningLock** object. **System capability:** SystemCapability.PowerManager.PowerManager.Core -| Name | Default Value | Description | -| ------------------------ | ---- | ------------------- | -| BACKGROUND | 1 | A lock that prevents the system from hibernating when the screen is off. | -| PROXIMITY_SCREEN_CONTROL | 2 | A lock that determines whether to turn on or off the screen based on the distance away from the screen.| +**Required permission:** ohos.permission.RUNNING_LOCK +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------- | ---- | ------------------ | +| name | string | Yes | Name of the **RunningLock** object. | +| type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object to be created.| + +**Return value** + +| Type | Description | +| ------------------------------------------ | ------------------------------------ | +| Promise<[RunningLock](#runninglock)> | Promise used to return the result.| -## isRunningLockTypeSupported +**Error codes** + +For details about the error codes, see [RunningLock Error Codes](../errorcodes/errorcode-runninglock.md). + +| Code | Error Message | +|---------|----------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +runningLock.create('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + console.info('created running lock: ' + lock); +}) +.catch(err => { + console.error('create running lock failed, error: ' + err); +}); +``` + +## runningLock.isRunningLockTypeSupported(deprecated) isRunningLockTypeSupported(type: RunningLockType, callback: AsyncCallback<boolean>): void -Checks whether a specified type of **RunningLock** is supported. This function uses an asynchronous callback to return the result. +> This API is deprecated since API version 9. You are advised to use [runningLock.isSupported](#runninglockissupported9) instead. + +Checks whether a specified type of **RunningLock** is supported. This API uses an asynchronous callback to return the result. **System capability:** SystemCapability.PowerManager.PowerManager.Core **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------- | ---- | ---------------------------------------- | -| type | RunningLockType | Yes | Type of the **RunningLock** object. | -| callback | AsyncCallback<boolean> | Yes | Callback used to obtain the return value.
Return value: The value **true** indicates that the specified type of **RunningLock** is supported, and the value **false** indicates the opposite.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | ------------------------------------------------------------ | +| type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the query result obtained, where the value **true** indicates that **RunningLock** is supported and **false** indicates the opposite. Otherwise, **err** is an error object.| **Example** -``` -runningLock.isRunningLockTypeSupported(runningLock.RunningLockType.BACKGROUND, (error, supported) => { - if (typeof error === "undefined") { - console.info('BACKGROUND support status is ' + supported); +```js +runningLock.isRunningLockTypeSupported(runningLock.RunningLockType.BACKGROUND, (err, data) => { + if (typeof err === 'undefined') { + console.info('BACKGROUND lock support status: ' + data); } else { - console.log('error: ' + error); + console.log('check BACKGROUND lock support status failed, err: ' + err); } -}) +}); ``` +## runningLock.isRunningLockTypeSupported(deprecated) -## isRunningLockTypeSupported +isRunningLockTypeSupported(type: RunningLockType): Promise<boolean> -isRunningLockTypeSupported(type: RunningLockType): Promise<boolean> +> This API is deprecated since API version 9. You are advised to use [runningLock.isSupported](#runninglockissupported9) instead. -Checks whether a specified type of **RunningLock** is supported. This function uses an asynchronous callback to return the result. +Checks whether a specified type of **RunningLock** is supported. This API uses a promise to return the result. **System capability:** SystemCapability.PowerManager.PowerManager.Core **Parameters** -| Name | Type | Mandatory | Description | -| ---- | --------------- | ---- | ---------- | -| type | RunningLockType | Yes | Type of the **RunningLock** object.| +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------- | ---- | -------------------- | +| type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object.| -**Return Value** +**Return value** -| Type | Description | -| ---------------------- | ---------------------------------------- | -| Promise<boolean> | Promise used to asynchronously obtain the return value.
Return value: The value **true** indicates that the specified type of **RunningLock** is supported, and the value **false** indicates the opposite.| +| Type | Description | +| ---------------------- | ---------------------------------------------------- | +| Promise<boolean> | Promise used to return the result. The value **true** indicates that the specified type of **RunningLock** is supported, and the value **false** indicates the opposite.| **Example** -``` -runningLock.isRunningLockTypeSupported(runningLock.RunningLockType.PROXIMITY_SCREEN_CONTROL) -.then(supported => { - console.info('PROXIMITY_SCREEN_CONTROL support status is ' + supported); +```js +runningLock.isRunningLockTypeSupported(runningLock.RunningLockType.BACKGROUND) +.then(data => { + console.info('BACKGROUND lock support status: ' + data); }) -.catch(error => { - console.log('error: ' + error); +.catch(err => { + console.log('check BACKGROUND lock support status failed, err: ' + err); }); ``` - -## createRunningLock +## runningLock.createRunningLock(deprecated) createRunningLock(name: string, type: RunningLockType, callback: AsyncCallback<RunningLock>): void +> This API is deprecated since API version 9. You are advised to use [runningLock.create](#runninglockcreate9) instead. + Creates a **RunningLock** object. **System capability:** SystemCapability.PowerManager.PowerManager.Core @@ -98,33 +208,30 @@ Creates a **RunningLock** object. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | -------------------------------------- | -| name | string | Yes | Name of the **RunningLock** object. | -| type | RunningLockType | Yes | Type of the **RunningLock** object to be created. | -| callback | AsyncCallback<[RunningLock](#runninglock)> | Yes | Callback used to obtain the return value.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | +| name | string | Yes | Name of the **RunningLock** object. | +| type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object to be created. | +| callback | AsyncCallback<[RunningLock](#runninglock)> | Yes | Callback used to return the result. If a lock is successfully created, **err** is **undefined** and **data** is the created **RunningLock**. Otherwise, **err** is an error object.| **Example** -``` -runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND, (error, lockIns) => { - if (typeof error === "undefined") { - var used = lockIns.isUsed(); - console.info('runninglock is used: ' + used); - lockIns.lock(500); - used = lockIns.isUsed(); - console.info('after lock runninglock is used ' + used); +```js +runningLock.createRunningLock('running_lock_test', runningLock.RunningLockType.BACKGROUND, (err, lock) => { + if (typeof err === 'undefined') { + console.info('created running lock: ' + lock); } else { - console.log('create runningLock test error: ' + error); + console.error('create running lock failed, err: ' + err); } -}) +}); ``` - -## createRunningLock +## runningLock.createRunningLock(deprecated) createRunningLock(name: string, type: RunningLockType): Promise<RunningLock> +> This API is deprecated since API version 9. You are advised to use [runningLock.create](#runninglockcreate9) instead. + Creates a **RunningLock** object. **System capability:** SystemCapability.PowerManager.PowerManager.Core @@ -133,39 +240,157 @@ Creates a **RunningLock** object. **Parameters** -| Name | Type | Mandatory | Description | -| ---- | --------------- | ---- | --------- | -| name | string | Yes | Name of the **RunningLock** object. | -| type | RunningLockType | Yes | Type of the **RunningLock** object to be created.| +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------- | ---- | ------------------ | +| name | string | Yes | Name of the **RunningLock** object. | +| type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object to be created.| -**Return Value** +**Return value** | Type | Description | -| ---------------------------------------- | ---------------------------------- | -| Promise<[RunningLock](#runninglock)> | Promise used to asynchronously obtain the returned **RunningLock** object.| +| ------------------------------------------ | ------------------------------------ | +| Promise<[RunningLock](#runninglock)> | Promise used to return the result.| **Example** +```js +runningLock.createRunningLock('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + console.info('created running lock: ' + lock); +}) +.catch(err => { + console.log('create running lock failed, err: ' + err); +}); ``` -runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND) -.then(runninglock => { - console.info('create runningLock success'); + +## RunningLock + +Represents a **RunningLock** object. + +### hold9+ + +hold(timeout: number): void + +Locks and holds a **RunningLock** object. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Required permission:** ohos.permission.RUNNING_LOCK + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ----------------------------------------- | +| timeout | number | Yes | Duration for locking and holding the **RunningLock** object, in ms.| + +**Error codes** + +For details about the error codes, see [RunningLock Error Codes](../errorcodes/errorcode-runninglock.md). + +| Code | Error Message | +|---------|----------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +runningLock.create('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + console.info('create running lock success'); + try { + lock.hold(500); + console.info('hold running lock success'); + } catch(err) { + console.error('hold running lock failed, err: ' + err); + } }) -.catch(error => { - console.log('create runningLock test error: ' + error); +.catch(err => { + console.error('create running lock failed, err: ' + err); +}); +``` + +### unhold9+ + +unhold(): void + +Releases a **RunningLock** object. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Required permission:** ohos.permission.RUNNING_LOCK + +**Error codes** + +For details about the error codes, see [RunningLock Error Codes](../errorcodes/errorcode-runninglock.md). + +| Code | Error Message | +|---------|----------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +runningLock.create('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + console.info('create running lock success'); + try { + lock.unhold(); + console.info('unhold running lock success'); + } catch(err) { + console.error('unhold running lock failed, err: ' + err); + } }) +.catch(err => { + console.error('create running lock failed, err: ' + err); +}); ``` +### isHolding9+ -## RunningLock +isHolding(): boolean + +Checks the hold status of the **Runninglock** object. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core -Defines a **RunningLock** object. +**Return value** +| Type | Description | +| ------- | ------------------------------------------------------------ | +| boolean | The value **true** indicates that the **Runninglock** object is held; and the value **false** indicates that the **Runninglock** object is released.| -### lock +**Error codes** + +For details about the error codes, see [RunningLock Error Codes](../errorcodes/errorcode-runninglock.md). + +| Code | Error Message | +|---------|---------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +runningLock.create('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + console.info('create running lock success'); + try { + var isHolding = lock.isHolding(); + console.info('check running lock holding status: ' + isHolding); + } catch(err) { + console.error('check running lock holding status failed, err: ' + err); + } +}) +.catch(err => { + console.error('create running lock failed, err: ' + err); +}); +``` + +### lock(deprecated) lock(timeout: number): void +> This API is deprecated since API version 9. You are advised to use [RunningLock.hold](#hold9) instead. + Locks and holds a **RunningLock** object. **System capability:** SystemCapability.PowerManager.PowerManager.Core @@ -174,29 +399,30 @@ Locks and holds a **RunningLock** object. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------ | ---- | -------------------------- | -| timeout | number | No | Duration for locking and holding the **RunningLock** object, in ms.| +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ----------------------------------------- | +| timeout | number | Yes | Duration for locking and holding the **RunningLock** object, in ms.| **Example** -``` -runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND) -.then(runningLock => { - runningLock.lock(100) - console.info('create runningLock success') +```js +runningLock.createRunningLock('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + lock.lock(500); + console.info('create running lock and lock success'); }) -.catch(error => { - console.log('create runningLock test error: ' + error) +.catch(err => { + console.error('create running lock failed, err: ' + err); }); ``` - -### unlock +### unlock(deprecated) unlock(): void -Releases a **Runninglock** object. +> This API is deprecated since API version 9. You are advised to use [RunningLock.unhold](#unhold9) instead. + +Releases a **RunningLock** object. **System capability:** SystemCapability.PowerManager.PowerManager.Core @@ -204,40 +430,52 @@ Releases a **Runninglock** object. **Example** -``` -runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND) -.then(runningLock => { - runningLock.unlock() - console.info('create and unLock runningLock success') +```js +runningLock.createRunningLock('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + lock.unlock(); + console.info('create running lock and unlock success'); }) -.catch(error => { - console.log('create runningLock test error: ' + error) +.catch(err => { + console.error('create running lock failed, err: ' + err); }); ``` - -### isUsed +### isUsed(deprecated) isUsed(): boolean -Checks the status of the **Runninglock** object. +> This API is deprecated since API version 9. You are advised to use [RunningLock.isHolding](#isholding9) instead. + +Checks the hold status of the **Runninglock** object. **System capability:** SystemCapability.PowerManager.PowerManager.Core -**Return Value** -| Type | Description | -| ------- | ------------------------------------- | -| boolean | Returns **true** if the **Runninglock** object is held; returns **false** if the **Runninglock** object is released.| +**Return value** +| Type | Description | +| ------- | ------------------------------------------------------------ | +| boolean | The value **true** indicates that the **Runninglock** object is held; and the value **false** indicates that the **Runninglock** object is released.| **Example** -``` -runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND) -.then(runningLock => { - var used = runningLock.isUsed() - console.info('runningLock used status: ' + used) +```js +runningLock.createRunningLock('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + var isUsed = lock.isUsed(); + console.info('check running lock used status: ' + isUsed); }) -.catch(error => { - console.log('runningLock isUsed test error: ' + error) +.catch(err => { + console.error('check running lock used status failed, err: ' + err); }); ``` + +## RunningLockType + +Enumerates the types of **RunningLock** objects. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +| Name | Value | Description | +| ------------------------ | ---- | -------------------------------------- | +| BACKGROUND | 1 | A lock that prevents the system from hibernating when the screen is off. | +| PROXIMITY_SCREEN_CONTROL | 2 | A lock that determines whether to turn on or off the screen based on the distance away from the screen.| diff --git a/en/application-dev/reference/apis/js-apis-screenshot.md b/en/application-dev/reference/apis/js-apis-screenshot.md index 0e8b04295567caf1a018a9f9d3c8122b7f89e41d..4fa5e15b59c8d70b09f5bcf8cd1e9686ba329a14 100644 --- a/en/application-dev/reference/apis/js-apis-screenshot.md +++ b/en/application-dev/reference/apis/js-apis-screenshot.md @@ -1,4 +1,5 @@ -# Screenshot +# @ohos.screenshot + The **Screenshot** module provides APIs for you to set information such as the region to capture and the size of the screen region when capturing a screen. > **NOTE** diff --git a/en/application-dev/reference/apis/js-apis-settings.md b/en/application-dev/reference/apis/js-apis-settings.md index 9474b7a298b40546ae1b5fe1a7c639efb1195de3..5972e0cd9a278dcc49b634b6d05e8d76f3fa0a1d 100644 --- a/en/application-dev/reference/apis/js-apis-settings.md +++ b/en/application-dev/reference/apis/js-apis-settings.md @@ -1,4 +1,4 @@ -# Settings +# @ohos.settings The **settings** module provides APIs for setting data items. @@ -24,8 +24,8 @@ Provides data items for setting the time and date formats. | ------------------- | ------ | ---- | ---- | ------------------------------------------------------------ | | DATE_FORMAT | string | Yes | Yes | Date format.
The value can be **mm/dd/yyyy**, **dd/mm/yyyy**, or **yyyy/mm/dd**, where **mm** indicates the month, **dd** indicates the day, and **yyyy** indicates the year.| | TIME_FORMAT | string | Yes | Yes | Time format.
**12**: 12-hour format.
**24**: 24-hour format.| -| AUTO_GAIN_TIME | string | Yes | Yes | Whether the date, time, and time zone are automatically obtained from the Network Identity and Time Zone (NITZ).
The value **true** means that the date, time, and time zone are automatically obtained from NITZ; and **false** means the opposite.| -| AUTO_GAIN_TIME_ZONE | string | Yes | Yes | Whether the time zone is automatically obtained from NITZ.
The value **true** means that the time zone is automatically obtained from NITZ; and **false** means the opposite.| +| AUTO_GAIN_TIME | string | Yes | Yes | Whether the date, time, and time zone are automatically obtained from the Network Identity and Time Zone (NITZ).
The value **true** means that the date, time, and time zone are automatically obtained from NITZ; and **false** means the opposite. | +| AUTO_GAIN_TIME_ZONE | string | Yes | Yes | Whether the time zone is automatically obtained from NITZ.
The value **true** means that the time zone is automatically obtained from NITZ; and **false** means the opposite. | ## display @@ -39,7 +39,7 @@ Provides data items for setting the display effects. | ----------------------------- | ------ | ---- | ---- | ------------------------------------------------------------ | | FONT_SCALE | string | Yes | Yes | Scale factor of the font. The value is a floating point number. | | SCREEN_BRIGHTNESS_STATUS | string | Yes | Yes | Screen brightness. The value ranges from 0 to 255. | -| AUTO_SCREEN_BRIGHTNESS | string | Yes | Yes | Whether automatic screen brightness adjustment is enabled.
**AUTO_SCREEN_BRIGHTNESS_MODE**: Automatic screen brightness adjustment is enabled.
**MANUAL_SCREEN_BRIGHTNESS_MODE**: Automatic screen brightness adjustment is disabled.| +| AUTO_SCREEN_BRIGHTNESS | string | Yes | Yes | Whether automatic screen brightness adjustment is enabled.
**AUTO_SCREEN_BRIGHTNESS_MODE**: Automatic screen brightness adjustment is enabled.
**MANUAL_SCREEN_BRIGHTNESS_MODE**: Automatic screen brightness adjustment is disabled. | | AUTO_SCREEN_BRIGHTNESS_MODE | number | Yes | Yes | Value of **AUTO_SCREEN_BRIGHTNESS** when automatic screen brightness adjustment is enabled. | | MANUAL_SCREEN_BRIGHTNESS_MODE | number | Yes | Yes | Value of **AUTO_SCREEN_BRIGHTNESS** when automatic screen brightness adjustment is disabled. | | SCREEN_OFF_TIMEOUT | string | Yes | Yes | Waiting time for the device to enter the sleep state when not in use (unit: ms). | @@ -47,7 +47,7 @@ Provides data items for setting the display effects. | ANIMATOR_DURATION_SCALE | string | Yes | Yes | Scale factor for the animation duration. This affects the start delay and duration of all such animations.
If the value is **0**, the animation ends immediately. The default value is **1**.| | TRANSITION_ANIMATION_SCALE | string | Yes | Yes | Scale factor for transition animations.
The value **0** indicates that the transition animations are disabled. | | WINDOW_ANIMATION_SCALE | string | Yes | Yes | Scale factor for normal window animations.
The value **0** indicates that window animations are disabled. | -| DISPLAY_INVERSION_STATUS | string | Yes | Yes | Whether display color inversion is enabled.
**1**: Display color inversion is enabled.
**0**: Display color inversion is disabled.| +| DISPLAY_INVERSION_STATUS | string | Yes | Yes | Whether display color inversion is enabled.
**1**: Display color inversion is enabled.
**0**: Display color inversion is disabled. | ## general @@ -248,7 +248,7 @@ Obtains the value of a data item in the database. This API uses an asynchronous | Name | Type | Mandatory| Description | | ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | -| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | +| dataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | | name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| | callback | AsyncCallback\ | Yes | Callback used to return the value of the data item. | @@ -280,7 +280,7 @@ Obtains the value of a data item in the database. This API uses a promise to ret | Name | Type | Mandatory| Description | | ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | -| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | +| dataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | | name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| **Return value** @@ -315,7 +315,7 @@ Sets the value for a data item. This API uses an asynchronous callback to return | Name | Type | Mandatory| Description | | ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | -| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | +| dataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | | name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| | value | object | Yes | Value of the data item. The value range varies by service. | | callback | AsyncCallback\ | Yes | Callback used to return the result. Returns **true** if the operation is successful; returns **false** otherwise. | @@ -347,7 +347,7 @@ Sets the value for a data item. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | -| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | +| dataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | | name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| | value | object | Yes | Value of the data item. The value range varies by service. | @@ -512,9 +512,9 @@ Obtains the value of a data item. Unlike **getValue**, this API returns the resu | Name | Type | Mandatory| Description | | ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | -| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | +| dataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | | name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| -| defValue | string | Yes | Default value, which is returned when the value of a data item is not found in the database. Set this attribute as needed.| +| defValue | string | Yes | Default value, which is returned when the value of a data item is not found in the database. Set this parameter as needed. | **Return value** @@ -541,7 +541,7 @@ Sets the value for a data item. Unlike **setValue**, this API returns the result If the specified data item exists in the database, the **setValueSync** method updates the value of the data item. If the data item does not exist in the database, the **setValueSync** method inserts the data item into the database. -**Required permissions**: ohos.permission.MANAGE_SECUER_SETTINGS (available only to system applications) +**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS (available only to system applications) **System capability**: SystemCapability.Applications.settings.Core @@ -549,7 +549,7 @@ If the specified data item exists in the database, the **setValueSync** method u | Name | Type | Mandatory| Description | | ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | -| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | +| dataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | | name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| | value | string | Yes | Value of the data item. The value range varies by service. | diff --git a/en/application-dev/reference/apis/js-apis-stack.md b/en/application-dev/reference/apis/js-apis-stack.md index 479550783c54d87accf6436cf6556e1b33a12ccc..d7c5dcb66c511aa8ade7ad6e4fa94041162f2380 100644 --- a/en/application-dev/reference/apis/js-apis-stack.md +++ b/en/application-dev/reference/apis/js-apis-stack.md @@ -1,4 +1,4 @@ -# Linear Container Stack +# @ohos.util.Stack (Linear Container Stack) > **NOTE** > @@ -19,9 +19,6 @@ This topic uses the following to identify the use of generics: import Stack from '@ohos.util.Stack'; ``` - - - ## Stack ### Attributes @@ -53,11 +50,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let stack = new Stack(); -try { - let stack2 = Stack(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -99,11 +91,6 @@ let b = [1, 2, 3]; let result2 = stack.push(b); let c = {name : "Dylon", age : "13"}; let result3 = stack.push(c); -try { - stack.push.bind({}, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### pop @@ -138,11 +125,6 @@ stack.push(5); stack.push(2); stack.push(4); let result = stack.pop(); -try { - stack.pop.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### peek @@ -176,11 +158,6 @@ stack.push(4); stack.push(5); stack.push(2); let result = stack.peek(); -try { - stack.peek.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### locate @@ -220,16 +197,11 @@ stack.push(4); stack.push(5); stack.push(2); let result = stack.locate(2); -try { - stack.locate.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value: T, index?: number, stack?: Stack<T>) => void, +forEach(callbackFn: (value: T, index?: number, stack?: Stack<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -240,7 +212,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -270,13 +242,6 @@ stack.push(4); stack.forEach((value, index) => { console.log("value:" + value, index); }); -try { - stack.forEach.bind({}, (value, index) => { - console.log("value:" + value, index); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### isEmpty @@ -310,11 +275,6 @@ stack.push(4); stack.push(5); stack.push(4); let result = stack.isEmpty(); -try { - stack.isEmpty.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### [Symbol.iterator] @@ -359,9 +319,4 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - stack[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-stationary.md b/en/application-dev/reference/apis/js-apis-stationary.md new file mode 100644 index 0000000000000000000000000000000000000000..ceae25ac4c711e8dd3664520290fda7b897c9ae9 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-stationary.md @@ -0,0 +1,130 @@ +# @ohos.stationary (Device Status Awareness Framework) + +The **stationary** module provides APIs to report the device status, including absolute still and relative still. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import stationary from '@ohos.stationary' +``` + +## ActivityResponse + +Defines the response interface to receive the device status. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Stationary + +### Attributes + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| state | [ActivityState](#activitystate) | Yes| No| New device status.| + +## ActivityType + +Enumerates the device status types. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Stationary + +| Name| Description| +| -------- | -------- | +| still | Absolutely still.| +| relativeStill | Relatively still.| + +## ActivityEvent + +Enumerates the device status events. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Stationary + +| Name | Value | Description | +| ------------------------------ | ---- | ---------------------------------------- | +| ENTER | 1 | Event indicating entering device status. | +| EXIT | 2 | Event indicating exiting device status.| +| ENTER_EXIT | 3 | Event indicating entering and exiting device status.| + +## ActivityState + +Enumerates the device statuses. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Stationary + +| Name | Value | Description | +| ------------------------------ | ---- | ---------------------------------------- | +| ENTER | 1 | Entering device status. | +| EXIT | 2 | Exiting device status.| + +## stationary.on('still' | 'relativeStill') + +on(activity: ActivityType, event: ActivityEvent, reportLatencyNs: number, callback: Callback<ActivityResponse>): void + +Subscribes to the device status. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Stationary + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------------- | -------------------------------------------------- | ---- | ---------------------------- | +| activity | [ActivityType](#activitytype) | Yes | Device status type. | +| event | [ActivityEvent](#activityevent) | Yes | Event type. | +| reportLatencyNs | number | Yes | Event reporting period. | +| callback | Callback<[ActivityResponse](#activityresponse)\> | Yes | Callback used to receive reported data. | + +**Example** + +```js +var reportLatencyNs = 100; +stationary.on('still', stationary.ActivityEvent.ENTER, reportLatencyNs, (data) => { + console.log('data='+ JSON.stringify(data)); +}) +``` + +## stationary.once('still' | 'relativeStill') + +once(activity: ActivityType, callback: Callback<ActivityResponse>): void + +Obtains the device status. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Stationary + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------------- | -------------------------------------------------- | ---- | ---------------------------- | +| activity | [ActivityType](#activitytype) | Yes | Device status type. | +| callback | Callback<[ActivityResponse](#activityresponse)\> | Yes | Callback used to receive reported data. | + +**Example** + +```js +stationary.once('still', (data) => { + console.log("data="+ JSON.stringify(data)); +}) +``` + +## stationary.off('still' | 'relativeStill') + +off(activity: ActivityType, event: ActivityEvent, callback?: Callback<ActivityResponse>): void + +Unsubscribes from the device status. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Stationary + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------------- | -------------------------------------------------- | ---- | ---------------------------- | +| activity | [ActivityType](#activitytype) | Yes | Device status type. | +| event | [ActivityEvent](#activityevent) | Yes | Event type. | +| callback | Callback<[ActivityResponse](#activityresponse)\> | No | Callback used to receive reported data. | + +**Example** + +```js +stationary.off('still', stationary.ActivityEvent.ENTER); +``` diff --git a/en/application-dev/reference/apis/js-apis-system-battery.md b/en/application-dev/reference/apis/js-apis-system-battery.md index 7b577c8ee81c733cdb1aa1f2ccfcced87829f304..31959da80f23b90f54ea10883417eec202152d1a 100644 --- a/en/application-dev/reference/apis/js-apis-system-battery.md +++ b/en/application-dev/reference/apis/js-apis-system-battery.md @@ -1,9 +1,10 @@ -# Battery Level +# Battery Info -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.batteryInfo`](js-apis-battery-info.md) instead. -> -> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. +This module allows you to query the charging status and remaining power of a device. + +> **NOTE** +> - The APIs of this module are no longer maintained since API version 6. It is recommended that you use [`@ohos.batteryInfo`](js-apis-battery-info.md) instead. +> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -16,40 +17,46 @@ import battery from '@system.battery'; ## battery.getStatus -getStatus(Object): void +getStatus(options?: GetStatusOptions): void; Obtains the current charging state and battery level. **System capability**: SystemCapability.PowerManager.BatteryManager.Core -**Parameter** +**Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| success | Function | No | Called when the check result is obtained | -| fail | Function | No | Called when the check result fails to be obtained | -| complete | Function | No | Called when the execution is complete | - -The following value will be returned when the check result is obtained. - -| Name | Type | Description | -| -------- | -------- | -------- | -| charging | boolean | Whether the battery is being charged | -| level | number | Current battery level, which ranges from 0.00 to 1.00. | +| options | [GetStatusOptions](#getstatusoptions) | No| Object that contains the API calling result.| **Example** ```js -export default { - getStatus() { - battery.getStatus({ - success: function(data) { - console.log('success get battery level:' + data.level); - }, - fail: function(data, code) { - console.log('fail to get battery level code:' + code + ', data: ' + data); - }, - }); - }, -} -``` \ No newline at end of file +battery.getStatus({ + success: function(data) { + console.log('success get battery level:' + data.level); + }, + fail: function(data, code) { + console.error('fail to get battery level code:' + code + ', data: ' + data); + } +}); +``` + +## GetStatusOptions + +Object that contains the API calling result. + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ | +| success | (data: [BatteryResponse](#batteryresponse)) => void | No | Called when API call is successful. **data** is a return value of the [BatteryResponse](#batteryresponse) type.| +| fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code. | +| complete | () => void | No | Called when API call is complete. | + +## BatteryResponse + +Defines a response that returns the charging status and remaining power of the device. + +| Name| Type| Description| +| -------- | -------- | -------- | +| charging | boolean | Whether the battery is being charged.| +| level | number | Current battery level, which ranges from **0.00** to **1.00**.| diff --git a/en/application-dev/reference/apis/js-apis-system-brightness.md b/en/application-dev/reference/apis/js-apis-system-brightness.md index 71e9b7072d03d8c25297cfd2c8f3c97c295097eb..2773c74397046c44784b65cc458be75eef8c21ea 100644 --- a/en/application-dev/reference/apis/js-apis-system-brightness.md +++ b/en/application-dev/reference/apis/js-apis-system-brightness.md @@ -1,8 +1,9 @@ # Screen Brightness -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +This module provides APIs for querying and adjusting the screen brightness and mode. + +> **NOTE** > - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.brightness`](js-apis-brightness.md) instead. -> > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -16,7 +17,7 @@ import brightness from '@system.brightness'; ## brightness.getValue -getValue(Object): void +getValue(options?: GetBrightnessOptions): void Obtains the current screen brightness. @@ -24,39 +25,27 @@ Obtains the current screen brightness. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| success | Function | No | Called when the execution is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete | - -The following values will be returned when the operation is successful. - -| Name | Type | Description | -| -------- | -------- | -------- | -| value | number | Screen brightness, which ranges from 1 to 255. | +| options | [GetBrightnessOptions](#getbrightnessoptions) | No | Options for obtaining the screen brightness.| **Example** -```js -export default { - getValue() { - brightness.getValue({ - success: function(data){ - console.log('success get brightness value:' + data.value); - }, - fail: function(data, code) { - console.log('get brightness fail, code: ' + code + ', data: ' + data); + ```js + brightness.getValue({ + success: function(data) { + console.log('success get brightness value:' + data.value); }, - }); - }, -} -``` + fail: function(data, code) { + console.error('get brightness fail, code: ' + code + ', data: ' + data); + } + }); + ``` ## brightness.setValue -setValue(Object): void +etValue(options?: SetBrightnessOptions): void Sets the screen brightness. @@ -64,35 +53,28 @@ Sets the screen brightness. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | number | Yes | Screen brightness. The value is an integer ranging from 1 to 255.
- If the value is less than or equal to **0**, value **1** will be used.
- If the value is greater than **255**, value **255** will be used.
- If the value contains decimals, the integral part of the value will be used. For example, if value **8.1** is set, value **8** will be used. | -| success | Function | No | Called when the execution is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| options | [SetBrightnessOptions](#setbrightnessoptions) | No | Options for setting the screen brightness.| **Example** -```js -export default { - setValue() { - brightness.setValue({ - value: 100, - success: function(){ - console.log('handling set brightness success.'); - }, - fail: function(data, code){ - console.log('handling set brightness value fail, code:' + code + ', data: ' + data); - }, - }); - }, -} -``` + ```js + brightness.setValue({ + value: 100, + success: function() { + console.log('handling set brightness success.'); + }, + fail: function(data, code) { + console.error('handling set brightness value fail, code:' + code + ', data: ' + data); + } + }); + ``` ## brightness.getMode -getMode(Object): void +getMode(options?: GetBrightnessModeOptions: void Obtains the screen brightness adjustment mode. @@ -100,75 +82,57 @@ Obtains the screen brightness adjustment mode. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| success | Function | No | Called when the execution is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete | - -The following values will be returned when the operation is successful. - -| Name | Type | Description | -| -------- | -------- | -------- | -| mode | number | The value can be **0** or **1**.
- **0**: The screen brightness is manually adjusted.
- **1**: The screen brightness is automatically adjusted. | +| options | [GetBrightnessModeOptions](#getbrightnessmodeoptions) | No| Options for obtaining the screen brightness mode.| **Example** -```js -export default { - getMode() { - brightness.getMode({ - success: function(data){ - console.log('success get mode:' + data.mode); - }, - fail: function(data, code){ - console.log('handling get mode fail, code:' + code + ', data: ' + data); + ```js + brightness.getMode({ + success: function(data) { + console.log('success get mode:' + data.mode); }, - }); - }, -} -``` + fail: function(data, code){ + console.error('handling get mode fail, code:' + code + ', data: ' + data); + } + }); + ``` ## brightness.setMode -setMode(Object): void +setMode(options?: SetBrightnessModeOptions): void Sets the screen brightness adjustment mode. **System capability**: SystemCapability.PowerManager.DisplayPowerManager **Parameters** - -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| mode | number | Yes | The value can be **0** or **1**.
- **0**: The screen brightness is manually adjusted.
- **1**: The screen brightness is automatically adjusted. | -| success | Function | No | Called when the execution is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| options | [SetBrightnessModeOptions](#setbrightnessmodeoptions) | No | Options for setting the screen brightness mode.| **Example** -```js -export default { - setMode() { - brightness.setMode({ - mode: 1, - success: function(){ - console.log('handling set mode success.'); - }, - fail: function(data, code){ - console.log('handling set mode fail, code:' + code + ', data: ' + data); - }, - }); - }, -} -``` + ```js + brightness.setMode({ + mode: 1, + success: function() { + console.log('handling set mode success.'); + }, + fail: function(data, code) { + console.error('handling set mode fail, code:' + code + ', data: ' + data); + } + }); + ``` ## brightness.setKeepScreenOn -setKeepScreenOn(Object): void +setKeepScreenOn(options?: SetKeepScreenOnOptions): void + +>This API is no longer maintained since API version 7. It is recommended that you use [window.setKeepScreenOn](js-apis-window.md#setkeepscreenon) instead. Sets whether to always keep the screen on. Call this API in **onShow()**. @@ -176,27 +140,88 @@ Sets whether to always keep the screen on. Call this API in **onShow()**. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| keepScreenOn | boolean | Yes | Whether to always keep the screen on | -| success | Function | No | Called when the execution is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| options | [SetKeepScreenOnOptions](#setkeepscreenonoptions) | No| Options for setting the screen to be steady on.| **Example** -```js -export default { - setKeepScreenOn() { - brightness.setKeepScreenOn({ - keepScreenOn: true, - success: function () { - console.log('handling set keep screen on success.') - }, - fail: function (data, code) { - console.log('handling set keep screen on fail, code:' + code + ', data: ' + data); - }, - }); - }, -} -``` \ No newline at end of file + ```js + brightness.setKeepScreenOn({ + keepScreenOn: true, + success: function () { + console.log('handling set keep screen on success.'); + }, + fail: function (data, code) { + console.error('handling set keep screen on fail, code:' + code + ', data: ' + data); + } + }); + ``` +## GetBrightnessOptions + +Defines the options for obtaining the screen brightness. + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| success | (data: [BrightnessResponse](#brightnessresponse)) => void | No | Called when API call is successful. **data** is a return value of the [BrightnessResponse](#brightnessresponse) type.| +| fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code. | +| complete | () => void | No | Called when API call is complete. | + +## SetBrightnessOptions + +Defines the options for setting the screen brightness. + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | +| value | number | Yes | Screen brightness. The value is an integer ranging from **1** to **255**.
- If the value is less than or equal to **0**, value **1** will be used.
- If the value is greater than **255**, value **255** will be used.
- If the value contains decimals, the integral part of the value will be used. For example, if value **8.1** is set, value **8** will be used.| +| success | () => void | No | Called when API call is successful. | +| fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code. | +| complete | () => void | No | Called when API call is complete. | + +## BrightnessResponse + +Defines a response that returns the screen brightness. + +| Parameter| Type | Description| +| -------- | -------- | -------- | +| value | number | Screen brightness. The value ranges from 1 to 255.| + +## GetBrightnessModeOptions + +Defines the options for obtaining the screen brightness mode. + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| success | (data: [BrightnessModeResponse](#brightnessmoderesponse)) => void | No | Called when API call is successful. **data** is a return value of the [BrightnessModeResponse](#brightnessmoderesponse) type.| +| fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code. | +| complete | () => void | No | Called when API call is complete. | + +## SetBrightnessModeOptions + +Defines the options for setting the screen brightness mode. + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | ------------------------------------------------------ | +| mode | number | Yes | The value **0** indicates the manual adjustment mode, and the value **1** indicates the automatic adjustment mode.| +| success | () => void | No | Called when API call is successful. | +| fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code.| +| complete | () => void | No | Called when API call is complete. | + +## BrightnessModeResponse + +Defines a response that returns the screen brightness mode. + +| Name| Type | Description| +| -------- | -------- | -------- | +| mode | number | The value **0** indicates the manual adjustment mode, and the value **1** indicates the automatic adjustment mode.| + +## SetKeepScreenOnOptions + +Defines the options for setting the screen to be steady on. + +| Name | Type | Mandatory| Description | +| ------------ | ------------------------------------ | ---- | ------------------------------------------------------ | +| keepScreenOn | boolean | Yes | The value **true** means to keep the screen steady on, and the value **false** indicates the opposite. | +| success | () => void | No | Called when API call is successful. | +| fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code.| +| complete | () => void | No | Called when API call is complete. | diff --git a/en/application-dev/reference/apis/js-apis-system-device.md b/en/application-dev/reference/apis/js-apis-system-device.md index c5b92831958ea79cb7b868fbf549974cdf39a669..6da9ae481fe8ef4aeb440090f478fb1069596882 100644 --- a/en/application-dev/reference/apis/js-apis-system-device.md +++ b/en/application-dev/reference/apis/js-apis-system-device.md @@ -1,61 +1,61 @@ -# Device Information +# @system.device -> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** -> - The APIs of this module are no longer maintained since API version 6. It is recommended that you use [`@ohos.deviceInfo`](js-apis-device-info.md) instead. +The **device** module provides APIs for checking information about the current device. + +> **NOTE** +> - The APIs of this module are no longer maintained since API version 6. It is recommended that you use [@ohos.deviceInfo](js-apis-device-info.md) instead. > > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. - ## Modules to Import - ``` import device from '@system.device'; ``` - ## device.getInfo getInfo(Object): void Obtains the device information. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> **NOTE** +> > Do not call **device.getInfo** before the **onShow** event of the home page. -**System capability**: SystemCapability.Startup.SysInfo +**System capability**: SystemCapability.Startup.SystemInfo **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| success | Function | No | Called when the device information is obtained | -| fail | Function | No | Called when the device information fails to be obtained | -| complete | Function | No | Called when the execution is complete | +| success | Function | No| Called when API call is successful.| +| fail | Function | No| Called when API call has failed.| +| complete | Function | No| Called when API call is complete.| -The following values will be returned when the device information is obtained. +**Return value of success()** -| Name | Type | Description | +| Name| Type| Description| | -------- | -------- | -------- | -| brand | string | Brand | -| manufacturer | string | Manufacturer | -| model | string | Model | -| product | string | Product number | -| language4+ | string | System language | -| region4+ | string | System region | -| windowWidth | number | Window width | -| windowHeight | number | Window height | -| screenDensity4+ | number | Screen density | -| screenShape4+ | string | Screen shape. The options are as follows:
- rect: rectangle screen
- circle: circle screen | -| apiVersion4+ | number | API version | -| releaseType4+ | string | Release type. The value includes both the release type and the API version, for example, Beta1.
Available release types are as follows:
- **Canary**: For the same API version, different canary releases are compatible with each other, but not compatible with those of the **beta** and **release** type.
- **Beta**: For the same API version, different beta releases are compatible with each other, but not compatible with those of the **release** type.
- **Release**: Releases of this type are compatible with the latest five API versions. | -| deviceType4+ | string | Device type | - -The following error code will be returned if the device information fails to be obtained. - -| Error Code | Description | +| brand | string | Brand.| +| manufacturer | string | Manufacturer.| +| model | string | Model. | +| product | string | Product number.| +| language4+ | string | System language.| +| region4+ | string | System region.| +| windowWidth | number | Window width.| +| windowHeight | number | Window height.| +| screenDensity4+ | number | Screen density.| +| screenShape4+ | string | Screen shape. The options are as follows:
- **rect**: rectangle screen
- **circle**: circle screen| +| apiVersion4+ | number | API version.| +| releaseType4+ | string | Release type. The value includes both the release type and the API version, for example, Beta1.
Available release types are as follows:
- **Canary**: For the same API version, different canary releases are compatible with each other, but not compatible with those of the **beta** and **release** type.
- **Beta**: For the same API version, different beta releases are compatible with each other, but not compatible with those of the **release** type.
- **Release**: Releases of this type are compatible with the latest five API versions.| +| deviceType4+ | string | Device type.| + +**Return value of fail()** + +| Error Code| Description| | -------- | -------- | -| 200 | The returned result contains information that cannot be obtained. | +| 200 | The returned result contains information that cannot be obtained.| **Example** @@ -72,4 +72,4 @@ export default { }); }, } -``` \ No newline at end of file +``` diff --git a/en/application-dev/reference/apis/js-apis-system-location.md b/en/application-dev/reference/apis/js-apis-system-location.md index ab53fb2d188b7b929c591a67c33cec12984e063c..b0648efc475396e317d6f8da4891ecb66e6164df 100644 --- a/en/application-dev/reference/apis/js-apis-system-location.md +++ b/en/application-dev/reference/apis/js-apis-system-location.md @@ -1,6 +1,6 @@ # Geographic Location -> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> **Note:** > - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.geolocation`](js-apis-geolocation.md) instead. > > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. diff --git a/en/application-dev/reference/apis/js-apis-system-package.md b/en/application-dev/reference/apis/js-apis-system-package.md index c6453ec28f1dca4749d8f8c91414a609af161466..3dec0fa1e2fd325479ac688443e67500d60f570b 100644 --- a/en/application-dev/reference/apis/js-apis-system-package.md +++ b/en/application-dev/reference/apis/js-apis-system-package.md @@ -1,9 +1,9 @@ -# Application Management +# @system.package (Bundle Management) -> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> **NOTE** > -> - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.bundle`](js-apis-Bundle.md) instead. +> - This module is deprecated since API version 9. You are advised to use [@ohos.bundle.bundleManager](js-apis-bundleManager.md) instead. > > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -12,11 +12,12 @@ ``` -import pkg from '@system.package'; +import package from '@system.package'; ``` -## package.hasInstalled +## package.hasInstalled(deprecated) +> This API is deprecated since API version 9. You are advised to use [@ohos.bundle.bundleManager](js-apis-bundleManager.md) instead. hasInstalled(Object): void @@ -26,35 +27,57 @@ Checks whether an application exists, or whether a native application has been i **System capability**: SystemCapability.BundleManager.BundleFramework -**Parameter** +**Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| bundleName | string | Yes | Application bundle name | -| success | Function | No | Called when the check result is obtained | -| fail | Function | No | Called when the check result fails to be obtained | -| complete | Function | No | Called when the execution is complete | +|options | [CheckPackageHasInstalledOptions](#checkpackagehasinstalledoptions) | Yes| Options.| -The following value will be returned when the check result is obtained. +**Return value** -| Name | Type | Description | +| Name| Type| Description| | -------- | -------- | -------- | -| result | boolean | Whether the application exists, or whether the native application has been installed | +| result | boolean | The value **true** means that the application exists or the native application has been installed, and **false** means the opposite.| **Example** -``` -export default { - hasInstalled() { - pkg.hasInstalled({ - bundleName: 'com.example.bundlename', - success: function(data) { - console.log('package has installed: ' + data); - }, - fail: function(data, code) { - console.log('query package fail, code: ' + code + ', data: ' + data); - }, - }); +``` ts +export default { + hasInstalled() { + package.hasInstalled({ + bundleName: 'com.example.bundlename', + success: function(data) { + console.log('package has installed: ' + data); + }, + fail: function(data, code) { + console.log('query package fail, code: ' + code + ', data: ' + data); + }, + }); }, } -``` \ No newline at end of file +``` + +## CheckPackageHasInstalledResponse + +> This API is deprecated since API version 9. + +Checks whether a bundle has been installed. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name| Type| Description| +| --- | --- | ---- | +| result | boolean | The value **true** means that the bundle has been installed, and **false** means the opposite.| + +## CheckPackageHasInstalledOptions + +> This API is deprecated since API version 9. + +Defines the options used for checking whether a bundle has been installed. + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name.| +| success | Function | No| Called when API call is successful.| +| fail | Function | No| Called when API call has failed.| +| complete | Function | No| Called when API call is complete.| diff --git a/en/application-dev/reference/apis/js-apis-system-parameter.md b/en/application-dev/reference/apis/js-apis-system-parameter.md index 6ccbc31664329e94861a503f1995682f104c6d79..ab3ae31887d1a2c55eb94c0164573834321e96c0 100644 --- a/en/application-dev/reference/apis/js-apis-system-parameter.md +++ b/en/application-dev/reference/apis/js-apis-system-parameter.md @@ -1,11 +1,10 @@ -# SystemParameter +# @ohos.systemParameter -The **SystemParameter** module provides system services with easy access to key-value pairs. You can use the APIs of this module to describe the service status and change the service behavior. The basic operation primitives are get and set. You can obtain the values of system parameters through getters and modify the values through setters. +The **SystemParameter** module provides system services with easy access to key-value pairs. You can use the APIs provided by this module to describe the service status and change the service behavior. The basic operation primitives are get and set. You can obtain the values of system parameters through getters and modify the values through setters. For details about the system parameter design principles and definitions, see [Service Management](../../../device-dev/subsystems/subsys-boot-init-sysparam.md). > **NOTE** -> > - The APIs of this module are no longer maintained since API version 9. It is recommended that you use [@ohos.systemParameterV9](js-apis-system-parameterV9.md) instead. > - The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The APIs provided by this module are system APIs. @@ -54,7 +53,7 @@ try { get(key: string, callback: AsyncCallback<string>): void -Obtains the value of the system parameter with the specified key. This API uses an asynchronous callback to return the result. +Obtains the value of the system parameter with the specified key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Startup.SystemInfo @@ -164,9 +163,9 @@ Sets a value for the system parameter with the specified key. | value | string | Yes| Value of the system parameter to set.| > **NOTE** -> > - This API can be used only for setting parameters of system applications. -> - SELinux and DAC rules must be configured for authorized system applications. For details, see [Service Management](../../../device-dev/subsystems/subsys-boot-init-sysparam.md). +> - SELinux and Discretionary Access Control (DAC) rules must be configured for authorized system applications. For details about how to configure SELinux and DAC rules, see [Parameter Management](../../../device-dev/subsystems/subsys-boot-init-sysparam.md). + **Example** @@ -195,9 +194,8 @@ Sets a value for the system parameter with the specified key. This API uses an a | callback | AsyncCallback<void> | Yes| Callback used to return the result.| > **NOTE** -> > - This API can be used only for setting parameters of system applications. -> - SELinux and discretionary access control (DAC) rules must be configured for authorized system applications. For details, see [Service Management](../../../device-dev/subsystems/subsys-boot-init-sysparam.md). +> - SELinux and Discretionary Access Control (DAC) rules must be configured for authorized system applications. For details about how to configure SELinux and DAC rules, see [Parameter Management](../../../device-dev/subsystems/subsys-boot-init-sysparam.md). **Example** @@ -236,9 +234,8 @@ Sets a value for the system parameter with the specified key. This API uses a pr | Promise<void> | Promise used to return the execution result.| > **NOTE** -> > - This API can be used only for setting parameters of system applications. -> - SELinux and discretionary access control (DAC) rules must be configured for authorized system applications. For details, see [Service Management](../../../device-dev/subsystems/subsys-boot-init-sysparam.md). +> - SELinux and Discretionary Access Control (DAC) rules must be configured for authorized system applications. For details about how to configure SELinux and DAC rules, see [Parameter Management](../../../device-dev/subsystems/subsys-boot-init-sysparam.md). **Example** diff --git a/en/application-dev/reference/apis/js-apis-tagSession.md b/en/application-dev/reference/apis/js-apis-tagSession.md index e6073f2dca4b101454fbdf14dd9bdd406a8eaade..3138f52c7089ba4a53809711c442b79f6a1aa1aa 100644 --- a/en/application-dev/reference/apis/js-apis-tagSession.md +++ b/en/application-dev/reference/apis/js-apis-tagSession.md @@ -1,8 +1,9 @@ -# NFC Tag Session +# tagSession The **tagSession** module provides common APIs for establishing connections and transferring data. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## **Modules to Import** @@ -15,17 +16,15 @@ import tag from '@ohos.nfc.tag'; Provides common APIs for establishing connections and transferring data. **tagSession** is the base class of all [NFC tag technologies](js-apis-nfctech.md). -A child class instance is required to access the following interfaces. You can use **get**XX**Tag()** to obtain a child class instance. +A child class instance is required to access the following interfaces. You can use **get**XXX() to obtain a child class instance. The specific API varies with the NFC tag technology in use. For details, see [NFC Tags](js-apis-nfcTag.md). -### tagSession.connectTag - -connectTag(): boolean; +### tagSession.getTagInfo -Connects to this tag. +getTagInfo(): tag.TagInfo -Call this API to set up a connection before reading data from or writing data to a tag. +Obtains the **tagInfo** object provided by the NFC service when the tag is dispatched. **Required permissions**: ohos.permission.NFC_TAG @@ -35,23 +34,25 @@ Call this API to set up a connection before reading data from or writing data to | **Type**| **Description** | | ------------------ | --------------------------| -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| TagInfo | **Taginfo** object obtained.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let isNfcConnected = tag.getXXXTag(taginfo).connectTag(); -console.log("isNfcConnected:" +isNfcConnected); +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +let tagInfo = tag.getIsoDep(tagInfo).getTagInfo(); +console.log("tag tagInfo: " + tagInfo); ``` -### tagSession.reset() +### tagSession.connectTag -reset(): void +connectTag(): boolean; -Resets the connection to this tag and restores the default timeout duration for writing data to the tag. +Connects to this tag. Call this API to set up a connection before reading data from or writing data to a tag. **Required permissions**: ohos.permission.NFC_TAG @@ -68,9 +69,32 @@ Resets the connection to this tag and restores the default timeout duration for ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let reset = tag.getXXXTag(taginfo).reset(); -console.log("reset:" +reset); +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +let connectStatus = tag.getIsoDep(tagInfo).connectTag(); +console.log("connectStatus: " + connectStatus); +``` + +### tagSession.reset() + +reset(): void + +Resets the connection to this tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +tag.getIsoDep(tagInfo).reset(); ``` ### tagSession.isTagConnected @@ -94,16 +118,18 @@ Checks whether the tag is connected. ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let isTagConnected = tag.getXXXTag(taginfo).isTagConnected(); -console.log("isTagConnected:" +isTagConnected); +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +let isTagConnected = tag.getIsoDep(tagInfo).isTagConnected(); +console.log("isTagConnected: " + isTagConnected); ``` ### tagSession.getMaxSendLength getMaxSendLength(): number -Obtains the maximum length of the data that can be sent to the tag. +Obtains the maximum length of the data that can be sent to this tag. **Required permissions**: ohos.permission.NFC_TAG @@ -113,14 +139,167 @@ Obtains the maximum length of the data that can be sent to the tag. | **Type**| **Description** | | ------------------ | --------------------------| -| number | Maximum data length obtained.| +| number | Maximum data length obtained. The value cannot be a negative number.| + +**Example** +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +let maxSendLen = tag.getIsoDep(tagInfo).getMaxSendLength(); +console.log("tag maxSendLen: " + maxSendLen); +``` + +### tagSession.getSendDataTimeout + +getSendDataTimeout(): number + +Obtains the timeout period for sending data to this tag, in milliseconds. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number | Timeout period obtained, in milliseconds. The value cannot be a negative number.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +let sendDataTimeout = tag.getIsoDep(tagInfo).getSendDataTimeout(); +console.log("tag sendDataTimeout: " + sendDataTimeout); +``` + +### tagSession.setSendDataTimeout + +setSendDataTimeout(timeout: number): boolean + +Sets the timeout period for sending data to this tag, in milliseconds. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| timeout | number | Yes| Timeout period to set, in milliseconds. The value cannot be a negative number.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| boolean | Returns **true** if the timeout period is set successfully; returns **false** otherwise.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +let timeoutMs = 700; // Change it as required. +let setStatus = tag.getIsoDep(tagInfo).setSendDataTimeout(timeoutMs); +console.log("tag setSendDataTimeout setStatus: " + setStatus); +``` + +### tagSession.sendData + +sendData(data: number[]): Promise + +Sends data to this tag. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| data | number[] | Yes| Data to send. The data consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise | Promise used to return the response from the tag. The response consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +// Connect to the tag if it is not connected. +if (!tag.getIsoDep(tagInfo).isTagConnected()) { + if (!tag.getIsoDep(tagInfo).connectTag()) { + console.log("tagSession connectTag failed."); + return; + } +} + +let cmdData = [0x01, 0x02, 0x03, 0x04]; // Change it as required. +tag.getIsoDep(tagInfo).sendData(cmdData).then((response) => { + console.log("tagSession sendData Promise response: " + response); +}).catch((err)=> { + console.log("tagSession sendData Promise err: " + err); +}); +``` + +### tagSession.sendData + +sendData(data: number[], callback: AsyncCallback): void + +Sends data to this tag. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| data | number[] | Yes| Data to send. The data consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| +| callback | AsyncCallback | Yes| Callback invoked to return the response from the tag. The response consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let mazSendLen = tag.getXXXTag(taginfo).getMaxSendLength(); -console.log("mazSendLen:" +mazSendLen); +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +// Connect to the tag if it is not connected. +if (!tag.getIsoDep(tagInfo).isTagConnected()) { + if (!tag.getIsoDep(tagInfo).connectTag()) { + console.log("tagSession connectTag failed."); + return; + } +} + +let cmdData = [0x01, 0x02, 0x03, 0x04]; // Change it as required. +tag.getIsoDep(tagInfo).sendData(cmdData, (err, response)=> { + if (err) { + console.log("tagSession sendData AsyncCallback err: " + err); + } else { + console.log("tagSession sendData AsyncCallback response: " + response); + } +}); ``` diff --git a/en/application-dev/reference/apis/js-apis-thermal.md b/en/application-dev/reference/apis/js-apis-thermal.md index b7b7e08a0a6a5a82a8813aad1f9d2010ff899a50..e0d809d06ab24702e5eaf67eb6b1b841a7944ffc 100644 --- a/en/application-dev/reference/apis/js-apis-thermal.md +++ b/en/application-dev/reference/apis/js-apis-thermal.md @@ -1,11 +1,9 @@ # Thermal Manager -> **NOTE** -> -> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. - This module provides thermal level-related callback and query APIs to obtain the information required for thermal control. +> **NOTE** +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -13,78 +11,168 @@ This module provides thermal level-related callback and query APIs to obtain the import thermal from '@ohos.thermal'; ``` +## thermal.registerThermalLevelCallback9+ -## ThermalLevel +registerThermalLevelCallback(callback: Callback<ThermalLevel>): void -Represents the thermal level. +Subscribes to thermal level changes. **System capability:** SystemCapability.PowerManager.ThermalManager -| Name | Default Value | Description | -| ---------- | ---- | ---------------------------------------- | -| COOL | 0 | The device is cool, and services are not restricted.| -| NORMAL | 1 | The device is operational but is not cool. You need to pay attention to its heating.| -| WARM | 2 | The device is warm. You need to stop or delay some imperceptible services.| -| HOT | 3 | The device is heating up. You need to stop all imperceptible services and downgrade or reduce the load of other services.| -| OVERHEATED | 4 | The device is overheated. You need to stop all imperceptible services and downgrade or reduce the load of major services.| -| WARNING | 5 | The device is overheated and is about to enter the emergency state. You need to stop all imperceptible services and downgrade major services to the maximum extent.| -| EMERGENCY | 6 | The device has entered the emergency state. You need to stop all services except those for the emergency help purposes.| +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------ | +| callback | Callback<ThermalLevel> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-thermal.md). + +| Code | Error Message | +|---------|---------| +| 4800101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + thermal.registerThermalLevelCallback(level => { + console.info('thermal level is: ' + level); + }); + console.info('register thermal level callback success.'); +} catch(err) { + console.error('register thermal level callback failed, err: ' + err); +} +``` + +## thermal.unregisterThermalLevelCallback9+ + +unregisterThermalLevelCallback(callback?: Callback\): void + +Unsubscribes from thermal level changes. + +**System capability:** SystemCapability.PowerManager.ThermalManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------------------------- | +| callback | Callback<void> | No | Callback used to return the result. No value is returned. If this parameter is not set, this API unsubscribes from all callbacks.| + +**Error codes** + +For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-thermal.md). + +| Code | Error Message | +|---------|---------| +| 4800101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + thermal.unregisterThermalLevelCallback(() => { + console.info('unsubscribe thermal level success.'); + }); + console.info('unregister thermal level callback success.'); +} catch(err) { + console.error('unregister thermal level callback failed, err: ' + err); +} +``` + +## thermal.getLevel9+ + +getLevel(): ThermalLevel + +Obtains the current thermal level. + +**System capability:** SystemCapability.PowerManager.ThermalManager +**Return value** -## thermal.subscribeThermalLevel +| Type | Description | +| ------------ | ------------ | +| ThermalLevel | Thermal level obtained.| + +**Error codes** + +For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-thermal.md). + +| Code | Error Message | +|---------|---------| +| 4800101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + var level = thermal.getLevel(); + console.info('thermal level is: ' + level); +} catch(err) { + console.error('get thermal level failed, err: ' + err); +} +``` + +## thermal.subscribeThermalLevel(deprecated) subscribeThermalLevel(callback: AsyncCallback<ThermalLevel>): void +> This API is deprecated since API version 9. You are advised to use [thermal.registerThermalLevelCallback](#thermalregisterthermallevelcallback9) instead. + Subscribes to thermal level changes. **System capability:** SystemCapability.PowerManager.ThermalManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------------- | ---- | ---------------------------------------- | -| callback | AsyncCallback<ThermalLevel> | Yes | Callback used to obtain the return value.
The return value contains only one parameter, that is, thermal level. If an alarm is generated, you can use `// @ts-ignore` to suppress the alarm.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<ThermalLevel> | Yes | Callback used to return the result. The return value contains only one parameter, that is, thermal level. If an alarm is generated, you can use `// @ts-ignore` to suppress the alarm.| **Example** ```js -var lev = 0; -thermal.subscribeThermalLevel((lev) => { - console.info("Thermal level is: " + lev); -}) +thermal.subscribeThermalLevel((level) => { + console.info('thermal level is: ' + level); +}); ``` -## thermal.unsubscribeThermalLevel +## thermal.unsubscribeThermalLevel(deprecated) unsubscribeThermalLevel(callback?: AsyncCallback\): void +> This API is deprecated since API version 9. You are advised to use [thermal.unregisterThermalLevelCallback](#thermalunregisterthermallevelcallback9) instead. + Unsubscribes from thermal level changes. **System capability:** SystemCapability.PowerManager.ThermalManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | ---- | --------------------- | -| callback | AsyncCallback<void> | No | Callback without a return value.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------------------------------------------- | +| callback | AsyncCallback<void> | No | Callback used to return the result. No value is returned. If this parameter is not set, this API unsubscribes from all callbacks.| **Example** ```js thermal.unsubscribeThermalLevel(() => { - console.info("Unsubscribe completed."); + console.info('unsubscribe thermal level success.'); }); ``` -## thermal.getThermalLevel +## thermal.getThermalLevel(deprecated) getThermalLevel(): ThermalLevel +> This API is deprecated since API version 9. You are advised to use [thermal.getLevel](#thermalgetlevel9) instead. + Obtains the current thermal level. **System capability:** SystemCapability.PowerManager.ThermalManager -**Return value**: +**Return value** | Type | Description | | ------------ | ------ | @@ -93,6 +181,22 @@ Obtains the current thermal level. **Example** ```js -var lev = thermal.getThermalLevel(); -console.info("Thermal level is: " + lev); +var level = thermal.getThermalLevel(); +console.info('thermal level is: ' + level); ``` + +## ThermalLevel + +Represents the thermal level. + +**System capability:** SystemCapability.PowerManager.ThermalManager + +| Name | Value | Description | +| ---------- | ---- | ------------------------------------------------------------ | +| COOL | 0 | The device is cool, and services are not restricted. | +| NORMAL | 1 | The device is operational but is not cool. You need to pay attention to its heating.| +| WARM | 2 | The device is warm. You need to stop or delay some imperceptible services.| +| HOT | 3 | The device is heating up. You need to stop all imperceptible services and downgrade or reduce the load of other services.| +| OVERHEATED | 4 | The device is overheated. You need to stop all imperceptible services and downgrade or reduce the load of major services.| +| WARNING | 5 | The device is overheated and is about to enter the emergency state. You need to stop all imperceptible services and downgrade major services to the maximum extent.| +| EMERGENCY | 6 | The device has entered the emergency state. You need to stop all services except those for the emergency help purposes.| diff --git a/en/application-dev/reference/apis/js-apis-treemap.md b/en/application-dev/reference/apis/js-apis-treemap.md index e2a41d26819c96d3ef4321bfaf9a0e9f058300c9..573732b5474552added2d9918986e2add3982b01 100644 --- a/en/application-dev/reference/apis/js-apis-treemap.md +++ b/en/application-dev/reference/apis/js-apis-treemap.md @@ -1,4 +1,4 @@ -# Nonlinear Container TreeMap +# @ohos.util.TreeMap (Nonlinear Container TreeMap) > **NOTE** > @@ -59,11 +59,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let treeMap = new TreeMap(); -try { - let treeMap2 = TreeMap(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -94,11 +89,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts const treeMap = new TreeMap(); let result = treeMap.isEmpty(); -try { - treeMap.isEmpty.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -137,11 +127,6 @@ let treeMap = new TreeMap(); let result = treeMap.hasKey("squirrel"); treeMap.set("squirrel", 123); let result1 = treeMap.hasKey("squirrel"); -try { - treeMap.hasKey.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -180,11 +165,6 @@ let treeMap = new TreeMap(); let result = treeMap.hasValue(123); treeMap.set("squirrel", 123); let result1 = treeMap.hasValue(123); -try { - treeMap.hasValue.bind({}, 123)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -223,11 +203,6 @@ let treeMap = new TreeMap(); treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); let result = treeMap.get("sparrow"); -try { - treeMap.get.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -260,11 +235,6 @@ let treeMap = new TreeMap(); treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); let result = treeMap.getFirstKey(); -try { - treeMap.getFirstKey.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -297,11 +267,6 @@ let treeMap = new TreeMap(); treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); let result = treeMap.getLastKey(); -try { - treeMap.getLastKey.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -335,11 +300,6 @@ treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); let map = new TreeMap(); treeMap.setAll(map); -try { - treeMap.setAll.bind({}, map)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -377,11 +337,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let treeMap = new TreeMap(); treeMap.set("squirrel", 123); -try { - treeMap.set.bind({}, "squirrel", 123)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -420,11 +375,6 @@ let treeMap = new TreeMap(); treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); treeMap.remove("sparrow"); -try { - treeMap.remove.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -464,11 +414,6 @@ treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); treeMap.set("gander", 356); let result = treeMap.getLowerKey("sparrow"); -try { - treeMap.getLowerKey.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -508,11 +453,6 @@ treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); treeMap.set("gander", 356); let result = treeMap.getHigherKey("sparrow"); -try { - treeMap.getHigherKey.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### replace @@ -550,11 +490,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er let treeMap = new TreeMap(); treeMap.set("sparrow", 123); let result = treeMap.replace("sparrow", 357); -try { - treeMap.replace.bind({}, "sparrow", 357)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -581,11 +516,6 @@ let treeMap = new TreeMap(); treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); treeMap.clear(); -try { - treeMap.clear.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -623,11 +553,6 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - treeMap.keys.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -665,17 +590,12 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - treeMap.values.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value?: V, key?: K, map?: TreeMap) => void, thisArg?: Object): void +forEach(callbackFn: (value?: V, key?: K, map?: TreeMap) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -685,7 +605,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -712,13 +632,6 @@ treeMap.set("gull", 357); treeMap.forEach((value, key) => { console.log("value:" + value, key); }); -try { - treeMap.forEach.bind({}, (value, key) => { - console.log("value:" + value, key); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -757,11 +670,6 @@ while(temp != undefined) { console.log("value:" + temp[1]); temp = iter.next().value; } -try { - treeMap.entries.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -807,9 +715,4 @@ while(temp != undefined) { console.log("value:" + temp[1]); temp = iter.next().value; } -try { - treeMap[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-treeset.md b/en/application-dev/reference/apis/js-apis-treeset.md index ef10035349bf185462f803ad967270e79b8cc93d..bc6f1272452fd35d0458b6232f7c03a1bd19ce9b 100644 --- a/en/application-dev/reference/apis/js-apis-treeset.md +++ b/en/application-dev/reference/apis/js-apis-treeset.md @@ -1,4 +1,4 @@ -# Nonlinear Container TreeSet +# @ohos.util.TreeSet (Nonlinear Container TreeSet) > **NOTE** > @@ -56,11 +56,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let treeSet = new TreeSet(); -try { - let treeSet2 = TreeSet(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -91,11 +86,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts const treeSet = new TreeSet(); let result = treeSet.isEmpty(); -try { - treeSet.isEmpty.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -134,11 +124,6 @@ let treeSet = new TreeSet(); treeSet.has(123); treeSet.add(123); let result1 = treeSet.has(123); -try { - treeSet.has.bind({}, 123)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -171,11 +156,6 @@ let treeSet = new TreeSet(); treeSet.add("squirrel"); treeSet.add("sparrow"); let result = treeSet.getFirstValue(); -try { - treeSet.getFirstValue.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -208,11 +188,6 @@ let treeSet = new TreeSet(); treeSet.add("squirrel"); treeSet.add("sparrow"); let result = treeSet.getLastValue(); -try { - treeSet.getLastValue.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -249,11 +224,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let treeSet = new TreeSet(); let result = treeSet.add("squirrel"); -try { - treeSet.add.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -292,11 +262,6 @@ let treeSet = new TreeSet(); treeSet.add("squirrel"); treeSet.add("sparrow"); let result = treeSet.remove("sparrow"); -try { - treeSet.remove.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -336,11 +301,6 @@ treeSet.add("squirrel"); treeSet.add("sparrow"); treeSet.add("gander"); let result = treeSet.getLowerValue("sparrow"); -try { - treeSet.getLowerValue.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -380,11 +340,6 @@ treeSet.add("squirrel"); treeSet.add("sparrow"); treeSet.add("gander"); let result = treeSet.getHigherValue("sparrow"); -try { - treeSet.getHigherValue.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -417,11 +372,6 @@ let treeSet = new TreeSet(); treeSet.add("squirrel"); treeSet.add("sparrow"); let result = treeSet.popFirst(); -try { - treeSet.popFirst.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -454,11 +404,6 @@ let treeSet = new TreeSet(); treeSet.add("squirrel"); treeSet.add("sparrow"); let result = treeSet.popLast(); -try { - treeSet.popLast.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -485,11 +430,6 @@ let treeSet = new TreeSet(); treeSet.add("squirrel"); treeSet.add("sparrow"); treeSet.clear(); -try { - treeSet.clear.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -527,17 +467,12 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - treeSet.values.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value?: T, key?: T, set?: TreeSet<T>) => void, thisArg?: Object): void +forEach(callbackFn: (value?: T, key?: T, set?: TreeSet<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -547,7 +482,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -574,13 +509,6 @@ treeSet.add("gull"); treeSet.forEach((value, key) => { console.log("value:" + value, key) }); -try { - treeSet.forEach.bind({}, (value, key) => { - console.log("value:" + value, key) - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -619,11 +547,6 @@ while(temp != undefined) { console.log("value:" + temp[1]); temp = iter.next().value; } -try { - treeSet.entries.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -668,9 +591,4 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - treeSet[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-uri.md b/en/application-dev/reference/apis/js-apis-uri.md index d058b555c87be4fe5f9601ef4b9f9c7198964463..6bad7dde783939b10243f10824e98ef991235499 100644 --- a/en/application-dev/reference/apis/js-apis-uri.md +++ b/en/application-dev/reference/apis/js-apis-uri.md @@ -1,4 +1,4 @@ -# URI String Parsing +# @ohos.uri (URI String Parsing) > **NOTE** > @@ -40,18 +40,18 @@ A constructor used to create a URI instance. **Parameters** -| Name| Type.| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| uri | string | Yes| Yes| Input object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| uri | string | Yes| Input object.| **Example** ```js -let mm = 'http://username:password@host:8080/directory/file?foo=1&bar=2#fragment'; -new uri.URI(mm); // Output 'http://username:password@host:8080/directory/file?foo=1&bar=2#fragment'; +let mm = 'https://username:password@host:8080/directory/file?foo=1&bar=2#fragment'; +new uri.URI(mm); // Output 'https://username:password@host:8080/directory/file?foo=1&bar=2#fragment'; ``` ```js -new uri.URI('http://username:password@host:8080'); // Output 'http://username:password@host:8080'; +new uri.URI('https://username:password@host:8080'); // Output 'https://username:password@host:8080'; ``` @@ -65,22 +65,23 @@ Obtains the query string applicable to this URI. **Return value** -| Type.| Description| +| Type| Description| | -------- | -------- | | string | Website address in a serialized string.| **Example** ```js -const result = new uri.URI('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); +const result = new uri.URI('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); result.toString() ``` ### equals(deprecated) + > **NOTE** > -> This API is deprecated since API version 9. You are advised to use [equalsTo9+](#equalsto9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [equalsTo9+](#equalsto9) instead. equals(other: URI): boolean @@ -90,21 +91,21 @@ Checks whether this URI is the same as another URI object. **Parameters** -| Name| Type.| Mandatory| Description| +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | other | [URI](#uri) | Yes| URI object to compare.| **Return value** -| Type.| Description| +| Type| Description| | -------- | -------- | | boolean | Returns **true** if the two URIs are the same; returns **false** otherwise.| **Example** ```js -const uriInstance = new uri.URI('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); -const uriInstance1 = new uri.URI('http://username:password@host:8080/directory/file?query=pppppp#qwer=da#fragment'); +const uriInstance = new uri.URI('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); +const uriInstance1 = new uri.URI('https://username:password@host:8080/directory/file?query=pppppp#qwer=da#fragment'); uriInstance.equals(uriInstance1); ``` ### equalsTo9+ @@ -117,21 +118,21 @@ Checks whether this URI is the same as another URI object. **Parameters** -| Name| Type.| Mandatory| Description| +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | other | [URI](#uri) | Yes| URI object to compare.| **Return value** -| Type.| Description| +| Type| Description| | -------- | -------- | | boolean | Returns **true** if the two URIs are the same; returns **false** otherwise.| **Example** ```js -const uriInstance = new uri.URI('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); -const uriInstance1 = new uri.URI('http://username:password@host:8080/directory/file?query=pppppp#qwer=da#fragment'); +const uriInstance = new uri.URI('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); +const uriInstance1 = new uri.URI('https://username:password@host:8080/directory/file?query=pppppp#qwer=da#fragment'); uriInstance.equalsTo(uriInstance1); ``` @@ -145,14 +146,14 @@ Checks whether this URI is an absolute URI (whether the scheme component is defi **Return value** -| Type.| Description| +| Type| Description| | -------- | -------- | | boolean | Returns **true** if the URI is an absolute URI; returns **false** otherwise.| **Example** ```js -const uriInstance = new uri.URI('http://username:password@www.qwer.com:8080?query=pppppp'); +const uriInstance = new uri.URI('https://username:password@www.qwer.com:8080?query=pppppp'); uriInstance.checkIsAbsolute(); ``` @@ -167,13 +168,14 @@ Normalizes the path of this URI. **Return value** -| Type.| Description| +| Type| Description| | -------- | -------- | | URI | URI with the normalized path.| **Example** + ```js -const uriInstance = new uri.URI('http://username:password@www.qwer.com:8080/path/path1/../path2/./path3?query=pppppp'); +const uriInstance = new uri.URI('https://username:password@www.qwer.com:8080/path/path1/../path2/./path3?query=pppppp'); let uriInstance1 = uriInstance.normalize(); uriInstance1.path; ``` diff --git a/en/application-dev/reference/apis/js-apis-url.md b/en/application-dev/reference/apis/js-apis-url.md index 383dd4b3862b849db5e9292d4b841acbc8e3cc33..442c62ee76cf48b60361ee939c0f116bf98fb1fa 100755 --- a/en/application-dev/reference/apis/js-apis-url.md +++ b/en/application-dev/reference/apis/js-apis-url.md @@ -1,4 +1,4 @@ -# URL String Parsing +# @ohos.url (URL String Parsing) > **NOTE** > @@ -14,7 +14,7 @@ import Url from '@ohos.url' ### constructor9+ -constructor(init?: string[][] | Record<string, string> | string | URLParams) +constructor(init?: string[][] | Record<string, string> | string | URLSearchParams) A constructor used to create a **URLParams** instance. @@ -24,7 +24,7 @@ A constructor used to create a **URLParams** instance. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| init | string[][] \| Record<string, string> \| string \| URLParams | No| Input parameter objects, which include the following:
- **string[][]**: two-dimensional string array
- **Record<string, string>**: list of objects
- **string**: string
- **URLParams**: object| +| init | string[][] \| Record<string, string> \| string \| URLSearchParams | No| Input parameter objects, which include the following:
- **string[][]**: two-dimensional string array
- **Record<string, string>**: list of objects
- **string**: string
- **URLSearchParams**: object| **Example** @@ -140,7 +140,7 @@ for (var pair of searchParamsObject .entries()) { // Show keyName/valueName pair ### forEach9+ -forEach(callbackfn: (value: string, key: string, searchParams: this) => void, thisArg?: Object): void +forEach(callbackFn: (value: string, key: string, searchParams: this) => void, thisArg?: Object): void Traverses the key-value pairs in the **URLSearchParams** instance by using a callback. @@ -150,10 +150,10 @@ Traverses the key-value pairs in the **URLSearchParams** instance by using a cal | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the key-value pairs in the **URLSearchParams** instance.| -| thisArg | Object | No| Value to use when the callback is invoked.| +| callbackFn | function | Yes| Callback invoked to traverse the key-value pairs in the **URLSearchParams** instance.| +| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked.| -**Table 1** callbackfn parameter description +**Table 1** callbackFn parameter description | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | @@ -165,7 +165,7 @@ Traverses the key-value pairs in the **URLSearchParams** instance by using a cal ```js const myURLObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); -myURLObject.URLParams.forEach((value, name, searchParams) => { +myURLObject.searchParams.forEach((value, name, searchParams) => { console.log(name, value, myURLObject.searchParams === searchParams); }); ``` @@ -366,18 +366,148 @@ params.append('fod', '3'); console.log(params.toString()); ``` -## URLSearchParams(deprecated) +## URL + +### Attributes + +**System capability**: SystemCapability.Utils.Lang + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| hash | string | Yes| Yes| String that contains a harsh mark (#) followed by the fragment identifier of a URL.| +| host | string | Yes| Yes| Host information in a URL.| +| hostname | string | Yes| Yes| Hostname (without the port) in a URL.| +| href | string | Yes| Yes| String that contains the whole URL.| +| origin | string | Yes| No| Read-only string that contains the Unicode serialization of the origin of the represented URL.| +| password | string | Yes| Yes| Password in a URL.| +| pathname | string | Yes| Yes| Path in a URL.| +| port | string | Yes| Yes| Port in a URL.| +| protocol | string | Yes| Yes| Protocol in a URL.| +| search | string | Yes| Yes| Serialized query string in a URL.| +| searchParams | URLSearchParams | Yes| No| **URLSearchParams** object allowing access to the query parameters in a URL.| +| URLParams | URLParams | Yes| No| **URLParams** object allowing access to the query parameters in a URL.| +| username | string | Yes| Yes| Username in a URL.| ### constructor(deprecated) +constructor(url: string, base?: string | URL) + +Creates a URL. + > **NOTE** > -> This API is deprecated since API version 9. You are advised to use [URLParams9+](#constructor9+) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [parseURL9+](#parseurl9) instead. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| url | string | Yes| Input object.| +| base | string \| URL | No| Input parameter, which can be any of the following:
- **string**: string
- **URL**: string or object| + +**Example** + +```js +let mm = 'http://username:password@host:8080'; +let a = new Url.URL("/", mm); // Output 'http://username:password@host:8080/'; +let b = new Url.URL(mm); // Output 'http://username:password@host:8080/'; +new Url.URL('path/path1', b); // Output 'http://username:password@host:8080/path/path1'; +let c = new Url.URL('/path/path1', b); // Output 'http://username:password@host:8080/path/path1'; +new Url.URL('/path/path1', c); // Output 'http://username:password@host:8080/path/path1'; +new Url.URL('/path/path1', a); // Output 'http://username:password@host:8080/path/path1'; +new Url.URL('/path/path1', "https://www.exampleUrl/fr-FR/toto"); // Output https://www.exampleUrl/path/path1 +new Url.URL('/path/path1', ''); // Raises a TypeError exception as '' is not a valid URL +new Url.URL('/path/path1'); // Raises a TypeError exception as '/path/path1' is not a valid URL +new Url.URL('https://www.example.com', ); // Output https://www.example.com/ +new Url.URL('https://www.example.com', b); // Output https://www.example.com/ +``` + +### parseURL9+ + +static parseURL(url : string, base?: string | URL): URL + +Parses a URL. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| url | string | Yes| Input object.| +| base | string \| URL | No| Input parameter, which can be any of the following:
- **string**: string
- **URL**: string or object| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200002 | Invalid url string. | + +**Example** + +```js +let mm = 'http://username:password@host:8080'; +Url.URL.parseURL(mm); // Output 'http://username:password@host:8080/'; +``` + +### tostring + +toString(): string + +Converts the parsed URL into a string. + +**System capability**: SystemCapability.Utils.Lang + +**Return value** + +| Type| Description| +| -------- | -------- | +| string | Website address in a serialized string.| + +**Example** + +```js +const url = new Url.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); +url.toString(); +``` + + +### toJSON + +toJSON(): string + +Converts the parsed URL into a JSON string. + +**System capability**: SystemCapability.Utils.Lang + +**Return value** + +| Type| Description| +| -------- | -------- | +| string | Website address in a serialized string.| + +**Example** +```js +const url = new Url.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); +url.toJSON(); +``` + +## URLSearchParams(deprecated) + +### constructor(deprecated) constructor(init?: string[][] | Record<string, string> | string | URLSearchParams) A constructor used to create a **URLSearchParams** instance. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+](#constructor9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -398,14 +528,14 @@ let params = new Url.URLSearchParams(urlObject.search); ### append(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.append9+](#append9) instead. - append(name: string, value: string): void Appends a key-value pair into the query string. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.append9+](#append9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -425,14 +555,14 @@ paramsObject.append('fod', '3'); ### delete(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.delete9+](#delete9) instead. - delete(name: string): void Deletes key-value pairs of the specified key. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.delete9+](#delete9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -451,14 +581,14 @@ paramsobject.delete('fod'); ### getAll(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.getAll9+](#getall9) instead. - getAll(name: string): string[] Obtains all the key-value pairs based on the specified key. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.getAll9+](#getall9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -484,14 +614,14 @@ console.log(params.getAll('fod').toString()) // Output ["1","3"]. ### entries(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.entries9+](#entries9) instead. - entries(): IterableIterator<[string, string]> Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and the first and second fields of each array are the key and value respectively. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.entries9+](#entries9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -511,24 +641,25 @@ for (var pair of searchParamsObject .entries()) { // Show keyName/valueName pair ### forEach(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.forEach9+](#foreach9) instead. -forEach(callbackfn: (value: string, key: string, searchParams: this) => void, thisArg?: Object): void +forEach(callbackFn: (value: string, key: string, searchParams: this) => void, thisArg?: Object): void Traverses the key-value pairs in the **URLSearchParams** instance by using a callback. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.forEach9+](#foreach9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the key-value pairs in the **URLSearchParams** instance.| -| thisArg | Object | No| Value to use when the callback is invoked.| +| callbackFn | function | Yes| Callback invoked to traverse the key-value pairs in the **URLSearchParams** instance.| +| thisArg | Object | No| Value to use when **callbackFn** is invoked.| -**Table 1** callbackfn parameter description +**Table 1** callbackFn parameter description | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | @@ -547,14 +678,15 @@ myURLObject.searchParams.forEach((value, name, searchParams) => { ### get(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.get9+](#get9) instead. get(name: string): string | null Obtains the value of the first key-value pair based on the specified key. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.get9+](#get9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -580,14 +712,15 @@ let age = parseInt(paramsObject.get("age"), 10); // is the number 18 ### has(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.has9+](#has9) instead. has(name: string): boolean Checks whether a key has a value. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.has9+](#has9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -612,14 +745,15 @@ paramsObject.has('bard') === true; ### set(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.set9+](#set9) instead. set(name: string, value: string): void Sets the value for a key. If key-value pairs matching the specified key exist, the value of the first key-value pair will be set to the specified value and other key-value pairs will be deleted. Otherwise, the key-value pair will be appended to the query string. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.set9+](#set9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -639,14 +773,15 @@ paramsObject.set('baz', '3'); // Add a third parameter. ### sort(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.sort9+](#sort9) instead. sort(): void Sorts all key-value pairs contained in this object based on the Unicode code points of the keys and returns undefined. This method uses a stable sorting algorithm, that is, the relative order between key-value pairs with equal keys is retained. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.sort9+](#sort9) instead. + **System capability**: SystemCapability.Utils.Lang **Example** @@ -659,14 +794,15 @@ console.log(searchParamsObject.toString()); // Display the sorted query string / ### keys(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.keys9+](#keys9) instead. keys(): IterableIterator<string> Obtains an ES6 iterator that contains the keys of all the key-value pairs. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.keys9+](#keys9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -686,14 +822,15 @@ for (var key of searchParamsObject .keys()) { // Output key-value pairs ### values(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.values9+](#values9) instead. values(): IterableIterator<string> Obtains an ES6 iterator that contains the values of all the key-value pairs. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.values9+](#values9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -714,15 +851,14 @@ for (var value of searchParams.values()) { ### [Symbol.iterator](deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [[Symbol.iterator]9+](#symboliterator9) instead. - - [Symbol.iterator]\(): IterableIterator<[string, string]> Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and the first and second fields of each array are the key and value respectively. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [Symbol.iterator]9+](#symboliterator9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -741,14 +877,15 @@ for (const [name, value] of paramsObject) { ``` ### tostring(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.tostring9+](#tostring9) instead. toString(): string Obtains search parameters that are serialized as a string and, if necessary, percent-encodes the characters in the string. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [tostring9+](#tostring9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -784,14 +921,17 @@ console.log(params.toString()); | port | string | Yes| Yes| Port in a URL.| | protocol | string | Yes| Yes| Protocol in a URL.| | search | string | Yes| Yes| Serialized query string in a URL.| -| searchParams | URLsearchParams | Yes| No| **URLSearchParams** object allowing access to the query parameters in a URL.| +| searchParams | URLSearchParams | Yes| No| **URLSearchParams** object allowing access to the query parameters in a URL.| | URLParams | URLParams | Yes| No| **URLParams** object allowing access to the query parameters in a URL.| | username | string | Yes| Yes| Username in a URL.| +### constructor(deprecated) -### constructor +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [parseURL9+](#parseurl9) instead. -constructor(url?: string, base?: string | URL) +constructor(url: string, base?: string | URL) Creates a URL. @@ -807,23 +947,23 @@ Creates a URL. **Example** ```js -let mm = 'http://username:password@host:8080'; -let a = new Url.URL("/", mm); // Output 'http://username:password@host:8080/'; -let b = new Url.URL(mm); // Output 'http://username:password@host:8080/'; -new Url.URL('path/path1', b); // Output 'http://username:password@host:8080/path/path1'; -let c = new Url.URL('/path/path1', b); // Output 'http://username:password@host:8080/path/path1'; -new Url.URL('/path/path1', c); // Output 'http://username:password@host:8080/path/path1'; -new Url.URL('/path/path1', a); // Output 'http://username:password@host:8080/path/path1'; +let mm = 'https://username:password@host:8080'; +let a = new Url.URL("/", mm); // Output 'https://username:password@host:8080/'; +let b = new Url.URL(mm); // Output 'https://username:password@host:8080/'; +new Url.URL('path/path1', b); // Output 'https://username:password@host:8080/path/path1'; +let c = new Url.URL('/path/path1', b); // Output 'https://username:password@host:8080/path/path1'; +new Url.URL('/path/path1', c); // Output 'https://username:password@host:8080/path/path1'; +new Url.URL('/path/path1', a); // Output 'https://username:password@host:8080/path/path1'; new Url.URL('/path/path1', "https://www.exampleUrl/fr-FR/toto"); // Output https://www.exampleUrl/path/path1 new Url.URL('/path/path1', ''); // Raises a TypeError exception as '' is not a valid URL new Url.URL('/path/path1'); // Raises a TypeError exception as '/path/path1' is not a valid URL -new Url.URL('http://www.shanxi.com', ); // Output http://www.shanxi.com/ -new Url.URL('http://www.shanxi.com', b); // Output http://www.shanxi.com/ +new Url.URL('https://www.example.com', ); // Output https://www.example.com/ +new Url.URL('https://www.example.com', b); // Output https://www.example.com/ ``` ### parseURL9+ -static parseURL(inputUrl : string, inputBase ?: string | URL) +static parseURL(url : string, base?: string | URL): URL Parses a URL. @@ -833,14 +973,14 @@ Parses a URL. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| inputUrl | string | Yes| Input object.| -| inputBase | string \| URL | No| Input parameter, which can be any of the following:
- **string**: string
- **URL**: string or object| +| url | string | Yes| Input object.| +| base | string \| URL | No| Input parameter, which can be any of the following:
- **string**: string
- **URL**: string or object| **Example** ```js -let mm = 'http://username:password@host:8080'; -Url.URL.parseURL(mm); // Output 'http://username:password@host:8080/'; +let mm = 'https://username:password@host:8080'; +Url.URL.parseURL(mm); // Output 'https://username:password@host:8080/'; ``` ### tostring @@ -860,7 +1000,7 @@ Converts the parsed URL into a string. **Example** ```js -const url = new Url.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); +const url = new Url.URL('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); url.toString(); ``` @@ -881,7 +1021,7 @@ Converts the parsed URL into a JSON string. **Example** ```js -const url = new Url.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); +const url = new Url.URL('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); url.toJSON(); ``` diff --git a/en/application-dev/reference/apis/js-apis-util.md b/en/application-dev/reference/apis/js-apis-util.md index 226f7686f490b2d3fd28e8263d7226eb02091c09..8897b51f07b4e00feae752e792820e6b9b32370f 100755 --- a/en/application-dev/reference/apis/js-apis-util.md +++ b/en/application-dev/reference/apis/js-apis-util.md @@ -1,17 +1,15 @@ -# util +# @ohos.util +This module provides common utility functions, such as **TextEncoder** and **TextDecoder** for string encoding and decoding, **RationalNumber** for rational number operations, **LruBuffer** for buffer management, **Scope** for range determination, **Base64** for Base64 encoding and decoding, and **Types** for checks of built-in object types. > **NOTE** > > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -This module provides common utility functions, such as **TextEncoder** and **TextDecoder** for string encoding and decoding, **RationalNumber** for rational number operations, **LruBuffer** for buffer management, **Scope** for range determination, **Base64** for Base64 encoding and decoding, and **Types** for checks of built-in object types. - - ## Modules to Import -``` +```js import util from '@ohos.util'; ``` @@ -45,14 +43,14 @@ console.log(res); ## util.printf(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [util.format9+](#utilformat9) instead. - printf(format: string, ...args: Object[]): string Formats the specified values and inserts them into the string by replacing the wildcard in the string. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [util.format9+](#utilformat9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -60,7 +58,7 @@ Formats the specified values and inserts them into the string by replacing the w | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | format | string | Yes| String.| -| ...args | Object[] | No| Values to format. The formatted values will be replaced the wildcard in the string. | +| ...args | Object[] | No| Values to format. The formatted values will be replaced the wildcard in the string.| **Return value** @@ -69,6 +67,7 @@ Formats the specified values and inserts them into the string by replacing the w | string | String containing the formatted values.| **Example** + ```js let res = util.printf("%s", "hello world!"); console.log(res); @@ -96,22 +95,22 @@ Obtains detailed information about a system error code. **Example** - ```js +```js let errnum = 10; // 10 is a system error code. let result = util.errnoToString(errnum); console.log("result = " + result); - ``` +``` ## util.getErrorString(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [util.errnoToString9+](#utilerrnotostring9) instead. - getErrorString(errno: number): string Obtains detailed information about a system error code. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [util.errnoToString9+](#utilerrnotostring9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -127,6 +126,7 @@ Obtains detailed information about a system error code. | string | Detailed information about the error code.| **Example** + ```js let errnum = 10; // 10 is a system error code. let result = util.getErrorString(errnum); @@ -154,6 +154,7 @@ Calls back an asynchronous function. In the callback, the first parameter indica | Function | Callback, in which the first parameter indicates the cause of the rejection (the value is **null** if the promise has been resolved) and the second parameter indicates the resolved value.| **Example** + ```js async function promiseFn() { return Promise.reject('value'); @@ -187,6 +188,7 @@ Processes an asynchronous function and returns a promise. | Function | Function in the error-first style (that is, **(err, value) =>...** is called as the last parameter) and the promise.| **Example** + ```js function aysnFun(str1, str2) { if (typeof str1 === 'object' && typeof str2 === 'object') { @@ -205,11 +207,11 @@ Processes an asynchronous function and returns a promise. promiseWrapper(original: (err: Object, value: Object) => void): Object +Processes an asynchronous function and returns a promise. + > **NOTE** > -> This API is deprecated since API version 9. You are advised to use **[util.promisify9+](#utilpromisify9)** instead. - -Processes an asynchronous function and returns a promise. +> This API is unavailable. You are advised to use [util.promisify9+](#utilpromisify9) instead. **System capability**: SystemCapability.Utils.Lang @@ -246,6 +248,7 @@ Uses a secure random number generator to generate a random universally unique id | string | A string representing the UUID generated.| **Example** + ```js let uuid = util.randomUUID(true); console.log("RFC 4122 Version 4 UUID:" + uuid); @@ -274,6 +277,7 @@ Uses a secure random number generator to generate a random binary UUID of RFC 41 | Uint8Array | A Uint8Array value representing the UUID generated.| **Example** + ```js let uuid = util.randomBinaryUUID(true); console.log(JSON.stringify(uuid)); @@ -302,6 +306,7 @@ Parses a UUID from a string, as described in RFC 4122 version 4. | Uint8Array | A Uint8Array value representing the UUID parsed. If the parsing fails, **SyntaxError** is thrown.| **Example** + ```js let uuid = util.parseUUID("84bdf796-66cc-4655-9b89-d6218d100f9c"); console.log(JSON.stringify(uuid)); @@ -335,6 +340,8 @@ create(encoding?: string,options?: { fatal?: boolean; ignoreBOM?: boolean },): T Creates a **TextDecoder** object. It provides the same function as the deprecated argument constructor. +**System capability**: SystemCapability.Utils.Lang + **Parameters** | Name | Type | Mandatory| Description | @@ -342,7 +349,7 @@ Creates a **TextDecoder** object. It provides the same function as the deprecate | encoding | string | No | Encoding format. | | options | Object | No | Encoding-related options, which include **fatal** and **ignoreBOM**.| - **Table 1.1** options +**Table 1.1** options | Name | Type| Mandatory| Description | | --------- | -------- | ---- | ------------------ | @@ -351,21 +358,21 @@ Creates a **TextDecoder** object. It provides the same function as the deprecate **Example** - ```js +```js let textDecoder = new util.TextDecoder() textDecoder.create('utf-8', { ignoreBOM : true }); - ``` +``` ### constructor(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. - constructor(encoding?: string, options?: { fatal?: boolean; ignoreBOM?: boolean },) A constructor used to create a **TextDecoder** object. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -383,6 +390,7 @@ A constructor used to create a **TextDecoder** object. | ignoreBOM | boolean | No| Whether to ignore the BOM.| **Example** + ```js let textDecoder = new util.TextDecoder("utf-8",{ignoreBOM: true}); ``` @@ -402,7 +410,7 @@ Decodes the input content. | input | Uint8Array | Yes| Uint8Array to decode.| | options | Object | No| Options related to decoding.| - **Table 2** options +**Table 2** options | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | @@ -415,6 +423,7 @@ Decodes the input content. | string | Data decoded.| **Example** + ```js let textDecoder = new util.TextDecoder("utf-8",{ignoreBOM: true}); let result = new Uint8Array(6); @@ -445,7 +454,7 @@ Decodes the input content. | input | Uint8Array | Yes| Uint8Array to decode.| | options | Object | No| Options related to decoding.| - **Table 2** options +**Table 2** options | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | @@ -458,6 +467,7 @@ Decodes the input content. | string | Data decoded.| **Example** + ```js let textDecoder = new util.TextDecoder("utf-8",{ignoreBOM: true}); let result = new Uint8Array(6); @@ -493,6 +503,7 @@ A constructor used to create a **TextEncoder** object. **System capability**: SystemCapability.Utils.Lang **Example** + ```js let textEncoder = new util.TextEncoder(); ``` @@ -509,7 +520,7 @@ Encodes the input content. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------ | -| input | string | Yes | String to encode.| +| input | string | No | String to encode.| **Return value** @@ -528,21 +539,21 @@ result = textEncoder.encodeInto("\uD800¥¥"); ### encode(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [encodeInto9+](#encodeinto9) instead. - encode(input?: string): Uint8Array Encodes the input content. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [encodeInto9+](#encodeinto9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| input | string | Yes| String to encode.| +| input | string | No| String to encode.| **Return value** @@ -591,14 +602,14 @@ result = that.encodeInto('abcd', dest) ### encodeInto(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [encodeIntoUint8Array9+](#encodeintouint8array9) instead. - encodeInto(input: string, dest: Uint8Array, ): { read: number; written: number } Stores the UTF-8 encoded text. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [encodeIntoUint8Array9+](#encodeintouint8array9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -635,13 +646,13 @@ A constructor used to create a **RationalNumber** object. **Example** - ```js +```js let rationalNumber = new util.RationalNumber(); - ``` +``` ### parseRationalNumber9+ -parseRationalNumber(numerator: number,denominator: number) +parseRationalNumber(numerator: number,denominator: number): RationalNumber Parses a rational number. Previously, this processing is an internal action of the deprecated constructor. @@ -656,21 +667,20 @@ Parses a rational number. Previously, this processing is an internal action of t **Example** - ```js -let rationalNumber = new util.RationalNumber(); -rationalNumber.parseRationalNumber(1,2) - ``` +```js +let rationalNumber = util.RationalNumber.parseRationalNumber(1,2) +``` ### constructor(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. - constructor(numerator: number,denominator: number) A constructor used to create a **RationalNumber** object. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -682,9 +692,9 @@ A constructor used to create a **RationalNumber** object. **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - ``` +```js +let rationalNumber = new util.RationalNumber(1,2); +``` ### createRationalFromString8+ @@ -707,10 +717,11 @@ Creates a **RationalNumber** object based on the given string. | object | **RationalNumber** object created.| **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let rational = util.RationalNumber.createRationalFromString("3/4"); - ``` + +```js +let rationalNumber = new util.RationalNumber(1,2); +let rational = util.RationalNumber.createRationalFromString("3/4"); +``` ### compare9+ @@ -740,16 +751,16 @@ let rational = util.RationalNumber.createRationalFromString("3/4"); let result = rationalNumber.compare(rational); ``` -### compareTo8+(deprecated) - -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [compare9+](#compare9) instead. +### compareTo(deprecated) compareTo​(another: RationalNumber): number​ Compares this **RationalNumber** object with a given object. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [compare9+](#compare9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -765,11 +776,12 @@ Compares this **RationalNumber** object with a given object. | number | Returns **0** if the two objects are equal; returns **1** if the given object is less than this object; return **-1** if the given object is greater than this object.| **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let rational = util.RationalNumber.createRationalFromString("3/4"); - let result = rationalNumber.compareTo(rational); - ``` + +```js +let rationalNumber = new util.RationalNumber(1,2); +let rational = util.RationalNumber.createRationalFromString("3/4"); +let result = rationalNumber.compareTo(rational); +``` ### valueOf8+ @@ -786,10 +798,11 @@ Obtains the value of this **RationalNumber** object as an integer or a floating- | number | An integer or a floating-point number.| **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let result = rationalNumber.valueOf(); - ``` + +```js +let rationalNumber = new util.RationalNumber(1,2); +let result = rationalNumber.valueOf(); +``` ### equals8+ @@ -812,11 +825,12 @@ Checks whether this **RationalNumber** object equals the given object. | boolean | Returns **true** if the two objects are equal; returns **false** otherwise.| **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let rational = util.RationalNumber.createRationalFromString("3/4"); - let result = rationalNumber.equals(rational); - ``` + +```js +let rationalNumber = new util.RationalNumber(1,2); +let rational = util.RationalNumber.createRationalFromString("3/4"); +let result = rationalNumber.equals(rational); +``` ### getCommonFactor9+ @@ -841,20 +855,21 @@ Obtains the greatest common divisor of two specified integers. **Example** - ```js +```js let rationalNumber = new util.RationalNumber(1,2); let result = util.RationalNumber.getCommonFactor(4,6); - ``` +``` ### getCommonDivisor(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getCommonFactor9+](#getcommonfactor9) instead. static getCommonDivisor​(number1: number,number2: number): number Obtains the greatest common divisor of two specified integers. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getCommonFactor9+](#getcommonfactor9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -871,10 +886,11 @@ Obtains the greatest common divisor of two specified integers. | number | Greatest common divisor obtained.| **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let result = util.RationalNumber.getCommonDivisor(4,6); - ``` + +```js +let rationalNumber = new util.RationalNumber(1,2); +let result = util.RationalNumber.getCommonDivisor(4,6); +``` ### getNumerator8+ @@ -891,10 +907,11 @@ Obtains the numerator of this **RationalNumber** object. | number | Numerator of this **RationalNumber** object.| **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let result = rationalNumber.getNumerator(); - ``` + +```js +let rationalNumber = new util.RationalNumber(1,2); +let result = rationalNumber.getNumerator(); +``` ### getDenominator8+ @@ -911,10 +928,11 @@ Obtains the denominator of this **RationalNumber** object. | number | Denominator of this **RationalNumber** object.| **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let result = rationalNumber.getDenominator(); - ``` + +```js +let rationalNumber = new util.RationalNumber(1,2); +let result = rationalNumber.getDenominator(); +``` ### isZero8+ @@ -931,10 +949,11 @@ Checks whether this **RationalNumber** object is **0**. | boolean | Returns **true** if the value of this **RationalNumber** object is **0**; returns **false** otherwise.| **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let result = rationalNumber.isZero(); - ``` + +```js +let rationalNumber = new util.RationalNumber(1,2); +let result = rationalNumber.isZero(); +``` ### isNaN8+ @@ -951,10 +970,11 @@ Checks whether this **RationalNumber** object is a Not a Number (NaN). | boolean | Returns **true** if this **RationalNumber** object is a NaN (the denominator and numerator are both **0**); returns **false** otherwise.| **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let result = rationalNumber.isNaN(); - ``` + +```js +let rationalNumber = new util.RationalNumber(1,2); +let result = rationalNumber.isNaN(); +``` ### isFinite8+ @@ -971,10 +991,11 @@ Checks whether this **RationalNumber** object represents a finite value. | boolean | Returns **true** if this **RationalNumber** object represents a finite value (the denominator is not **0**); returns **false** otherwise.| **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let result = rationalNumber.isFinite(); - ``` + +```js +let rationalNumber = new util.RationalNumber(1,2); +let result = rationalNumber.isFinite(); +``` ### toString8+ @@ -991,10 +1012,11 @@ Obtains the string representation of this **RationalNumber** object. | string | Returns **NaN** if the numerator and denominator of this object are both **0**; returns a string in Numerator/Denominator format otherwise, for example, **3/5**.| **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let result = rationalNumber.toString(); - ``` + +```js +let rationalNumber = new util.RationalNumber(1,2); +let result = rationalNumber.toString(); +``` ## LRUCache9+ @@ -1005,22 +1027,22 @@ Obtains the string representation of this **RationalNumber** object. | Name | Type | Readable| Writable| Description | | ------ | ------ | ---- | ---- | ---------------------- | -| length | number | Yes | No | Total number of values in this buffer. | +| length | number | Yes | No | Total number of values in this cache.| **Example** - ```js +```js let pro = new util.LRUCache(); pro.put(2,10); pro.put(1,8); let result = pro.length; - ``` +``` ### constructor9+ constructor(capacity?: number) -A constructor used to create a **LruBuffer** instance. The default capacity of the buffer is 64. +A constructor used to create a **LruCache** instance. The default capacity of the cache is 64. **System capability**: SystemCapability.Utils.Lang @@ -1028,20 +1050,20 @@ A constructor used to create a **LruBuffer** instance. The default capacity of t | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ---------------------------- | -| capacity | number | No | Capacity of the **LruBuffer** to create.| +| capacity | number | No | Capacity of the **LruCache** to create.| **Example** - ```js +```js let lrubuffer= new util.LRUCache(); - ``` +``` ### updateCapacity9+ updateCapacity(newCapacity: number): void -Changes the **LruBuffer** capacity. If the new capacity is less than or equal to **0**, an exception will be thrown. +Changes the **LruCache** capacity. If the new capacity is less than or equal to **0**, an exception will be thrown. **System capability**: SystemCapability.Utils.Lang @@ -1049,21 +1071,21 @@ Changes the **LruBuffer** capacity. If the new capacity is less than or equal to | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ---------------------------- | -| newCapacity | number | Yes | New capacity of the **LruBuffer**.| +| newCapacity | number | Yes | New capacity of the **LruCache**.| **Example** - ```js +```js let pro = new util.LRUCache(); let result = pro.updateCapacity(100); - ``` +``` ### toString9+ toString(): string -Obtains the string representation of this **LruBuffer** object. +Obtains the string representation of this **LruCache** object. **System capability**: SystemCapability.Utils.Lang @@ -1071,24 +1093,24 @@ Obtains the string representation of this **LruBuffer** object. | Type | Description | | ------ | -------------------------- | -| string | String representation of this **LruBuffer** object.| +| string | String representation of this **LruCache** object.| **Example** - ```js +```js let pro = new util.LRUCache(); pro.put(2,10); pro.get(2); pro.remove(20); let result = pro.toString(); - ``` +``` ### getCapacity9+ getCapacity(): number -Obtains the capacity of this buffer. +Obtains the capacity of this cache. **System capability**: SystemCapability.Utils.Lang @@ -1096,7 +1118,7 @@ Obtains the capacity of this buffer. | Type | Description | | ------ | ---------------------- | -| number | Capacity of this buffer.| +| number | Capacity of this cache.| **Example** @@ -1110,7 +1132,7 @@ let result = pro.getCapacity(); clear(): void -Clears key-value pairs from this buffer. The **afterRemoval()** method will be called to perform subsequent operations. +Clears key-value pairs from this cache. The **afterRemoval()** method will be called to perform subsequent operations. **System capability**: SystemCapability.Utils.Lang @@ -1175,7 +1197,7 @@ let result = pro.getMissCount(); getRemovalCount(): number -Obtains the number of removals from this buffer. +Obtains the number of removals from this cache. **System capability**: SystemCapability.Utils.Lang @@ -1183,7 +1205,7 @@ Obtains the number of removals from this buffer. | Type | Description | | ------ | -------------------------- | -| number | Number of removals from the buffer.| +| number | Number of removals from the cache.| **Example** @@ -1224,7 +1246,7 @@ let result = pro.getMatchCount(); getPutCount(): number -Obtains the number of additions to this buffer. +Obtains the number of additions to this cache. **System capability**: SystemCapability.Utils.Lang @@ -1232,7 +1254,7 @@ Obtains the number of additions to this buffer. | Type | Description | | ------ | ---------------------------- | -| number | Number of additions to the buffer.| +| number | Number of additions to the cache.| **Example** @@ -1247,7 +1269,7 @@ let result = pro.getPutCount(); isEmpty(): boolean -Checks whether this buffer is empty. +Checks whether this cache is empty. **System capability**: SystemCapability.Utils.Lang @@ -1255,7 +1277,7 @@ Checks whether this buffer is empty. | Type | Description | | ------- | ---------------------------------------- | -| boolean | Returns **true** if the buffer does not contain any value.| +| boolean | Returns **true** if the cache does not contain any value.| **Example** @@ -1284,7 +1306,7 @@ Obtains the value of the specified key. | Type | Description | | ------------------------ | ------------------------------------------------------------ | -| V \| undefined | Returns the value of the key if a match is found in the buffer; returns **undefined** otherwise.| +| V \| undefined | Returns the value of the key if a match is found in the cache; returns **undefined** otherwise.| **Example** @@ -1299,7 +1321,7 @@ let result = pro.get(2); put(key: K,value: V): V -Adds a key-value pair to this buffer. +Adds a key-value pair to this cache. **System capability**: SystemCapability.Utils.Lang @@ -1327,7 +1349,7 @@ let result = pro.put(2,10); values(): V[] -Obtains all values in this buffer, listed from the most to the least recently accessed. +Obtains all values in this cache, listed from the most to the least recently accessed. **System capability**: SystemCapability.Utils.Lang @@ -1335,7 +1357,7 @@ Obtains all values in this buffer, listed from the most to the least recently ac | Type | Description | | --------- | ------------------------------------------------------------ | -| V [] | All values in the buffer, listed from the most to the least recently accessed.| +| V [] | All values in the cache, listed from the most to the least recently accessed.| **Example** @@ -1352,7 +1374,7 @@ let result = pro.values(); keys(): K[] -Obtains all keys in this buffer, listed from the most to the least recently accessed. +Obtains all keys in this cache, listed from the most to the least recently accessed. **System capability**: SystemCapability.Utils.Lang @@ -1360,7 +1382,7 @@ Obtains all keys in this buffer, listed from the most to the least recently acce | Type | Description | | --------- | ------------------------------------------------------------ | -| K [] | All keys in the buffer, listed from the most to the least recently accessed.| +| K [] | All keys in the cache, listed from the most to the least recently accessed.| **Example** @@ -1375,7 +1397,7 @@ let result = pro.keys(); remove(key: K): V | undefined -Removes the specified key and its value from this buffer. +Removes the specified key and its value from this cache. **System capability**: SystemCapability.Utils.Lang @@ -1389,7 +1411,7 @@ Removes the specified key and its value from this buffer. | Type | Description | | ------------------------ | ------------------------------------------------------------ | -| V \| undefined | Returns an **Optional** object containing the removed key-value pair if the key exists in the buffer; returns an empty **Optional** object otherwise. If the key is null, an exception will be thrown.| +| V \| undefined | Returns an **Optional** object containing the removed key-value pair if the key exists in the cache; returns an empty **Optional** object otherwise. If the key is null, an exception will be thrown.| **Example** @@ -1412,10 +1434,10 @@ Performs subsequent operations after a value is removed. | Name | Type | Mandatory| Description | | -------- | ------- | ---- | ------------------------------------------------------------ | -| isEvict | boolean | No | Whether the buffer capacity is insufficient. If the value is **true**, this method is called due to insufficient capacity. | +| isEvict | boolean | Yes | Whether the cache capacity is insufficient. If the value is **true**, this method is called due to insufficient capacity. | | key | K | Yes | Key removed. | | value | V | Yes | Value removed. | -| newValue | V | No | New value for the key if the **put()** method is called and the key to be added already exists. In other cases, this parameter is left blank.| +| newValue | V | Yes | New value for the key if the **put()** method is called and the key to be added already exists. In other cases, this parameter is left blank.| **Example** @@ -1442,30 +1464,31 @@ lru.afterRemoval(false,10,30,null); ### contains9+ -contains(key: K): boolean +contains(key: object): boolean -Checks whether this buffer contains the specified key. +Checks whether this cache contains the specified key. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ---------------- | -| key | K | Yes | Key to check.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------- | +| key | object | Yes | Key to check.| **Return value** | Type | Description | | ------- | ------------------------------------------ | -| boolean | Returns **true** if the buffer contains the specified key; returns **false** otherwise.| +| boolean | Returns **true** if the cache contains the specified key; returns **false** otherwise.| **Example** ```js let pro = new util.LRUCache(); pro.put(2,10); -let result = pro.contains(20); +let obj = {1:"key"}; +let result = pro.contains(obj); ``` @@ -1545,7 +1568,7 @@ let result = pro[Symbol.iterator](); > **NOTE** > -> This API is deprecated since API version 9. You are advised to use [LRUCache9+](#lrucache9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [LRUCache9+](#lrucache9) instead. ### Attributes @@ -1556,6 +1579,7 @@ let result = pro[Symbol.iterator](); | length | number | Yes| No| Total number of values in this buffer.| **Example** + ```js let pro = new util.LruBuffer(); pro.put(2,10); @@ -1565,14 +1589,14 @@ let result = pro[Symbol.iterator](); ### constructor(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. - constructor(capacity?: number) A constructor used to create a **LruBuffer** instance. The default capacity of the buffer is 64. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -1582,20 +1606,21 @@ A constructor used to create a **LruBuffer** instance. The default capacity of t | capacity | number | No| Capacity of the **LruBuffer** to create.| **Example** + ```js let lrubuffer= new util.LruBuffer(); ``` ### updateCapacity(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [updateCapacity9+](#updatecapacity9) instead. - updateCapacity(newCapacity: number): void Changes the **LruBuffer** capacity. If the new capacity is less than or equal to **0**, an exception will be thrown. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [updateCapacity9+](#updatecapacity9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -1605,6 +1630,7 @@ Changes the **LruBuffer** capacity. If the new capacity is less than or equal to | newCapacity | number | Yes| New capacity of the **LruBuffer**.| **Example** + ```js let pro = new util.LruBuffer(); let result = pro.updateCapacity(100); @@ -1612,14 +1638,14 @@ Changes the **LruBuffer** capacity. If the new capacity is less than or equal to ### toString(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [toString9+](#tostring9) instead. - toString(): string Obtains the string representation of this **LruBuffer** object. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [toString9+](#tostring9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -1629,6 +1655,7 @@ Obtains the string representation of this **LruBuffer** object. | string | String representation of this **LruBuffer** object.| **Example** + ```js let pro = new util.LruBuffer(); pro.put(2,10); @@ -1639,14 +1666,14 @@ Obtains the string representation of this **LruBuffer** object. ### getCapacity(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getCapacity9+](#getcapacity9) instead. - getCapacity(): number Obtains the capacity of this buffer. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getCapacity9+](#getcapacity9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -1663,17 +1690,18 @@ Obtains the capacity of this buffer. ### clear(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [clear9+](#clear9) instead. - clear(): void Clears key-value pairs from this buffer. The **afterRemoval()** method will be called to perform subsequent operations. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [clear9+](#clear9) instead. + **System capability**: SystemCapability.Utils.Lang **Example** + ```js let pro = new util.LruBuffer(); pro.put(2,10); @@ -1683,14 +1711,14 @@ Clears key-value pairs from this buffer. The **afterRemoval()** method will be c ### getCreateCount(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getCreateCount9+](#getcreatecount9) instead. - getCreateCount(): number Obtains the number of return values for **createDefault()**. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getCreateCount9+](#getcreatecount9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -1700,6 +1728,7 @@ Obtains the number of return values for **createDefault()**. | number | Number of return values for **createDefault()**.| **Example** + ```js let pro = new util.LruBuffer(); pro.put(1,8); @@ -1708,14 +1737,14 @@ Obtains the number of return values for **createDefault()**. ### getMissCount(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getMissCount9+](#getmisscount9) instead. - getMissCount(): number Obtains the number of times that the queried values are mismatched. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getMissCount9+](#getmisscount9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -1725,6 +1754,7 @@ Obtains the number of times that the queried values are mismatched. | number | Number of times that the queried values are mismatched.| **Example** + ```js let pro = new util.LruBuffer(); pro.put(2,10); @@ -1734,14 +1764,14 @@ Obtains the number of times that the queried values are mismatched. ### getRemovalCount(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getRemovalCount9+](#getremovalcount9) instead. - getRemovalCount(): number Obtains the number of removals from this buffer. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getRemovalCount9+](#getremovalcount9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -1751,6 +1781,7 @@ Obtains the number of removals from this buffer. | number | Number of removals from the buffer.| **Example** + ```js let pro = new util.LruBuffer(); pro.put(2,10); @@ -1761,14 +1792,14 @@ Obtains the number of removals from this buffer. ### getMatchCount(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getMatchCount9+](#getmatchcount9) instead. - getMatchCount(): number Obtains the number of times that the queried values are matched. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getMatchCount9+](#getmatchcount9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -1778,6 +1809,7 @@ Obtains the number of times that the queried values are matched. | number | Number of times that the queried values are matched.| **Example** + ```js let pro = new util.LruBuffer(); pro.put(2,10); @@ -1787,14 +1819,14 @@ Obtains the number of times that the queried values are matched. ### getPutCount(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getPutCount9+](#getputcount9) instead. - getPutCount(): number Obtains the number of additions to this buffer. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getPutCount9+](#getputcount9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -1804,6 +1836,7 @@ Obtains the number of additions to this buffer. | number | Number of additions to the buffer.| **Example** + ```js let pro = new util.LruBuffer(); pro.put(2,10); @@ -1812,14 +1845,14 @@ Obtains the number of additions to this buffer. ### isEmpty(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [isEmpty9+](#isempty9) instead. - isEmpty(): boolean Checks whether this buffer is empty. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [isEmpty9+](#isempty9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -1829,6 +1862,7 @@ Checks whether this buffer is empty. | boolean | Returns **true** if the buffer does not contain any value.| **Example** + ```js let pro = new util.LruBuffer(); pro.put(2,10); @@ -1837,14 +1871,14 @@ Checks whether this buffer is empty. ### get(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [get9+](#get9) instead. - get(key: K): V | undefined Obtains the value of the specified key. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [get9+](#get9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -1860,6 +1894,7 @@ Obtains the value of the specified key. | V \| undefined | Returns the value of the key if a match is found in the buffer; returns **undefined** otherwise.| **Example** + ```js let pro = new util.LruBuffer(); pro.put(2,10); @@ -1868,14 +1903,14 @@ Obtains the value of the specified key. ### put(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [put9+](#put9) instead. - put(key: K,value: V): V Adds a key-value pair to this buffer. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [put9+](#put9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -1892,6 +1927,7 @@ Adds a key-value pair to this buffer. | V | Returns the existing value if the key already exists; returns the value added otherwise. If the key or value is null, an exception will be thrown. | **Example** + ```js let pro = new util.LruBuffer(); let result = pro.put(2,10); @@ -1899,14 +1935,14 @@ Adds a key-value pair to this buffer. ### values(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [values9+](#values9) instead. - values(): V[] Obtains all values in this buffer, listed from the most to the least recently accessed. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [values9+](#values9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -1916,6 +1952,7 @@ Obtains all values in this buffer, listed from the most to the least recently ac | V [] | All values in the buffer, listed from the most to the least recently accessed.| **Example** + ```js let pro = new util.LruBuffer(); pro.put(2,10); @@ -1926,14 +1963,14 @@ Obtains all values in this buffer, listed from the most to the least recently ac ### keys(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [keys9+](#keys9) instead. - keys(): K[] Obtains all keys in this buffer, listed from the most to the least recently accessed. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [keys9+](#keys9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -1951,14 +1988,14 @@ Obtains all keys in this buffer, listed from the most to the least recently acce ### remove(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [remove9+](#remove9) instead. - remove(key: K): V | undefined Removes the specified key and its value from this buffer. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [remove9+](#remove9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -1982,26 +2019,27 @@ Removes the specified key and its value from this buffer. ### afterRemoval(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [afterRemoval9+](#afterremoval9) instead. - afterRemoval(isEvict: boolean,key: K,value: V,newValue: V): void Performs subsequent operations after a value is removed. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [afterRemoval9+](#afterremoval9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| isEvict | boolean | No| Whether the buffer capacity is insufficient. If the value is **true**, this method is called due to insufficient capacity.| +| isEvict | boolean | Yes| Whether the buffer capacity is insufficient. If the value is **true**, this method is called due to insufficient capacity.| | key | K | Yes| Key removed.| | value | V | Yes| Value removed.| -| newValue | V | No| New value for the key if the **put()** method is called and the key to be added already exists. In other cases, this parameter is left blank.| +| newValue | V | Yes| New value for the key if the **put()** method is called and the key to be added already exists. In other cases, this parameter is left blank.| **Example** + ```js let arr = []; class ChildLruBuffer extends util.LruBuffer @@ -2024,14 +2062,15 @@ Performs subsequent operations after a value is removed. ### contains(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. - contains(key: K): boolean Checks whether this buffer contains the specified key. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -2047,6 +2086,7 @@ Checks whether this buffer contains the specified key. | boolean | Returns **true** if the buffer contains the specified key; returns **false** otherwise.| **Example** + ```js let pro = new util.LruBuffer(); pro.put(2,10); @@ -2055,14 +2095,14 @@ Checks whether this buffer contains the specified key. ### createDefault(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [createDefault9+](#createdefault9) instead. - createDefault(key: K): V Creates a value if the value of the specified key is not available. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [createDefault9+](#createdefault9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -2078,6 +2118,7 @@ Creates a value if the value of the specified key is not available. | V | Value of the key.| **Example** + ```js let pro = new util.LruBuffer(); let result = pro.createDefault(50); @@ -2085,14 +2126,14 @@ Creates a value if the value of the specified key is not available. ### entries(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [entries9+](#entries9) instead. - entries(): IterableIterator<[K,V]> Obtains a new iterator object that contains all key-value pairs in this object. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [entries9+](#entries9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -2102,6 +2143,7 @@ Obtains a new iterator object that contains all key-value pairs in this object. | [K, V] | Iterable array.| **Example** + ```js let pro = new util.LruBuffer(); pro.put(2,10); @@ -2110,14 +2152,14 @@ Obtains a new iterator object that contains all key-value pairs in this object. ### [Symbol.iterator](deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [Symbol.iterator9+](#symboliterator9) instead. - [Symbol.iterator]\(): IterableIterator<[K, V]> Obtains a two-dimensional array in key-value pairs. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [Symbol.iterator9+](#symboliterator9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -2127,6 +2169,7 @@ Obtains a two-dimensional array in key-value pairs. | [K, V] | Two-dimensional array in key-value pairs.| **Example** + ```js let pro = new util.LruBuffer(); pro.put(2,10); @@ -2138,6 +2181,7 @@ Obtains a two-dimensional array in key-value pairs. Defines the type of values in a **Scope** object. The value type can be **ScopeComparable** or **number**. The values of the **ScopeComparable** type are used to implement the **compareTo** method. Therefore, ensure that the input parameters are comparable. + ```js interface ScopeComparable{ compareTo(other: ScopeComparable): boolean; @@ -2229,9 +2273,9 @@ Obtains the intersection of this **Scope** and the given **Scope**. **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------------ | ---- | ------------------ | -| range | [ScopeHelper9+](#scopehelper9) | Yes | **Scope** specified.| +| Name| Type | Mandatory| Description | +| ------ | ---------------------------- | ---- | ------------------ | +| range | [ScopeHelper](#scopehelper9) | Yes | **Scope** specified.| **Return value** @@ -2269,9 +2313,9 @@ Obtains the intersection of this **Scope** and the given lower and upper limits. **Return value** -| Type | Description | -| ------------------------------ | ---------------------------------------- | -| [ScopeHelper9+](#scopehelper9) | Intersection of this **Scope** and the given lower and upper limits.| +| Type | Description | +| ---------------------------- | ---------------------------------------- | +| [ScopeHelper](#scopehelper9) | Intersection of this **Scope** and the given lower and upper limits.| **Example** @@ -2350,9 +2394,9 @@ Obtains the union set of this **Scope** and the given lower and upper limits. **Return value** -| Type | Description | -| ------------------------------ | ------------------------------------ | -| [ScopeHelper9+](#scopehelper9) | Union set of this **Scope** and the given lower and upper limits.| +| Type | Description | +| ---------------------------- | ------------------------------------ | +| [ScopeHelper](#scopehelper9) | Union set of this **Scope** and the given lower and upper limits.| **Example** @@ -2376,15 +2420,15 @@ Obtains the union set of this **Scope** and the given **Scope**. **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------------ | ---- | ------------------ | -| range | [ScopeHelper9+](#scopehelper9) | Yes | **Scope** specified.| +| Name| Type | Mandatory| Description | +| ------ | ---------------------------- | ---- | ------------------ | +| range | [ScopeHelper](#scopehelper9) | Yes | **Scope** specified.| **Return value** -| Type | Description | -| ------------------------------ | ---------------------------------- | -| [ScopeHelper9+](#scopehelper9) | Union set of this **Scope** and the given **Scope**.| +| Type | Description | +| ---------------------------- | ---------------------------------- | +| [ScopeHelper](#scopehelper9) | Union set of this **Scope** and the given **Scope**.| **Example** @@ -2415,9 +2459,9 @@ Obtains the union set of this **Scope** and the given value. **Return value** -| Type | Description | -| ------------------------------ | -------------------------------- | -| [ScopeHelper9+](#scopehelper9) | Union set of this **Scope** and the given value.| +| Type | Description | +| ---------------------------- | -------------------------------- | +| [ScopeHelper](#scopehelper9) | Union set of this **Scope** and the given value.| **Example** @@ -2471,9 +2515,9 @@ Checks whether a range is within this **Scope**. **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------------ | ---- | ------------------ | -| range | [ScopeHelper9+](#scopehelper9) | Yes | **Scope** specified.| +| Name| Type | Mandatory| Description | +| ------ | ---------------------------- | ---- | ------------------ | +| range | [ScopeHelper](#scopehelper9) | Yes | **Scope** specified.| **Return value** @@ -2528,18 +2572,19 @@ let result = range.clamp(tempMiDF); > **NOTE** > -> This class is deprecated since API version 9. You are advised to use [ScopeHelper9+](#scopehelper9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [ScopeHelper9+](#scopehelper9) instead. ### constructor(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. - constructor(lowerObj: ScopeType, upperObj: ScopeType) A constructor used to create a **Scope** object with the specified upper and lower limits. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. + + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -2558,14 +2603,14 @@ A constructor used to create a **Scope** object with the specified upper and low ### toString(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [toString9+](#tostring9) instead. - toString(): string Obtains a string representation that contains this **Scope**. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [toString9+](#tostring9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -2575,6 +2620,7 @@ Obtains a string representation that contains this **Scope**. | string | String representation containing the **Scope**.| **Example** + ```js let tempLower = new Temperature(30); let tempUpper = new Temperature(40); @@ -2584,14 +2630,14 @@ Obtains a string representation that contains this **Scope**. ### intersect(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [intersect9+](#intersect9) instead. - intersect(range: Scope): Scope Obtains the intersection of this **Scope** and the given **Scope**. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [intersect9+](#intersect9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -2620,14 +2666,14 @@ Obtains the intersection of this **Scope** and the given **Scope**. ### intersect(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [intersect9+](#intersect9) instead. - intersect(lowerObj:ScopeType,upperObj:ScopeType):Scope Obtains the intersection of this **Scope** and the given lower and upper limits. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [intersect9+](#intersect9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -2644,6 +2690,7 @@ Obtains the intersection of this **Scope** and the given lower and upper limits. | [Scope](#scopedeprecated) | Intersection of this **Scope** and the given lower and upper limits.| **Example** + ```js let tempLower = new Temperature(30); let tempUpper = new Temperature(40); @@ -2655,14 +2702,14 @@ Obtains the intersection of this **Scope** and the given lower and upper limits. ### getUpper(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getUpper9+](#getupper9) instead. - getUpper(): ScopeType Obtains the upper limit of this **Scope**. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getUpper9+](#getupper9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -2672,6 +2719,7 @@ Obtains the upper limit of this **Scope**. | [ScopeType](#scopetype8) | Upper limit of this **Scope**.| **Example** + ```js let tempLower = new Temperature(30); let tempUpper = new Temperature(40); @@ -2681,14 +2729,14 @@ Obtains the upper limit of this **Scope**. ### getLower(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getLower9+](#getlower9) instead. - getLower(): ScopeType Obtains the lower limit of this **Scope**. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getLower9+](#getlower9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -2698,6 +2746,7 @@ Obtains the lower limit of this **Scope**. | [ScopeType](#scopetype8) | Lower limit of this **Scope**.| **Example** + ```js let tempLower = new Temperature(30); let tempUpper = new Temperature(40); @@ -2707,14 +2756,14 @@ Obtains the lower limit of this **Scope**. ### expand(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. - expand(lowerObj: ScopeType,upperObj: ScopeType): Scope Obtains the union set of this **Scope** and the given lower and upper limits. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -2743,14 +2792,14 @@ Obtains the union set of this **Scope** and the given lower and upper limits. ### expand(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. - expand(range: Scope): Scope Obtains the union set of this **Scope** and the given **Scope**. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -2766,6 +2815,7 @@ Obtains the union set of this **Scope** and the given **Scope**. | [Scope](#scopedeprecated) | Union set of this **Scope** and the given **Scope**.| **Example** + ```js let tempLower = new Temperature(30); let tempUpper = new Temperature(40); @@ -2778,14 +2828,14 @@ Obtains the union set of this **Scope** and the given **Scope**. ### expand(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. - expand(value: ScopeType): Scope Obtains the union set of this **Scope** and the given value. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -2801,6 +2851,7 @@ Obtains the union set of this **Scope** and the given value. | [Scope](#scopedeprecated) | Union set of this **Scope** and the given value.| **Example** + ```js let tempLower = new Temperature(30); let tempUpper = new Temperature(40); @@ -2811,14 +2862,14 @@ Obtains the union set of this **Scope** and the given value. ### contains(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. - contains(value: ScopeType): boolean Checks whether a value is within this **Scope**. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -2834,6 +2885,7 @@ Checks whether a value is within this **Scope**. | boolean | Returns **true** if the value is within this **Scope**; returns **false** otherwise.| **Example** + ```js let tempLower = new Temperature(30); let tempUpper = new Temperature(40); @@ -2844,14 +2896,14 @@ Checks whether a value is within this **Scope**. ### contains(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. - contains(range: Scope): boolean Checks whether a range is within this **Scope**. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -2880,14 +2932,15 @@ Checks whether a range is within this **Scope**. ### clamp(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [clamp9+](#clamp9) instead. clamp(value: ScopeType): ScopeType Limits a value to this **Scope**. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [clamp9+](#clamp9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -2903,6 +2956,7 @@ Limits a value to this **Scope**. | [ScopeType](#scopetype8) | Returns **lowerObj** if the specified value is less than the lower limit; returns **upperObj** if the specified value is greater than the upper limit; returns the specified value if it is within this **Scope**.| **Example** + ```js let tempLower = new Temperature(30); let tempUpper = new Temperature(40); @@ -3117,35 +3171,36 @@ that.decode(array).then(val=>{ > **NOTE** > -> This class is deprecated since API version 9. You are advised to use [Base64Helper9+](#base64helper9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [Base64Helper9+](#base64helper9) instead. ### constructor(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. - constructor() A constructor used to create a **Base64** object. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. + **System capability**: SystemCapability.Utils.Lang **Example** + ```js let base64 = new util.Base64(); ``` ### encodeSync(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [encodeSync9+](#encodesync9) instead. - encodeSync(src: Uint8Array): Uint8Array Encodes the input content. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encodeSync9+](#encodesync9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -3170,14 +3225,14 @@ Encodes the input content. ### encodeToStringSync(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [encodeToStringSync9+](#encodetostringsync9) instead. - encodeToStringSync(src: Uint8Array): string Encodes the input content. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encodeToStringSync9+](#encodetostringsync9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -3193,6 +3248,7 @@ Encodes the input content. | string | String encoded from the Uint8Array.| **Example** + ```js let that = new util.Base64(); let array = new Uint8Array([115,49,51]); @@ -3201,14 +3257,14 @@ Encodes the input content. ### decodeSync(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [decodeSync9+](#decodesync9) instead. - decodeSync(src: Uint8Array | string): Uint8Array Decodes the input content. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [decodeSync9+](#decodesync9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -3224,6 +3280,7 @@ Decodes the input content. | Uint8Array | Uint8Array decoded.| **Example** + ```js let that = new util.Base64(); let buff = 'czEz'; @@ -3232,14 +3289,14 @@ Decodes the input content. ### encode(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [encode9+](#encode9) instead. - encode(src: Uint8Array): Promise<Uint8Array> Encodes the input content asynchronously. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encode9+](#encode9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -3255,6 +3312,7 @@ Encodes the input content asynchronously. | Promise<Uint8Array> | Uint8Array obtained after asynchronous encoding.| **Example** + ```js let that = new util.Base64(); let array = new Uint8Array([115,49,51]); @@ -3268,14 +3326,14 @@ Encodes the input content asynchronously. ### encodeToString(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [encodeToString9+](#encodetostring9) instead. - encodeToString(src: Uint8Array): Promise<string> Encodes the input content asynchronously. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encodeToString9+](#encodetostring9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -3291,6 +3349,7 @@ Encodes the input content asynchronously. | Promise<string> | String obtained after asynchronous encoding.| **Example** + ```js let that = new util.Base64(); let array = new Uint8Array([115,49,51]); @@ -3301,14 +3360,15 @@ Encodes the input content asynchronously. ### decode(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [decode9+](#decode9) instead. decode(src: Uint8Array | string): Promise<Uint8Array> Decodes the input content asynchronously. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [decode9+](#decode9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -3324,6 +3384,7 @@ Decodes the input content asynchronously. | Promise<Uint8Array> | Uint8Array obtained after asynchronous decoding.| **Example** + ```js let that = new util.Base64(); let array = new Uint8Array([99,122,69,122]); @@ -3347,6 +3408,7 @@ A constructor used to create a **Types** object. **System capability**: SystemCapability.Utils.Lang **Example** + ```js let type = new util.types(); ``` @@ -3373,6 +3435,7 @@ Checks whether the input value is of the **ArrayBuffer** type. | boolean | Returns **true** if the input value is of the **ArrayBuffer** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isAnyArrayBuffer(new ArrayBuffer(0)); @@ -3402,6 +3465,7 @@ Checks whether the input value is of the **ArrayBufferView** type. | boolean | Returns **true** if the input value is of the **ArrayBufferView** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isArrayBufferView(new Int8Array([])); @@ -3429,6 +3493,7 @@ Checks whether the input value is of the **arguments** type. | boolean | Returns **true** if the input value is of the **arguments** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); function foo() { @@ -3459,6 +3524,7 @@ Checks whether the input value is of the **ArrayBuffer** type. | boolean | Returns **true** if the input value is of the **ArrayBuffer** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isArrayBuffer(new ArrayBuffer(0)); @@ -3486,6 +3552,7 @@ Checks whether the input value is an asynchronous function. | boolean | Returns **true** if the input value is an asynchronous function; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isAsyncFunction(async function foo() {}); @@ -3513,6 +3580,7 @@ Checks whether the input value is of the **Boolean** type. | boolean | Returns **true** if the input value is of the **Boolean** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isBooleanObject(new Boolean(true)); @@ -3540,6 +3608,7 @@ Checks whether the input value is of the **Boolean**, **Number**, **String**, or | boolean | Returns **true** if the input value is of the **Boolean**, **Number**, **String**, or **Symbol** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isBoxedPrimitive(new Boolean(false)); @@ -3567,6 +3636,7 @@ Checks whether the input value is of the **DataView** type. | boolean | Returns **true** if the input value is of the **DataView** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); const ab = new ArrayBuffer(20); @@ -3595,6 +3665,7 @@ Checks whether the input value is of the **Date** type. | boolean | Returns **true** if the input value is of the **Date** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isDate(new Date()); @@ -3622,6 +3693,7 @@ Checks whether the input value is of the **native external** type. | boolean | Returns **true** if the input value is of the **native external** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isExternal(true); @@ -3649,6 +3721,7 @@ Checks whether the input value is of the **Float32Array** type. | boolean | Returns **true** if the input value is of the **Float32Array** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isFloat32Array(new Float32Array()); @@ -3676,6 +3749,7 @@ Checks whether the input value is of the **Float64Array** type. | boolean | Returns **true** if the input value is of the **Float64Array** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isFloat64Array(new Float64Array()); @@ -3703,6 +3777,7 @@ Checks whether the input value is a generator function. | boolean | Returns **true** if the input value is a generator function; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isGeneratorFunction(function* foo() {}); @@ -3730,6 +3805,7 @@ Checks whether the input value is a generator object. | boolean | Returns **true** if the input value is a generator object; returns **false** otherwise.| **Example** + ```js let that = new util.types(); function* foo() {} @@ -3759,6 +3835,7 @@ Checks whether the input value is of the **Int8Array** type. | boolean | Returns **true** if the input value is of the **Int8Array** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isInt8Array(new Int8Array([])); @@ -3786,6 +3863,7 @@ Checks whether the input value is of the **Int16Array** type. | boolean | Returns **true** if the input value is of the **Int16Array** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isInt16Array(new Int16Array([])); @@ -3813,6 +3891,7 @@ Checks whether the input value is of the **Int32Array** type. | boolean | Returns **true** if the input value is of the **Int32Array** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isInt32Array(new Int32Array([])); @@ -3840,6 +3919,7 @@ Checks whether the input value is of the **Map** type. | boolean | Returns **true** if the input value is of the **Map** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isMap(new Map()); @@ -3856,6 +3936,7 @@ Checks whether the input value is of the **MapIterator** type. **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| @@ -3867,6 +3948,7 @@ Checks whether the input value is of the **MapIterator** type. | boolean | Returns **true** if the input value is of the **MapIterator** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); const map = new Map(); @@ -3895,6 +3977,7 @@ Checks whether the input value is of the **Error** type. | boolean | Returns **true** if the input value is of the **Error** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isNativeError(new TypeError()); @@ -3922,6 +4005,7 @@ Checks whether the input value is a number object. | boolean | Returns **true** if the input value is a number object; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isNumberObject(new Number(0)); @@ -3949,6 +4033,7 @@ Checks whether the input value is a promise. | boolean | Returns **true** if the input value is a promise; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isPromise(Promise.resolve(1)); @@ -3976,6 +4061,7 @@ Checks whether the input value is a proxy. | boolean | Returns **true** if the input value is a proxy; returns **false** otherwise.| **Example** + ```js let that = new util.types(); const target = {}; @@ -4005,6 +4091,7 @@ Checks whether the input value is of the **RegExp** type. | boolean | Returns **true** if the input value is of the **RegExp** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isRegExp(new RegExp('abc')); @@ -4032,6 +4119,7 @@ Checks whether the input value is of the **Set** type. | boolean | Returns **true** if the input value is of the **Set** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isSet(new Set()); @@ -4059,6 +4147,7 @@ Checks whether the input value is of the **SetIterator** type. | boolean | Returns **true** if the input value is of the **SetIterator** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); const set = new Set(); @@ -4087,6 +4176,7 @@ Checks whether the input value is a string object. | boolean | Returns **true** if the input value is a string object; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isStringObject(new String('foo')); @@ -4114,6 +4204,7 @@ Checks whether the input value is a symbol object. | boolean | Returns **true** if the input value is a symbol object; returns **false** otherwise.| **Example** + ```js let that = new util.types(); const symbols = Symbol('foo'); @@ -4144,6 +4235,7 @@ Checks whether the input value is of the **TypedArray** type. | boolean | Returns **true** if the input value is of the **TypedArray** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isTypedArray(new Float64Array([])); @@ -4171,6 +4263,7 @@ Checks whether the input value is of the **Uint8Array** type. | boolean | Returns **true** if the input value is of the **Uint8Array** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isUint8Array(new Uint8Array([])); @@ -4198,6 +4291,7 @@ Checks whether the input value is of the **Uint8ClampedArray** type. | boolean | Returns **true** if the input value is of the **Uint8ClampedArray** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isUint8ClampedArray(new Uint8ClampedArray([])); @@ -4225,6 +4319,7 @@ Checks whether the input value is of the **Uint16Array** type. | boolean | Returns **true** if the input value is of the **Uint16Array** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isUint16Array(new Uint16Array([])); @@ -4252,6 +4347,7 @@ Checks whether the input value is of the **Uint32Array** type. | boolean | Returns **true** if the input value is of the **Uint32Array** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isUint32Array(new Uint32Array([])); @@ -4279,6 +4375,7 @@ Checks whether the input value is of the **WeakMap** type. | boolean | Returns **true** if the input value is of the **WeakMap** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isWeakMap(new WeakMap()); @@ -4306,6 +4403,7 @@ Checks whether the input value is of the **WeakSet** type. | boolean | Returns **true** if the input value is of the **WeakSet** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isWeakSet(new WeakSet()); @@ -4333,6 +4431,7 @@ Checks whether the input value is of the **BigInt64Array** type. | boolean | Returns **true** if the input value is of the **BigInt64Array** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isBigInt64Array(new BigInt64Array([])); @@ -4360,6 +4459,7 @@ Checks whether the input value is of the **BigUint64Array** type. | boolean | Returns **true** if the input value is of the **BigUint64Array** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isBigUint64Array(new BigUint64Array([])); @@ -4387,6 +4487,7 @@ Checks whether the input value is a module namespace object. | boolean | Returns **true** if the input value is a module namespace object; returns **false** otherwise.| **Example** + ```js import url from '@ohos.url' let that = new util.types(); @@ -4415,6 +4516,7 @@ Checks whether the input value is of the **SharedArrayBuffer** type. | boolean | Returns **true** if the input value is of the **SharedArrayBuffer** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isSharedArrayBuffer(new SharedArrayBuffer(0)); diff --git a/en/application-dev/reference/apis/js-apis-vector.md b/en/application-dev/reference/apis/js-apis-vector.md index 57b38f31c7e609fb59e1ff5266713e59d588c247..302b8223c0b720390c82cb28afa921b439fef7fd 100644 --- a/en/application-dev/reference/apis/js-apis-vector.md +++ b/en/application-dev/reference/apis/js-apis-vector.md @@ -1,4 +1,4 @@ -# Linear Container Vector +# @ohos.util.Vector (Linear Container Vector) > **NOTE** > @@ -290,7 +290,7 @@ vector.removeByRange(2,4); ### replaceAllElements -replaceAllElements(callbackfn: (value: T, index?: number, vector?: Vector<T>) => T, +replaceAllElements(callbackFn: (value: T, index?: number, vector?: Vector<T>) => T, thisArg?: Object): void Replaces all elements in this container with new elements, and returns the new ones. @@ -301,7 +301,7 @@ Replaces all elements in this container with new elements, and returns the new o | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked for replacement.| +| callbackFn | function | Yes| Callback invoked for replacement.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -330,7 +330,7 @@ vector.replaceAllElements((value: number, index: number) => { ### forEach -forEach(callbackfn: (value: T, index?: number, vector?: Vector<T>) => void, +forEach(callbackFn: (value: T, index?: number, vector?: Vector<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -341,7 +341,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked for replacement.| +| callbackFn | function | Yes| Callback invoked for replacement.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn diff --git a/en/application-dev/reference/apis/js-apis-wallpaper.md b/en/application-dev/reference/apis/js-apis-wallpaper.md index b7a9bad454b15ce99e38ff407df3aa4dc5e7b653..371e69dd03b0e5886456a189f9aceeb4444610c0 100644 --- a/en/application-dev/reference/apis/js-apis-wallpaper.md +++ b/en/application-dev/reference/apis/js-apis-wallpaper.md @@ -1,20 +1,19 @@ -# Wallpaper +# @ohos.wallpaper The **wallpaper** module is part of the theme framework and provides the system-level wallpaper management service in OpenHarmony. You can use the APIs of this module to show, set, and switch between wallpapers. > **NOTE** -> +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -``` +```js import wallpaper from '@ohos.wallpaper'; ``` - ## WallpaperType Enumerates the wallpaper types. @@ -27,15 +26,25 @@ Enumerates the wallpaper types. | WALLPAPER_LOCKSCREEN | 1 |Lock screen wallpaper.| -## wallpaper.getColors +## RgbaColor -getColors(wallpaperType: WallpaperType, callback: AsyncCallback<Array<RgbaColor>>): void +Defines the RGBA color space for the wallpaper. -Obtains the main color information of the wallpaper of the specified type. This API uses an asynchronous callback to return the result. +**System capability**: SystemCapability.MiscServices.Wallpaper -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getColorsSync9+](#wallpapergetcolorssync9) instead. +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| red | number | Yes| Yes| Red color. The value ranges from 0 to 255.| +| green | number | Yes| Yes| Green color. The value ranges from 0 to 255.| +| blue | number | Yes| Yes| Blue color. The value ranges from 0 to 255.| +| alpha | number | Yes| Yes| Alpha value. The value ranges from 0 to 255.| + + +## wallpaper.getColorsSync9+ + +getColorsSync(wallpaperType: WallpaperType): Array<RgbaColor> + +Obtains the main color information of the wallpaper of the specified type. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -44,30 +53,24 @@ Obtains the main color information of the wallpaper of the specified type. This | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| -| callback | AsyncCallback<Array<[RgbaColor](#rgbacolor)>> | Yes| Callback used to return the main color information of the wallpaper.| -**Example** +**Return value** - ```js - wallpaper.getColors(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to getColors because: ` + JSON.stringify(error)); - return; - } - console.log(`success to getColors.`); - }); - ``` +| Type| Description| +| -------- | -------- | +| Array<[RgbaColor](#rgbacolor)> | Promise used to return the main color information of the wallpaper.| +**Example** -## wallpaper.getColors +```js +let colors = wallpaper.getColorsSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM); +``` -getColors(wallpaperType: WallpaperType): Promise<Array<RgbaColor>> +## wallpaper.getIdSync9+ -Obtains the main color information of the wallpaper of the specified type. This API uses a promise to return the result. +getIdSync(wallpaperType: WallpaperType): number -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getColorsSync9+](#wallpapergetcolorssync9) instead. +Obtains the ID of the wallpaper of the specified type. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -81,24 +84,130 @@ Obtains the main color information of the wallpaper of the specified type. This | Type| Description| | -------- | -------- | -| Promise<Array<[RgbaColor](#rgbacolor)>> | Promise used to return the main color information of the wallpaper.| +| number | ID of the wallpaper. If this type of wallpaper is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to 2^31-1.| **Example** - ```js - wallpaper.getColors(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to getColors.`); - }).catch((error) => { - console.error(`failed to getColors because: ` + JSON.stringify(error)); - }); - ``` +```js +let id = wallpaper.getIdSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM); +``` +## wallpaper.getMinHeightSync9+ -## wallpaper.getColorsSync9+ +getMinHeightSync(): number -getColorsSync(wallpaperType: WallpaperType): Array<RgbaColor> +Obtains the minimum height of this wallpaper. -Obtains the main color information of the wallpaper of the specified type. This API uses an asynchronous callback to return the result. +**System capability**: SystemCapability.MiscServices.Wallpaper + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Promise used to return the minimum wallpaper height, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default height should be used instead.| + +**Example** + +```js +let minHeight = wallpaper.getMinHeightSync(); +``` + +## wallpaper.getMinWidthSync9+ + +getMinWidthSync(): number + +Obtains the minimum width of this wallpaper. + +**System capability**: SystemCapability.MiscServices.Wallpaper + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Promise used to return the minimum wallpaper width, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default width should be used instead.| + +**Example** + +```js +let minWidth = wallpaper.getMinWidthSync(); +``` + +## wallpaper.isChangeAllowed9+ + +isChangeAllowed(): boolean + +Checks whether to allow the application to change the wallpaper for the current user. + +**System capability**: SystemCapability.MiscServices.Wallpaper + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Whether to allow the application to change the wallpaper for the current user. The value **true** means that the operation is allowed, and **false** means the opposite.| + +**Example** + +```js +let isChangeAllowed = wallpaper.isChangeAllowed(); +``` + +## wallpaper.isUserChangeAllowed9+ + +isUserChangeAllowed(): boolean + +Checks whether the user is allowed to set wallpapers. + +**System capability**: SystemCapability.MiscServices.Wallpaper + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Whether the user is allowed to set wallpapers. The value **true** means that the operation is allowed, and **false** means the opposite.| + +**Example** + +```js +let isUserChangeAllowed = wallpaper.isUserChangeAllowed(); +``` + +## wallpaper.restore9+ + +restore(wallpaperType: WallpaperType, callback: AsyncCallback<void>): void + +Resets the wallpaper of the specified type to the default wallpaper. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.SET_WALLPAPER + +**System capability**: SystemCapability.MiscServices.Wallpaper + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is error information.| + +**Example** + +```js +wallpaper.restore(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => { + if (error) { + console.error(`failed to restore because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to restore.`); +}); +``` + +## wallpaper.restore9+ + +restore(wallpaperType: WallpaperType): Promise<void> + +Resets the wallpaper of the specified type to the default wallpaper. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.SET_WALLPAPER **System capability**: SystemCapability.MiscServices.Wallpaper @@ -112,24 +221,25 @@ Obtains the main color information of the wallpaper of the specified type. This | Type| Description| | -------- | -------- | -| Array<[RgbaColor](#rgbacolor)> | Promise used to return the main color information of the wallpaper.| +| Promise<void> | Promise that returns no value.| **Example** - ```js - var colors = wallpaper.getColorsSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM); - ``` - +```js +wallpaper.restore(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => { + console.log(`success to restore.`); + }).catch((error) => { + console.error(`failed to restore because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.getId +## wallpaper.setImage9+ -getId(wallpaperType: WallpaperType, callback: AsyncCallback<number>): void +setImage(source: string | image.PixelMap, wallpaperType: WallpaperType, callback: AsyncCallback<void>): void -Obtains the ID of the wallpaper of the specified type. This API uses an asynchronous callback to return the result. +Sets a specified source as the wallpaper of a specified type. This API uses an asynchronous callback to return the result. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getIdSync9+](#wallpapergetidsync9) instead. +**Required permissions**: ohos.permission.SET_WALLPAPER **System capability**: SystemCapability.MiscServices.Wallpaper @@ -137,31 +247,52 @@ Obtains the ID of the wallpaper of the specified type. This API uses an asynchro | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | +| source | string \| [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.| | wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| -| callback | AsyncCallback<number> | Yes| Callback used to return the wallpaper ID. If the wallpaper of the specified type is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to 2^31-1.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is error information.| **Example** - ```js - wallpaper.getId(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to getId because: ` + JSON.stringify(error)); - return; - } - console.log(`success to getId: ` + JSON.stringify(data)); - }); - ``` - +```js +//The source type is string. +let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; +wallpaper.setImage(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => { + if (error) { + console.error(`failed to setImage because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to setImage.`); +}); + +// The source type is image.PixelMap. +import image from '@ohos.multimedia.image'; +let imageSource = image.createImageSource("file://" + wallpaperPath); +let opts = { + "desiredSize": { + "height": 3648, + "width": 2736 + } +}; +imageSource.createPixelMap(opts).then((pixelMap) => { + wallpaper.setImage(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => { + if (error) { + console.error(`failed to setImage because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to setImage.`); + }); +}).catch((error) => { + console.error(`failed to createPixelMap because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.getId +## wallpaper.setImage9+ -getId(wallpaperType: WallpaperType): Promise<number> +setImage(source: string | image.PixelMap, wallpaperType: WallpaperType): Promise<void> -Obtains the ID of the wallpaper of the specified type. This API uses a promise to return the result. +Sets a specified source as the wallpaper of a specified type. This API uses a promise to return the result. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getIdSync9+](#wallpapergetidsync9) instead. +**Required permissions**: ohos.permission.SET_WALLPAPER **System capability**: SystemCapability.MiscServices.Wallpaper @@ -169,30 +300,53 @@ Obtains the ID of the wallpaper of the specified type. This API uses a promise t | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | +| source | string \| [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.| | wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| **Return value** | Type| Description| | -------- | -------- | -| Promise<number> | Promise used to return the wallpaper ID. If this type of wallpaper is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to 2^31-1.| +| Promise<void> | Promise that returns no value.| **Example** - ```js - wallpaper.getId(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to getId: ` + JSON.stringify(data)); - }).catch((error) => { - console.error(`failed to getId because: ` + JSON.stringify(error)); - }); - ``` +```js +//The source type is string. +let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; +wallpaper.setImage(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => { + console.log(`success to setImage.`); +}).catch((error) => { + console.error(`failed to setImage because: ${JSON.stringify(error)}`); +}); + +// The source type is image.PixelMap. +import image from '@ohos.multimedia.image'; +let imageSource = image.createImageSource("file://" + wallpaperPath); +let opts = { + "desiredSize": { + "height": 3648, + "width": 2736 + } +}; +imageSource.createPixelMap(opts).then((pixelMap) => { + wallpaper.setImage(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => { + console.log(`success to setImage.`); + }).catch((error) => { + console.error(`failed to setImage because: ${JSON.stringify(error)}`); + }); +}).catch((error) => { + console.error(`failed to createPixelMap because: ${JSON.stringify(error)}`); +}); +``` +## wallpaper.getFileSync9+ -## wallpaper.getIdSync9+ +getFileSync(wallpaperType: WallpaperType): number; -getIdSync(wallpaperType: WallpaperType): number +Obtains the wallpaper of the specified type. -Obtains the ID of the wallpaper of the specified type. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.GET_WALLPAPER **System capability**: SystemCapability.MiscServices.Wallpaper @@ -206,105 +360,109 @@ Obtains the ID of the wallpaper of the specified type. This API uses an asynchro | Type| Description| | -------- | -------- | -| number | ID of the wallpaper. If this type of wallpaper is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to 2^31-1.| +| number | Promise used to return the result. If the operation is successful, the file descriptor ID to the wallpaper is returned. Otherwise, error information is returned.| **Example** - ```js - var id = wallpaper.getIdSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM); - ``` - +```js +let file = wallpaper.getFileSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM); +``` -## wallpaper.getMinHeight +## wallpaper.getImage9+ -getMinHeight(callback: AsyncCallback<number>): void +getImage(wallpaperType: WallpaperType, callback: AsyncCallback<image.PixelMap>): void; -Obtains the minimum height of this wallpaper. This API uses an asynchronous callback to return the result. +Obtains the pixel map for the wallpaper of the specified type. This API uses an asynchronous callback to return the result. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getMinHeightSync9+](#wallpapergetminheightsync9) instead. +**Required permissions**: ohos.permission.GET_WALLPAPER **System capability**: SystemCapability.MiscServices.Wallpaper +**System API**: This is a system API. + **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<number> | Yes| Callback used to return the minimum wallpaper height, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default height should be used instead.| +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| +| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | Yes| Callback used to return the result. Returns the pixel map size of the wallpaper if the operation is successful; returns an error message otherwise.| **Example** - ```js - wallpaper.getMinHeight((error, data) => { - if (error) { - console.error(`failed to getMinHeight because: ` + JSON.stringify(error)); - return; - } - console.log(`success to getMinHeight: ` + JSON.stringify(data)); - }); - ``` +```js +wallpaper.getImage(wallpaper.WallpaperType.WALLPAPER_SYSTEM, function (error, data) { + if (error) { + console.error(`failed to getImage because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to getImage: ${JSON.stringify(data)}`); +}); +``` -## wallpaper.getMinHeight +## wallpaper.getImage9+ -getMinHeight(): Promise<number> +getImage(wallpaperType: WallpaperType): Promise<image.PixelMap> -Obtains the minimum height of this wallpaper. This API uses a promise to return the result. +Obtains the pixel map for the wallpaper of the specified type. This API uses a promise to return the result. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getMinHeightSync9+](#wallpapergetminheightsync9) instead. +**Required permissions**: ohos.permission.GET_WALLPAPER **System capability**: SystemCapability.MiscServices.Wallpaper +**System API**: This is a system API. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| + **Return value** | Type| Description| | -------- | -------- | -| Promise<number> | Promise used to return the minimum wallpaper height, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default height should be used instead.| +| Promise<[image.PixelMap](js-apis-image.md#pixelmap7)> | Promise used to return the result. Returns the pixel map size of the wallpaper if the operation is successful; returns an error message otherwise.| **Example** - ```js - wallpaper.getMinHeight().then((data) => { - console.log(`success to getMinHeight: ` + JSON.stringify(data)); +```js +wallpaper.getImage(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { + console.log(`success to getImage: ${JSON.stringify(data)}`); }).catch((error) => { - console.error(`failed to getMinHeight because: ` + JSON.stringify(error)); - }); - ``` - + console.error(`failed to getImage because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.getMinHeightSync9+ +## wallpaper.on('colorChange')9+ -getMinHeightSync(): number +on(type: 'colorChange', callback: (colors: Array<RgbaColor>, wallpaperType: WallpaperType) => void): void -Obtains the minimum height of this wallpaper. This API uses an asynchronous callback to return the result. +Subscribes to the wallpaper color change event. **System capability**: SystemCapability.MiscServices.Wallpaper -**Return value** +**Parameters** -| Type| Description| -| -------- | -------- | -| number | Promise used to return the minimum wallpaper height, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default height should be used instead.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value **'colorChange'** indicates subscribing to the wallpaper color change event.| +| callback | function | Yes| Callback triggered when the wallpaper color changes. The wallpaper type and main colors are returned.
- colors
Main color information of the wallpaper. For details, see [RgbaColor](#rgbacolor).
- wallpaperType
Wallpaper type.| **Example** - ```js - var minHeight = wallpaper.getMinHeightSync(); - ``` - - -## wallpaper.getMinWidth +```js +let listener = (colors, wallpaperType) => { + console.log(`wallpaper color changed.`); +}; +wallpaper.on('colorChange', listener); +``` -getMinWidth(callback: AsyncCallback<number>): void +## wallpaper.off('colorChange')9+ -Obtains the minimum width of this wallpaper. This API uses an asynchronous callback to return the result. +off(type: 'colorChange', callback?: (colors: Array<RgbaColor>, wallpaperType: WallpaperType) => void): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getMinWidthSync9+](#wallpapergetminwidthsync9) instead. +Unsubscribes from the wallpaper color change event. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -312,80 +470,96 @@ Obtains the minimum width of this wallpaper. This API uses an asynchronous callb | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<number> | Yes| Callback used to return the minimum wallpaper width, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default width should be used instead.| +| type | string | Yes| Type of the event to unsubscribe from. The value **'colorChange'** indicates unsubscribing from the wallpaper color change event.| +| callback | function | No| Callback for the wallpaper color change event. If this parameter is not set, this API unsubscribes from all callbacks corresponding to **type**.
- colors
Main color information of the wallpaper. For details, see [RgbaColor](#rgbacolor).
- wallpaperType
Wallpaper type.| **Example** - ```js - wallpaper.getMinWidth((error, data) => { - if (error) { - console.error(`failed to getMinWidth because: ` + JSON.stringify(error)); - return; - } - console.log(`success to getMinWidth: ` + JSON.stringify(data)); - }); - ``` - +```js +let listener = (colors, wallpaperType) => { + console.log(`wallpaper color changed.`); +}; +wallpaper.on('colorChange', listener); +// Unsubscribe from the listener. +wallpaper.off('colorChange', listener); +// Unsubscribe from all subscriptions of the colorChange type. +wallpaper.off('colorChange'); +``` -## wallpaper.getMinWidth +## wallpaper.getColors(deprecated) -getMinWidth(): Promise<number> +getColors(wallpaperType: WallpaperType, callback: AsyncCallback<Array<RgbaColor>>): void -Obtains the minimum width of this wallpaper. This API uses a promise to return the result. +Obtains the main color information of the wallpaper of the specified type. This API uses an asynchronous callback to return the result. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getMinWidthSync9+](#wallpapergetminwidthsync9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getColorsSync9+](#wallpapergetcolorssync9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper -**Return value** +**Parameters** -| Type| Description| -| -------- | -------- | -| Promise<number> | Promise used to return the minimum wallpaper width, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default width should be used instead.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| +| callback | AsyncCallback<Array<[RgbaColor](#rgbacolor)>> | Yes| Callback used to return the main color information of the wallpaper.| **Example** - ```js - wallpaper.getMinWidth().then((data) => { - console.log(`success to getMinWidth: ` + JSON.stringify(data)); - }).catch((error) => { - console.error(`failed to getMinWidth because: ` + JSON.stringify(error)); - }); - ``` +```js +wallpaper.getColors(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { + if (error) { + console.error(`failed to getColors because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to getColors: ${JSON.stringify(data)}`); +}); +``` +## wallpaper.getColors(deprecated) -## wallpaper.getMinWidthSync9+ +getColors(wallpaperType: WallpaperType): Promise<Array<RgbaColor>> -getMinWidthSync(): number +Obtains the main color information of the wallpaper of the specified type. This API uses a promise to return the result. -Obtains the minimum width of this wallpaper. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getColorsSync9+](#wallpapergetcolorssync9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| + **Return value** | Type| Description| | -------- | -------- | -| number | Promise used to return the minimum wallpaper width, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default width should be used instead.| +| Promise<Array<[RgbaColor](#rgbacolor)>> | Promise used to return the main color information of the wallpaper.| **Example** - ```js - var minWidth = wallpaper.getMinWidthSync(); - ``` - +```js +wallpaper.getColors(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { + console.log(`success to getColors: ${JSON.stringify(data)}`); + }).catch((error) => { + console.error(`failed to getColors because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.isChangePermitted +## wallpaper.getId(deprecated) -isChangePermitted(callback: AsyncCallback<boolean>): void +getId(wallpaperType: WallpaperType, callback: AsyncCallback<number>): void -Checks whether to allow the application to change the wallpaper for the current user. This API uses an asynchronous callback to return the result. +Obtains the ID of the wallpaper of the specified type. This API uses an asynchronous callback to return the result. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.isChangeAllowed9+](#wallpaperischangeallowed9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getIdSync9+](#wallpapergetidsync9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -393,136 +567,152 @@ Checks whether to allow the application to change the wallpaper for the current | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes| Callback used to return whether to allow the application to change the wallpaper for the current user. The value **true** means that the operation is allowed, and **false** means the opposite.| +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| +| callback | AsyncCallback<number> | Yes| Callback used to return the wallpaper ID. If the wallpaper of the specified type is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to 2^31-1.| **Example** - ```js - wallpaper.isChangePermitted((error, data) => { - if (error) { - console.error(`failed to isChangePermitted because: ` + JSON.stringify(error)); - return; - } - console.log(`success to isChangePermitted: ` + JSON.stringify(data)); - }); - ``` - +```js +wallpaper.getId(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { + if (error) { + console.error(`failed to getId because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to getId: ${JSON.stringify(data)}`); +}); +``` -## wallpaper.isChangePermitted +## wallpaper.getId(deprecated) -isChangePermitted(): Promise<boolean> +getId(wallpaperType: WallpaperType): Promise<number> -Checks whether to allow the application to change the wallpaper for the current user. This API uses a promise to return the result. +Obtains the ID of the wallpaper of the specified type. This API uses a promise to return the result. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.isChangeAllowed9+](#wallpaperischangeallowed9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getIdSync9+](#wallpapergetidsync9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| + **Return value** | Type| Description| | -------- | -------- | -| Promise<boolean> | Promise used to return whether to allow the application to change the wallpaper for the current user. The value **true** means that the operation is allowed, and **false** means the opposite.| +| Promise<number> | Promise used to return the wallpaper ID. If this type of wallpaper is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to 2^31-1.| **Example** - ```js - wallpaper.isChangePermitted().then((data) => { - console.log(`success to isChangePermitted: ` + JSON.stringify(data)); +```js +wallpaper.getId(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { + console.log(`success to getId: ${JSON.stringify(data)}`); }).catch((error) => { - console.error(`failed to isChangePermitted because: ` + JSON.stringify(error)); - }); - ``` + console.error(`failed to getId because: ${JSON.stringify(error)}`); +}); +``` +## wallpaper.getMinHeight(deprecated) -## wallpaper.isChangeAllowed9+ +getMinHeight(callback: AsyncCallback<number>): void -isChangeAllowed(): boolean +Obtains the minimum height of this wallpaper. This API uses an asynchronous callback to return the result. -Checks whether to allow the application to change the wallpaper for the current user. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getMinHeightSync9+](#wallpapergetminheightsync9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper -**Return value** +**Parameters** -| Type| Description| -| -------- | -------- | -| boolean | Whether to allow the application to change the wallpaper for the current user. The value **true** means that the operation is allowed, and **false** means the opposite.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<number> | Yes| Callback used to return the minimum wallpaper height, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default height should be used instead.| **Example** - ```js - var isChangeAllowed = wallpaper.isChangeAllowed(); - ``` - +```js +wallpaper.getMinHeight((error, data) => { + if (error) { + console.error(`failed to getMinHeight because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to getMinHeight: ${JSON.stringify(data)}`); +}); +``` -## wallpaper.isOperationAllowed +## wallpaper.getMinHeight(deprecated) -isOperationAllowed(callback: AsyncCallback<boolean>): void +getMinHeight(): Promise<number> -Checks whether the user is allowed to set wallpapers. This API uses an asynchronous callback to return the result. +Obtains the minimum height of this wallpaper. This API uses a promise to return the result. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.isUserChangeAllowed9+](#wallpaperisuserchangeallowed9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getMinHeightSync9+](#wallpapergetminheightsync9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper -**Parameters** +**Return value** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes| Callback used to return whether the user is allowed to set wallpapers. The value **true** means that the operation is allowed, and **false** means the opposite.| +| Type| Description| +| -------- | -------- | +| Promise<number> | Promise used to return the minimum wallpaper height, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default height should be used instead.| **Example** - ```js - wallpaper.isOperationAllowed((error, data) => { - if (error) { - console.error(`failed to isOperationAllowed because: ` + JSON.stringify(error)); - return; - } - console.log(`success to isOperationAllowed: ` + JSON.stringify(data)); - }); - ``` - +```js +wallpaper.getMinHeight().then((data) => { + console.log(`success to getMinHeight: ${JSON.stringify(data)}`); +}).catch((error) => { + console.error(`failed to getMinHeight because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.isOperationAllowed +## wallpaper.getMinWidth(deprecated) -isOperationAllowed(): Promise<boolean> +getMinWidth(callback: AsyncCallback<number>): void -Checks whether the user is allowed to set wallpapers. This API uses a promise to return the result. +Obtains the minimum width of this wallpaper. This API uses an asynchronous callback to return the result. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.isUserChangeAllowed9+](#wallpaperisuserchangeallowed9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getMinWidthSync9+](#wallpapergetminwidthsync9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper -**Return value** +**Parameters** -| Type| Description| -| -------- | -------- | -| Promise<boolean> | Promise used to return whether the user is allowed to set wallpapers. The value **true** means that the operation is allowed, and **false** means the opposite.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<number> | Yes| Callback used to return the minimum wallpaper width, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default width should be used instead.| **Example** - ```js - wallpaper.isOperationAllowed().then((data) => { - console.log(`success to isOperationAllowed: ` + JSON.stringify(data)); - }).catch((error) => { - console.error(`failed to isOperationAllowed because: ` + JSON.stringify(error)); - }); - ``` +```js +wallpaper.getMinWidth((error, data) => { + if (error) { + console.error(`failed to getMinWidth because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to getMinWidth: ${JSON.stringify(data)}`); +}); +``` +## wallpaper.getMinWidth(deprecated) -## wallpaper.isUserChangeAllowed9+ +getMinWidth(): Promise<number> -isUserChangeAllowed(): boolean +Obtains the minimum width of this wallpaper. This API uses a promise to return the result. -Checks whether the user is allowed to set wallpapers. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getMinWidthSync9+](#wallpapergetminwidthsync9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -530,26 +720,27 @@ Checks whether the user is allowed to set wallpapers. This API uses an asynchron | Type| Description| | -------- | -------- | -| boolean | Whether the user is allowed to set wallpapers. The value **true** means that the operation is allowed, and **false** means the opposite.| +| Promise<number> | Promise used to return the minimum wallpaper width, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default width should be used instead.| **Example** - ```js - var isUserChangeAllowed = wallpaper.isUserChangeAllowed(); - ``` - +```js +wallpaper.getMinWidth().then((data) => { + console.log(`success to getMinWidth: ${JSON.stringify(data)}`); + }).catch((error) => { + console.error(`failed to getMinWidth because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.reset +## wallpaper.isChangePermitted(deprecated) -reset(wallpaperType: WallpaperType, callback: AsyncCallback<void>): void +isChangePermitted(callback: AsyncCallback<boolean>): void -Resets the wallpaper of the specified type to the default wallpaper. This API uses an asynchronous callback to return the result. +Checks whether to allow the application to change the wallpaper for the current user. This API uses an asynchronous callback to return the result. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.restore9+](#wallpaperrestore9) instead. - -**Required permissions**: ohos.permission.SET_WALLPAPER +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.isChangeAllowed9+](#wallpaperischangeallowed9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -557,66 +748,57 @@ Resets the wallpaper of the specified type to the default wallpaper. This API us | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, the result of removal is returned. Otherwise, error information is returned.| +| callback | AsyncCallback<boolean> | Yes| Callback used to return whether to allow the application to change the wallpaper for the current user. The value **true** means that the operation is allowed, and **false** means the opposite.| **Example** - ```js - wallpaper.reset(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to reset because: ` + JSON.stringify(error)); - return; - } - console.log(`success to reset.`); - }); - ``` - +```js +wallpaper.isChangePermitted((error, data) => { + if (error) { + console.error(`failed to isChangePermitted because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to isChangePermitted: ${JSON.stringify(data)}`); +}); +``` -## wallpaper.reset +## wallpaper.isChangePermitted(deprecated) -reset(wallpaperType: WallpaperType): Promise<void> +isChangePermitted(): Promise<boolean> -Resets the wallpaper of the specified type to the default wallpaper. This API uses a promise to return the result. +Checks whether to allow the application to change the wallpaper for the current user. This API uses a promise to return the result. > **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.restore9+](#wallpaperrestore9) instead. - -**Required permissions**: ohos.permission.SET_WALLPAPER +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.isChangeAllowed9+](#wallpaperischangeallowed9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| - **Return value** | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result. If the operation is successful, the result is returned. Otherwise, error information is returned.| +| Promise<boolean> | Promise used to return whether to allow the application to change the wallpaper for the current user. The value **true** means that the operation is allowed, and **false** means the opposite.| **Example** - ```js - wallpaper.reset(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to reset.`); - }).catch((error) => { - console.error(`failed to reset because: ` + JSON.stringify(error)); - }); - ``` - +```js +wallpaper.isChangePermitted().then((data) => { + console.log(`success to isChangePermitted: ${JSON.stringify(data)}`); +}).catch((error) => { + console.error(`failed to isChangePermitted because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.restore9+ +## wallpaper.isOperationAllowed(deprecated) -restore(wallpaperType: WallpaperType, callback: AsyncCallback<void>): void +isOperationAllowed(callback: AsyncCallback<boolean>): void -Resets the wallpaper of the specified type to the default wallpaper. This API uses an asynchronous callback to return the result. +Checks whether the user is allowed to set wallpapers. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.SET_WALLPAPER +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.isUserChangeAllowed9+](#wallpaperisuserchangeallowed9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -624,64 +806,57 @@ Resets the wallpaper of the specified type to the default wallpaper. This API us | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, the result of removal is returned. Otherwise, error information is returned.| +| callback | AsyncCallback<boolean> | Yes| Callback used to return whether the user is allowed to set wallpapers. The value **true** means that the operation is allowed, and **false** means the opposite.| **Example** - ```js - wallpaper.restore(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to restore because: ` + JSON.stringify(error)); - return; - } - console.log(`success to restore.`); - }); - ``` - +```js +wallpaper.isOperationAllowed((error, data) => { + if (error) { + console.error(`failed to isOperationAllowed because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to isOperationAllowed: ${JSON.stringify(data)}`); +}); +``` -## wallpaper.restore9+ +## wallpaper.isOperationAllowed(deprecated) -restore(wallpaperType: WallpaperType): Promise<void> +isOperationAllowed(): Promise<boolean> -Resets the wallpaper of the specified type to the default wallpaper. This API uses an asynchronous callback to return the result. +Checks whether the user is allowed to set wallpapers. This API uses a promise to return the result. -**Required permissions**: ohos.permission.SET_WALLPAPER +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.isUserChangeAllowed9+](#wallpaperisuserchangeallowed9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| - **Return value** | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result. If the operation is successful, the result is returned. Otherwise, error information is returned.| +| Promise<boolean> | Promise used to return whether the user is allowed to set wallpapers. The value **true** means that the operation is allowed, and **false** means the opposite.| **Example** - ```js - wallpaper.restore(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to restore.`); +```js +wallpaper.isOperationAllowed().then((data) => { + console.log(`success to isOperationAllowed: ${JSON.stringify(data)}`); }).catch((error) => { - console.error(`failed to restore because: ` + JSON.stringify(error)); - }); - ``` - + console.error(`failed to isOperationAllowed because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.setWallpaper +## wallpaper.reset(deprecated) -setWallpaper(source: string | image.PixelMap, wallpaperType: WallpaperType, callback: AsyncCallback<void>): void +reset(wallpaperType: WallpaperType, callback: AsyncCallback<void>): void -Sets a specified source as the wallpaper of a specified type. This API uses an asynchronous callback to return the result. +Resets the wallpaper of the specified type to the default wallpaper. This API uses an asynchronous callback to return the result. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.setImage9+](#wallpapersetimage9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.restore9+](#wallpaperrestore9) instead. **Required permissions**: ohos.permission.SET_WALLPAPER @@ -691,55 +866,30 @@ Sets a specified source as the wallpaper of a specified type. This API uses an a | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| source | string \|[image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.| | wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, the setting result is returned. Otherwise, error information is returned.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is error information.| **Example** - ```js - //The source type is string. - let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; - wallpaper.setWallpaper(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to setWallpaper because: ` + JSON.stringify(error)); - return; - } - console.log(`success to setWallpaper.`); - }); - - // The source type is image.PixelMap. - import image from '@ohos.multimedia.image'; - let imageSource = image.createImageSource("file://" + wallpaperPath); - let opts = { - "desiredSize": { - "height": 3648, - "width": 2736 - } - }; - imageSource.createPixelMap(opts).then((pixelMap) => { - wallpaper.setWallpaper(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to setWallpaper because: ` + JSON.stringify(error)); - return; - } - console.log(`success to setWallpaper.`); - }); - }).catch((error) => { - console.error(`failed to createPixelMap because: ` + JSON.stringify(error)); - }); - ``` - +```js +wallpaper.reset(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => { + if (error) { + console.error(`failed to reset because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to reset.`); +}); +``` -## wallpaper.setWallpaper +## wallpaper.reset(deprecated) -setWallpaper(source: string | image.PixelMap, wallpaperType: WallpaperType): Promise<void> +reset(wallpaperType: WallpaperType): Promise<void> -Sets a specified source as the wallpaper of a specified type. This API uses a promise to return the result. +Resets the wallpaper of the specified type to the default wallpaper. This API uses a promise to return the result. > **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.setImage9+](#wallpapersetimage9) instead. +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.restore9+](#wallpaperrestore9) instead. **Required permissions**: ohos.permission.SET_WALLPAPER @@ -749,53 +899,34 @@ Sets a specified source as the wallpaper of a specified type. This API uses a pr | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| source | string \|[image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.| | wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| **Return value** | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result. If the operation is successful, the setting result is returned. Otherwise, error information is returned.| +| Promise<void> | Promise that returns no value.| **Example** - ```js - //The source type is string. - let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; - wallpaper.setWallpaper(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to setWallpaper.`); - }).catch((error) => { - console.error(`failed to setWallpaper because: ` + JSON.stringify(error)); - }); - - // The source type is image.PixelMap. - import image from '@ohos.multimedia.image'; - let imageSource = image.createImageSource("file://" + wallpaperPath); - let opts = { - "desiredSize": { - "height": 3648, - "width": 2736 - } - }; - imageSource.createPixelMap(opts).then((pixelMap) => { - wallpaper.setWallpaper(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to setWallpaper.`); - }).catch((error) => { - console.error(`failed to setWallpaper because: ` + JSON.stringify(error)); - }); - }).catch((error) => { - console.error(`failed to createPixelMap because: ` + JSON.stringify(error)); - }); - ``` - +```js +wallpaper.reset(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => { + console.log(`success to reset.`); +}).catch((error) => { + console.error(`failed to reset because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.setImage9+ +## wallpaper.setWallpaper(deprecated) -setImage(source: string | image.PixelMap, wallpaperType: WallpaperType, callback: AsyncCallback<void>): void +setWallpaper(source: string | image.PixelMap, wallpaperType: WallpaperType, callback: AsyncCallback<void>): void Sets a specified source as the wallpaper of a specified type. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.setImage9+](#wallpapersetimage9) instead. + **Required permissions**: ohos.permission.SET_WALLPAPER **System capability**: SystemCapability.MiscServices.Wallpaper @@ -804,51 +935,54 @@ Sets a specified source as the wallpaper of a specified type. This API uses an a | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| source | string \|[image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.| +| source | string \| [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.| | wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, the setting result is returned. Otherwise, error information is returned.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is error information.| **Example** - ```js - //The source type is string. - let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; - wallpaper.setImage(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to setImage because: ` + JSON.stringify(error)); - return; - } - console.log(`success to setImage.`); - }); - - // The source type is image.PixelMap. - import image from '@ohos.multimedia.image'; - let imageSource = image.createImageSource("file://" + wallpaperPath); - let opts = { - "desiredSize": { - "height": 3648, - "width": 2736 - } - }; - imageSource.createPixelMap(opts).then((pixelMap) => { - wallpaper.setImage(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to setImage because: ` + JSON.stringify(error)); - return; - } - console.log(`success to setImage.`); - }); - }).catch((error) => { - console.error(`failed to createPixelMap because: ` + JSON.stringify(error)); - }); - ``` +```js +//The source type is string. +let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; +wallpaper.setWallpaper(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => { + if (error) { + console.error(`failed to setWallpaper because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to setWallpaper.`); +}); + +// The source type is image.PixelMap. +import image from '@ohos.multimedia.image'; +let imageSource = image.createImageSource("file://" + wallpaperPath); +let opts = { + "desiredSize": { + "height": 3648, + "width": 2736 + } +}; +imageSource.createPixelMap(opts).then((pixelMap) => { + wallpaper.setWallpaper(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => { + if (error) { + console.error(`failed to setWallpaper because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to setWallpaper.`); + }); +}).catch((error) => { + console.error(`failed to createPixelMap because: ${JSON.stringify(error)}`); +}); +``` +## wallpaper.setWallpaper(deprecated) -## wallpaper.setImage9+ +setWallpaper(source: string | image.PixelMap, wallpaperType: WallpaperType): Promise<void> -setImage(source: string | image.PixelMap, wallpaperType: WallpaperType): Promise<void> +Sets a specified source as the wallpaper of a specified type. This API uses a promise to return the result. -Sets a specified source as the wallpaper of a specified type. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.setImage9+](#wallpapersetimage9) instead. **Required permissions**: ohos.permission.SET_WALLPAPER @@ -858,48 +992,48 @@ Sets a specified source as the wallpaper of a specified type. This API uses an a | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| source | string \|[image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.| +| source | string \| [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.| | wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| **Return value** | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result. If the operation is successful, the setting result is returned. Otherwise, error information is returned.| +| Promise<void> | Promise that returns no value.| **Example** - ```js - //The source type is string. - let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; - wallpaper.setImage(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to setImage.`); +```js +//The source type is string. +let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; +wallpaper.setWallpaper(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => { + console.log(`success to setWallpaper.`); }).catch((error) => { - console.error(`failed to setImage because: ` + JSON.stringify(error)); - }); + console.error(`failed to setWallpaper because: ${JSON.stringify(error)}`); +}); - // The source type is image.PixelMap. - import image from '@ohos.multimedia.image'; - let imageSource = image.createImageSource("file://" + wallpaperPath); - let opts = { - "desiredSize": { - "height": 3648, - "width": 2736 - } - }; - imageSource.createPixelMap(opts).then((pixelMap) => { - wallpaper.setImage(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to setImage.`); - }).catch((error) => { - console.error(`failed to setImage because: ` + JSON.stringify(error)); - }); - }).catch((error) => { - console.error(`failed to createPixelMap because: ` + JSON.stringify(error)); - }); - ``` +// The source type is image.PixelMap. +import image from '@ohos.multimedia.image'; +let imageSource = image.createImageSource("file://" + wallpaperPath); +let opts = { + "desiredSize": { + "height": 3648, + "width": 2736 + } +}; +imageSource.createPixelMap(opts).then((pixelMap) => { + wallpaper.setWallpaper(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => { + console.log(`success to setWallpaper.`); + }).catch((error) => { + console.error(`failed to setWallpaper because: ${JSON.stringify(error)}`); + }); + }).catch((error) => { + console.error(`failed to createPixelMap because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.getFile8+ +## wallpaper.getFile(deprecated) getFile(wallpaperType: WallpaperType, callback: AsyncCallback<number>): void @@ -922,17 +1056,17 @@ Obtains the wallpaper of the specified type. This API uses an asynchronous callb **Example** - ```js - wallpaper.getFile(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to getFile because: ` + JSON.stringify(error)); - return; - } - console.log(`success to getFile: ` + JSON.stringify(data)); - }); - ``` +```js +wallpaper.getFile(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { + if (error) { + console.error(`failed to getFile because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to getFile: ${JSON.stringify(data)}`); +}); +``` -## wallpaper.getFile8+ +## wallpaper.getFile(deprecated) getFile(wallpaperType: WallpaperType): Promise<number> @@ -960,45 +1094,15 @@ Obtains the wallpaper of the specified type. This API uses a promise to return t **Example** - ```js - wallpaper.getFile(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to getFile: ` + JSON.stringify(data)); +```js +wallpaper.getFile(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { + console.log(`success to getFile: ${JSON.stringify(data)}`); }).catch((error) => { - console.error(`failed to getFile because: ` + JSON.stringify(error)); - }); - ``` - - -## wallpaper.getFileSync9+ - -getFileSync(wallpaperType: WallpaperType): number; - -Obtains the wallpaper of the specified type. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.GET_WALLPAPER - -**System capability**: SystemCapability.MiscServices.Wallpaper - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| number | Promise used to return the result. If the operation is successful, the file descriptor ID to the wallpaper is returned. Otherwise, error information is returned.| - -**Example** - - ```js - var file = wallpaper.getFileSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM); - ``` - + console.error(`failed to getFile because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.getPixelMap +## wallpaper.getPixelMap(deprecated) getPixelMap(wallpaperType: WallpaperType, callback: AsyncCallback<image.PixelMap>): void; @@ -1012,7 +1116,7 @@ Obtains the pixel map for the wallpaper of the specified type. This API uses an **System capability**: SystemCapability.MiscServices.Wallpaper -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1023,15 +1127,17 @@ Obtains the pixel map for the wallpaper of the specified type. This API uses an **Example** - ```js - wallpaper.getPixelMap(wallpaper.WallpaperType.WALLPAPER_SYSTEM, function (err, data) { - console.info('wallpaperXTS ===> testGetPixelMapCallbackSystem err : ' + JSON.stringify(err)); - console.info('wallpaperXTS ===> testGetPixelMapCallbackSystem data : ' + JSON.stringify(data)); +```js +wallpaper.getPixelMap(wallpaper.WallpaperType.WALLPAPER_SYSTEM, function (error, data) { + if (error) { + console.error(`failed to getPixelMap because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to getPixelMap : ${JSON.stringify(data)}`); }); - ``` - +``` -## wallpaper.getPixelMap +## wallpaper.getPixelMap(deprecated) getPixelMap(wallpaperType: WallpaperType): Promise<image.PixelMap> @@ -1045,7 +1151,7 @@ Obtains the pixel map for the wallpaper of the specified type. This API uses a p **System capability**: SystemCapability.MiscServices.Wallpaper -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1061,144 +1167,10 @@ Obtains the pixel map for the wallpaper of the specified type. This API uses a p **Example** - ```js - wallpaper.getPixelMap(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.info('wallpaperXTS ===> testGetPixelMapPromiseSystem data : ' + data); - console.info('wallpaperXTS ===> testGetPixelMapPromiseSystem data : ' + JSON.stringify(data)); - }).catch((err) => { - console.info('wallpaperXTS ===> testGetPixelMapPromiseSystem err : ' + err); - console.info('wallpaperXTS ===> testGetPixelMapPromiseSystem err : ' + JSON.stringify(err)); - }); - ``` - - -## wallpaper.getImage9+ - -getImage(wallpaperType: WallpaperType, callback: AsyncCallback<image.PixelMap>): void; - -Obtains the pixel map for the wallpaper of the specified type. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.GET_WALLPAPER - -**System capability**: SystemCapability.MiscServices.Wallpaper - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| -| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | Yes| Callback used to return the result. Returns the pixel map size of the wallpaper if the operation is successful; returns an error message otherwise.| - -**Example** - - ```js - wallpaper.getImage(wallpaper.WallpaperType.WALLPAPER_SYSTEM, function (err, data) { - console.info('wallpaperXTS ===> testgetImageCallbackSystem err : ' + JSON.stringify(err)); - console.info('wallpaperXTS ===> testgetImageCallbackSystem data : ' + JSON.stringify(data)); - }); - ``` - - -## wallpaper.getImage9+ - -getImage(wallpaperType: WallpaperType): Promise<image.PixelMap> - -Obtains the pixel map for the wallpaper of the specified type. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.GET_WALLPAPER - -**System capability**: SystemCapability.MiscServices.Wallpaper - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<[image.PixelMap](js-apis-image.md#pixelmap7)> | Promise used to return the result. Returns the pixel map size of the wallpaper if the operation is successful; returns an error message otherwise.| - -**Example** - - ```js - wallpaper.getImage(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.info('wallpaperXTS ===> testgetImagePromiseSystem data : ' + data); - console.info('wallpaperXTS ===> testgetImagePromiseSystem data : ' + JSON.stringify(data)); - }).catch((err) => { - console.info('wallpaperXTS ===> testgetImagePromiseSystem err : ' + err); - console.info('wallpaperXTS ===> testgetImagePromiseSystem err : ' + JSON.stringify(err)); - }); - ``` - - -## wallpaper.on('colorChange')9+ - -on(type: 'colorChange', callback: (colors: Array<RgbaColor>, wallpaperType: WallpaperType) => void): void - -Subscribes to the wallpaper color change event. - -**System capability**: SystemCapability.MiscServices.Wallpaper - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the event to subscribe to. The value **'colorChange'** indicates subscribing to the wallpaper color change event.| -| callback | function | Yes| Callback triggered when the wallpaper color changes. The wallpaper type and main colors are returned.
- colors
Main color information of the wallpaper. For details, see [RgbaColor](#rgbacolor).
- wallpaperType
Wallpaper type.| - -**Example** - - ```js - let listener = (colors, wallpaperType) => { - console.log(`wallpaper color changed.`); - }; - wallpaper.on('colorChange', listener); - ``` - - -## wallpaper.off('colorChange')9+ - -off(type: 'colorChange', callback?: (colors: Array<RgbaColor>, wallpaperType: WallpaperType) => void): void - -Unsubscribes from the wallpaper color change event. - -**System capability**: SystemCapability.MiscServices.Wallpaper - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the event to unsubscribe from. The value **colorChange** indicates unsubscribing from the wallpaper color change event.| -| callback | function | No| Callback for the wallpaper color change event. If this parameter is not specified, all callbacks corresponding to the wallpaper color change event are invoked.
- colors
Main color information of the wallpaper. For details, see [RgbaColor](#rgbacolor).
- wallpaperType
Wallpaper type.| - -**Example** - - ```js - let listener = (colors, wallpaperType) => { - console.log(`wallpaper color changed.`); - }; - wallpaper.on('colorChange', listener); - // Unsubscribe from the listener. - wallpaper.off('colorChange', listener); - // Unsubscribe from all subscriptions of the colorChange type. - wallpaper.off('colorChange'); - ``` - - -## RgbaColor - -**System capability**: SystemCapability.MiscServices.Wallpaper - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| red | number | Yes| Yes| Red color. The value ranges from 0 to 255.| -| green | number | Yes| Yes| Green color. The value ranges from 0 to 255.| -| blue | number | Yes| Yes| Blue color. The value ranges from 0 to 255.| -| alpha | number | Yes| Yes| Alpha value. The value ranges from 0 to 255.| +```js +wallpaper.getPixelMap(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { + console.log(`success to getPixelMap : ${JSON.stringify(data)}`); + }).catch((error) => { + console.error(`failed to getPixelMap because: ${JSON.stringify(error)}`); +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-wantAgent.md b/en/application-dev/reference/apis/js-apis-wantAgent.md index 5421d20c5fc129c726f31deaae6610d2bdc28d2e..252dc45b802251e8cf0eb7493ce51ef917a5fa99 100644 --- a/en/application-dev/reference/apis/js-apis-wantAgent.md +++ b/en/application-dev/reference/apis/js-apis-wantAgent.md @@ -1,10 +1,10 @@ -# WantAgent +# @ohos.wantAgent The **WantAgent** module provides APIs for triggering, canceling, and comparing **WantAgent** objects. You can use the APIs to create a **WantAgent** object, and obtain the user ID, bundle name, and want information of the object. > **NOTE** > -> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported since API version 7 and deprecated since API version 9. You are advised to use [@ohos.app.ability.wantAgent](js-apis-app-ability-wantAgent.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -22,10 +22,10 @@ Obtains a **WantAgent** object. This API uses an asynchronous callback to return **Parameters** -| Name | Readable| Writable | Type | Mandatory| Description | -| -------- | --- | ---- | -------------------------- | ---- | ----------------------- | -| info | Yes | No | WantAgentInfo | Yes | Information about the **WantAgent** object to obtain. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the **WantAgent** object.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------- | ---- | ----------------------- | +| info | WantAgentInfo | Yes | Information about the **WantAgent** object to obtain. | +| callback | AsyncCallback\ | Yes | Callback used to return the **WantAgent** object.| **Example** @@ -79,9 +79,9 @@ Obtains a **WantAgent** object. This API uses a promise to return the result. **Parameters** -| Name| Readable| Writable | Type | Mandatory| Description | -| ---- | --- | ---- | ------------- | ---- | ------------- | -| info | Yes | No | WantAgentInfo | Yes | Information about the **WantAgent** object to obtain.| +| Name| Type | Mandatory| Description | +| ---- | ------------- | ---- | ------------- | +| info | WantAgentInfo | Yes | Information about the **WantAgent** object to obtain.| **Return value** @@ -140,10 +140,10 @@ Obtains the bundle name of a **WantAgent** object. This API uses an asynchronous **Parameters** -| Name | Readable| Writable | Type | Mandatory| Description | -| -------- | --- | ---- | ----------------------- | ---- | --------------------------------- | -| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the bundle name.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | --------------------------------- | +| agent | WantAgent | Yes | Target **WantAgent** object. | +| callback | AsyncCallback\ | Yes | Callback used to return the bundle name.| **Example** @@ -212,9 +212,9 @@ Obtains the bundle name of a **WantAgent** object. This API uses a promise to re **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ----- | --- | ---- | --------- | ---- | ------------- | -| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object.| +| Name | Type | Mandatory| Description | +| ----- | --------- | ---- | ------------- | +| agent | WantAgent | Yes | Target **WantAgent** object.| **Return value** @@ -281,10 +281,10 @@ Obtains the user ID of a **WantAgent** object. This API uses an asynchronous cal **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | --- | ---- | ----------------------- | ---- | ----------------------------------- | -| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the user ID.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ----------------------------------- | +| agent | WantAgent | Yes | Target **WantAgent** object. | +| callback | AsyncCallback\ | Yes | Callback used to return the user ID.| **Example** @@ -353,9 +353,9 @@ Obtains the user ID of a **WantAgent** object. This API uses a promise to return **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ----- | --- | ---- | --------- | ---- | ------------- | -| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object.| +| Name | Type | Mandatory| Description | +| ----- | --------- | ---- | ------------- | +| agent | WantAgent | Yes | Target **WantAgent** object.| **Return value** @@ -424,10 +424,10 @@ Obtains the want in a **WantAgent** object. This API uses an asynchronous callba **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | --- | ---- | --------------------- | ---- | ------------------------------- | -| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the want.| +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------------------------- | +| agent | WantAgent | Yes | Target **WantAgent** object. | +| callback | AsyncCallback\ | Yes | Callback used to return the want.| **Example** @@ -498,9 +498,9 @@ Obtains the want in a **WantAgent** object. This API uses a promise to return th **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ----- | --- | ---- | --------- | ---- | ------------- | -| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object.| +| Name | Type | Mandatory| Description | +| ----- | --------- | ---- | ------------- | +| agent | WantAgent | Yes | Target **WantAgent** object.| **Return value** @@ -567,10 +567,10 @@ Cancels a **WantAgent** object. This API uses an asynchronous callback to return **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | --- | ---- | --------------------- | ---- | --------------------------- | -| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | --------------------------- | +| agent | WantAgent | Yes | Target **WantAgent** object. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -639,9 +639,9 @@ Cancels a **WantAgent** object. This API uses a promise to return the result. **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ----- | --- | ---- | --------- | ---- | ------------- | -| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object.| +| Name | Type | Mandatory| Description | +| ----- | --------- | ---- | ------------- | +| agent | WantAgent | Yes | Target **WantAgent** object.| **Return value** @@ -708,11 +708,11 @@ Triggers a **WantAgent** object. This API uses an asynchronous callback to retur **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ----------- | --- | ---- | ----------------------------- | ---- | ------------------------------- | -| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object. | -| triggerInfo | Yes | No | TriggerInfo | Yes | **TriggerInfo** object. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| ----------- | ----------------------------- | ---- | ------------------------------- | +| agent | WantAgent | Yes | Target **WantAgent** object. | +| triggerInfo | TriggerInfo | Yes | **TriggerInfo** object. | +| callback | AsyncCallback\ | No | Callback used to return the result.| **Example** @@ -785,11 +785,11 @@ Checks whether two **WantAgent** objects are equal. This API uses an asynchronou **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ---------- | --- | ---- | ------------------------ | ---- | --------------------------------------- | -| agent | Yes | No | WantAgent | Yes | The first **WantAgent** object. | -| otherAgent | Yes | No | WantAgent | Yes | The second **WantAgent** object. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------------ | ---- | --------------------------------------- | +| agent | WantAgent | Yes | The first **WantAgent** object. | +| otherAgent | WantAgent | Yes | The second **WantAgent** object. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -860,10 +860,10 @@ Checks whether two **WantAgent** objects are equal. This API uses a promise to r **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ---------- | --- | ---- | --------- | ---- | ------------- | -| agent | Yes | No | WantAgent | Yes | The first **WantAgent** object.| -| otherAgent | Yes | No | WantAgent | Yes | The second **WantAgent** object.| +| Name | Type | Mandatory| Description | +| ---------- | --------- | ---- | ------------- | +| agent | WantAgent | Yes | The first **WantAgent** object.| +| otherAgent | WantAgent | Yes | The second **WantAgent** object.| **Return value** @@ -930,10 +930,10 @@ Obtains the operation type of a **WantAgent** object. This API uses an asynchron **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ---------- | --- | ---- | ------------------------ | ---- | --------------------------------------- | -| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the operation type.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------------ | ---- | --------------------------------------- | +| agent | WantAgent | Yes | Target **WantAgent** object. | +| callback | AsyncCallback\ | Yes | Callback used to return the operation type.| **Example** @@ -991,9 +991,9 @@ Obtains the operation type of a **WantAgent** object. This API uses a promise to **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ---------- | --- | ---- | --------- | ---- | ------------- | -| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object.| +| Name | Type | Mandatory| Description | +| ---------- | --------- | ---- | ------------- | +| agent | WantAgent | Yes | Target **WantAgent** object.| **Return value** @@ -1050,39 +1050,22 @@ WantAgent.getOperationType(wantAgent).then((OperationType) => { ``` - -## WantAgentInfo - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name | Readable| Writable| Type | Mandatory| Description | -| -------------- | --- | ---- | ------------------------------- | ---- | ---------------------- | -| wants | Yes | Yes | Array\ | Yes | Array of all **Want** objects. | -| operationType | Yes | Yes | wantAgent.OperationType | Yes | Operation type. | -| requestCode | Yes | Yes | number | Yes | Request code defined by the user.| -| wantAgentFlags | Yes | Yes | Array | No | Array of flags for using the **WantAgent** object. | -| extraInfo | Yes | Yes | {[key: string]: any} | No | Extra information. | - - - ## WantAgentFlags **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Value | Description | | ------------------- | -------------- | ------------------------------------------------------------ | -| ONE_TIME_FLAG | WantAgentFlags | The **WantAgent** object can be used only once. | -| NO_BUILD_FLAG | WantAgentFlags | The **WantAgent** object does not exist and hence it is not created. In this case, **null** is returned. | -| CANCEL_PRESENT_FLAG | WantAgentFlags | The existing **WantAgent** object should be canceled before a new object is generated.| -| UPDATE_PRESENT_FLAG | WantAgentFlags | Extra information of the existing **WantAgent** object is replaced with that of the new object.| -| CONSTANT_FLAG | WantAgentFlags | The **WantAgent** object is immutable. | -| REPLACE_ELEMENT | WantAgentFlags | The **element** attribute of the current **Want** can be replaced by the **element** attribute of the **Want** in **WantAgent.trigger()**.| -| REPLACE_ACTION | WantAgentFlags | The **action** attribute of the current **Want** can be replaced by the **action** attribute of the **Want** in **WantAgent.trigger()**.| -| REPLACE_URI | WantAgentFlags | The **uri** attribute of the current **Want** can be replaced by the **uri** attribute of the **Want** in **WantAgent.trigger()**.| -| REPLACE_ENTITIES | WantAgentFlags | The **entities** attribute of the current **Want** can be replaced by the **entities** attribute of the **Want** in **WantAgent.trigger()**.| -| REPLACE_BUNDLE | WantAgentFlags | The **bundleName** attribute of the current **Want** can be replaced by the **bundleName** attribute of **Want** in **WantAgent.trigger()**.| - - +| ONE_TIME_FLAG | 0 | The **WantAgent** object can be used only once. | +| NO_BUILD_FLAG | 1 | The **WantAgent** object does not exist and hence it is not created. In this case, **null** is returned. | +| CANCEL_PRESENT_FLAG | 2 | The existing **WantAgent** object should be canceled before a new object is generated.| +| UPDATE_PRESENT_FLAG | 3 | Extra information of the existing **WantAgent** object is replaced with that of the new object.| +| CONSTANT_FLAG | 4 | The **WantAgent** object is immutable. | +| REPLACE_ELEMENT | 5 | The **element** attribute of the current **Want** can be replaced by the **element** attribute of the **Want** in **WantAgent.trigger()**.| +| REPLACE_ACTION | 6 | The **action** attribute of the current **Want** can be replaced by the **action** attribute of the **Want** in **WantAgent.trigger()**.| +| REPLACE_URI | 7 | The **uri** attribute of the current **Want** can be replaced by the **uri** attribute of the **Want** in **WantAgent.trigger()**.| +| REPLACE_ENTITIES | 8 | The **entities** attribute of the current **Want** can be replaced by the **entities** attribute of the **Want** in **WantAgent.trigger()**.| +| REPLACE_BUNDLE | 9 | The **bundleName** attribute of the current **Want** can be replaced by the **bundleName** attribute of **Want** in **WantAgent.trigger()**.| ## OperationType @@ -1090,35 +1073,20 @@ WantAgent.getOperationType(wantAgent).then((OperationType) => { | Name | Value | Description | | ----------------- | ------------- | ------------------------- | -| UNKNOWN_TYPE | OperationType | Unknown operation type. | -| START_ABILITY | OperationType | Starts an ability with a UI.| -| START_ABILITIES | OperationType | Starts multiple abilities with a UI.| -| START_SERVICE | OperationType | Starts an ability without a UI.| -| SEND_COMMON_EVENT | OperationType | Sends a common event. | - - +| UNKNOWN_TYPE | 0 | Unknown operation type. | +| START_ABILITY | 1 | Starts an ability with a UI.| +| START_ABILITIES | 2 | Starts multiple abilities with a UI.| +| START_SERVICE | 3 | Starts an ability without a UI.| +| SEND_COMMON_EVENT | 4 | Sends a common event. | ## CompleteData **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name | Readable| Writable| Type | Mandatory| Description | -| -------------- | --- | ---- | ------------------------------ | ---- | ---------------------- | -| info | Yes | Yes | WantAgent | Yes | A triggered **WantAgent** object. | -| want | Yes | Yes | Want | Yes | An existing triggered **want**. | -| finalCode | Yes | Yes | number | Yes | Request code that triggers the **WantAgent** object.| -| finalData | Yes | Yes | string | No | Final data collected by the common event. | -| extraInfo | Yes | Yes | {[key: string]: any} | No | Extra information. | - - - -## TriggerInfo - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name | Readable| Writable| Type | Mandatory| Description | -| ---------- | --- | ---- | -------------------- | ---- | ----------- | -| code | Yes | Yes | number | Yes | Result code.| -| want | Yes | Yes | Want | No | Want. | -| permission | Yes | Yes | string | No | Permission. | -| extraInfo | Yes | Yes | {[key: string]: any} | No | Extra information. | +| Name | Type | Mandatory| Description | +| -------------- | ------------------------------ | ---- | ---------------------- | +| info | WantAgent | Yes | A triggered **WantAgent** object. | +| want | Want | Yes | An existing triggered **want**. | +| finalCode | number | Yes | Request code that triggers the **WantAgent** object.| +| finalData | string | No | Final data collected by the common event. | +| extraInfo | {[key: string]: any} | No | Extra information. | diff --git a/en/application-dev/reference/apis/js-apis-wifi.md b/en/application-dev/reference/apis/js-apis-wifi.md index a8221a78898accf8d18724193df311a13693b998..6af6bc0a51e3a862a159b6bf450c9ce90bd31346 100644 --- a/en/application-dev/reference/apis/js-apis-wifi.md +++ b/en/application-dev/reference/apis/js-apis-wifi.md @@ -1,7 +1,9 @@ -# WLAN +# @ohos.wifi (WLAN) + The **WLAN** module provides basic wireless local area network (WLAN) functions, peer-to-peer (P2P) functions, and WLAN message notification services. It allows applications to communicate with other devices over WLAN. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -166,20 +168,17 @@ Represents WLAN hotspot information. **System capability**: SystemCapability.Communication.WiFi.STA -| **Name**| **Type**| **Readable/Writable**| **Description**| -| -------- | -------- | -------- | -------- | -| ssid | string | Read only| Service set identifier (SSID) of the hotspot, in UTF-8 format.| -| bssid | string | Read only| Basic service set identifier (BSSID) of the hotspot.| -| capabilities | string | Read only| Hotspot capabilities.| -| securityType | [WifiSecurityType](#wifisecuritytype) | Read only| WLAN security type.| -| rssi | number | Read only| Received signal strength indicator (RSSI) of the hotspot, in dBm.| -| band | number | Read only| Frequency band of the WLAN access point (AP).| -| frequency | number | Read only| Frequency of the WLAN AP.| -| channelWidth | number | Read only| Channel width of the WLAN AP.| -| centerFrequency09+ | number | Read only| Center frequency of the hotspot.| -| centerFrequency19+ | number | Read only| Center frequency of the hotspot. If the hotspot uses two non-overlapping WLAN channels, two center frequencies, namely **centerFrequency0** and **centerFrequency1**, are returned.| -| infoElems9+ | Array<[WifiInfoElem](#wifiinfoelem9)> | Read only| Information elements.| -| timestamp | number | Read only| Timestamp.| +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| 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.| +| 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.| +| band | number | Yes| No| Frequency band of the WLAN access point (AP).| +| frequency | number | Yes| No| Frequency of the WLAN AP.| +| channelWidth | number | Yes| No| Channel width of the WLAN AP.| +| timestamp | number | Yes| No| Timestamp.| ## WifiSecurityType @@ -189,50 +188,13 @@ Enumerates the WLAN security types. **System capability**: SystemCapability.Communication.WiFi.Core -| **Name**| **Default Value**| **Description**| +| **Name**| **Value**| **Description**| | -------- | -------- | -------- | | WIFI_SEC_TYPE_INVALID | 0 | Invalid security type.| | WIFI_SEC_TYPE_OPEN | 1 | Open security type.| | WIFI_SEC_TYPE_WEP | 2 | Wired Equivalent Privacy (WEP).| | WIFI_SEC_TYPE_PSK | 3 | Pre-shared key (PSK).| | WIFI_SEC_TYPE_SAE | 4 | Simultaneous Authentication of Equals (SAE).| -| WIFI_SEC_TYPE_EAP9+ | 5 | Extensible Authentication protocol (EAP).| -| WIFI_SEC_TYPE_EAP_SUITE_B9+ | 6 | Suite B 192-bit encryption.| -| WIFI_SEC_TYPE_OWE9+ | 7 | Opportunistic Wireless Encryption (OWE).| -| WIFI_SEC_TYPE_WAPI_CERT9+ | 8 | WLAN Authentication and Privacy Infrastructure (WAPI) in certificate-based mode (WAPI-CERT).| -| WIFI_SEC_TYPE_WAPI_PSK9+ | 9 | WAPI-PSK.| - - -## WifiInfoElem9+ - -Represents a WLAN information element. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Communication.WiFi.STA - - -| **Name**| **Type**| **Readable/Writable**| **Description**| -| -------- | -------- | -------- | -------- | -| eid | number | Read only| ID of the information element.| -| content | Uint8Array | Read only| Content of the information element.| - - -## WifiChannelWidth9+ - -Enumerates the WLAN channel widths. - -**System capability**: SystemCapability.Communication.WiFi.STA - - -| **Name**| **Default Value**| **Description**| -| -------- | -------- | -------- | -| WIDTH_20MHZ | 0 | 20 MHz.| -| WIDTH_40MHZ | 1 | 40 MHz.| -| WIDTH_80MHZ | 2 | 80 MHz.| -| WIDTH_160MHZ | 3 | 160 MHz.| -| WIDTH_80MHZ_PLUS | 4 | 80 MHz+.| -| WIDTH_INVALID | 5 | Invalid value.| ## wifi.getScanInfosSync9+ @@ -274,7 +236,7 @@ Adds network configuration. This API uses a promise to return the result. | **Type**| **Description**| | -------- | -------- | - | Promise<number> | Promise used to return the WLAN configuration ID. If **-1** is returned, the operation has failed.| + | Promise<number> | Promise used to return the WLAN configuration ID. If **-1** is returned, the network configuration fails to be added.| ## WifiDeviceConfig @@ -283,33 +245,32 @@ Represents the WLAN configuration. **System capability**: SystemCapability.Communication.WiFi.STA -| **Name**| **Type**| **Readable/Writable**| **Description**| -| -------- | -------- | -------- | -------- | -| ssid | string | Read only| SSID of the hotspot, in UTF-8 format.| -| bssid | string | Read only| BSSID of the hotspot.| -| preSharedKey | string | Read only| PSK of the hotspot.| -| isHiddenSsid | boolean | Read only| Whether the network is hidden.| -| securityType | [WifiSecurityType](#wifisecuritytype) | Read only| Security type.| -| creatorUid | number | Read only| ID of the creator.
**System API**: This is a system API.| -| disableReason | number | Read only| Reason for disabling WLAN.
**System API**: This is a system API.| -| netId | number | Read only| Network ID.
**System API**: This is a system API.| -| randomMacType | number | Read only| Random MAC type.
**System API**: This is a system API.| -| randomMacAddr | string | Read only| Random MAC address.
**System API**: This is a system API.| -| ipType | [IpType](#iptype7) | Read only| IP address type.
**System API**: This is a system API.| -| staticIp | [IpConfig](#ipconfig7) | Read only| Static IP address configuration.
**System API**: This is a system API.| -| eapConfig9+ | [WifiEapConfig](#wifieapconfig9) | Read only| EAP configuration.
**System API**: This is a system API.| +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.| +| bssid | string | Yes| No| BSSID 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.| +| creatorUid | number | Yes| No| ID of the creator.
**System API**: This is a system API.| +| disableReason | number | Yes| No| Reason for disabling WLAN.
**System API**: This is a system API.| +| netId | number | Yes| No| Network ID.
**System API**: This is a system API.| +| randomMacType | number | Yes| No| Random MAC type.
**System API**: This is a system API.| +| randomMacAddr | string | Yes| No| Random MAC address.
**System API**: This is a system API.| +| ipType | [IpType](#iptype7) | Yes| No| IP address type.
**System API**: This is a system API.| +| staticIp | [IpConfig](#ipconfig7) | Yes| No| Static IP address configuration.
**System API**: This is a system API.| ## IpType7+ -Enumerates the IP address types. +Enumerate the IP address types. **System API**: This is a system API. **System capability**: SystemCapability.Communication.WiFi.STA -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | STATIC | 0 | Static IP address.| | DHCP | 1 | IP address allocated by DHCP.| @@ -324,78 +285,12 @@ Represents IP configuration information. **System capability**: SystemCapability.Communication.WiFi.STA -| **Name**| **Type**| **Readable/Writable**| **Description**| -| -------- | -------- | -------- | -------- | -| ipAddress | number | Read only| IP address.| -| gateway | number | Read only| Gateway.| -| dnsServers | number[] | Read only| Domain name server (DNS) information.| -| domains | Array<string> | Read only| Domain information.| - - -## WifiEapConfig9+ - -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) | Read only| EAP authentication method.| -| phase2Method | [Phase2Method](#phase2method9) | Read only| Phase 2 authentication method.| -| identity | string | Read only| Identity Information.| -| anonymousIdentity | string | Read only| Anonymous identity.| -| password | string | Read only| Password.| -| caCertAliases | string | Read only| CA certificate alias.| -| caPath | string | Read only| CA certificate path.| -| clientCertAliases | string | Read only| Client certificate alias.| -| altSubjectMatch | string | Read only| A string to match the alternate subject.| -| domainSuffixMatch | string | Read only| A string to match the domain suffix.| -| realm | string | Read only| Realm for the passpoint credential.| -| plmn | string | Read only| Public land mobile network (PLMN) of the passpoint credential provider.| -| eapSubId | number | Read only| Sub-ID of the SIM card.| - - -## EapMethod9+ - -Enumerates the EAP authentication methods. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Communication.WiFi.STA - -| Name| Default Value| Description| -| -------- | -------- | -------- | -| EAP_NONE | 0 | Not specified.| -| EAP_PEAP | 1 | PEAP.| -| EAP_TLS | 2 | TLS.| -| EAP_TTLS | 3 | TTLS.| -| EAP_PWD | 4 | Password.| -| EAP_SIM | 5 | SIM.| -| EAP_AKA | 6 | AKA.| -| EAP_AKA_PRIME | 7 | AKA Prime.| -| EAP_UNAUTH_TLS | 8 | UNAUTH TLS.| - - -## Phase2Method9+ - -Enumerates the Phase 2 authentication methods. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Communication.WiFi.STA - -| Name| Default Value| Description| -| -------- | -------- | -------- | -| PHASE2_NONE | 0 | Not specified.| -| PHASE2_PAP | 1 | PAP.| -| PHASE2_MSCHAP | 2 | MS-CHAP.| -| PHASE2_MSCHAPV2 | 3 | MS-CHAPv2.| -| PHASE2_GTC | 4 | GTC .| -| PHASE2_SIM | 5 | SIM.| -| PHASE2_AKA | 6 | AKA.| -| PHASE2_AKA_PRIME | 7 | AKA Prime.| +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ipAddress | number | Yes| No| IP address.| +| gateway | number | Yes| No| Gateway.| +| dnsServers | number[] | Yes| No| Domain name server (DNS) information.| +| domains | Array<string> | Yes| No| Domain information.| ## wifi.addDeviceConfig @@ -500,122 +395,6 @@ Removes the configuration of an untrusted network. This API uses an asynchronous | 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.| -## wifi.addCandidateConfig9+ - -addCandidateConfig(config: WifiDeviceConfig): Promise<number> - -Adds the configuration of a candidate network. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.SET_WIFI_INFO - -**System capability**: SystemCapability.Communication.WiFi.STA - -**Parameters** - - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| - -**Return value** - - | **Type**| **Description**| - | -------- | -------- | - | Promise<number> | Promise used to return the network configuration ID.| - - -## wifi.addCandidateConfig9+ - -addCandidateConfig(config: WifiDeviceConfig, callback: AsyncCallback<number>): void - -Adds the configuration of a candidate network. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.SET_WIFI_INFO - -**System capability**: SystemCapability.Communication.WiFi.STA - -**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.| - - -## wifi.removeCandidateConfig9+ - -removeCandidateConfig(networkId: number): Promise<void> - -Removes the configuration of a candidate network. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.SET_WIFI_INFO - -**System capability**: SystemCapability.Communication.WiFi.STA - -**Parameters** - - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | -| networkId | number | Yes| ID of the network configuration to remove.| - -**Return value** - - | **Type**| **Description**| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - - -## wifi.removeCandidateConfig9+ - -removeCandidateConfig(networkId: number, callback: AsyncCallback<void>): void - -Removes the configuration of a candidate network. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.SET_WIFI_INFO - -**System capability**: SystemCapability.Communication.WiFi.STA - -**Parameters** - - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | -| networkId | number | Yes| ID of the network configuration to remove.| -| callback | AsyncCallback<void> | Yes| Callback invoked to return the result. If the operation is successful, the value of **err** is **0**. If **err** is not **0**, an error has occurred.| - - -## wifi.getCandidateConfigs9+ - -getCandidateConfigs():  Array<[WifiDeviceConfig](#wifideviceconfig)> - -Obtains candidate network configuration. - -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION - -**System capability**: SystemCapability.Communication.WiFi.STA - -**Return value** - - | **Type**| **Description**| - | -------- | -------- | - |  Array<[WifiDeviceConfig](#wifideviceconfig)> | Candidate network configuration obtained.| - - -## wifi.connectToCandidateConfig9+ - -connectToCandidateConfig(networkId: number): void - -Connects to a candidate network. - -**Required permissions**: ohos.permission.SET_WIFI_INFO - -**System capability**: SystemCapability.Communication.WiFi.STA - -**Parameters** - - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | networkId | number | Yes| ID of the candidate network configuration.| - - ## wifi.connectToNetwork connectToNetwork(networkId: number): boolean @@ -725,7 +504,7 @@ Obtains WLAN connection information. This API uses a promise to return the resul | Type| Description| | -------- | -------- | - | Promise<[WifiLinkedInfo](#wifilinkedinfo)> | Promise used to return the WLAN connection information obtained.| + | Promise<[WifiLinkedInfo](#wifilinkedinfo)> | Promise used to return the WLAN connection information.| ## wifi.getLinkedInfo @@ -770,24 +549,23 @@ Represents the WLAN connection information. **System capability**: SystemCapability.Communication.WiFi.STA -| Name| Type| Readable/Writable| Description| -| -------- | -------- | -------- | -------- | -| ssid | string | Read only| SSID of the hotspot, in UTF-8 format.| -| bssid | string | Read only| BSSID of the hotspot.| -| networkId | number | Read only| Network configuration ID.
**System API**: This is a system API.| -| rssi | number | Read only| RSSI of the hotspot, in dBm.| -| band | number | Read only| Frequency band of the WLAN AP.| -| linkSpeed | number | Read only| Speed of the WLAN AP.| -| frequency | number | Read only| Frequency of the WLAN AP.| -| isHidden | boolean | Read only| Whether to hide the WLAN AP.| -| isRestricted | boolean | Read only| Whether to restrict data volume at the WLAN AP.| -| chload | number | Read only| Channel load. A larger value indicates a higher load.
**System API**: This is a system API.| -| snr | number | Read only| Signal-to-noise ratio (SNR).
**System API**: This is a system API.| -| macType9+ | number | Read only| MAC address type.| -| macAddress | string | Read only| MAC address of the device.| -| ipAddress | number | Read only| IP address of the device that sets up the WLAN connection.| -| suppState | [SuppState](#suppstate) | Read only| Supplicant state.
**System API**: This is a system API.| -| connState | [ConnState](#connstate) | Read only| WLAN connection state.| +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.| +| bssid | string | Yes| No| BSSID of the hotspot.| +| networkId | number | Yes| No| Network configuration ID.
**System API**: This is a system API.| +| rssi | number | Yes| No| RSSI of the hotspot, in dBm.| +| band | number | Yes| No| Frequency band of the WLAN AP.| +| linkSpeed | number | Yes| No| Speed of the WLAN AP.| +| frequency | number | Yes| No| Frequency of the WLAN AP.| +| isHidden | boolean | Yes| No| Whether to hide the WLAN AP.| +| isRestricted | boolean | Yes| No| Whether to restrict data volume at the WLAN AP.| +| chload | number | Yes| No| Channel load. A larger value indicates a higher load.
**System API**: This is a system API.| +| snr | number | Yes| No| Signal-to-noise ratio (SNR).
**System API**: This is a system API.| +| macAddress | string | Yes| No| MAC address of the device.| +| ipAddress | number | Yes| No| IP address of the device that sets up the WLAN connection.| +| suppState | [SuppState](#suppstate) | Yes| No| Supplicant state.
**System API**: This is a system API.| +| connState | [ConnState](#connstate) | Yes| No| WLAN connection state.| ## ConnState @@ -796,7 +574,7 @@ Enumerates the WLAN connection states. **System capability**: SystemCapability.Communication.WiFi.STA -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | SCANNING | 0 | The device is scanning for available APs.| | CONNECTING | 1 | A WLAN connection is being established.| @@ -816,7 +594,7 @@ Enumerates the supplicant states. **System capability**: SystemCapability.Communication.WiFi.STA -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | DISCONNECTED | 0 | The supplicant is disconnected from the AP.| | INTERFACE_DISABLED | 1 | The network interface is disabled.| @@ -871,16 +649,16 @@ Obtains the features supported by this device. | Value| Description| | -------- | -------- | -| 0x0001 | WLAN infrastructure mode. | -| 0x0002 | 5 GHz feature. | -| 0x0004 | Generic Advertisement Service (GAS)/Access Network Query Protocol (ANQP) feature. | -| 0x0008 | Wi-Fi Direct. | -| 0x0010 | SoftAP. | -| 0x0040 | Wi-Fi AWare. | -| 0x8000 | WLAN AP/STA concurrency. | -| 0x8000000 | WPA3 Personal (WPA-3 SAE). | -| 0x10000000 | WPA3-Enterprise Suite B. | -| 0x20000000 | Enhanced open feature. | +| 0x0001 | WLAN infrastructure mode| +| 0x0002 | 5 GHz feature| +| 0x0004 | Generic Advertisement Service (GAS)/Access Network Query Protocol (ANQP) feature| +| 0x0008 | Wi-Fi Direct| +| 0x0010 | SoftAP| +| 0x0040 | Wi-Fi AWare| +| 0x8000 | WLAN AP/STA concurrency| +| 0x8000000 | WPA3 Personal (WPA-3 SAE)| +| 0x10000000 | WPA3-Enterprise Suite B | +| 0x20000000 | Enhanced open feature| ## wifi.isFeatureSupported7+ @@ -949,15 +727,15 @@ Represents IP information. **System capability**: SystemCapability.Communication.WiFi.STA -| **Name**| **Type**| **Readable/Writable**| **Description**| -| -------- | -------- | -------- | -------- | -| ipAddress | number | Read only| IP address.| -| gateway | number | Read only| Gateway.| -| netmask | number | Read only| Subnet mask.| -| primaryDns | number | Read only| IP address of the preferred DNS server.| -| secondDns | number | Read only| IP address of the alternate DNS server.| -| serverIp | number | Read only| IP address of the DHCP server.| -| leaseDuration | number | Read only| Lease duration of the IP address.| +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ipAddress | number | Yes| No| IP address.| +| gateway | number | Yes| No| Gateway.| +| netmask | number | Yes| No| Subnet mask.| +| primaryDns | number | Yes| No| IP address of the preferred DNS server.| +| secondDns | number | Yes| No| IP address of the alternate DNS server.| +| serverIp | number | Yes| No| IP address of the DHCP server.| +| leaseDuration | number | Yes| No| Lease duration of the IP address.| ## wifi.getCountryCode7+ @@ -1237,13 +1015,13 @@ Represents the hotspot configuration. **System capability**: SystemCapability.Communication.WiFi.AP.Core -| **Name**| **Type**| **Readable/Writable**| **Description**| -| -------- | -------- | -------- | -------- | -| ssid | string | Read only| SSID of the hotspot, in UTF-8 format.| -| securityType | [WifiSecurityType](#wifisecuritytype) | Read only| Security type.| -| band | number | Read only| Hotspot band. The value **1** stands for 2.4 GHz, the value **2** for 5 GHz, and the value **3** for dual band.| -| preSharedKey | string | Read only| PSK of the hotspot.| -| maxConn | number | Read only| Maximum number of connections allowed.| +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.| +| securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| Security type.| +| band | number | Yes| No| Hotspot band. The value **1** stands for 2.4 GHz, the value **2** for 5 GHz, and the value **3** for dual band.| +| preSharedKey | string | Yes| No| PSK of the hotspot.| +| maxConn | number | Yes| No| Maximum number of connections allowed.| ## wifi.getHotspotConfig7+ @@ -1292,11 +1070,11 @@ Represents the station information. **System capability**: SystemCapability.Communication.WiFi.AP.Core -| **Name**| **Type**| **Readable/Writable**| **Description**| -| -------- | -------- | -------- | -------- | -| name | string | Read only| Device name.| -| macAddress | string | Read only| MAC address.| -| ipAddress | string | Read only| IP address.| +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| name | string | Yes| No| Device name.| +| macAddress | string | Yes| No| MAC address.| +| ipAddress | string | Yes| No| IP address.| ## wifi.getP2pLinkedInfo8+ @@ -1323,11 +1101,11 @@ Represents the P2P link information. **System capability**: SystemCapability.Communication.WiFi.P2P -| Name| Type| Readable/Writable| Description| -| -------- | -------- | -------- | -------- | -| connectState | [P2pConnectState](#p2pconnectstate8) | Read only| P2P connection state.| -| isGroupOwner | boolean | Read only| Whether the device is the group owner.| -| groupOwnerAddr | string | Read only| MAC address of the group. +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| connectState | [P2pConnectState](#p2pconnectstate8) | Yes| No| P2P connection state.| +| isGroupOwner | boolean | Yes| No| Whether the device is the group owner.| +| groupOwnerAddr | string | Yes| No| MAC address of the group. ## P2pConnectState8+ @@ -1336,7 +1114,7 @@ Enumerates the P2P connection states. **System capability**: SystemCapability.Communication.WiFi.P2P -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | DISCONNECTED | 0 | Disconnected.| | CONNECTED | 1 | Connected.| @@ -1373,7 +1151,7 @@ Obtains the current P2P group information. This API uses a promise to return the | Type| Description| | -------- | -------- | - | Promise<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> | Promise used to return the group information obtained.| + | Promise<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> | Promise used to return the P2P group information obtained.| ## wifi.getCurrentGroup8+ @@ -1433,13 +1211,13 @@ Represents the P2P device information. **System capability**: SystemCapability.Communication.WiFi.P2P -| Name| Type| Readable/Writable| Description| -| -------- | -------- | -------- | -------- | -| deviceName | string | Read only| Device name.| -| deviceAddress | string | Read only| MAC address of the device.| -| primaryDeviceType | string | Read only| Type of the primary device.| -| deviceStatus | [P2pDeviceStatus](#p2pdevicestatus8) | Read only| Device status.| -| groupCapabilitys | number | Read only| Group capabilities.| +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| deviceName | string | Yes| No| Device name.| +| deviceAddress | string | Yes| No| MAC address of the device.| +| primaryDeviceType | string | Yes| No| Type of the primary device.| +| deviceStatus | [P2pDeviceStatus](#p2pdevicestatus8) | Yes| No| Device status.| +| groupCapabilitys | number | Yes| No| Group capabilities.| ## P2pDeviceStatus8+ @@ -1448,7 +1226,7 @@ Enumerates the P2P device states. **System capability**: SystemCapability.Communication.WiFi.P2P -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | CONNECTED | 0 | Connected.| | INVITED | 1 | Invited.| @@ -1457,40 +1235,6 @@ Enumerates the P2P device states. | UNAVAILABLE | 4 | Unavailable.| -## wifi.getP2pLocalDevice9+ - -getP2pLocalDevice(): Promise<WifiP2pDevice> - -Obtains the local device information in the P2P connection. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG - -**System capability**: SystemCapability.Communication.WiFi.P2P - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<[WifiP2pDevice](#wifip2pdevice8)> | Promise used to return the local device information obtained.| - - -## wifi.getP2pLocalDevice9+ - -getP2pLocalDevice(callback: AsyncCallback<WifiP2pDevice>): void - -Obtains the local device information in the P2P connection. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG - -**System capability**: SystemCapability.Communication.WiFi.P2P - -**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 local device information obtained. If **err** is not **0**, an error has occurred.| - - ## wifi.createGroup8+ createGroup(config: WifiP2PConfig): boolean @@ -1520,13 +1264,13 @@ Represents P2P group configuration. **System capability**: SystemCapability.Communication.WiFi.P2P -| Name| Type| Readable/Writable| Description| -| -------- | -------- | -------- | -------- | -| deviceAddress | string | Read only| Device address.| -| netId | number | Read only| Network ID. The value **-1** indicates a temporary group, and **-2** indicates a persistent group.| -| passphrase | string | Read only| Passphrase of the group.| -| groupName | string | Read only| Name of the group.| -| goBand | [GroupOwnerBand](#groupownerband8) | Read only| Frequency band of the group.| +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| deviceAddress | string | Yes| No| Device address.| +| 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.| +| goBand | [GroupOwnerBand](#groupownerband8) | Yes| No| Frequency band of the group.| ## GroupOwnerBand8+ @@ -1535,7 +1279,7 @@ Enumerates the P2P group frequency bands. **System capability**: SystemCapability.Communication.WiFi.P2P -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | GO_BAND_AUTO | 0 | Auto.| | GO_BAND_2GHZ | 1 | 2 GHz.| @@ -1727,61 +1471,23 @@ Deletes a persistent group. | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -## wifi.getP2pGroups9+ - -getP2pGroups(): Promise<Array<WifiP2pGroupInfo>> - -Obtains information about all P2P groups. This API uses a promise to return the result. - -**System API**: This is a system API. - -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION - -**System capability**: SystemCapability.Communication.WiFi.P2P - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> > | Promise used to return the group information obtained.| - - ## WifiP2pGroupInfo8+ Represents the P2P group information. **System capability**: SystemCapability.Communication.WiFi.P2P -| Name| Type| Readable/Writable| Description| -| -------- | -------- | -------- | -------- | -| isP2pGo | boolean | Read only| Whether the device is the group owner.| -| ownerInfo | [WifiP2pDevice](#wifip2pdevice8) | Read only| Device information of the group.| -| passphrase | string | Read only| Passphrase of the group.| -| interface | string | Read only| Interface name.| -| groupName | string | Read only| Group name.| -| networkId | number | Read only| Network ID.| -| frequency | number | Read only| Frequency of the group.| -| clientDevices | [WifiP2pDevice[]](#wifip2pdevice8) | Read only| List of connected devices.| -| goIpAddress | string | Read only| IP address of the group.| - - -## wifi.getP2pGroups9+ - -getP2pGroups(callback: AsyncCallback<Array<WifiP2pGroupInfo>>): void - -Obtains information about all P2P groups. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API. - -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION - -**System capability**: SystemCapability.Communication.WiFi.P2P - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback< Array<[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| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| isP2pGo | boolean | Yes| No| Whether the device is the group owner.| +| ownerInfo | [WifiP2pDevice](#wifip2pdevice8) | Yes| No| Device information of the group.| +| passphrase | string | Yes| No| Passphrase of the group.| +| interface | string | Yes| No| Interface name.| +| groupName | string | Yes| No| Group name.| +| networkId | number | Yes| No| Network ID.| +| frequency | number | Yes| No| Frequency of the group.| +| clientDevices | [WifiP2pDevice[]](#wifip2pdevice8) | Yes| No| List of connected devices.| +| goIpAddress | string | Yes| No| IP address of the group.| ## wifi.setDeviceName8+ @@ -1830,10 +1536,10 @@ Registers the WLAN state change events. | **Value**| **Description**| | -------- | -------- | -| 0 | Deactivated. | -| 1 | Activated. | -| 2 | Activating. | -| 3 | Deactivating. | +| 0 | Deactivated| +| 1 | Activated| +| 2 | Activating| +| 3 | Deactivating| ## wifi.off('wifiStateChange')7+ @@ -2012,10 +1718,10 @@ Registers the hotspot state change events. | **Value**| **Description**| | -------- | -------- | -| 0 | Deactivated. | -| 1 | Activated. | -| 2 | Activating. | -| 3 | Deactivating. | +| 0 | Deactivated| +| 1 | Activated| +| 2 | Activating| +| 3 | Deactivating| ## wifi.off('hotspotStateChange')7+ @@ -2057,11 +1763,11 @@ Registers the P2P state change events. | **Value**| **Description**| | -------- | -------- | -| 1 | Available. | -| 2 | Opening. | -| 3 | Opened. | -| 4 | Closing. | -| 5 | Closed. | +| 1 | Available| +| 2 | Opening| +| 3 | Opened| +| 4 | Closing| +| 5 | Closed| ## wifi.off('p2pStateChange')8+ diff --git a/en/application-dev/reference/apis/js-apis-wifiManager.md b/en/application-dev/reference/apis/js-apis-wifiManager.md new file mode 100644 index 0000000000000000000000000000000000000000..8e3526343a3f62066af7686b4fbe5cb587fa1cbc --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-wifiManager.md @@ -0,0 +1,2187 @@ +# WLAN + +The **WLAN** module provides basic wireless local area network (WLAN) functions, peer-to-peer (P2P) functions, and WLAN message notification services. It allows applications to communicate with other devices over WLAN. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + +```js +import wifiManager from '@ohos.wifiManager'; +``` + +## wifi.enableWifi9+ + +enableWifi(): void + +Enables WLAN. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.disableWifi9+ + +disableWifi(): void + +Disables WLAN. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.isWifiActive9+ + +isWifiActive(): boolean + +Checks whether WLAN is enabled. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if WLAN is enabled; returns **false** otherwise.| + + +## wifi.scan9+ + +scan(): void + +Starts a scan for WLAN. + +**Required permissions**: **ohos.permission.SET_WIFI_INFO** and **ohos.permission.LOCATION** + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.getScanResults9+ + +getScanResults(): Promise<Array<WifiScanInfo>> + +Obtains the scan result. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_PEERS_MAC (or ohos.permission.LOCATION) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | Promise< Array<[WifiScanInfo](#wifiscaninfo)> > | Promise used to return the detected hotspots.| + + +## wifi.getScanResults9+ + +getScanResults(callback: AsyncCallback<Array<WifiScanInfo>>): void + +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) + +**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.| + +**Example** + ```js + import wifi from '@ohos.wifi'; + + wifi.getScanInfos((err, result) => { + if (err) { + console.error("get scan info error"); + return; + } + + var len = Object.keys(result).length; + console.log("wifi received scan info: " + len); + for (var i = 0; i < len; ++i) { + console.info("ssid: " + result[i].ssid); + console.info("bssid: " + result[i].bssid); + console.info("capabilities: " + result[i].capabilities); + console.info("securityType: " + result[i].securityType); + console.info("rssi: " + result[i].rssi); + console.info("band: " + result[i].band); + console.info("frequency: " + result[i].frequency); + console.info("channelWidth: " + result[i].channelWidth); + console.info("timestamp: " + result[i].timestamp); + } + }); + + wifi.getScanInfos().then(result => { + var len = Object.keys(result).length; + console.log("wifi received scan info: " + len); + for (var i = 0; i < len; ++i) { + console.info("ssid: " + result[i].ssid); + console.info("bssid: " + result[i].bssid); + console.info("capabilities: " + result[i].capabilities); + console.info("securityType: " + result[i].securityType); + console.info("rssi: " + result[i].rssi); + console.info("band: " + result[i].band); + console.info("frequency: " + result[i].frequency); + console.info("channelWidth: " + result[i].channelWidth); + console.info("timestamp: " + result[i].timestamp); + } + }); + ``` + + +## WifiScanInfo9+ + +Represents WLAN hotspot information. + +**System capability**: SystemCapability.Communication.WiFi.STA + + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| 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.| +| 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.| +| band | number | Yes| No| Frequency band of the WLAN access point (AP).| +| frequency | number | Yes| No| Frequency of the WLAN AP.| +| channelWidth | number | Yes| No| Channel width of the WLAN AP.| +| centerFrequency0 | number | Yes| No| Center frequency of the hotspot.| +| centerFrequency1 | number | Yes| No| Center frequency of the hotspot. If the hotspot uses two non-overlapping WLAN channels, two center frequencies, namely **centerFrequency0** and **centerFrequency1**, are returned.| +| infoElems | Array<[WifiInfoElem](#wifiinfoelem9)> | Yes| No| Information elements.| +| timestamp | number | Yes| No| Timestamp.| + + +## WifiSecurityType9+ + +Enumerates the WLAN security types. + +**System capability**: SystemCapability.Communication.WiFi.Core + + +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| WIFI_SEC_TYPE_INVALID | 0 | Invalid security type.| +| WIFI_SEC_TYPE_OPEN | 1 | Open security type.| +| WIFI_SEC_TYPE_WEP | 2 | Wired Equivalent Privacy (WEP).| +| WIFI_SEC_TYPE_PSK | 3 | Pre-shared key (PSK).| +| WIFI_SEC_TYPE_SAE | 4 | Simultaneous Authentication of Equals (SAE).| +| WIFI_SEC_TYPE_EAP9+ | 5 | Extensible Authentication protocol (EAP).| +| WIFI_SEC_TYPE_EAP_SUITE_B9+ | 6 | Suite B 192-bit encryption.| +| WIFI_SEC_TYPE_OWE9+ | 7 | Opportunistic Wireless Encryption (OWE).| +| WIFI_SEC_TYPE_WAPI_CERT9+ | 8 | WLAN Authentication and Privacy Infrastructure (WAPI) in certificate-based mode (WAPI-CERT).| +| WIFI_SEC_TYPE_WAPI_PSK9+ | 9 | WAPI-PSK.| + + +## WifiInfoElem9+ + +Represents a WLAN information element. + +**System capability**: SystemCapability.Communication.WiFi.STA + + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| eid | number | Yes| No| ID of the information element.| +| content | Uint8Array | Yes| No| Content of the information element.| + + +## WifiChannelWidth9+ + +Enumerates the WLAN channel widths. + +**System capability**: SystemCapability.Communication.WiFi.STA + + +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| WIDTH_20MHZ | 0 | 20 MHz.| +| WIDTH_40MHZ | 1 | 40 MHz.| +| WIDTH_80MHZ | 2 | 80 MHz.| +| WIDTH_160MHZ | 3 | 160 MHz.| +| WIDTH_80MHZ_PLUS | 4 | 80 MHz+.| +| WIDTH_INVALID | 5 | Invalid value.| + + +## wifi.getScanResultsSync9+ + +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) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + |  Array<[WifiScanInfo](#wifiscaninfo)> | Scan result obtained.| + + +## wifi.addDeviceConfig9+ + +addDeviceConfig(config: WifiDeviceConfig): Promise<number> + +Adds network configuration. This API uses a promise to return the result. + +**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**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | Promise<number> | Promise used to return the ID of the added network configuration. If **-1** is returned, the network configuration fails to be added.| + +## WifiDeviceConfig9+ + +Represents the WLAN configuration. + +**System capability**: SystemCapability.Communication.WiFi.STA + + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.| +| bssid | string | Yes| No| BSSID 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.| +| creatorUid | number | Yes| No| ID of the creator.
**System API**: This is a system API.| +| disableReason | number | Yes| No| Reason for disabling WLAN.
**System API**: This is a system API.| +| netId | number | Yes| No| Network ID.
**System API**: This is a system API.| +| randomMacType | number | Yes| No| Random MAC type.
**System API**: This is a system API.| +| randomMacAddr | string | Yes| No| Random MAC address.
**System API**: This is a system API.| +| ipType | [IpType](#iptype9) | Yes| No| IP address type.
**System API**: This is a system API.| +| staticIp | [IpConfig](#ipconfig9) | Yes| No| Static IP address configuration.
**System API**: This is a system API.| +| eapConfig9+ | [WifiEapConfig](#wifieapconfig9) | Yes| No| EAP configuration.
**System API**: This is a system API.| + + +## IpType9+ + +Enumerates the IP address types. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.STA + + +| Name| Value| Description| +| -------- | -------- | -------- | +| STATIC | 0 | Static IP address.| +| DHCP | 1 | IP address allocated by DHCP.| +| UNKNOWN | 2 | Not specified.| + + +## IpConfig9+ + +Represents IP configuration information. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ipAddress | number | Yes| No| IP address.| +| gateway | number | Yes| No| Gateway.| +| prefixLength | number | Yes| No| Subnet mask.| +| dnsServers | number[] | Yes| No| Domain name server (DNS) information.| +| domains | Array<string> | Yes| No| Domain information.| + + +## WifiEapConfig9+ + +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.| +| identity | string | Yes| No| Identity Information.| +| anonymousIdentity | string | Yes| No| Anonymous identity.| +| password | string | Yes| No| Password.| +| caCertAliases | string | Yes| No| CA certificate alias.| +| caPath | string | Yes| No| CA certificate path.| +| clientCertAliases | string | Yes| No| Client certificate alias.| +| altSubjectMatch | string | Yes| No| A string to match the alternate subject.| +| domainSuffixMatch | string | Yes| No| A string to match the domain suffix.| +| realm | string | Yes| No| Realm for the passpoint credential.| +| plmn | string | Yes| No| Public land mobile network (PLMN) of the passpoint credential provider.| +| eapSubId | number | Yes| No| Sub-ID of the SIM card.| + + +## EapMethod9+ + +Enumerates the EAP authentication methods. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| Name| Value| Description| +| -------- | -------- | -------- | +| EAP_NONE | 0 | Not specified.| +| EAP_PEAP | 1 | PEAP.| +| EAP_TLS | 2 | TLS.| +| EAP_TTLS | 3 | TTLS.| +| EAP_PWD | 4 | Password.| +| EAP_SIM | 5 | SIM.| +| EAP_AKA | 6 | AKA.| +| EAP_AKA_PRIME | 7 | AKA Prime.| +| EAP_UNAUTH_TLS | 8 | UNAUTH TLS.| + + +## Phase2Method9+ + +Enumerates the Phase 2 authentication methods. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| Name| Value| Description| +| -------- | -------- | -------- | +| PHASE2_NONE | 0 | Not specified.| +| PHASE2_PAP | 1 | PAP.| +| PHASE2_MSCHAP | 2 | MS-CHAP.| +| PHASE2_MSCHAPV2 | 3 | MS-CHAPv2.| +| PHASE2_GTC | 4 | GTC .| +| PHASE2_SIM | 5 | SIM.| +| PHASE2_AKA | 6 | AKA.| +| PHASE2_AKA_PRIME | 7 | AKA Prime.| + + +## wifi.addDeviceConfig9+ + +addDeviceConfig(config: WifiDeviceConfig, callback: AsyncCallback<number>): void + +Adds network configuration. This API uses an asynchronous callback to return the result. + +**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**| + | -------- | -------- | -------- | -------- | + | 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.| + + +## wifi.addCandidateConfig9+ + +addCandidateConfig(config: WifiDeviceConfig): Promise<number> + +Adds the configuration of a candidate network. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.SET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | Promise<number> | Promise used to return the network configuration ID.| + + +## wifi.addCandidateConfig9+ + +addCandidateConfig(config: WifiDeviceConfig, callback: AsyncCallback<number>): void + +Adds the configuration of a candidate network. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.SET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**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.| + + +## wifi.removeCandidateConfig9+ + +removeCandidateConfig(networkId: number): Promise<void> + +Removes the configuration of a candidate network. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.SET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | networkId | number | Yes| ID of the network configuration to remove.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + + +## wifi.removeCandidateConfig9+ + +removeCandidateConfig(networkId: number, callback: AsyncCallback<void>): void + +Removes the configuration of a candidate network. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.SET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | networkId | number | Yes| ID of the network configuration to remove.| + | callback | AsyncCallback<void> | Yes| Callback invoked to return the result. If the operation is successful, the value of **err** is **0**. If **err** is not **0**, an error has occurred.| + + +## wifi.getCandidateConfigs9+ + +getCandidateConfigs():  Array<[WifiDeviceConfig](#wifideviceconfig)> + +Obtains candidate network configuration. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + |  Array<[WifiDeviceConfig](#wifideviceconfig)> | Candidate network configuration obtained.| + + +## wifi.connectToCandidateConfig9+ + +connectToCandidateConfig(networkId: number): void + +Connects to a candidate network. + +**Required permissions**: ohos.permission.SET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | networkId | number | Yes| ID of the candidate network configuration.| + + +## wifi.connectToNetwork9+ + +connectToNetwork(networkId: number): void + +Connects to the specified network. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **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.| + + +## wifi.connectToDevice9+ + +connectToDevice(config: WifiDeviceConfig): void + +Connects to the specified network. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO, ohos.permission.SET_WIFI_CONFIG, and ohos.permissio.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: + SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **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.| + + +## wifi.disconnect9+ + +disconnect(): void + +Disconnects the network. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: + SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.getSignalLevel9+ + +getSignalLevel(rssi: number, band: number): number + +Obtains the WLAN signal level. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **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].| + + +## wifi.getLinkedInfo9+ + +getLinkedInfo(): Promise<WifiLinkedInfo> + +Obtains WLAN connection information. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[WifiLinkedInfo](#wifilinkedinfo)> | Promise used to return the WLAN connection information obtained.| + + +## wifi.getLinkedInfo9+ + +getLinkedInfo(callback: AsyncCallback<WifiLinkedInfo>): void + +Obtains WLAN connection information. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**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.| + +**Example** + ```js + import wifi from '@ohos.wifi'; + + wifi.getLinkedInfo((err, data) => { + if (err) { + console.error("get linked info error"); + return; + } + console.info("get wifi linked info: " + JSON.stringify(data)); + }); + + wifi.getLinkedInfo().then(data => { + console.info("get wifi linked info: " + JSON.stringify(data)); + }).catch(error => { + console.info("get linked info error"); + }); + ``` + + +## WifiLinkedInfo9+ + +Represents the WLAN connection information. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.| +| bssid | string | Yes| No| BSSID of the hotspot.| +| networkId | number | Yes| No| Network configuration ID.
**System API**: This is a system API.| +| rssi | number | Yes| No| RSSI of the hotspot, in dBm.| +| band | number | Yes| No| Frequency band of the WLAN AP.| +| linkSpeed | number | Yes| No| Speed of the WLAN AP.| +| frequency | number | Yes| No| Frequency of the WLAN AP.| +| isHidden | boolean | Yes| No| Whether to hide the WLAN AP.| +| isRestricted | boolean | Yes| No| Whether to restrict data volume at the WLAN AP.| +| chload | number | Yes| No| Channel load. A larger value indicates a higher load.
**System API**: This is a system API.| +| snr | number | Yes| No| Signal-to-noise ratio (SNR).
**System API**: This is a system API.| +| macType9+ | number | Yes| No| MAC address type.| +| macAddress | string | Yes| No| MAC address of the device.| +| ipAddress | number | Yes| No| IP address of the device that sets up the WLAN connection.| +| suppState | [SuppState](#suppstate) | Yes| No| Supplicant state.
**System API**: This is a system API.| +| connState | [ConnState](#connstate) | Yes| No| WLAN connection state.| + + +## ConnState9+ + +Enumerates the WLAN connection states. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| Name| Value| Description| +| -------- | -------- | -------- | +| SCANNING | 0 | The device is scanning for available APs.| +| CONNECTING | 1 | A WLAN connection is being established.| +| AUTHENTICATING | 2 | An authentication is being performed for a WLAN connection.| +| OBTAINING_IPADDR | 3 | The IP address of the WLAN connection is being acquired.| +| CONNECTED | 4 | A WLAN connection is established.| +| DISCONNECTING | 5 | The WLAN connection is being disconnected.| +| DISCONNECTED | 6 | The WLAN connection is disconnected.| +| UNKNOWN | 7 | Failed to set up the WLAN connection.| + + +## SuppState9+ + +Enumerates the supplicant states. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| Name| Value| Description| +| -------- | -------- | -------- | +| DISCONNECTED | 0 | The supplicant is disconnected from the AP.| +| INTERFACE_DISABLED | 1 | The network interface is disabled.| +| INACTIVE | 2 | The supplicant is inactive.| +| SCANNING | 3 | The supplicant is scanning for a WLAN connection.| +| AUTHENTICATING | 4 | The supplicant is being authenticated.| +| ASSOCIATING | 5 | The supplicant is being associated with an AP.| +| ASSOCIATED | 6 | The supplicant is associated with an AP.| +| FOUR_WAY_HANDSHAKE | 7 | A four-way handshake is being performed for the supplicant.| +| GROUP_HANDSHAKE | 8 | A group handshake is being performed for the supplicant.| +| COMPLETED | 9 | The authentication is complete.| +| UNINITIALIZED | 10 | The supplicant failed to set up the connection.| +| INVALID | 11 | Invalid value.| + + +## wifi.isConnected9+ + +isConnected(): boolean + +Checks whether the WLAN is connected. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the WLAN is connected; returns **false** otherwise.| + + +## wifi.getSupportedFeatures9+ + +getSupportedFeatures(): number + +Obtains the features supported by this device. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | number | Feature value. | + +**Feature IDs** + +| Value| Description| +| -------- | -------- | +| 0x0001 | WLAN infrastructure mode| +| 0x0002 | 5 GHz feature| +| 0x0004 | Generic Advertisement Service (GAS)/Access Network Query Protocol (ANQP) feature| +| 0x0008 | Wi-Fi Direct| +| 0x0010 | SoftAP| +| 0x0040 | Wi-Fi AWare| +| 0x8000 | WLAN AP/STA concurrency| +| 0x8000000 | WPA3 Personal (WPA-3 SAE)| +| 0x10000000 | WPA3-Enterprise Suite B | +| 0x20000000 | Enhanced open feature| + + +## wifi.isFeatureSupported9+ + +isFeatureSupported(featureId: number): boolean + +Checks whether the device supports the specified WLAN feature. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.Core + +**Parameters** + + + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | featureId | number | Yes| Feature ID.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the feature is supported; returns **false** otherwise.| + + +## wifi.getDeviceMacAddress9+ + +getDeviceMacAddress(): string[] + +Obtains the device MAC address. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_LOCAL_MAC and ohos.permission.GET_WIFI_INFO (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | string[] | MAC address obtained.| + + +## wifi.getIpInfo9+ + +getIpInfo(): IpInfo + +Obtains IP information. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | [IpInfo](#ipinfo9) | IP information obtained.| + + +## IpInfo9+ + +Represents IP information. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ipAddress | number | Yes| No| IP address.| +| gateway | number | Yes| No| Gateway.| +| netmask | number | Yes| No| Subnet mask.| +| primaryDns | number | Yes| No| IP address of the preferred DNS server.| +| secondDns | number | Yes| No| IP address of the alternate DNS server.| +| serverIp | number | Yes| No| IP address of the DHCP server.| +| leaseDuration | number | Yes| No| Lease duration of the IP address.| + + +## wifi.getCountryCode9+ + +getCountryCode(): string + +Obtains the country code. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | string | Country code obtained.| + + +## wifi.reassociate9+ + +reassociate(): void + +Re-associates with the network. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.reconnect9+ + +reconnect(): void + +Reconnects to the network. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.getDeviceConfigs9+ + +getDeviceConfigs():  Array<[WifiDeviceConfig](#wifideviceconfig)> + +Obtains network configuration. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.GET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + |  Array<[WifiDeviceConfig](#wifideviceconfig)> | Array of network configuration obtained.| + + +## wifi.updateNetwork9+ + +updateNetwork(config: WifiDeviceConfig): number + +Updates network configuration. + +**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**| + | -------- | -------- | -------- | -------- | +| 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.| + + +## wifi.disableNetwork9+ + +disableNetwork(netId: number): void + +Disables network configuration. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **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.| + + +## wifi.removeAllNetwork9+ + +removeAllNetwork(): void + +Removes the configuration of all networks. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.removeDevice9+ + +removeDevice(id: number): void + +Removes the specified network configuration. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **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.| + + +## wifi.enableHotspot9+ + +enableHotspot(): void + +Enables this hotspot. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.disableHotspot9+ + +disableHotspot(): void + +Disables this hotspot. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.isHotspotDualBandSupported9+ + +isHotspotDualBandSupported(): boolean + +Checks whether the hotspot supports dual band. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.MANAGE_WIFI_HOTSPOT (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the feature is supported; returns **false** otherwise.| + + +## wifi.isHotspotActive9+ + +isHotspotActive(): boolean + +Checks whether this hotspot is active. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the hotspot is active; returns **false** otherwise.| + + +## wifi.setHotspotConfig9+ + +setHotspotConfig(config: HotspotConfig): void + +Sets hotspot configuration. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [HotspotConfig](#hotspotconfig9) | Yes| Hotspot configuration to set.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## HotspotConfig9+ + +Represents the hotspot configuration. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.| +| securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| Security type.| +| band | number | Yes| No| Hotspot band. The value **1** stands for 2.4 GHz, the value **2** for 5 GHz, and the value **3** for dual band.| +| preSharedKey | string | Yes| No| PSK of the hotspot.| +| maxConn | number | Yes| No| Maximum number of connections allowed.| + + +## wifi.getHotspotConfig9+ + +getHotspotConfig(): HotspotConfig + +obtains hotspot configuration. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | [HotspotConfig](#hotspotconfig9) | Hotspot configuration obtained.| + + +## wifi.getStations9+ + +getStations():  Array<[StationInfo](#stationinfo9)> + +Obtains information about the connected stations. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.MANAGE_WIFI_HOTSPOT (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + |  Array<[StationInfo](#stationinfo9)> | Connected stations obtained.| + + +## StationInfo9+ + +Represents the station information. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| name | string | Yes| No| Device name.| +| macAddress | string | Yes| No| MAC address.| +| ipAddress | string | Yes| No| IP address.| + + +## wifi.getP2pLinkedInfo9+ + +getP2pLinkedInfo(): Promise<WifiP2pLinkedInfo> + +Obtains P2P link information. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | Promise used to return the P2P link information obtained.| + + + +## WifiP2pLinkedInfo9+ + +Represents the P2P link information. + +**System capability**: SystemCapability.Communication.WiFi.P2P + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| connectState | [P2pConnectState](#p2pconnectstate9) | Yes| No| P2P connection state.| +| isGroupOwner | boolean | Yes| No| Whether the device is the group owner.| +| groupOwnerAddr | string | Yes| No| MAC address of the group. + + +## P2pConnectState9+ + +Enumerates the P2P connection states. + +**System capability**: SystemCapability.Communication.WiFi.P2P + +| Name| Value| Description| +| -------- | -------- | -------- | +| DISCONNECTED | 0 | Disconnected.| +| CONNECTED | 1 | Connected.| + + +## wifi.getP2pLinkedInfo9+ + +getP2pLinkedInfo(callback: AsyncCallback<WifiP2pLinkedInfo>): void + +Obtains P2P link information. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the P2P link information. If **err** is not **0**, an error has occurred.| + + +## wifi.getCurrentGroup9+ + +getCurrentGroup(): Promise<WifiP2pGroupInfo> + +Obtains the current P2P group information. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> | Promise used to return the P2P group information obtained.| + + +## wifi.getCurrentGroup9+ + +getCurrentGroup(callback: AsyncCallback<WifiP2pGroupInfo>): void + +Obtains the current P2P group information. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| + + +## wifi.getP2pPeerDevices9+ + +getP2pPeerDevices(): Promise<WifiP2pDevice[]> + +Obtains the peer device list in the P2P connection. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pDevice[]](#wifip2pdevice9)> | Promise used to return the peer device list.| + + +## wifi.getP2pPeerDevices9+ + +getP2pPeerDevices(callback: AsyncCallback<WifiP2pDevice[]>): void + +Obtains the peer device list in the P2P connection. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pDevice[]](#wifip2pdevice9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the peer device list obtained. If **err** is not **0**, an error has occurred.| + + +## WifiP2pDevice9+ + +Represents the P2P device information. + +**System capability**: SystemCapability.Communication.WiFi.P2P + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| deviceName | string | Yes| No| Device name.| +| deviceAddress | string | Yes| No| MAC address 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.| + + +## P2pDeviceStatus9+ + +Enumerates the P2P device states. + +**System capability**: SystemCapability.Communication.WiFi.P2P + +| Name| Value| Description| +| -------- | -------- | -------- | +| CONNECTED | 0 | Connected.| +| INVITED | 1 | Invited.| +| FAILED | 2 | Failed.| +| AVAILABLE | 3 | Available.| +| UNAVAILABLE | 4 | Unavailable.| + + +## wifi.getP2pLocalDevice9+ + +getP2pLocalDevice(): Promise<WifiP2pDevice> + +Obtains the local device information in the P2P connection. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pDevice](#wifip2pdevice9)> | Promise used to return the local device information obtained.| + + +## wifi.getP2pLocalDevice9+ + +getP2pLocalDevice(callback: AsyncCallback<WifiP2pDevice>): void + +Obtains the local device information in the P2P connection. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pDevice](#wifip2pdevice9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the local device information obtained. If **err** is not **0**, an error has occurred.| + + +## wifi.createGroup9+ + +createGroup(config: WifiP2PConfig): void + +Creates a P2P group. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiP2PConfig](#wifip2pconfig9) | Yes| Group configuration.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## WifiP2PConfig9+ + +Represents P2P group configuration. + +**System capability**: SystemCapability.Communication.WiFi.P2P + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| deviceAddress | string | Yes| No| Device address.| +| 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.| +| goBand | [GroupOwnerBand](#groupownerband9) | Yes| No| Frequency band of the group.| + + +## GroupOwnerBand9+ + +Enumerates the P2P group frequency bands. + +**System capability**: SystemCapability.Communication.WiFi.P2P + +| Name| Value| Description| +| -------- | -------- | -------- | +| GO_BAND_AUTO | 0 | Auto.| +| GO_BAND_2GHZ | 1 | 2 GHz.| +| GO_BAND_5GHZ | 2 | 5 GHz.| + + +## wifi.removeGroup9+ + +removeGroup(): void + +Removes this P2P group. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.p2pConnect9+ + +p2pConnect(config: WifiP2PConfig): void + +Sets up a P2P connection. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiP2PConfig](#wifip2pconfig9) | Yes| P2P group configuration.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +**Example** + ```js + import wifi from '@ohos.wifi'; + + var recvP2pConnectionChangeFunc = result => { + console.info("p2p connection change receive event: " + JSON.stringify(result)); + wifi.getP2pLinkedInfo((err, data) => { + if (err) { + console.error('failed to get getP2pLinkedInfo: ' + JSON.stringify(err)); + return; + } + console.info("get getP2pLinkedInfo: " + JSON.stringify(data)); + }); + } + wifi.on("p2pConnectionChange", recvP2pConnectionChangeFunc); + + var recvP2pDeviceChangeFunc = result => { + console.info("p2p device change receive event: " + JSON.stringify(result)); + } + wifi.on("p2pDeviceChange", recvP2pDeviceChangeFunc); + + var recvP2pPeerDeviceChangeFunc = result => { + console.info("p2p peer device change receive event: " + JSON.stringify(result)); + wifi.getP2pPeerDevices((err, data) => { + if (err) { + console.error('failed to get peer devices: ' + JSON.stringify(err)); + return; + } + console.info("get peer devices: " + JSON.stringify(data)); + var len = Object.keys(data).length; + for (var i = 0; i < len; ++i) { + if (data[i].deviceName === "my_test_device") { + console.info("p2p connect to test device: " + data[i].deviceAddress); + var config = { + "deviceAddress":data[i].deviceAddress, + "netId":-2, + "passphrase":"", + "groupName":"", + "goBand":0, + } + wifi.p2pConnect(config); + } + } + }); + } + wifi.on("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); + + var recvP2pPersistentGroupChangeFunc = () => { + console.info("p2p persistent group change receive event"); + + wifi.getCurrentGroup((err, data) => { + if (err) { + console.error('failed to get current group: ' + JSON.stringify(err)); + return; + } + console.info("get current group: " + JSON.stringify(data)); + }); + } + wifi.on("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); + + setTimeout(function() {wifi.off("p2pConnectionChange", recvP2pConnectionChangeFunc);}, 125 * 1000); + setTimeout(function() {wifi.off("p2pDeviceChange", recvP2pDeviceChangeFunc);}, 125 * 1000); + setTimeout(function() {wifi.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc);}, 125 * 1000); + setTimeout(function() {wifi.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc);}, 125 * 1000); + console.info("start discover devices -> " + wifi.startDiscoverDevices()); + ``` + +## wifi.p2pCancelConnect9+ + +p2pCancelConnect(): void + +Cancels this P2P connection. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.startDiscoverDevices9+ + +startDiscoverDevices(): void + +Starts to discover devices. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.stopDiscoverDevices9+ + +stopDiscoverDevices(): void + +Stops discovering devices. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.deletePersistentGroup9+ + +deletePersistentGroup(netId: number): void + +Deletes a persistent group. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + + | **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.| + + +## wifi.getP2pGroups9+ + +getP2pGroups(): Promise<Array<WifiP2pGroupInfo>> + +Obtains information about all P2P groups. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> > | Promise used to return the group information obtained.| + + +## WifiP2pGroupInfo9+ + +Represents the P2P group information. + +**System capability**: SystemCapability.Communication.WiFi.P2P + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| isP2pGo | boolean | Yes| No| Whether the device is the group owner.| +| ownerInfo | [WifiP2pDevice](#wifip2pdevice9) | Yes| No| Device information of the group.| +| passphrase | string | Yes| No| Passphrase of the group.| +| interface | string | Yes| No| Interface name.| +| groupName | string | Yes| No| Group name.| +| networkId | number | Yes| No| Network ID.| +| frequency | number | Yes| No| Frequency of the group.| +| clientDevices | [WifiP2pDevice[]](#wifip2pdevice9) | Yes| No| List of connected devices.| +| goIpAddress | string | Yes| No| IP address of the group.| + + +## wifi.getP2pGroups9+ + +getP2pGroups(callback: AsyncCallback<Array<WifiP2pGroupInfo>>): void + +Obtains information about all P2P groups. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo9)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| + + +## wifi.setDeviceName9+ + +setDeviceName(devName: string): void + +Sets the device name. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **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.| + + +## wifi.on('wifiStateChange')9+ + +on(type: "wifiStateChange", callback: Callback<number>): void + +Registers the WLAN state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**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.| + +**WLAN states** + +| **Value**| **Description**| +| -------- | -------- | +| 0 | Deactivated| +| 1 | Activated| +| 2 | Activating| +| 3 | Deactivating| + + +## wifi.off('wifiStateChange')9+ + +off(type: "wifiStateChange", callback?: Callback<number>): void + +Unregisters the WLAN state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**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.| + +**Example** + ```js + import wifi from '@ohos.wifi'; + + var recvPowerNotifyFunc = result => { + console.info("Receive power state change event: " + result); + } + + // Register an event. + wifi.on("wifiStateChange", recvPowerNotifyFunc); + + // Unregister an event. + wifi.off("wifiStateChange", recvPowerNotifyFunc); + ``` + + +## wifi.on('wifiConnectionChange')7+ + +on(type: "wifiConnectionChange", callback: Callback<number>): void + +Registers the WLAN connection state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**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.| + +**WLAN connection states** + +| **Value**| **Description**| +| -------- | -------- | +| 0 | Disconnected.| +| 1 | Connected.| + + +## wifi.off('wifiConnectionChange')9+ + +off(type: "wifiConnectionChange", callback?: Callback<number>): void + +Unregisters the WLAN connection state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**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.| + + +## wifi.on('wifiScanStateChange')9+ + +on(type: "wifiScanStateChange", callback: Callback<number>): void + +Registers the WLAN scan state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**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.| + +**WLAN scan states** + +| **Value**| **Description**| +| -------- | -------- | +| 0 | Scan failed.| +| 1 | Scan successful.| + + +## wifi.off('wifiScanStateChange')9+ + +off(type: "wifiScanStateChange", callback?: Callback<number>): void + +Unregisters the WLAN scan state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **wifiScanStateChange**.| +| callback | Callback<number> | No| Callback for the WLAN scan state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('wifiRssiChange')9+ + +on(type: "wifiRssiChange", callback: Callback<number>): void + +Registers the RSSI change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**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.| + + +## wifi.off('wifiRssiChange')9+ + +off(type: "wifiRssiChange", callback?: Callback<number>): void + +Unregisters the RSSI change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **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.| + + +## wifi.on('hotspotStateChange')9+ + +on(type: "hotspotStateChange", callback: Callback<number>): void + +Registers the hotspot state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**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.| + +**Hotspot states** + +| **Value**| **Description**| +| -------- | -------- | +| 0 | Deactivated| +| 1 | Activated| +| 2 | Activating| +| 3 | Deactivating| + + +## wifi.off('hotspotStateChange')9+ + +off(type: "hotspotStateChange", callback?: Callback<number>): void + +Unregisters the hotspot state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Parameters** + + | **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('p2pStateChange')9+ + +on(type: "p2pStateChange", callback: Callback<number>): void + +Registers the P2P state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**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.| + +**P2P states** + +| **Value**| **Description**| +| -------- | -------- | +| 1 | Available| +| 2 | Opening| +| 3 | Opened| +| 4 | Closing| +| 5 | Closed| + +## wifi.off('p2pStateChange')9+ + +off(type: "p2pStateChange", callback?: Callback<number>): void + +Unregisters the P2P state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **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.| + + + ## wifi.on('p2pConnectionChange')9+ + +on(type: "p2pConnectionChange", callback: Callback<WifiP2pLinkedInfo>): void + +Registers the P2P connection state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pConnectionChange**.| + | callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | Yes| Callback invoked to return the P2P connection state.| + + +## wifi.off('p2pConnectionChange')9+ + +off(type: "p2pConnectionChange", callback?: Callback<WifiP2pLinkedInfo>): void + +Unregisters the P2P connection state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pConnectionChange**.| + | callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | No| Callback for the P2P connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('p2pDeviceChange')9+ + +on(type: "p2pDeviceChange", callback: Callback<WifiP2pDevice>): void + +Registers the P2P device state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDeviceChange**.| + | callback | Callback<[WifiP2pDevice](#wifip2pdevice9)> | Yes| Callback invoked to return the P2P device state.| + + +## wifi.off('p2pDeviceChange')9+ + +off(type: "p2pDeviceChange", callback?: Callback<WifiP2pDevice>): void + +Unregisters the P2P device state change events. + +**Required permissions**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDeviceChange**.| + | callback | Callback<[WifiP2pDevice](#wifip2pdevice9)> | No| Callback for the P2P device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('p2pPeerDeviceChange')9+ + +on(type: "p2pPeerDeviceChange", callback: Callback<WifiP2pDevice[]>): void + +Registers the P2P peer device state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| + | callback | Callback<[WifiP2pDevice[]](#wifip2pdevice9)> | Yes| Callback invoked to return the P2P peer device state.| + + +## wifi.off('p2pPeerDeviceChange')9+ + +off(type: "p2pPeerDeviceChange", callback?: Callback<WifiP2pDevice[]>): void + +Unregisters the P2P peer device state change events. + +**Required permissions**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| + | callback | Callback<[WifiP2pDevice[]](#wifip2pdevice9)> | No| Callback for the peer device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('p2pPersistentGroupChange')9+ + +on(type: "p2pPersistentGroupChange", callback: Callback<void>): void + +Registers the P2P persistent group state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**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.| + + +## wifi.off('p2pPersistentGroupChange')9+ + +off(type: "p2pPersistentGroupChange", callback?: Callback<void>): void + +Unregisters the P2P persistent group state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| + | callback | Callback<void> | No| Callback for the P2P persistent group state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('p2pDiscoveryChange')9+ + +on(type: "p2pDiscoveryChange", callback: Callback<number>): void + +Registers the P2P device discovery state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**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.| + +**P2P discovered device states** + +| **Value**| **Description**| +| -------- | -------- | +| 0 | Initial state.| +| 1 | Discovered.| + + +## wifi.off('p2pDiscoveryChange')9+ + +off(type: "p2pDiscoveryChange", callback?: Callback<number>): void + +Unregisters the P2P device discovery state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| + | callback | Callback<number> | No| Callback for the P2P device discovery state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| diff --git a/en/application-dev/reference/apis/js-apis-wifiManagerExt.md b/en/application-dev/reference/apis/js-apis-wifiManagerExt.md new file mode 100644 index 0000000000000000000000000000000000000000..f024294ddbc393a57394a1ad20d2686d30060e52 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-wifiManagerExt.md @@ -0,0 +1,152 @@ +# WLAN Extension Interface + +This **wifiext** module provides WLAN extension interfaces for non-universal products. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +The APIs described in this document are used only for non-universal products, such as routers. + + +## Modules to Import + +```js +import wifiManagerExt from '@ohos.wifiManagerExt'; +``` + +## wifiext.enableHotspot + +enableHotspot(): boolean; + +Enables the WLAN hotspot. + +**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT_EXT + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifiext.disableHotspot + +disableHotspot(): boolean; + +Disables the WLAN hotspot. + +**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT_EXT + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifiext.getSupportedPowerModel + +getSupportedPowerModel(): Promise<Array<PowerModel>> + +Obtains the supported power models. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<Array<[PowerModel](#powermodel)>> | Promise used to return the power models obtained.| + + +## PowerModel + +Enumerates the power models. + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +| Name| Value| Description| +| -------- | -------- | -------- | +| SLEEPING | 0 | Sleeping| +| GENERAL | 1 | General| +| THROUGH_WALL | 2 | Through_wall| + + +## wifiext.getSupportedPowerModel + +getSupportedPowerModel(callback: AsyncCallback<Array<PowerModel>>): void + +Obtains the supported power models. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<Array<[PowerModel](#powermodel)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is 0 and **data** is the power models obtained. If **err** is not **0**, an error has occurred.| + + +## wifiext.getPowerModel + +getPowerModel(): Promise<PowerModel> + +Obtains the power model. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[PowerModel](#powermodel)> | Promise used to return the power model obtained.| + + +## wifiext.getPowerModel + +getPowerModel(callback: AsyncCallback<PowerModel>): void + +Obtains the power model. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[PowerModel](#powermodel)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the power model obtained. If **err** is not **0**, an error has occurred.| + + +## wifiext.setPowerModel + +setPowerModel(model: PowerModel) : boolean; + + Sets the power model. + +**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT_EXT + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | model | [PowerModel](#powermodel) | Yes| Power model to set.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| diff --git a/en/application-dev/reference/apis/js-apis-wifiext.md b/en/application-dev/reference/apis/js-apis-wifiext.md index 9ce53d76e2517eb199067f779168fb9fe9d8b032..70961ffe279bf5543bbe28168f8571a54ca46651 100644 --- a/en/application-dev/reference/apis/js-apis-wifiext.md +++ b/en/application-dev/reference/apis/js-apis-wifiext.md @@ -1,7 +1,9 @@ -# WLAN +# @ohos.wifiext + This **wifiext** module provides WLAN extension interfaces for non-universal products. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. The APIs described in this document are used only for non-universal products, such as routers. @@ -69,7 +71,7 @@ Enumerates the power models. **System capability**: SystemCapability.Communication.WiFi.AP.Extension -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | SLEEPING | 0 | Sleeping| | GENERAL | 1 | General| @@ -90,7 +92,7 @@ Obtains the supported power models. This API uses an asynchronous callback to re | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[PowerModel](#powermodel)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is 0 and **data** is the power models obtained. If **err** is not **0**, an error has occurred.| + | callback | AsyncCallback<Array<[PowerModel](#powermodel)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is 0 and **data** is the power models obtained. If **err** is not **0**, an error has occurred.| ## wifiext.getPowerModel @@ -141,7 +143,7 @@ setPowerModel(model: PowerModel) : boolean; | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | model | AsyncCallback<[PowerModel](#powermodel)> | Yes| Power model to set.| + | model | [PowerModel](#powermodel) | Yes| Power model to set.| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-window.md b/en/application-dev/reference/apis/js-apis-window.md index 9d60fe2118d81d8b423a851b6dbf759b48a10864..523758e9caf5ffcba94df7e7efc6756bb5d1fa28 100644 --- a/en/application-dev/reference/apis/js-apis-window.md +++ b/en/application-dev/reference/apis/js-apis-window.md @@ -1,4 +1,4 @@ -# Window +# @ohos.window The **Window** module provides basic window management capabilities, such as creating and destroying the current window, setting properties for the current window, and managing and scheduling windows. @@ -46,17 +46,15 @@ Enumerates the window types. ## Configuration9+ -Defines the parameters used for creating a subwindow. - -An asynchronous callback is used when a system window is created in the case that [ServiceExtensionContext](js-apis-service-extension-context.md) is used as the context. +Defines the parameters for creating a subwindow or system window. **System capability**: SystemCapability.WindowManager.WindowManager.Core | Name| Type| Mandatory| Description| | ---------- | -------------------------- | -- | ----------------------------------- | -| name | string | Yes| Name of the subwindow. | -| windowType | [WindowType](#windowtype7) | Yes| Type of the subwindow. | -| ctx | BaseContext | No| Current application context.
For details about the context in the FA model, see [Context](js-apis-Context.md).
For details about the context in the stage model, see [Context](js-apis-service-extension-context.md).
If this parameter is not set, no context is used. | +| name | string | Yes| Name of the window. | +| windowType | [WindowType](#windowtype7) | Yes| Type of the window. | +| ctx | BaseContext | No| Current application context.
For details about the context in the FA model, see [Context](js-apis-inner-app-context.md).
For details about the context in the stage model, see [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md). If this parameter is not set, no context is used.
A system window is created when **Context** is [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md).| | displayId | number | No| ID of the current physical screen. If this parameter is not set, the default value **-1** is used.| | parentId | number | No| ID of the parent window. If this parameter is not set, the default value **-1** is used. | @@ -302,7 +300,7 @@ Describes the translation parameters. createWindow(config: Configuration, callback: AsyncCallback<Window>): void -Creates a subwindow. This API uses an asynchronous callback to return the result. +Creates a subwindow or system window. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -310,8 +308,8 @@ Creates a subwindow. This API uses an asynchronous callback to return the result | Name| Type| Mandatory| Description| | -------- | -------------------------------------- | -- | --------------------------------- | -| config | [Configuration](#configuration9) | Yes| Current application context. | -| callback | AsyncCallback<[Window](#window)> | Yes| Callback used to return the subwindow created.| +| config | [Configuration](#configuration9) | Yes| Parameters used for creating the window. | +| callback | AsyncCallback<[Window](#window)> | Yes| Callback used to return the window created.| **Error codes** @@ -346,7 +344,7 @@ try { createWindow(config: Configuration): Promise<Window> -Creates a subwindow. This API uses a promise to return the result. +Creates a subwindow or system window. This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -354,13 +352,13 @@ Creates a subwindow. This API uses a promise to return the result. | Name| Type| Mandatory| Description| | ------ | -------------------------------- | -- | ------------------ | -| config | [Configuration](#configuration9) | Yes| Current application context.| +| config | [Configuration](#configuration9) | Yes| Parameters used for creating the window.| **Return value** | Type| Description| | -------------------------------- | ------------------------------------ | -| Promise<[Window](#window)> | Promise used to return the subwindow created.| +| Promise<[Window](#window)> | Promise used to return the window created.| **Error codes** @@ -393,7 +391,7 @@ try { findWindow(name: string): Window -Finds a window based on the ID. +Finds a window based on the name. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -432,7 +430,7 @@ Obtains the top window of the current application. This API uses an asynchronous | Name| Type| Mandatory| Description| | -------- | -------------------------------------- | -- | ---------------------------------------- | -| ctx | BaseContext | Yes| Current application context.
For details about the context in the FA model, see [Context](js-apis-Context.md).
For details about the context in the stage model, see [Context](js-apis-ability-context.md).| +| ctx | BaseContext | Yes| Current application context.
For details about the context in the FA model, see [Context](js-apis-inner-app-context.md).
For details about the context in the stage model, see [Context](js-apis-ability-context.md).| | callback | AsyncCallback<[Window](#window)> | Yes| Callback used to return the top window obtained.| **Error codes** @@ -474,7 +472,7 @@ Obtains the top window of the current application. This API uses a promise to re | Name| Type| Mandatory| Description| | ------ | ----------- | ---- | ------------------------------------------------------------ | -| ctx | BaseContext | Yes | Current application context.
For details about the context in the FA model, see [Context](js-apis-Context.md).
For details about the context in the stage model, see [Context](js-apis-ability-context.md).| +| ctx | BaseContext | Yes | Current application context.
For details about the context in the FA model, see [Context](js-apis-inner-app-context.md).
For details about the context in the stage model, see [Context](js-apis-ability-context.md).| **Return value** @@ -899,7 +897,7 @@ promise.then((data)=> { create(ctx: BaseContext, id: string, type: WindowType, callback: AsyncCallback<Window>): void -Creates a subwindow in the FA model or a system window in the stage model. This API uses an asynchronous callback to return the result. +Creates a subwindow (in API version 8) or a system window (from API version 9). This API uses an asynchronous callback to return the result. > **NOTE** > @@ -911,7 +909,7 @@ Creates a subwindow in the FA model or a system window in the stage model. This | Name | Type | Mandatory| Description | | -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| ctx | BaseContext | Yes | Current application context.
For details about the context in the FA model, see [Context](js-apis-Context.md).
For details about the context in the stage model, see [Context](js-apis-service-extension-context.md).| +| ctx | BaseContext | Yes | Current application context.
For details about the context in the FA model, see [Context](js-apis-inner-app-context.md).
For details about the context in the stage model, see [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md).| | id | string | Yes | Window ID. | | type | [WindowType](#windowtype7) | Yes | Window type. | | callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the subwindow created. | @@ -935,7 +933,7 @@ window.create(this.context, 'alertWindow', window.WindowType.TYPE_SYSTEM_ALERT, create(ctx: BaseContext, id: string, type: WindowType): Promise<Window> -Creates a subwindow in the FA model or a system window in the stage model. This API uses a promise to return the result. +Creates a subwindow (in API version 8) or a system window (from API version 9). This API uses a promise to return the result. > **NOTE** > @@ -947,7 +945,7 @@ Creates a subwindow in the FA model or a system window in the stage model. This | Name| Type | Mandatory| Description | | ------ | ------------------------- | ---- | ------------------------------------------------------------ | -| ctx | BaseContext | Yes | Current application context.
For details about the context in the FA model, see [Context](js-apis-Context.md).
For details about the context in the stage model, see [Context](js-apis-service-extension-context.md).| +| ctx | BaseContext | Yes | Current application context.
For details about the context in the FA model, see [Context](js-apis-inner-app-context.md).
For details about the context in the stage model, see [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md).| | id | string | Yes | Window ID. | | type | [WindowType](#windowtype7) | Yes | Window type. | @@ -1123,7 +1121,7 @@ Obtains the top window of the current application. This API uses an asynchronous | Name | Type | Mandatory| Description | | -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| ctx | BaseContext | Yes | Current application context.
For details about the context in the FA model, see [Context](js-apis-Context.md).
For details about the context in the stage model, see [Context](js-apis-ability-context.md).| +| ctx | BaseContext | Yes | Current application context.
For details about the context in the FA model, see [Context](js-apis-inner-app-context.md).
For details about the context in the stage model, see [Context](js-apis-ability-context.md).| | callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the top window obtained. | **Example** @@ -1156,7 +1154,7 @@ Obtains the top window of the current application. This API uses a promise to re | Name| Type | Mandatory| Description | | ------ | ----------- | ---- | ------------------------------------------------------------ | -| ctx | BaseContext | Yes | Current application context.
For details about the context in the FA model, see [Context](js-apis-Context.md).
For details about the context in the stage model, see [Context](js-apis-ability-context.md).| +| ctx | BaseContext | Yes | Current application context.
For details about the context in the FA model, see [Context](js-apis-inner-app-context.md).
For details about the context in the stage model, see [Context](js-apis-ability-context.md).| **Return value** @@ -1983,7 +1981,7 @@ Sets whether to display the status bar and navigation bar in this window. This A | Name| Type| Mandatory| Description| | -------- | ---------------------------- | -- | --------- | -| names | Array<'status'\|'navigation'> | Yes | Whether to display the status bar and navigation bar.
For example, to display the status bar and navigation bar, set this parameter to **['status', 'navigation']**. By default, they are not displayed.| +| names | Array<'status'\|'navigation'> | Yes| Whether to display the status bar and navigation bar.
For example, to display the status bar and navigation bar, set this parameter to **['status', 'navigation']**. By default, they are not displayed.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Error codes** @@ -3723,41 +3721,6 @@ try { ### snapshot9+ -snapshot(callback: AsyncCallback<image.PixelMap>): void - -Captures this window. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ------------------------------------------------------------ | --------- | ----------------------------------- | -| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | Yes | Callback used to return the result. | - -**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. | - -**Example** - -```js -windowClass.snapshot((err, pixelMap) => { - if (err.code) { - console.error('Failed to snapshot window. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in snapshotting window. Pixel bytes number: ' + pixelMap.getPixelBytesNumber()); - pixelMap.release(); // Release the memory in time after the PixelMap is used. -}); -``` - -### snapshot9+ - snapshot(): Promise<image.PixelMap> Captures this window. This API uses a promise to return the result. @@ -4078,7 +4041,6 @@ try { } catch (exception) { console.error('Failed to set backdrop blur. Cause: ' + JSON.stringify(exception)); } - ``` ### setBackdropBlurStyle9+ @@ -6697,7 +6659,6 @@ controller.animationForShown = (context : window.TransitionContext) => { ); console.info('complete transition end'); }; - ``` ### animationForHidden9+ @@ -6744,4 +6705,5 @@ controller.animationForHidden = (context : window.TransitionContext) => { ) console.info('complete transition end'); }; -``` \ No newline at end of file +``` + diff --git a/en/application-dev/reference/apis/js-apis-workScheduler.md b/en/application-dev/reference/apis/js-apis-workScheduler.md deleted file mode 100644 index d897bc91717348ee8addd00751741f83cc77c345..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-workScheduler.md +++ /dev/null @@ -1,361 +0,0 @@ -# Work Scheduler - -The **workScheduler** module provides the APIs for registering, canceling, and querying Work Scheduler tasks, which do not have real-time constraints. - -The system executes Work Scheduler tasks at an appropriate time, subject to the storage space, power consumption, temperature, and more. - -> **NOTE** -> -> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> - The APIs of this module can be used only in the stage model. -> - For details about the constraints on the Work Scheduler usage, see [Work Scheduler Overview](../../task-management/work-scheduler-overview.md). - - -## Modules to Import - -```js -import workScheduler from '@ohos.workScheduler'; -``` - -## workScheduler.startWork -startWork(work: WorkInfo): boolean - -Instructs the **WorkSchedulerService** to add the specified task to the execution queue. - -**System capability**: SystemCapability.ResourceSchedule.WorkScheduler - -**Parameters** - -| Name | Type | Mandatory | Description | -| ---- | --------------------- | ---- | -------------- | -| work | [WorkInfo](#workinfo) | Yes | Task to be added to the execution queue.| - -**Return value** - -| Type | Description | -| ------- | -------------------------------- | -| boolean | Returns **true** if the task is added to the execution queue; returns **false** otherwise.| - -**Example** - -```js - let workInfo = { - workId: 1, - batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW, - isRepeat: false, - isPersisted: true, - bundleName: "com.example.myapplication", - abilityName: "MyExtension", - parameters: { - mykey0: 1, - mykey1: "string value", - mykey2: true, - mykey3: 1.5 - } - } - var res = workScheduler.startWork(workInfo); - console.info(`workschedulerLog res: ${res}`); -``` - -## workScheduler.stopWork -stopWork(work: WorkInfo, needCancel?: boolean): boolean - -Instructs the **WorkSchedulerService** to stop the specified task. - -**System capability**: SystemCapability.ResourceSchedule.WorkScheduler - -**Parameters** - -| Name | Type | Mandatory | Description | -| ---------- | --------------------- | ---- | ---------- | -| work | [WorkInfo](#workinfo) | Yes | Task to stop. | -| needCancel | boolean | Yes | Whether to cancel the task.| - -**Return value** - -| Type | Description | -| ------- | ----------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - -**Example** - -```js - let workInfo = { - workId: 1, - batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW, - isRepeat: false, - isPersisted: true, - bundleName: "com.example.myapplication", - abilityName: "MyExtension", - parameters: { - mykey0: 1, - mykey1: "string value", - mykey2: true, - mykey3: 1.5 - } - } - var res = workScheduler.stopWork(workInfo, false); - console.info(`workschedulerLog res: ${res}`); -``` - -## workScheduler.getWorkStatus -getWorkStatus(workId: number, callback : AsyncCallback\): void - -Obtains the latest task status. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.ResourceSchedule.WorkScheduler - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ------------------------------------- | ---- | ---------------------------------------- | -| workId | number | Yes | Task ID. | -| callback | AsyncCallback\<[WorkInfo](#workinfo)> | Yes | Callback used to return the result. Returns the task status obtained from the **WorkSchedulerService** if the specified task ID is valid; returns **null** otherwise.| - -**Example** - -```js - workScheduler.getWorkStatus(50, (err, res) => { - if (err) { - console.info(`workschedulerLog getWorkStatus failed, because: ${err.code}`); - } else { - for (let item in res) { - console.info(`workschedulerLog getWorkStatus success, ${item} is: ${res[item]}`); - } - } - }); -``` - -## workScheduler.getWorkStatus -getWorkStatus(workId: number): Promise\ - -Obtains the latest task status. This API uses a promise to return the result. - -**System capability**: SystemCapability.ResourceSchedule.WorkScheduler - -**Parameters** - -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | -------- | -| workId | number | Yes | Task ID.| - -**Return value** - -| Type | Description | -| ------------------------------- | ---------------------------------------- | -| Promise\<[WorkInfo](#workinfo)> | Promise used to return the result. Returns the task status obtained from the **WorkSchedulerService** if the specified task ID is valid; returns **null** otherwise.| - -**Example** - -```js - workScheduler.getWorkStatus(50).then((res) => { - for (let item in res) { - console.info(`workschedulerLog getWorkStatus success, ${item} is: ${res[item]}`); - } - }).catch((err) => { - console.info(`workschedulerLog getWorkStatus failed, because: ${err.code}`); - }) -``` - -## workScheduler.obtainAllWorks -obtainAllWorks(callback : AsyncCallback\): Array\ - -Obtains all tasks associated with this application. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.ResourceSchedule.WorkScheduler - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | -------------------- | ---- | ------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return all tasks associated with the current application. | - -**Return value** - -| Type | Description | -| ----------------------------- | --------------- | -| Array\<[WorkInfo](#workinfo)> | All tasks associated with the current application.| - -**Example** - -```js - workScheduler.obtainAllWorks((err, res) =>{ - if (err) { - console.info(`workschedulerLog obtainAllWorks failed, because: ${err.code}`); - } else { - console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`); - } - }); -``` - -## workScheduler.obtainAllWorks -obtainAllWorks(): Promise> - -Obtains all tasks associated with this application. This API uses a promise to return the result. - -**System capability**: SystemCapability.ResourceSchedule.WorkScheduler - -**Return value** - -| Type | Description | -| -------------------------------------- | ------------------------------ | -| Promise> | Promise used to return all tasks associated with the current application. | - -**Example** - -```js - workScheduler.obtainAllWorks().then((res) => { - console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`); - }).catch((err) => { - console.info(`workschedulerLog obtainAllWorks failed, because: ${err.code}`); - }) -``` - -## workScheduler.stopAndClearWorks -stopAndClearWorks(): boolean - -Stops and cancels all tasks associated with the current application. - -**System capability**: SystemCapability.ResourceSchedule.WorkScheduler - -**Example** - -```js - let res = workScheduler.stopAndClearWorks(); - console.info(`workschedulerLog res: ${res}`); -``` - -## workScheduler.isLastWorkTimeOut -isLastWorkTimeOut(workId: number, callback : AsyncCallback\): boolean - -Checks whether the last execution of the specified task timed out. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.ResourceSchedule.WorkScheduler - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | -------------------- | ---- | ---------------------------------------- | -| workId | number | Yes | Task ID. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. Returns **true** if the last execution of the specified task timed out; returns **false** otherwise.| - -**Return value** - -| Type | Description | -| ------- | ---------------------------------------- | -| boolean | Callback used to return the result. Returns **true** if the last execution of the specified task timed out; returns **false** otherwise.| - -**Example** - -```js - workScheduler.isLastWorkTimeOut(500, (err, res) =>{ - if (err) { - console.info(`workschedulerLog isLastWorkTimeOut failed, because: ${err.code}`); - } else { - console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`); - } - }); -``` - -## workScheduler.isLastWorkTimeOut -isLastWorkTimeOut(workId: number): Promise\ - -Checks whether the last execution of the specified task timed out. This API uses a promise to return the result. - -**System capability**: SystemCapability.ResourceSchedule.WorkScheduler - -**Parameters** - -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | -------- | -| workId | number | Yes | Task ID.| - -**Return value** - -| Type | Description | -| ----------------- | ---------------------------------------- | -| Promise\ | Promise used to return the result. Returns **true** if the last execution of the specified task timed out; returns **false** otherwise.| - -**Example** - -```js - workScheduler.isLastWorkTimeOut(500) - .then(res => { - console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`); - }) - .catch(err => { - console.info(`workschedulerLog isLastWorkTimeOut failed, because: ${err.code}`); - }); -``` - -## WorkInfo -Provides detailed information about the task. For details about the constraints on configuring **WorkInfo**, see [Work Scheduler Overview](../../task-management/work-scheduler-overview.md). - -**System capability**: SystemCapability.ResourceSchedule.WorkScheduler - -| Name | Type | Mandatory | Description | -| --------------- | --------------------------------- | ---- | ---------------- | -| workId | number | Yes | Task ID. | -| bundleName | string | Yes | Name of the Work Scheduler task bundle. | -| abilityName | string | Yes | Name of the component to be notified by a Work Scheduler callback.| -| networkType | [NetworkType](#networktype) | No | Network type. | -| isCharging | boolean | No | Whether the device is charging. | -| chargerType | [ChargingType](#chargingtype) | No | Charging type. | -| batteryLevel | number | No | Battery level. | -| batteryStatus | [BatteryStatus](#batterystatus) | No | Battery status. | -| storageRequest | [StorageRequest](#storagerequest) | No | Storage status. | -| isRepeat | boolean | No | Whether the task is repeated. | -| repeatCycleTime | number | No | Repeat interval. | -| repeatCount | number | No | Number of repeat times. | -| isPersisted | boolean | No | Whether to enable persistent storage for the task. | -| isDeepIdle | boolean | No | Whether the device needs to enter the idle state. | -| idleWaitTime | number | No | Time to wait in the idle state. | -| parameters | {[key: string]: any} | No | Carried parameters. | - -## NetworkType -Enumerates the network types that can trigger the task. - -**System capability**: SystemCapability.ResourceSchedule.WorkScheduler - -| Name | Default Value | Description | -| ---------------------- | ---- | ----------------------- | -| NETWORK_TYPE_ANY | 0 | Any network type. | -| NETWORK_TYPE_MOBILE | 1 | Mobile network. | -| NETWORK_TYPE_WIFI | 2 | Wi-Fi network. | -| NETWORK_TYPE_BLUETOOTH | 3 | Bluetooth network.| -| NETWORK_TYPE_WIFI_P2P | 4 | Wi-Fi P2P network. | -| NETWORK_TYPE_ETHERNET | 5 | Ethernet. | - -## ChargingType -Enumerates the charging types that can trigger the task. - -**System capability**: SystemCapability.ResourceSchedule.WorkScheduler - -| Name | Default Value | Description | -| ------------------------- | ---- | -------------------- | -| CHARGING_PLUGGED_ANY | 0 | Any charging type.| -| CHARGING_PLUGGED_AC | 1 | DC charging. | -| CHARGING_PLUGGED_USB | 2 | USB charging. | -| CHARGING_PLUGGED_WIRELESS | 3 | Wireless charging. | - -## BatteryStatus -Enumerates the battery states that can trigger the task. - -**System capability**: SystemCapability.ResourceSchedule.WorkScheduler - -| Name | Default Value | Description | -| -------------------------- | ---- | -------------------------- | -| BATTERY_STATUS_LOW | 0 | A low battery alert is displayed. | -| BATTERY_STATUS_OKAY | 1 | The battery level is restored from low to normal. | -| BATTERY_STATUS_LOW_OR_OKAY | 2 | The battery level is restored from low to normal, or a low battery alert is displayed.| - -## StorageRequest -Enumerates the storage states that can trigger the task. - -**System capability**: SystemCapability.ResourceSchedule.WorkScheduler - -| Name | Default Value | Description | -| ------------------------- | ---- | ------------------------------ | -| STORAGE_LEVEL_LOW | 0 | The storage space is insufficient. | -| STORAGE_LEVEL_OKAY | 1 | The storage space is restored from insufficient to normal. | -| STORAGE_LEVEL_LOW_OR_OKAY | 2 | The storage space is restored from insufficient to normal, or the storage space is insufficient.| diff --git a/en/application-dev/reference/apis/js-apis-worker.md b/en/application-dev/reference/apis/js-apis-worker.md index a9bb769b0eccd89631f4747bcce6deba03c4533a..1b269ea33508c427b9480641ee08210b7906eddc 100644 --- a/en/application-dev/reference/apis/js-apis-worker.md +++ b/en/application-dev/reference/apis/js-apis-worker.md @@ -1,11 +1,13 @@ -# Worker Startup +# @ohos.worker + +The worker thread is an independent thread running in parallel with the main thread. The thread that creates the worker thread is referred to as the host thread. The URL file passed in during worker creation is executed in the worker thread. The worker thread can process time-consuming operations, but cannot directly operate the UI. + +With the **Worker** module, you can provide a multithreading environment for an application, so that the application can perform a time-consuming operation in a background thread. This greatly prevents a computing-intensive or high-latency task from blocking the running of the main thread. A **Worker** instance will not be proactively destroyed once it is created. It consumes resources to keep running. Therefore, you should call the API to terminate it in a timely manner. > **NOTE** > > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -The worker thread is an independent thread running in parallel with the main thread. The thread that creates the worker thread is referred to as the host thread. The URL file passed in during worker creation is executed in the worker thread. The worker thread can process time-consuming operations, but cannot directly operate the UI. - ## Modules to Import ```js @@ -17,10 +19,10 @@ import worker from '@ohos.worker'; **System capability**: SystemCapability.Utils.Lang -| Name | Type | Readable| Writable| Description | +| Name | Type | Readable| Writable| Description | | --------------------------------- | --------------------------------------------------------- | ---- | ---- | ------------------------------------------------------------ | | workerPort9+ | [ThreadWorkerGlobalScope](#threadworkerglobalscope9) | Yes | Yes | Object of the worker thread used to communicate with the host thread. | -| parentPort(deprecated) | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscope) | Yes | Yes | Object of the worker thread used to communicate with the host thread.
This attribute is deprecated since API version 9. You are advised to use **workerPort9+** instead.| +| parentPort(deprecated) | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscope) | Yes | Yes | Object of the worker thread used to communicate with the host thread.
This attribute is supported since API version 7 and deprecated since API version 9.
You are advised to use **workerPort9+** instead.| ## WorkerOptions @@ -31,7 +33,9 @@ Provides options that can be set for the **Worker** instance to create. | Name| Type| Readable| Writable| Description | | ---- | -------- | ---- | ---- | -------------- | +| type | "classic" \| "module" | Yes | Yes | Mode in which the **Worker** instance executes the script. The default value is **classic**. The module **type** is not supported yet.| | name | string | Yes | Yes | Name of the worker thread.| +| shared | boolean | Yes | Yes | Sharing of the **Worker** instance is not supported yet.| ## ThreadWorker9+ @@ -166,7 +170,7 @@ workerInstance.postMessage(buffer, [buffer]); on(type: string, listener: WorkerEventListener): void -Adds an event listener for the worker thread. +Adds an event listener for the worker thread. This API provides the same functionality as [addEventListener9+](#addeventlistener9). **System capability**: SystemCapability.Utils.Lang @@ -216,7 +220,7 @@ workerInstance.once("alert", (e)=>{ off(type: string, listener?: WorkerEventListener): void -Removes an event listener for the worker thread. +Removes an event listener for the worker thread. This API provides the same functionality as [removeEventListener9+](#removeeventlistener9). **System capability**: SystemCapability.Utils.Lang @@ -231,6 +235,7 @@ Removes an event listener for the worker thread. ```js const workerInstance = new worker.ThreadWorker("workers/worker.js"); +// Use on, once, or addEventListener to add a listener for the "alert" event, and use off to remove the listener. workerInstance.off("alert"); ``` @@ -263,7 +268,7 @@ Defines the event handler to be called when the worker thread exits. The handler | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------ | -| code | number | No | Code indicating the worker thread exit state.| +| code | number | Yes | Code indicating the worker thread exit state.| **Example** @@ -272,6 +277,13 @@ const workerInstance = new worker.ThreadWorker("workers/worker.js"); workerInstance.onexit = function(e) { console.log("onexit"); } + +// onexit is executed in either of the following ways: +// Main thread: +workerInstance.terminate(); + +// Worker thread: +//parentPort.close() ``` @@ -287,7 +299,7 @@ Defines the event handler to be called when an exception occurs during worker ex | Name| Type | Mandatory| Description | | ------ | ------------------------- | ---- | ---------- | -| err | [ErrorEvent](#errorevent) | No | Error data.| +| err | [ErrorEvent](#errorevent) | Yes | Error data.| **Example** @@ -301,7 +313,7 @@ workerInstance.onerror = function(e) { ### onmessage9+ -onmessage?: (event: MessageEvent\) => void +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. @@ -309,16 +321,16 @@ Defines the event handler to be called when the host thread receives a message s **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | ---------------------- | -| event | [MessageEvent](#messageevent) | No | Message received.| +| Name| Type | Mandatory| Description | +| ------ | -------------------------------- | ---- | ---------------------- | +| event | [MessageEvents](#messageevents9) | Yes | Message received.| **Example** ```js const workerInstance = new worker.ThreadWorker("workers/worker.js"); workerInstance.onmessage = function(e) { - // e: MessageEvent. The usage is as follows: + // e: MessageEvents. The usage is as follows: // let data = e.data; console.log("onmessage"); } @@ -327,7 +339,7 @@ workerInstance.onmessage = function(e) { ### onmessageerror9+ -onmessageerror?: (event: MessageEvent\) => void +onmessageerror?: (event: MessageEvents) => void Defines the event handler to be called when the worker thread receives a message that cannot be serialized. The event handler is executed in the host thread. @@ -335,9 +347,9 @@ Defines the event handler to be called when the worker thread receives a message **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | ---------- | -| event | [MessageEvent](#messageevent) | No | Error data.| +| Name| Type | Mandatory| Description | +| ------ | -------------------------------- | ---- | ---------- | +| event | [MessageEvents](#messageevents9) | Yes | Error data.| **Example** @@ -355,7 +367,7 @@ workerInstance.onmessageerror= function(e) { addEventListener(type: string, listener: WorkerEventListener): void -Adds an event listener for the worker thread. +Adds an event listener for the worker thread. This API provides the same functionality as [on9+](#on9). **System capability**: SystemCapability.Utils.Lang @@ -380,7 +392,7 @@ workerInstance.addEventListener("alert", (e)=>{ removeEventListener(type: string, callback?: WorkerEventListener): void -Removes an event listener for the worker thread. +Removes an event listener for the worker thread. This API provides the same functionality as [off9+](#off9). **System capability**: SystemCapability.Utils.Lang @@ -395,6 +407,9 @@ Removes an event listener for the worker thread. ```js const workerInstance = new worker.ThreadWorker("workers/worker.js"); +workerInstance.addEventListener("alert", (e)=>{ + console.log("alert listener callback"); +}) workerInstance.removeEventListener("alert"); ``` @@ -423,7 +438,41 @@ Dispatches the event defined for the worker thread. ```js const workerInstance = new worker.ThreadWorker("workers/worker.js"); -workerInstance.dispatchEvent({type:"alert"}); +// Usage 1: +workerInstance.on("alert_on", (e)=>{ + console.log("alert listener callback"); +}) +workerInstance.once("alert_once", (e)=>{ + console.log("alert listener callback"); +}) +workerInstance.addEventListener("alert_add", (e)=>{ + console.log("alert listener callback"); +}) + +// The event listener created by once is removed after being executed once. +workerInstance.dispatchEvent({type:"alert_once", timeStamp:0}); +// The event listener created by on will be always valid and will not be proactively deleted. +workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); +workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); +// The event listener created by addEventListener will be always valid and will not be proactively deleted. +workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); +workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); + +// Usage 2: +// The event type can be customized, and the special types "message", "messageerror", and "error" exist. +// When type = "message", the event handler defined by onmessage will also be executed. +// When type = "messageerror", the event handler defined by onmessageerror will also be executed. +// When type = "error", the event handler defined by onerror will also be executed. +// removeEventListener or off can be used to remove an event listener that is created by addEventListener, on, or once. + +workerInstance.addEventListener("message", (e)=>{ + console.log("message listener callback"); +}) +workerInstance.onmessage = function(e) { + console.log("onmessage : message listener callback"); +} +// When dispatchEvent is called to distribute the "message" event, the callback passed in addEventListener and onmessage will be invoked. +workerInstance.dispatchEvent({type:"message", timeStamp:0}); ``` @@ -439,13 +488,16 @@ Removes all event listeners for the worker thread. ```js const workerInstance = new worker.ThreadWorker("workers/worker.js"); +workerInstance.addEventListener("alert", (e)=>{ + console.log("alert listener callback"); +}) workerInstance.removeAllListener(); ``` ## ThreadWorkerGlobalScope9+ -Implements communication between the worker thread and the host thread. The **postMessage** API is used to send messages to the host thread, and the **close** API is used to terminate the worker thread. The **DedicatedWorkerGlobalScope** class inherits from [GlobalScope9+](#globalscope9). +Implements communication between the worker thread and the host thread. The **postMessage** API is used to send messages to the host thread, and the **close** API is used to terminate the worker thread. The **ThreadWorkerGlobalScope** class inherits from [GlobalScope9+](#globalscope9). ### postMessage9+ @@ -515,7 +567,7 @@ parentPort.onmessage = function(e) { ### onmessage9+ -onmessage?: (event: MessageEvent\) => void +onmessage?: (this: ThreadWorkerGlobalScope, event: MessageEvents) => void Defines the event handler to be called when the worker thread receives a message sent by the host thread through **postMessage**. The event handler is executed in the worker thread. @@ -523,9 +575,10 @@ Defines the event handler to be called when the worker thread receives a message **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | ------------------------ | -| event | [MessageEvent](#messageevent) | No | Message received.| +| Name| Type | Mandatory| Description | +| ------ | ---------------------------------------------------- | ---- | ------------------------ | +| this | [ThreadWorkerGlobalScope](#threadworkerglobalscope9) | Yes | Caller. | +| event | [MessageEvents](#messageevents9) | Yes | Message received.| **Example** @@ -548,7 +601,7 @@ parentPort.onmessage = function(e) { ### onmessageerror9+ -onmessageerror?: (event: MessageEvent\) => void +onmessageerror?: (this: ThreadWorkerGlobalScope, event: MessageEvents) => void Defines the event handler to be called when the worker thread receives a message that cannot be deserialized. The event handler is executed in the worker thread. @@ -556,9 +609,10 @@ Defines the event handler to be called when the worker thread receives a message **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | ---------- | -| event | [MessageEvent](#messageevent) | No | Error data.| +| Name| Type | Mandatory| Description | +| ------ | -------------------------------- | ---- | ---------- | +| this | [ThreadWorkerGlobalScope](#threadworkerglobalscope9) | Yes | Caller. | +| event | [MessageEvents](#messageevents9) | Yes | Error data.| **Example** @@ -572,7 +626,7 @@ const workerInstance = new worker.ThreadWorker("workers/worker.js"); // worker.js import worker from '@ohos.worker'; const parentPort = worker.workerPort; -parentPort.onmessageerror= function(e) { +parentPort.onmessageerror = function(e) { console.log("worker.js onmessageerror") } ``` @@ -610,13 +664,13 @@ workerInstance.addEventListener("alert", (e)=>{ ## GlobalScope9+ -Implements the running environment of the worker thread. The **WorkerGlobalScope** class inherits from [WorkerEventTarget](#workereventtarget9). +Implements the running environment of the worker thread. The **GlobalScope** class inherits from [WorkerEventTarget](#workereventtarget9). ### Attributes **System capability**: SystemCapability.Utils.Lang -| Name| Type | Readable| Writable| Description | +| Name| Type | Readable| Writable| Description | | ---- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------- | | name | string | Yes | No | **Worker** instance specified when there is a new **Worker** instance.| | self | [GlobalScope](#globalscope9) & typeof globalThis | Yes | No | **GlobalScope** itself. | @@ -634,7 +688,7 @@ Defines the event handler to be called when an exception occurs during worker ex | Name| Type | Mandatory| Description | | ------ | ------------------------- | ---- | ---------- | -| ev | [ErrorEvent](#errorevent) | No | Error data.| +| ev | [ErrorEvent](#errorevent) | Yes | Error data.| **Example** @@ -653,22 +707,33 @@ parentPort.onerror = function(e){ } ``` +## MessageEvents9+ + +Holds the data transferred between worker threads. + +**System capability**: SystemCapability.Utils.Lang + +| Name| Type| Readable| Writable| Description | +| ---- | ---- | ---- | ---- | ------------------ | +| data | any | Yes | No | Data transferred between threads.| ## Worker(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker9+](#threadworker9) instead. Before using the following APIs, you must create a **Worker** instance. The **Worker** class inherits from [EventTarget](#eventtarget). -### constructor(deprecated) > **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker.constructor9+](#constructor9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker9+](#threadworker9) instead. + +### constructor(deprecated) constructor(scriptURL: string, options?: WorkerOptions) A constructor used to create a **Worker** instance. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.constructor9+](#constructor9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -753,13 +818,13 @@ In the stage model: ``` ### postMessage(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker.postMessage9+](#postmessage9) instead. - postMessage(message: Object, options?: PostMessageOptions): void Sends a message to the worker thread. The data type of the message must be sequenceable. For details about the sequenceable data types, see [More Information](#more-information). +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.postMessage9+](#postmessage9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -783,12 +848,12 @@ workerInstance.postMessage(buffer, [buffer]); ### on(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker.on9+](#on9) instead. - on(type: string, listener: EventListener): void -Adds an event listener for the worker thread. +Adds an event listener for the worker thread. This API provides the same functionality as [addEventListener(deprecated)](#addeventlistenerdeprecated). + +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.on9+](#on9) instead. **System capability**: SystemCapability.Utils.Lang @@ -811,13 +876,13 @@ workerInstance.on("alert", (e)=>{ ### once(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker.once9+](#once9) instead. - once(type: string, listener: EventListener): void Adds an event listener for the worker thread and removes the event listener after it is invoked once. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.once9+](#once9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -839,12 +904,12 @@ workerInstance.once("alert", (e)=>{ ### off(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker.off9+](#off9) instead. - off(type: string, listener?: EventListener): void -Removes an event listener for the worker thread. +Removes an event listener for the worker thread. This API provides the same functionality as [removeEventListener(deprecated)](#removeeventlistenerdeprecated). + +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.off9+](#off9) instead. **System capability**: SystemCapability.Utils.Lang @@ -859,19 +924,20 @@ Removes an event listener for the worker thread. ```js const workerInstance = new worker.Worker("workers/worker.js"); +// Use on, once, or addEventListener to add a listener for the "alert" event, and use off to remove the listener. workerInstance.off("alert"); ``` ### terminate(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker.terminate9+](#terminate9) instead. - terminate(): void Terminates the worker thread to stop it from receiving messages. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.terminate9+](#terminate9) instead. + **System capability**: SystemCapability.Utils.Lang **Example** @@ -884,20 +950,20 @@ workerInstance.terminate(); ### onexit(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker.onexit9+](#onexit9) instead. - onexit?: (code: number) => void Defines the event handler to be called when the worker thread exits. The handler is executed in the host thread. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.onexit9+](#onexit9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------ | -| code | number | No | Code indicating the worker thread exit state.| +| code | number | Yes | Code indicating the worker thread exit state.| **Example** @@ -906,25 +972,32 @@ const workerInstance = new worker.Worker("workers/worker.js"); workerInstance.onexit = function(e) { console.log("onexit"); } + +// onexit is executed in either of the following ways: +// Main thread: +workerInstance.terminate(); + +// Worker thread: +//parentPort.close() ``` ### onerror(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker.onerror9+](#onerror9) instead. - onerror?: (err: ErrorEvent) => void Defines the event handler to be called when an exception occurs during worker execution. The event handler is executed in the host thread. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.onerror9+](#onerror9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type | Mandatory| Description | | ------ | ------------------------- | ---- | ---------- | -| err | [ErrorEvent](#errorevent) | No | Error data.| +| err | [ErrorEvent](#errorevent) | Yes | Error data.| **Example** @@ -938,27 +1011,27 @@ workerInstance.onerror = function(e) { ### onmessage(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker.onmessage9+](#onmessage9) instead. - -onmessage?: (event: MessageEvent\) => void +onmessage?: (event: MessageEvent) => 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. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.onmessage9+](#onmessage9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | ---------------------- | -| event | [MessageEvent](#messageevent) | No | Message received.| +| Name| Type | Mandatory| Description | +| ------ | ------------------------------ | ---- | ---------------------- | +| event | [MessageEvent](#messageeventt) | Yes | Message received.| **Example** ```js const workerInstance = new worker.Worker("workers/worker.js"); workerInstance.onmessage = function(e) { - // e: MessageEvent. The usage is as follows: + // e: MessageEvent. The usage is as follows: // let data = e.data; console.log("onmessage"); } @@ -967,20 +1040,20 @@ workerInstance.onmessage = function(e) { ### onmessageerror(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker.onmessageerror9+](#onmessageerror9) instead. - -onmessageerror?: (event: MessageEvent\) => void +onmessageerror?: (event: MessageEvent) => void Defines the event handler to be called when the worker thread receives a message that cannot be serialized. The event handler is executed in the host thread. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.onmessageerror9+](#onmessageerror9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | ---------- | -| event | [MessageEvent](#messageevent) | No | Error data.| +| Name| Type | Mandatory| Description | +| ------ | ------------------------------ | ---- | ---------- | +| event | [MessageEvent](#messageeventt) | Yes | Error data.| **Example** @@ -994,16 +1067,16 @@ workerInstance.onmessageerror= function(e) { ## EventTarget(deprecated) > **NOTE**
-> This API is deprecated since API version 9. You are advised to use [WorkerEventTarget9+](#workereventtarget9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [WorkerEventTarget9+](#workereventtarget9) instead. ### addEventListener(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [addEventListener9+](#addeventlistener9) instead. - addEventListener(type: string, listener: EventListener): void -Adds an event listener for the worker thread. +Adds an event listener for the worker thread. This API provides the same functionality as [on(deprecated)](#ondeprecated). + +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [addEventListener9+](#addeventlistener9) instead. **System capability**: SystemCapability.Utils.Lang @@ -1026,12 +1099,12 @@ workerInstance.addEventListener("alert", (e)=>{ ### removeEventListener(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [removeEventListener9+](#removeeventlistener9) instead. - removeEventListener(type: string, callback?: EventListener): void -Removes an event listener for the worker thread. +Removes an event listener for the worker thread. This API provides the same functionality as [off(deprecated)](#offdeprecated). + +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [removeEventListener9+](#removeeventlistener9) instead. **System capability**: SystemCapability.Utils.Lang @@ -1046,19 +1119,22 @@ Removes an event listener for the worker thread. ```js const workerInstance = new worker.Worker("workers/worker.js"); +workerInstance.addEventListener("alert", (e)=>{ + console.log("alert listener callback"); +}) workerInstance.removeEventListener("alert"); ``` ### dispatchEvent(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [dispatchEvent9+](#dispatchevent9) instead. - dispatchEvent(event: Event): boolean Dispatches the event defined for the worker thread. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [dispatchEvent9+](#dispatchevent9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -1077,46 +1153,81 @@ Dispatches the event defined for the worker thread. ```js const workerInstance = new worker.Worker("workers/worker.js"); -workerInstance.dispatchEvent({type:"alert"}); -``` +// Usage 1: +workerInstance.on("alert_on", (e)=>{ + console.log("alert listener callback"); +}) +workerInstance.once("alert_once", (e)=>{ + console.log("alert listener callback"); +}) +workerInstance.addEventListener("alert_add", (e)=>{ + console.log("alert listener callback"); +}) +// The event listener created by once is removed after being executed once. +workerInstance.dispatchEvent({type:"alert_once", timeStamp:0}); +// The event listener created by on will not be proactively deleted. +workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); +workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); +// The event listener created by addEventListener will not be proactively deleted. +workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); +workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); + +// Usage 2: +// The event type can be customized, and the special types "message", "messageerror", and "error" exist. +// When type = "message", the event handler defined by onmessage will also be executed. +// When type = "messageerror", the event handler defined by onmessageerror will also be executed. +// When type = "error", the event handler defined by onerror will also be executed. +// removeEventListener or off can be used to remove an event listener that is created by addEventListener, on, or once. + +workerInstance.addEventListener("message", (e)=>{ + console.log("message listener callback"); +}) +workerInstance.onmessage = function(e) { + console.log("onmessage : message listener callback"); +} +// When dispatchEvent is called to distribute the "message" event, the callback passed in addEventListener and onmessage will be invoked. +workerInstance.dispatchEvent({type:"message", timeStamp:0}); +``` ### removeAllListener(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [removeAllListener9+](#removealllistener9) instead. - removeAllListener(): void Removes all event listeners for the worker thread. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [removeAllListener9+](#removealllistener9) instead. + **System capability**: SystemCapability.Utils.Lang **Example** ```js const workerInstance = new worker.Worker("workers/worker.js"); +workerInstance.addEventListener("alert", (e)=>{ + console.log("alert listener callback"); +}) workerInstance.removeAllListener(); ``` ## DedicatedWorkerGlobalScope(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9) instead. - Implements communication between the worker thread and the host thread. The **postMessage** API is used to send messages to the host thread, and the **close** API is used to terminate the worker thread. This class inherits from [WorkerGlobalScope](#workerglobalscope). +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9) instead. ### postMessage(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).postMessage9+ instead. - postMessage(messageObject: Object, options?: PostMessageOptions): void Sends a message to the host thread from the worker thread. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).postMessage9+ instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -1151,13 +1262,13 @@ parentPort.onmessage = function(e){ ### close(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).close9+ instead. - close(): void Terminates the worker thread to stop it from receiving messages. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).close9+ instead. + **System capability**: SystemCapability.Utils.Lang **Example** @@ -1179,20 +1290,21 @@ parentPort.onmessage = function(e) { ### onmessage(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).onmessage9+ instead. - -onmessage?: (event: MessageEvent\) => void +onmessage?: (this: DedicatedWorkerGlobalScope, event: MessageEvent) => void Defines the event handler to be called when the worker thread receives a message sent by the host thread through **postMessage**. The event handler is executed in the worker thread. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).onmessage9+ instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | ------------------------ | -| event | [MessageEvent](#messageevent) | No | Message received.| +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------ | +| this | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscopedeprecated) | Yes | Caller. | +| event | [MessageEvent](#messageeventt) | Yes | Message received.| **Example** @@ -1214,20 +1326,21 @@ parentPort.onmessage = function(e) { ### onmessageerror(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).onmessageerror9+ instead. - -onmessageerror?: (event: MessageEvent\) => void +onmessageerror?: (this: DedicatedWorkerGlobalScope, event: MessageEvent) => void Defines the event handler to be called when the worker thread receives a message that cannot be deserialized. The event handler is executed in the worker thread. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).onmessageerror9+ instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | ---------- | -| event | [MessageEvent](#messageevent) | No | Error data.| +| Name| Type | Mandatory| Description | +| ------ | ------------------------------ | ---- | ---------- | +| this | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscopedeprecated) | Yes | Caller.| +| event | [MessageEvent](#messageeventt) | Yes | Error data.| **Example** @@ -1240,7 +1353,7 @@ const workerInstance = new worker.Worker("workers/worker.js"); // worker.js import worker from '@ohos.worker'; const parentPort = worker.parentPort; -parentPort.onmessageerror= function(e) { +parentPort.onmessageerror = function(e) { console.log("worker.js onmessageerror") } ``` @@ -1252,7 +1365,7 @@ Specifies the object whose ownership needs to be transferred during data transfe **System capability**: SystemCapability.Utils.Lang -| Name | Type| Readable| Writable| Description | +| Name | Type | Readable| Writable| Description | | -------- | -------- | ---- | ---- | --------------------------------- | | transfer | Object[] | Yes | Yes | **ArrayBuffer** array used to transfer the ownership.| @@ -1263,21 +1376,21 @@ Defines the event. **System capability**: SystemCapability.Utils.Lang -| Name | Type| Readable| Writable| Description | -| --------- | -------- | ---- | ---- | ---------------------------------- | -| type | string | Yes | No | Type of the event. | -| timeStamp | number | Yes | No | Timestamp (accurate to millisecond) when the event is created.| +| Name | Type | Readable| Writable| Description | +| --------- | ------ | ---- | ---- | ---------------------------------- | +| type | string | Yes | No | Type of the event. | +| timeStamp | number | Yes | No | Timestamp (accurate to millisecond) when the event is created.| ## EventListener(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [WorkerEventListener9+](#workereventlistener9) instead. - (evt: Event): void | Promise<void> Implements event listening. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [WorkerEventListener9+](#workereventlistener9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -1308,38 +1421,38 @@ Provides detailed information about the exception that occurs during worker exec **System capability**: SystemCapability.Utils.Lang -| Name | Type| Readable| Writable| Description | -| -------- | -------- | ---- | ---- | -------------------- | -| message | string | Yes | No | Information about the exception.| -| filename | string | Yes | No | File where the exception is located.| -| lineno | number | Yes | No | Serial number of the line where the exception is located. | -| colno | number | Yes | No | Serial number of the column where the exception is located. | -| error | Object | Yes | No | Type of the exception. | +| Name | Type | Readable| Writable| Description | +| -------- | ------ | ---- | ---- | -------------------- | +| message | string | Yes | No | Information about the exception.| +| filename | string | Yes | No | File where the exception is located.| +| lineno | number | Yes | No | Serial number of the line where the exception is located. | +| colno | number | Yes | No | Serial number of the column where the exception is located. | +| error | Object | Yes | No | Type of the exception. | -## MessageEvent +## MessageEvent\ Holds the data transferred between worker threads. **System capability**: SystemCapability.Utils.Lang | Name| Type| Readable| Writable| Description | -| ---- | -------- | ---- | ---- | ------------------ | -| data | T | Yes | No | Data transferred between threads.| +| ---- | ---- | ---- | ---- | ------------------ | +| data | T | Yes | No | Data transferred between threads.| ## WorkerGlobalScope(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [GlobalScope9+](#globalscope9) instead. - Implements the running environment of the worker thread. The **WorkerGlobalScope** class inherits from [EventTarget](#eventtarget). +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [GlobalScope9+](#globalscope9) instead. + ### Attributes **System capability**: SystemCapability.Utils.Lang -| Name| Type | Readable| Writable| Description | +| Name| Type | Readable| Writable| Description | | ---- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------- | | name | string | Yes | No | **Worker** instance specified when there is a new **Worker** instance.| | self | [WorkerGlobalScope](#workerglobalscope) & typeof globalThis | Yes | No | **WorkerGlobalScope**. | @@ -1347,20 +1460,20 @@ Implements the running environment of the worker thread. The **WorkerGlobalScope ### onerror(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [GlobalScope9+](#globalscope9).onerror instead. - onerror?: (ev: ErrorEvent) => void Defines the event handler to be called when an exception occurs during worker execution. The event handler is executed in the worker thread. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [GlobalScope9+](#globalscope9).onerror instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type | Mandatory| Description | | ------ | ------------------------- | ---- | ---------- | -| ev | [ErrorEvent](#errorevent) | No | Error data.| +| ev | [ErrorEvent](#errorevent) | Yes | Error data.| **Example** @@ -1402,7 +1515,7 @@ Exception: When an object created through a custom class is passed, no serializa ```js // main.js import worker from '@ohos.worker'; -const workerInstance = new worker.Thread("workers/worker.js"); +const workerInstance = new worker.ThreadWorker("workers/worker.js"); workerInstance.postMessage("message from main to worker"); workerInstance.onmessage = function(d) { // When the worker thread passes obj2, data contains obj2, excluding the Init or SetName method. @@ -1414,12 +1527,9 @@ workerInstance.onmessage = function(d) { import worker from '@ohos.worker'; const parentPort = worker.workerPort; class MyModel { + name = "undefined" Init() { - this.name = "wzy" - this.age = 18 - } - SetName() { - this.name = "WZY" + this.name = "MyModel" } } parentPort.onmessage = function(d) { @@ -1460,6 +1570,7 @@ Each actor concurrently processes tasks of the main thread. For each actor, ther - To proactively destroy a worker thread, you can call **terminate()** or **parentPort.close()** of the newly created **Worker** instance. - Since API version 9, if a **Worker** instance in a non-running state (such as destroyed or being destroyed) calls an API, a business error is thrown. - Creating and terminating worker threads consume performance. Therefore, you are advised to manage available workers and reuse them. +- Do not use both **new worker.Worker** and **new worker.ThreadWorker** to create a **Worker** project. Otherwise, **Worker** functions abnormally. Since API version 9, you are advised to use [new worker.ThreadWorker](#constructor9). In API version 8 and earlier versions, you are advised to use [new worker.Worker](#constructordeprecated). ## Sample Code > **NOTE**
@@ -1589,3 +1700,4 @@ Configuration of the **build-profile.json5** file: } } ``` + diff --git a/en/application-dev/reference/apis/js-apis-xml.md b/en/application-dev/reference/apis/js-apis-xml.md index 945c5219bedb22f5efdd6f53b5d55d4cdd97f260..ec3549a4051ea6784a56be33c902fc167e1311a1 100644 --- a/en/application-dev/reference/apis/js-apis-xml.md +++ b/en/application-dev/reference/apis/js-apis-xml.md @@ -1,4 +1,4 @@ -# XML Parsing and Generation +# @ohos.xml (XML Parsing and Generation) > **NOTE** > @@ -24,10 +24,10 @@ A constructor used to create an **XmlSerializer** instance. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| buffer | ArrayBuffer \| DataView | Yes| **ArrayBuffer** or **DataView** for storing the XML information to write.| -| encoding | string | No| Encoding format.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ------------------------------------------------ | +| buffer | ArrayBuffer \| DataView | Yes | **ArrayBuffer** or **DataView** for storing the XML information to write.| +| encoding | string | No | Encoding format. | **Example** @@ -48,10 +48,10 @@ Sets an attribute. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| name | string | Yes| Key of the attribute.| -| value | string | Yes| Value of the attribute.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | --------------- | +| name | string | Yes | Key of the attribute. | +| value | string | Yes | Value of the attribute.| **Example** @@ -60,8 +60,8 @@ let arrayBuffer = new ArrayBuffer(1024); let bufView = new DataView(arrayBuffer); let thatSer = new xml.XmlSerializer(bufView); thatSer.startElement("note"); -thatSer.setAttributes("importance", "high"); -thatSer.endElement(); +thatSer.setAttributes("importance", "high"); +thatSer.endElement(); ``` @@ -75,9 +75,9 @@ Adds an empty element. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| name | string | Yes| Name of the empty element to add.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| name | string | Yes | Name of the empty element to add.| **Example** @@ -117,9 +117,9 @@ Writes the start tag based on the given element name. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| name | string | Yes| Name of the element.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| name | string | Yes | Name of the element.| **Example** @@ -145,11 +145,11 @@ Writes the end tag of the element. let arrayBuffer = new ArrayBuffer(1024); let bufView = new DataView(arrayBuffer); let thatSer = new xml.XmlSerializer(bufView); -thatSer.setNamespace("h", "http://www.w3.org/TR/html4/"); +thatSer.setNamespace("h", "https://www.w3.org/TR/html4/"); thatSer.startElement("table"); thatSer.setAttributes("importance", "high"); thatSer.setText("Happy"); -thatSer.endElement(); // => Happy +thatSer.endElement(); // => Happy ``` @@ -163,10 +163,10 @@ Sets the namespace for an element tag. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| prefix | string | Yes| Prefix of the element and its child elements.| -| namespace | string | Yes| Namespace to set.| +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ------------------------------ | +| prefix | string | Yes | Prefix of the element and its child elements. | +| namespace | string | Yes | Namespace to set.| **Example** @@ -174,9 +174,9 @@ Sets the namespace for an element tag. let arrayBuffer = new ArrayBuffer(1024); let thatSer = new xml.XmlSerializer(arrayBuffer); thatSer.setDeclaration(); -thatSer.setNamespace("h", "http://www.w3.org/TR/html4/"); +thatSer.setNamespace("h", "https://www.w3.org/TR/html4/"); thatSer.startElement("note"); -thatSer.endElement();// = >'\r\n'; +thatSer.endElement();// = >'\r\n'; ``` ### setComment @@ -189,9 +189,9 @@ Sets the comment. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| text | string | Yes| Comment to set.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------- | +| text | string | Yes | Comment to set.| **Example** @@ -214,9 +214,9 @@ Sets CDATA attributes. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| text | string | Yes| CDATA attribute to set.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ----------------- | +| text | string | Yes | CDATA attribute to set.| **Example** @@ -237,9 +237,9 @@ Sets **Text**. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| text | string | Yes| Content of the **Text** to set.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------- | +| text | string | Yes | Content of the **Text** to set.| **Example** @@ -263,9 +263,9 @@ Sets **DocType**. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| text | string | Yes| Content of **DocType** to set.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------- | +| text | string | Yes | Content of **DocType** to set.| **Example** @@ -289,10 +289,10 @@ Creates and returns an **XmlPullParser** object. The **XmlPullParser** object pa **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| buffer | ArrayBuffer \| DataView | Yes| **ArrayBuffer** or **DataView** that contains XML text information.| -| encoding | string | No| Encoding format. Only UTF-8 is supported.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ------------------------------------------ | +| buffer | ArrayBuffer \| DataView | Yes | **ArrayBuffer** or **DataView** that contains XML text information.| +| encoding | string | No | Encoding format. Only UTF-8 is supported. | **Example** @@ -324,9 +324,9 @@ Parses XML information. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| option | [ParseOptions](#parseoptions) | Yes| Options for controlling and obtaining the parsed information.| +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | -------------------------------- | +| option | [ParseOptions](#parseoptions) | Yes | Options for controlling and obtaining the parsed information.| **Example** @@ -372,13 +372,13 @@ Defines the XML parsing options. **System capability**: SystemCapability.Utils.Lang -| 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**.| -| attributeValueCallbackFunction | (name: string, value: string)=> boolean | No| Callback used to return **attributeValue**.| -| tokenValueCallbackFunction | (eventType: [EventType](#eventtype), value: [ParseInfo](#parseinfo))=> boolean | No| Callback used to return **tokenValue**.| +| 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**. | +| attributeValueCallbackFunction | (name: string, value: string) => boolean | No | Callback used to return **attributeValue**. | +| tokenValueCallbackFunction | (eventType: [EventType](#eventtype), value: [ParseInfo](#parseinfo)) => boolean | No | Callback used to return **tokenValue**. | ## ParseInfo @@ -395,8 +395,8 @@ Obtains the column line number, starting from 1. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------ | -------------- | | number | Column number obtained.| @@ -410,8 +410,8 @@ Obtains the depth of this element. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------ | -------------------- | | number | Depth obtained.| @@ -425,8 +425,8 @@ Obtains the current line number, starting from 1. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------ | -------------- | | number | Line number obtained.| @@ -440,8 +440,8 @@ Obtains the name of this element. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------ | ------------------ | | string | Element name obtained.| @@ -455,8 +455,8 @@ Obtains the namespace of this element. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------ | ------------------------ | | string | Namespace obtained.| @@ -470,8 +470,8 @@ Obtains the prefix of this element. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------ | ------------------ | | string | Element prefix obtained.| @@ -485,8 +485,8 @@ Obtains the text of the current event. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------ | ------------------------ | | string | Text content obtained.| @@ -500,8 +500,8 @@ Checks whether the current element is empty. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------- | ---------------------------- | | boolean | Returns **true** if the element is empty; returns **false** otherwise.| @@ -515,8 +515,8 @@ Checks whether the current text event contains only whitespace characters. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------- | -------------------------------------- | | boolean | Returns **true** if the text event contains only whitespace characters; returns **false** otherwise.| @@ -529,8 +529,8 @@ Obtains the number of attributes for the current start tag. **System capability**: SystemCapability.Utils.Lang **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------ | ---------------------- | | number | Number of attributes obtained.| @@ -540,16 +540,16 @@ Enumerates the events. **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.| +| 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. | diff --git a/en/application-dev/reference/apis/js-apis-zlib.md b/en/application-dev/reference/apis/js-apis-zlib.md index bc2a9504185453888cf8ba53416f38a44519c5a2..aa7d700534b09bb582ca96d61740fdd6ff9681b9 100644 --- a/en/application-dev/reference/apis/js-apis-zlib.md +++ b/en/application-dev/reference/apis/js-apis-zlib.md @@ -1,4 +1,4 @@ -# zlib +# @ohos.zlib The **zlib** module provides APIs for file compression and decompression. @@ -25,7 +25,7 @@ Zips a file. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the folder or file to zip. For details about the path, see [FA Model](js-apis-Context.md) or [Stage Model](js-apis-application-context.md).| +| inFile | string | Yes | Path of the folder or file to zip. For details about the path, see [FA Model](js-apis-inner-app-context.md) or [Stage Model](js-apis-application-context.md).| | outFile | string | Yes | Path of the zipped file. The file name extension is .zip. | | options | [Options](#options) | Yes | Optional parameters for the zip operation. | @@ -89,7 +89,7 @@ Unzips a file. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the folder or file to unzip. For details about the path, see [FA Model](js-apis-Context.md) or [Stage Model](js-apis-application-context.md).| +| inFile | string | Yes | Path of the folder or file to unzip. For details about the path, see [FA Model](js-apis-inner-app-context.md) or [Stage Model](js-apis-application-context.md).| | outFile | string | Yes | Path of the unzipped file. | | options | [Options](#options) | Yes | Optional parameters for the unzip operation. | @@ -131,7 +131,7 @@ Compresses a file. This API uses an asynchronous callback to return the result. | Name | Type | Mandatory| Description | | ----------------------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the folder or file to compress. For details about the path, see [FA Model](js-apis-Context.md) or [Stage Model](js-apis-application-context.md).| +| inFile | string | Yes | Path of the folder or file to compress. For details about the path, see [FA Model](js-apis-inner-app-context.md) or [Stage Model](js-apis-application-context.md).| | outFile | string | Yes | Path of the compressed file. | | options | [Options](#options) | Yes | Compression parameters. | | AsyncCallback<**void**> | callback | No | Callback used to return the result. If the operation is successful, **null** is returned; otherwise, a specific error code is returned. | @@ -179,7 +179,7 @@ Compresses a file. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the folder or file to compress. For details about the path, see [FA Model](js-apis-Context.md) or [Stage Model](js-apis-application-context.md).| +| inFile | string | Yes | Path of the folder or file to compress. For details about the path, see [FA Model](js-apis-inner-app-context.md) or [Stage Model](js-apis-application-context.md).| | outFile | string | Yes | Path of the compressed file. | | options | [Options](#options) | Yes | Compression parameters. | @@ -229,7 +229,7 @@ Decompresses a file. This API uses an asynchronous callback to return the result | Name | Type | Mandatory| Description | | ----------------------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the file to decompress. For details about the path, see [FA Model](js-apis-Context.md) or [Stage Model](js-apis-application-context.md).| +| inFile | string | Yes | Path of the file to decompress. For details about the path, see [FA Model](js-apis-inner-app-context.md) or [Stage Model](js-apis-application-context.md).| | outFile | string | Yes | Path of the decompressed file. | | options | [Options](#options) | Yes | Decompression parameters. | | AsyncCallback<**void**> | callback | No | Callback used to return the result. If the operation is successful, **null** is returned; otherwise, a specific error code is returned. | @@ -278,7 +278,7 @@ Decompress a file. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the file to decompress. For details about the path, see [FA Model](js-apis-Context.md) or [Stage Model](js-apis-application-context.md).| +| inFile | string | Yes | Path of the file to decompress. For details about the path, see [FA Model](js-apis-inner-app-context.md) or [Stage Model](js-apis-application-context.md).| | outFile | string | Yes | Path of the decompressed file. | | options | [Options](#options) | Yes | Decompression parameters. | diff --git a/en/application-dev/reference/arkui-js/figures/2.png b/en/application-dev/reference/arkui-js/figures/2.png deleted file mode 100644 index e506fd8f37b0e522d5925b509def595e5db653c3..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/2.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/3.png b/en/application-dev/reference/arkui-js/figures/3.png deleted file mode 100644 index 495f967777f91ce6e654c278683807ef6560809c..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/3.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125114.gif b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125114.gif deleted file mode 100644 index f4d097a34aef9e583651d11133dff575345f0272..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125114.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001152610806.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001152610806.png index b3a47a84d8086ca0806bc958f745f29821c47cc2..30ab31575654579e9a00a64d3d67f7420662f203 100644 Binary files a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001152610806.png and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001152610806.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001152862510.gif b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001152862510.gif deleted file mode 100644 index 6641ac7b1a0108d46bed16e64d65369c3515e8fb..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001152862510.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001176075554.gif b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001176075554.gif new file mode 100644 index 0000000000000000000000000000000000000000..16e7ff213bd5caf5a9802001d3ced2996c66e0bc Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001176075554.gif differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214619417.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214619417.png index 5da42e3e14d601745274cb62d914c6600620bb25..4f6c19892155444ecf63dab3ca80575a8046cc1b 100644 Binary files a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214619417.png and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214619417.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214704759.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214704759.png index 6afdd1b39e4bcb3664c7664a55b47b8537f4aeaa..0b4837fc44abc0e1005de3d1259ed924f2969806 100644 Binary files a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214704759.png and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214704759.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214811029.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214811029.png index 1d71cee4618f1f2822cea1031c9b0e5d602e0a9b..447e5b819bdddc57b98ccf7629d612eb499aec8b 100644 Binary files a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214811029.png and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214811029.png differ diff --git a/en/application-dev/reference/arkui-js/figures/pickerview1.gif b/en/application-dev/reference/arkui-js/figures/pickerview1.gif new file mode 100644 index 0000000000000000000000000000000000000000..e255be05356073aa2cd2a8cf1fe9080da0cce7bf Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/pickerview1.gif differ diff --git a/en/application-dev/reference/arkui-js/figures/pickerview2.gif b/en/application-dev/reference/arkui-js/figures/pickerview2.gif new file mode 100644 index 0000000000000000000000000000000000000000..ab30fdac7ab76ea4759a61c52cb326b53396d1dc Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/pickerview2.gif differ diff --git a/en/application-dev/reference/arkui-js/figures/pickerview5.gif b/en/application-dev/reference/arkui-js/figures/pickerview5.gif new file mode 100644 index 0000000000000000000000000000000000000000..fd3a65d962df54eca02bd0a30c06bc1254c11df7 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/pickerview5.gif differ diff --git a/en/application-dev/reference/arkui-js/figures/rainbow.gif b/en/application-dev/reference/arkui-js/figures/rainbow.gif new file mode 100644 index 0000000000000000000000000000000000000000..2dd14c106005c014e3daa8b6132f610280d06516 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/rainbow.gif differ diff --git a/en/application-dev/reference/arkui-js/figures/slider.png b/en/application-dev/reference/arkui-js/figures/slider.png index d0167fe6773371fa70d8bf32c3a3953ed1e1455b..be1ee572a931ec2f06614e5f17c5616eba462e85 100644 Binary files a/en/application-dev/reference/arkui-js/figures/slider.png and b/en/application-dev/reference/arkui-js/figures/slider.png differ diff --git a/en/application-dev/reference/arkui-js/figures/stepper.gif b/en/application-dev/reference/arkui-js/figures/stepper.gif new file mode 100644 index 0000000000000000000000000000000000000000..cfaa06512dacaa75acbc26a65f040c1b1caf32ff Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/stepper.gif differ diff --git a/en/application-dev/reference/arkui-js/figures/switch.gif b/en/application-dev/reference/arkui-js/figures/switch.gif new file mode 100644 index 0000000000000000000000000000000000000000..1ba8e3e6401faf9c70fe97e4a2eac2181eeec974 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/switch.gif differ diff --git a/en/application-dev/reference/arkui-js/figures/text.png b/en/application-dev/reference/arkui-js/figures/text.png new file mode 100644 index 0000000000000000000000000000000000000000..65f36bddf4015f870e67edf7a96d1457014d1b3c Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/text.png differ diff --git a/en/application-dev/reference/arkui-js/js-components-basic-button.md b/en/application-dev/reference/arkui-js/js-components-basic-button.md index 29061668cc3ddd2c59a2b057a97bb09970807693..bec475bb4689aea314bb6e251e3d270da78000f2 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-button.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-button.md @@ -18,7 +18,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri | Name | Type | Default Value | Mandatory | Description | | ---------------------- | ------- | ----- | ---- | ---------------------------------------- | -| type | string | - | No | Button type. The value cannot be dynamically updated. If this attribute is not set, a capsule-like button is displayed. Unlike the capsule button, the capsule-like button allows its corners to be configured using **border-radius**. Available button types are as follows:
- **capsule**: capsule button with fillets, background color, and text.
- **circle**: circle button that can accommodate icons.
- **text**: text button, which displays only text.
- **arc**: arc button. This value is applicable to wearables only.
- **download**: download button, with an extra download progress bar.| +| type | string | - | No | Button type. The value cannot be dynamically updated. By default, a capsule-like button is displayed. Unlike the capsule button, the capsule-like button allows its corners to be configured using **border-radius**. The options are as follows:
- **capsule**: capsule button with fillets, background color, and text.
- **circle**: circle button that can accommodate icons.
- **text**: text button, which displays only text.
- **arc**: arc button. This value is applicable to wearables only.
- **download**: download button, with an extra download progress bar.| | value | string | - | No | Text value of the button. | | icon | string | - | No | Path of the button icon. The supported icon formats are JPG, PNG, and SVG. | | placement5+ | string | end | No | Position of the button icon in text. This attribute is valid only when **type** is not set. Available values are as follows:
- **start**: The button icon is at the beginning of the text.
- **end**: The button icon is at the end of the text.
- **top**: The button icon is at the top of the text.
- **bottom**: The button icon is at the bottom of the text.| @@ -39,7 +39,7 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md | allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.
If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.| | font-style | string | normal | No | Font style of the button. | | font-weight | number \| string | normal | No | Font weight of the button. For details, see **font-weight** of the [**\** component](../arkui-js/js-components-basic-text.md#styles).| -| font-family | <string> | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text. | +| font-family | <string> | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.| | icon-width | <length> | - | No | Width of the internal icon of a circle button. The entire circle button is filled by default.
This style must be set when the icon uses the SVG image.| | icon-height | <length> | - | No | Height of the internal icon of a circle button. The entire circle button is filled by default.
This style must be set when the icon uses the SVG image.| | radius | <length> | - | No | Corner radius of the button. For a circle button, this style takes precedence over **width** and **height** in the universal styles.| @@ -55,8 +55,8 @@ In addition to the **background-color**, **opacity**, **display**, **visibility* | font-size | <length> | 37.5px | No | Font size of the arc button. | | allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings. | | font-style | string | normal | No | Font style of the arc button. | -| font-weight | number \| string | normal | No | Font weight of the arc button. For details, see **font-weight** of the [**\** component](../arkui-js/js-components-basic-text.md#styles).| -| font-family | <string> | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text. | +| font-weight | number \| string | normal | No | Font weight of the arc button. For details, see **font-weight** of the [**\**](../arkui-js/js-components-basic-text.md#styles) component. | +| font-family | <string> | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.| ## Events diff --git a/en/application-dev/reference/arkui-js/js-components-basic-chart.md b/en/application-dev/reference/arkui-js/js-components-basic-chart.md index 26ac1ef03d97536474103465f8f61cc5108ab126..a11c5aaabf8fa65f15399d5e8b13d9e040e77397 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-chart.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-chart.md @@ -22,7 +22,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri | Name | Type | Default Value | Mandatory | Description | | ------------------------------ | ---------------------------------------- | ---- | ---- | ---------------------------------------- | -| type | string | line | No | Chart type. Dynamic modification is not supported. Available values include:
- **bar**: bar chart.
- **line**: line chart.
- **gauge**: gauge chart.
- **progress**5+: circle chart of progresses.
- **loading**5+: circle chart of loading processes.
- **rainbow**5+: circle chart of proportions.| +| type | string | line | No | Chart type. Dynamic modification is not supported. Available values include:
- **bar**: bar chart
- **line**: line chart
- **gauge**: gauge chart
- **progress**5+: circle chart of progresses
- **loading**5+: circle chart of loading processes
- **rainbow**5+: circle chart of proportions| | options | ChartOptions | - | No | Chart parameters. You must set parameters for bar charts and line charts. Parameter settings for gauge charts do not take effect. You can set the minimum value, maximum value, scale, and line width of the x-axis or y-axis, whether to display the x-axis and y-axis, and whether the line is smooth. Dynamic modification is not supported.| | datasets | Array<ChartDataset> | - | No | Data sets. You must set data sets for bar charts and line charts. Data sets for a gauge chart do not take effect. You can set multiple datasets and their background colors.| | segments5+ | DataSegment \| Array<DataSegment> | - | No | Data structures used by **progress**, **loading**, and **rainbow** charts.
**DataSegment** is available for **progress** and **loading** charts.
**Array<DataSegment>** is available for **rainbow** charts. A maximum of nine **DataSegment**s are supported in the array.| @@ -99,7 +99,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri | description | string | - | No | Description text of the point. | | textLocation | string | - | No | Position of the description text relative to the point. Available values are as follows: **top**: above the point
**bottom**: below the point
**none**: not displayed| | textColor | <color> | \#000000 | No | Color of the description text. | -| lineDash | string | solid | No | Dashed line pattern. You can set the dash length and space length between the dashes. For example, **"dashed, 5, 5"** indicates a dashed line with each dash in 5 px and a 5 px space between each two dashes. Default value **"solid"** indicates a solid line.| +| lineDash | string | solid | No | Dashed line pattern. You can set the dash length and space length between the dashes. - **"dashed, 5, 5"**: dashed line with each dash in 5 px and a 5 px space between each two dashes. Default value **"solid"** indicates a solid line.| | lineColor | <color> | \#000000 | No | Line color. If this attribute is not set, the value of **strokeColor** is used. | **Table 9** DataSegment5+ @@ -144,7 +144,7 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md | center-x | <length> | - | No | Center of the scale bar of the gauge component. This style is supported by the gauge chart only. This style takes precedence over the **position** style in the common styles, and must be used together with **center-y** and **radius**. This style is supported by the gauge chart only.| | center-y | <length> | - | No | Center of the scale bar of the gauge component. This style is supported by the gauge chart only. This style takes precedence over the **position** style in the common styles, and must be used together with **center-x** and **radius**. This style is supported by the gauge chart only.| | radius | <length> | - | No | Radius of the scale bar of the gauge component. This style is supported by the gauge chart only. This style takes precedence over the **width** and **height** in the common styles, and must be used together with **center-x** and **center-y**. This style is supported by the gauge chart only.| -| colors | Array | - | No | Color of each section for the scale bar of the gauge component.
For example, **colors: \#ff0000, #00ff00**. This style is supported by the gauge chart only.| +| colors | Array | - | No | Color of each section for the scale bar of the gauge component.
For example, **colors: \#ff0000, \#00ff00**. This style is supported by the gauge chart only.| | weights | Array | - | No | Weight of each section for the scale bar of the gauge component.
For example, **weights: 2, 2**. This style is supported by the gauge chart only.| | font-family5+ | Array | - | No | Font style of the description text. You can use a [custom font](../arkui-js/js-components-common-customizing-font.md).| | font-size5+ | <length> | - | No | Font size of the description text. | @@ -161,7 +161,7 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. | Name | Parameter | Description | | ------ | ---------------------------------------- | ---------------------------------------- | -| append | {
serial: number, // Set the data subscript of the line chart to be updated.
data: Array<number>, // Set the new data.
} | Data is dynamically added to an existing data sequence. The target sequence is specified based on **serial**, which is the subscript of the datasets array and starts from 0. **datasets[index].data** is not updated. Only line charts support this attribute. The value is incremented by 1 based on the horizontal coordinate and is related to the **xAxis min/max** setting.| +| append | {
serial: number,
data: Array<number>,
} | Data is dynamically added to an existing data sequence. The target sequence is specified based on **serial**, which is the subscript of the datasets array and starts from 0. For example, if the value of **serial** is **index**, use **data** to update **datasets[index].data**. Only line charts support this attribute. The value is incremented by 1 based on the horizontal coordinate and is related to the **xAxis min/max** setting.| ## Example @@ -212,24 +212,24 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. 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: true } ], lineOps: { xAxis: { min: 0, max: 20, - display: false, + display: false }, yAxis: { min: 0, max: 1000, - display: false, + display: false }, series: { lineStyle: { width: "5px", - smooth: true, + smooth: true }, headPoint: { shape: "circle", @@ -237,14 +237,14 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. strokeWidth: 5, fillColor: '#ffffff', strokeColor: '#007aff', - display: true, + display: true }, loop: { margin: 2, - gradient: true, + gradient: true } } - }, + } }, addData() { this.$refs.linechart.append({ @@ -295,15 +295,15 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. barData: [ { fillColor: '#f07826', - data: [763, 550, 551, 554, 731, 654, 525, 696, 595, 628], + data: [763, 550, 551, 554, 731, 654, 525, 696, 595, 628] }, { fillColor: '#cce5ff', - data: [535, 776, 615, 444, 694, 785, 677, 609, 562, 410], + data: [535, 776, 615, 444, 694, 785, 677, 609, 562, 410] }, { fillColor: '#ff88bb', - data: [673, 500, 574, 483, 702, 583, 437, 506, 693, 657], + data: [673, 500, 574, 483, 702, 583, 437, 506, 693, 657] }, ], barOps: { @@ -311,14 +311,14 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. min: 0, max: 20, display: false, - axisTick: 10, + axisTick: 10 }, yAxis: { min: 0, max: 1000, - display: false, - }, - }, + display: false + } + } } } ``` @@ -353,3 +353,76 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. ``` ![en-us_image_0000001127125264](figures/en-us_image_0000001127125264.png) + +4. Circle chart of progresses, loading progresses, or proportions + ```html + +
+ progress Example + + + + loading Example + + + + rainbow Example + + + +
+ ``` + ```css + /* xxx.css */ + .container { + flex-direction: column; + justify-content: center; + align-items: center; + } + .chart-region { + height: 400px; + width: 700px; + margin-top: 10px; + } + .text { + margin-top: 30px; + } + ``` + ```js + // xxx.js + export default { + data: { + progressdata: { + value: 50, + name: 'progress' + }, + loadingdata: { + startColor: "#ffc0cb", + endColor: "#00bfff", + }, + rainbowdata: [ + { + value: 50, + name: 'item1' + }, + { + value: 10, + name: 'item2' + }, + { + value: 20, + name: 'item3' + }, + { + value: 10, + name: 'item4' + }, + { + value: 10, + name: 'item5' + } + ] + } + } + ``` + ![rainbow](figures/rainbow.gif) diff --git a/en/application-dev/reference/arkui-js/js-components-basic-image.md b/en/application-dev/reference/arkui-js/js-components-basic-image.md index 53b335e34c30317f99f789bd22358bad5d8ad279..89643b3aaa104e4f15b91db6098e74611c1aa42d 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-image.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-image.md @@ -31,7 +31,7 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md | object-fit | string | cover | No | Image scale type. This style is not supported for SVG images. For details about available values, see **object-fit**.| | match-text-direction | boolean | false | No | Whether image orientation changes with the text direction. This style is not supported for SVG images. | | fit-original-size | boolean | false | No | Whether the **\** component adapts to the image source size when its width and height are not set. If this style is set to **true**, **object-fit** will not take effect. This style is not supported for SVG images.| -| object-position7+ | string | 0px 0px | No | Position of an image in the component.
The options are as follows:
1. Pixels. For example, **15px 15px** indicates the moving position along the x-axis or y-axis.
2. Characters. Optional values are as follows:
- **left**: The image is displayed on the left of the component.
- **top** The image is displayed on the top of the component.
- **right** The image is displayed on the right of the component.
- **bottom** The image is displayed at the bottom of the component.| +| object-position7+ | string | 0px 0px | No | Position of the image in the component.
The options are as follows:
1. Pixels, in px. For example, **15px 15px** indicates the position to move along the x-axis or y-axis.
2. Characters. Optional values are as follows:
- **left**: The image is displayed on the left of the component.<
- **top**: The image is displayed on the top of the component.
- **right**: The image is displayed on the right of the component.
- **bottom**: The image is displayed at the bottom of the component.| **Table 1** object-fit @@ -56,16 +56,18 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md > 1. If the **\** component is too small to afford the SVG image, the SVG image is cropped and only its upper left part is displayed in the component. > > 2. If the **\** component is big enough to afford the SVG image, this SVG image is displayed in the upper left corner of the component. +> +> - For SVG images, only the following tags are included in the supported list: **svg**, **rect**, **circle**, **ellipse**, **path**, **line**, **polyline**, **polygon**, **animate**, **animateMotion**, and **animateTransform**. ## Events In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported. -| Name | Parameter | Description | -| -------------- | ---------------------------------------- | ------------------------- | -| complete(Rich) | {
width: width,
height: height
} | Triggered when an image is successfully loaded. The loaded image size is returned.| -| error(Rich) | {
width: width,
height: height
} | Triggered when an exception occurs during image loading. In this case, the width and height are **0**. | +| Name | Parameter | Description | +| -------- | ---------------------------------------- | ------------------------- | +| complete | {
width: width,
height: height
} | Triggered when an image is successfully loaded. The loaded image size is returned.| +| error | {
width: width,
height: height
} | Triggered when an exception occurs during image loading. In this case, the width and height are **0**. | ## Methods diff --git a/en/application-dev/reference/arkui-js/js-components-basic-input.md b/en/application-dev/reference/arkui-js/js-components-basic-input.md index 2ce4c7d3b07a6e8dbdcd47c4d3143ec8e4b285df..13c42c2f80fe31b010cf38829a6d3a388bb19629 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-input.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-input.md @@ -20,44 +20,44 @@ Not supported In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported. -| Name | Type | Default Value | Mandatory | Description | -| -------------------------------- | ----------------------- | ------------- | --------- | ---------------------------------------- | -| type | string | text
| No | Type of the input component. Available values include **text**, **email**, **date**, **time**, **number**, **password**, **button**, **checkbox**, and **radio**.
The **text**, **email**, **date**, **time**, **number**, and **password** types can be dynamically switched and modified.
The **button**, **checkbox**, and **radio** types cannot be dynamically modified.
- **button**: a button that can be clicked.
- **checkbox**: a check box.
- **radio**: a radio button that allows users to select one from multiple others with the same name.
- **text**: a single-line text field.
- **email**: a field used for an email address.
- **date**: date component, including the year, month, and day, but excluding time.
- **time**: time component, without the time zone.
- **number**: field for entering digits.
- **password**: password field, in which characters will be shielded. | -| checked | boolean | false | No | Whether the **\** component is selected. This attribute is valid only when **type** is set to **checkbox** or **radio**. | -| name | string | - | No | Name of the **\** component.
This attribute is mandatory when **type** is set to **radio**. | -| value | string | - | No | Value of the **\** component. When **type** is **radio**, this attribute is mandatory and the value must be unique for radio buttons with the same name. | -| placeholder | string | - | No | Content of the hint text. This attribute is available only when the component type is set to **text** \|email\|date\|time\|number\|**password**. | -| maxlength | number | - | No | Maximum number of characters that can be entered in the input box. The empty value indicates no limit. | -| enterkeytype | string | default | No | Type of the **Enter** key on the soft keyboard. The value cannot be dynamically updated.
Available values include:
- default
- next
- go
- done
- send
- search
Except for the **next** type, clicking the Enter key hides the soft keyboard. | -| headericon | string | - | No | Icon resource path before text input. This icon does not support click events and is unavailable for **button**, **checkbox**, and **radio** types. The supported icon image formats are JPG, PNG, and SVG. | -| showcounter5+ | boolean | false | No | Whether to display the character counter for an input box. This attribute takes effect only when **maxlength** is set. | -| menuoptions5+ | Array<MenuOption> | - | No | Menu options displayed after users click the **More** button. | -| autofocus6+ | boolean | false | No | Whether to automatically obtain focus.
This attribute setting does not take effect on the application home page. You can enable a text box on the home page to automatically obtain focus, by delaying the **focus** method call (for about 100–500 ms) in **onActive**. | -| selectedstart6+ | number | -1 | No | Start position for text selection. | -| selectedend6+ | number | -1 | No | End position for text selection. | -| softkeyboardenabled6+ | boolean | true | No | Whether to display the soft keyboard during editing. | -| showpasswordicon6+ | boolean | true | No | Whether to display the icon at the end of the password text box. This attribute is available only when **type** is set to **password**. | +| Name | Type | Default Value | Mandatory | Description | +| -------------------------------- | ----------------------- | --------- | ---- | ---------------------------------------- | +| type | string | text
| No | Type of the input component. Available values include **text**, **email**, **date**, **time**, **number**, **password**, **button**, **checkbox**, and **radio**.
The **text**, **email**, **date**, **time**, **number**, and **password** types can be dynamically switched and modified.
The **button**, **checkbox**, and **radio** types cannot be dynamically modified.
- **button**: a button that can be clicked.
- **checkbox**: a check box.
- **radio**: a radio button that allows users to select one from multiple others with the same name.
- **text**: a single-line text field.
- **email**: a field used for an email address.
- **date**: date component, including the year, month, and day, but excluding time.
- **time**: time component, without the time zone.
- **number**: field for entering digits.
- **password**: password field, in which characters will be shielded.| +| checked | boolean | false | No | Whether the **\** component is selected. This attribute is valid only when **type** is set to **checkbox** or **radio**. | +| name | string | - | No | Name of the **\** component.
This attribute is mandatory when **type** is set to **radio**. | +| value | string | - | No | Value of the **\** component. When **type** is **radio**, this attribute is mandatory and the value must be unique for radio buttons with the same name.| +| placeholder | string | - | No | Content of the hint text. This attribute is available only when the component type is set to **text** \|email\|date\|time\|number\|**password**.| +| maxlength | number | - | No | Maximum number of characters that can be entered in the input box. The empty value indicates no limit. | +| enterkeytype | string | default | No | Type of the **Enter** key on the soft keyboard. The value cannot be dynamically updated.
Available values include:
- default
- next
- go
- done
- send
- search
Except for the **next** type, clicking the Enter key hides the soft keyboard.| +| headericon | string | - | No | Icon resource path before text input. This icon does not support click events and is unavailable for **button**, **checkbox**, and **radio** types. The supported icon image formats are JPG, PNG, and SVG.| +| showcounter5+ | boolean | false | No | Whether to display the character counter for an input box. This attribute takes effect only when **maxlength** is set. | +| menuoptions5+ | Array<MenuOption> | - | No | Menu options displayed after users click the **More** button. | +| autofocus6+ | boolean | false | No | Whether to automatically obtain focus.
This attribute setting does not take effect on the application home page. You can enable a text box on the home page to automatically obtain focus, by delaying the **focus** method call (for about 100–500 ms) in **onActive**.| +| selectedstart6+ | number | -1 | No | Start position for text selection. | +| selectedend6+ | number | -1 | No | End position for text selection. | +| softkeyboardenabled6+ | boolean | true | No | Whether to display the soft keyboard during editing. | +| showpasswordicon6+ | boolean | true | No | Whether to display the icon at the end of the password text box. This attribute is available only when **type** is set to **password**. | **Table 1** MenuOption5+ -| Name | Type | Description | -| ------- | ------ | ----------------------------------- | -| icon | string | Path of the icon for a menu option. | -| content | string | Text content of a menu option. | +| Name | Type | Description | +| ------- | ------ | ----------- | +| icon | string | Path of the icon for a menu option.| +| content | string | Text content of a menu option.| ## Styles In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported. -| Name | Type | Default Value | Mandatory | Description | -| ------------------------ | ---------------- | ------------- | --------- | ---------------------------------------- | -| color | <color> | \#e6000000 | No | Font color of the single-line text box or button. | -| font-size | <length> | 16px | No | Font size of the single-line text box or button. | -| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.
If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart. | -| placeholder-color | <color> | \#99000000 | No | Color of the hint text in the single-line text box. This attribute is available only when **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**. | -| font-weight | number \| string | normal | No | Font weight of the single-line text box or button. For details, see **font-weight** of the [**\**](../arkui-js/js-components-basic-text.md) component. | -| caret-color6+ | <color> | - | No | Color of the caret. | +| Name | Type | Default Value | Mandatory | Description | +| ------------------------ | -------------------------- | ---------- | ---- | ---------------------------------------- | +| color | <color> | \#e6000000 | No | Font color of the single-line text box or button. | +| font-size | <length> | 16px | No | Font size of the single-line text box or button. | +| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.
If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.| +| placeholder-color | <color> | \#99000000 | No | Color of the hint text in the single-line text box. This attribute is available only when the component type is set to **text**, **email**, **date**, **time**, **number**, or **password**. | +| font-weight | number \| string | normal | No | Font weight of the single-line text box or button. For details, see **font-weight** of the [**\**](../arkui-js/js-components-basic-text.md) component. | +| caret-color6+ | <color> | - | No | Color of the caret. | ## Events @@ -66,27 +66,27 @@ In addition to the [universal events](../arkui-js/js-components-common-events.md - When **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**, the following events are supported. - | Name | Parameter | Description | + | Name | Parameter | Description | | ------------------------- | ---------------------------------------- | ---------------------------------------- | - | change | {
value: inputValue
} | Triggered when the content entered in the input box changes. The most recent content entered by the user is returned.
If you change the **value** attribute directly, this event will not be triggered. | - | enterkeyclick | {
value: enterKey
} | Triggered when the **Enter** key on the soft keyboard is clicked. The type of the **Enter** key is returned, which is of the number type. Available values are as follows:
- **2**: returned if **enterkeytype** is **go**.
- **3**: returned if **enterkeytype** is **search**.
- **4**: returned if **enterkeytype** is **send**.
- **5**: returned if **enterkeytype** is **next**.
- **6**: returned if **enterkeytype** is **default**, **done**, or is not set. | - | translate5+ | {
value: selectedText
} | Triggered when users click the translate button in the menu displayed after they select a text segment. The selected text content is returned. | - | share5+ | {
value: selectedText
} | Triggered when users click the share button in the menu displayed after they select a text segment. The selected text content is returned. | - | search5+ | {
value: selectedText
} | Triggered when users click the search button in the menu displayed after they select a text segment. The selected text content is returned. | - | optionselect5+ | {
index: optionIndex,
value: selectedText
} | Triggered when users click a menu option in the menu displayed after they select a text segment. This event is valid only when the **menuoptions** attribute is set. The option index and selected text content are returned. | - | selectchange6+ | {
start: number,
end: number
} | Triggered when the text selection changes. | + | change | {
value: inputValue
} | Triggered when the content entered in the input box changes. The most recent content entered by the user is returned.
If you change the **value** attribute directly, this event will not be triggered.| + | enterkeyclick | {
value: enterKey
} | Triggered when the **Enter** key on the soft keyboard is clicked. The type of the **Enter** key is returned, which is of the number type. Available values are as follows:
- **2**: returned if **enterkeytype** is **go**.
- **3**: returned if **enterkeytype** is **search**.
- **4**: returned if **enterkeytype** is **send**.
- **5**: returned if **enterkeytype** is **next**.
- **6**: returned if **enterkeytype** is **default**, **done**, or is not set.| + | translate5+ | {
value: selectedText
} | Triggered when users click the translate button in the menu displayed after they select a text segment. The selected text content is returned.| + | share5+ | {
value: selectedText
} | Triggered when users click the share button in the menu displayed after they select a text segment. The selected text content is returned.| + | search5+ | {
value: selectedText
} | Triggered when users click the search button in the menu displayed after they select a text segment. The selected text content is returned.| + | optionselect5+ | {
index: optionIndex,
value: selectedText
} | Triggered when users click a menu option in the menu displayed after they select a text segment. This event is valid only when the **menuoptions** attribute is set. The option index and selected text content are returned.| + | selectchange6+ | {
start: number,
end: number
} | Triggered when the text selection changes. | - When **type** is set to **checkbox** or **radio**, the following events are supported. - | Name | Parameter | Description | - | ------ | --------------------------------- | ---------------------------------------- | - | change | {
checked:true \| false
} | Triggered when the checked status of the **checkbox** or **radio** button changes. | + | Name | Parameter | Description | + | ------ | ---------------------------------------- | ---------------------------------------- | + | change | {
checked:true \| false
} | Triggered when the checked status of the **checkbox** or **radio** button changes.| ## Methods In addition to the [universal methods](../arkui-js/js-components-common-methods.md), the following methods are supported. -| Name | Parameter | Description | +| Name | Parameter | Description | | ------------------- | ---------------------------------------- | ---------------------------------------- | | focus | {
focus: true\|false
}:
If **focus** is not passed, the default value **true** is used. | Obtains or loses focus. When **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**, the input method can be displayed or collapsed. | | showError | {
error: string
} | Displays the error message. This method is available when **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**. | @@ -102,38 +102,40 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. headericon="/common/search.svg" placeholder="Please input text" onchange="change" onenterkeyclick="enterkeyClick"> - + ``` ```css /* xxx.css */ .content { - width: 60%; + width: 100%; flex-direction: column; align-items: center; } .input { + width: 60%; placeholder-color: gray; } .button { + width: 60%; background-color: gray; margin-top: 20px; - } + } ``` - + ```js // xxx.js - import prompt from '@system.prompt' + import promptAction from '@ohos.promptAction' export default { change(e){ - prompt.showToast({ + promptAction.showToast({ message: "value: " + e.value, duration: 3000, }); }, enterkeyClick(e){ - prompt.showToast({ + promptAction.showToast({ message: "enterkey clicked", duration: 3000, }); @@ -143,11 +145,11 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. error: 'error text' }); }, - } + } ``` ![1-2](figures/1-2.png) - + 2. Common button ```html @@ -190,10 +192,10 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. ```js // xxx.js - import prompt from '@system.prompt' + import promptAction from '@ohos.promptAction' export default { checkboxOnChange(e) { - prompt.showToast({ + promptAction.showToast({ message:'checked: ' + e.checked, duration: 3000, }); @@ -225,11 +227,11 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. ```js // xxx.js - import prompt from '@system.prompt' + import promptAction from '@ohos.promptAction' export default { onRadioChange(inputValue, e) { if (inputValue === e.value) { - prompt.showToast({ + promptAction.showToast({ message: 'The chosen radio is ' + e.value, duration: 3000, }); diff --git a/en/application-dev/reference/arkui-js/js-components-basic-label.md b/en/application-dev/reference/arkui-js/js-components-basic-label.md index 3adcd954efec63b002f90f923cd8fe5b5dfdd500..9a45521ecb6ed4d614ab43abafdcd6317c31530a 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-label.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-label.md @@ -35,8 +35,8 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md | font-size | <length> | 30px | No | Font size. | | allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.
For details about how to make the configuration take effect dynamically, see the **config-changes** attribute in the **config.json** file.| | letter-spacing | <length> | 0px | No | Character spacing (px). | -| font-style | string | normal | No | Font style. Available values are as follows:
- **normal**: standard font style
- **italic**: italic font style| -| font-weight | number \| string | normal | No | Font width. For the number type, the value ranges from 100 to 900. The default value is 400. A larger value indicates a larger font width.
The value of the number type must be an integer multiple of 100.
The value of the string type can be **lighter**, **normal**, **bold**, or **bolder**.| +| font-style | string | normal | No | Font style. Available values are as follows:
- **normal**: standard font style.
- **italic**: italic font style.| +| font-weight | number \| string | normal | No | Font weight. For the number type, the value ranges from 100 to 900. The default value is 400. A larger value indicates a heavier font weight.
The value of the number type must be an integer multiple of 100.
The value of the string type can be **lighter**, **normal**, **bold**, or **bolder**.| | text-decoration | string | none | No | Text decoration. Available values are as follows:
- **underline**: An underline is used.
- **line-through**: A strikethrough is used.
- **none**: The standard text is used.| | text-align | string | start
| No | Text alignment mode. Available values are as follows:
- **left**: The text is left-aligned.
- **center**: The text is center-aligned.
- **right**: The text is right-aligned.
- **start**: The text is aligned with the direction in which the text is written.
- **end**: The text is aligned with the opposite direction in which the text is written.
If the text width is not specified, the alignment effect may not be obvious when the text width is the same as the width of the parent container.| | line-height | <length> | 0px | No | Text line height. When this parameter is set to **0px**, the text line height is not limited and the font size is adaptive. | @@ -46,7 +46,7 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md | min-font-size | <length> | - | No | Minimum font size in the text. This style must be used together with **max-font-size**. The font size can be changed dynamically. After the maximum and minimum font sizes are set, **font-size** does not take effect.| | max-font-size | <length> | - | No | Maximum font size in the text. This style must be used together with **min-font-size**. The font size can be changed dynamically. After the maximum and minimum font sizes are set, **font-size** does not take effect.| | font-size-step | <length> | 1px | No | Step for dynamically adjusting the font size in the text. The minimum and maximum font sizes must be set. | -| prefer-font-sizes | <array> | - | No | Preset preferred font sizes. For dynamic font size adjustment, the preset sizes are used to match the maximum number of lines in the text. If the preferred font sizes were not set, the font size will be adjusted based on the maximum and minimum font sizes and the step you have set. If the maximum number of lines in the text cannot be met, **text-overflow** is used to truncate the text. If this parameter is set, **font-size**, **max-font-size**, **min-font-size**, and **font-size-step** do not take effect.
Example values: **12px,14px,16px**| +| prefer-font-sizes | <array> | - | No | Preset preferred font sizes. For dynamic font size adjustment, the preset sizes are used to match the maximum number of lines in the text. If the preferred font sizes were not set, the font size will be adjusted based on the maximum and minimum font sizes and the step you have set. If the maximum number of lines in the text cannot be met, **text-overflow** is used to truncate the text. If this parameter is set, **font-size**, **max-font-size**, **min-font-size**, and **font-size-step** do not take effect.
Example: prefer-font-sizes: 12px,14px,16px| ## Events @@ -83,7 +83,7 @@ Not supported /*xxx.css */ .container { flex-direction: column; - align-items: center; + margin-left: 20px; } .row { flex-direction: row; diff --git a/en/application-dev/reference/arkui-js/js-components-basic-marquee.md b/en/application-dev/reference/arkui-js/js-components-basic-marquee.md index 9f13895436ce5f1104994f9d6956deba5e04a928..a1072111daa65e9eab0e528e086b8955efa66e09 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-marquee.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-marquee.md @@ -37,7 +37,7 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md | color | <color> | \#e5000000 | No | Font color of the scrolling text. | | font-size | <length> | 37.5 | No | Font size of the scrolling text. | | allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.
If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.| -| font-weight | number \| string | normal | No | Font weight of the scrolling text. For details, see **font-weight** of the **[\ component](../arkui-js/js-components-basic-text.md#styles)**.| +| font-weight | number \| string | normal | No | Font weight of the scrolling text. For details, see **font-weight** of the **[\ component](../arkui-js/js-components-basic-text.md#styles)**.| | font-family | string | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.| @@ -45,17 +45,17 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported. -| Name | Parameter | Description | -| ------------ | ---- | ---------------------------------------- | -| bounce(Rich) | - | Triggered when the marquee scrolls to the end. | -| finish(Rich) | - | Triggered when the marquee finishes the specified number of scrollings (value of the **loop** attribute). It can be triggered only when the **loop** attribute is set to a number greater than 0.| -| start(Rich) | - | Triggered when the marquee starts to scroll. | +| Name | Parameter | Description | +| ------ | ---- | ---------------------------------------- | +| bounce | - | Triggered when the marquee scrolls to the end. | +| finish | - | Triggered when the marquee finishes the specified number of scrollings (value of the **loop** attribute). It can be triggered only when the **loop** attribute is set to a number greater than 0.| +| start | - | Triggered when the marquee starts to scroll. | ## Methods In addition to the [universal methods](../arkui-js/js-components-common-methods.md), the following methods are supported. -| Name | Parameter | Description | +| Name | Parameter | Description | | ----- | ---- | ----- | | start | - | Starts scrolling.| | stop | - | Stops scrolling.| @@ -65,72 +65,75 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. ```html -
- {{marqueeCustomData}} -
- - +
+
+ + Life is a journey, not the destination. + +
+
+ +
``` ```css /* xxx.css */ -.container { +.tutorial-page { + width: 750px; + height: 100%; flex-direction: column; - justify-content: center; align-items: center; - background-color: #ffffff; + justify-content: center; } -.customMarquee { - width: 100%; - height: 80px; - padding: 10px; - margin: 20px; - border: 4px solid #ff8888; - border-radius: 20px; - font-size: 40px; - color: #ff8888; - font-weight: bolder; - font-family: serif; - background-color: #ffdddd; +.marqueetext { + font-size: 37px; } -.content { - flex-direction: row; +.mymarquee { + margin-top: 20px; + width:100%; + height: 100px; + margin-left: 50px; + margin-right: 50px; + border: 1px solid #dc0f27; + border-radius: 15px; + align-items: center; } -.controlButton { - flex-grow: 1; - background-color: #F2F2F2; - text-color: #0D81F2; +button{ + width: 200px; + height: 80px; + margin-top: 100px; } ``` ```js // xxx.js export default { - data: { - scrollAmount: 30, - loop: 3, - marqueeDir: 'left', - marqueeCustomData: 'Custom marquee', - }, - onMarqueeBounce: function() { - console.log("onMarqueeBounce"); + private: { + loopval: 1, + scroll: 8, + color1: 'red' }, - onMarqueeStart: function() { - console.log("onMarqueeStart"); + onInit(){ }, - onMarqueeFinish: function() { - console.log("onMarqueeFinish"); + setfinish(e) { + this.loopval= this.loopval + 1, + this.r = Math.floor(Math.random()*255), + this.g = Math.floor(Math.random()*255), + this.b = Math.floor(Math.random()*255), + this.color1 = 'rgba('+ this.r +','+ this.g +','+ this.b +',0.8)', + this.$element('testmarquee').start(), + this.loopval= this.loopval - 1 }, - onStartClick (evt) { - this.$element('customMarquee').start(); + makestart(e) { + this.$element('testmarquee').start() }, - onStopClick (evt) { - this.$element('customMarquee').stop(); + makestop(e) { + this.$element('testmarquee').stop() } } ``` -![lite_bar](figures/lite_bar.gif) +![zh-cn_image_0000001176075554](figures/zh-cn_image_0000001176075554.gif) diff --git a/en/application-dev/reference/arkui-js/js-components-basic-picker-view.md b/en/application-dev/reference/arkui-js/js-components-basic-picker-view.md index 426e227f9009c06b9e6c82f3344719c9d988e948..3f1ac6a278adeaea3059c930e3e5098fa8392374 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-picker-view.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-picker-view.md @@ -20,7 +20,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri | ---- | ------ | ---- | ---- | ---------------------------------------- | | type | string | text | No | Type of the scrollable selector, which cannot be changed dynamically. Available values are as follows:
- **text**: text selector.
- **time**: time selector.
- **date**: date selector.
- **datetime**: date and time selector.
- **multi-text**: multi-column text selector.| -Text selector (**type** is **text**) +### Text Selector | Name | Type | Default Value | Mandatory | Description | | --------------- | ------ | ---- | ---- | ---------------------------------------- | @@ -29,15 +29,15 @@ Text selector (**type** is **text**) | indicatorprefix | string | - | No | Prefix field added when a value is specified for the text selector. | | indicatorsuffix | string | - | No | Suffix field added when a value is specified for the text selector. | -Time selector (**type** is **time**) +### Time Selector | Name | Type | Default Value | Mandatory | Description | | ------------- | ------- | ----------------------------------- | ---- | ---------------------------------------- | | containsecond | boolean | false | No | Whether seconds are contained. | | selected | string | Current time | No | Default value of the time selector, in the format of HH:mm.
If seconds are contained, the format is HH:mm:ss.| -| hours | number | 241-4 | No | Time format used by the time selector. Available values are as follows:
- **12**: displayed in 12-hour format and distinguished by a.m. and p.m.
- **24**: displayed in 24-hour format.
Since API version 5, the default value is the most commonly-used hour format in the current locale.| +| hours | number | 241-4
-5+ | No | Time format used by the time selector. Available values are as follows:
- **12**: displayed in 12-hour format and distinguished by a.m. and p.m.
- **24**: displayed in 24-hour format.
Since API version 5, the default value is the most commonly-used hour format in the current locale.| -Date selector (**type** is **date**) +### Date Selector | Name | Type | Default Value | Mandatory | Description | | ------------------ | ------------ | ---------- | ---- | ---------------------------------------- | @@ -47,16 +47,16 @@ Date selector (**type** is **date**) | lunar5+ | boolean | false | No | Whether the pop-up window displays the lunar calendar. | | lunarswitch | boolean | false | No | Whether to display the lunar calendar switch in the date selector. When this switch is displayed, the user can switch between the lunar calendar and Gregorian calendar. Turn on the switch to display the lunar calendar, and turn off the switch to hide the lunar calendar.| -Date and time selector (**type** is **datetime**) +### Date and Time Selector | Name | Type | Default Value | Mandatory | Description | | ------------------ | ------- | ----------------------------------- | ---- | ---------------------------------------- | | selected | string | Current date and time | No | Default value of the date and time selector. The value can be in the format of MM-DD-HH-mm or YYYY-MM-DD-HH-mm. If the year is not set, the current year is used by default. The value you set is the date selected by default in the pop-up window.| -| hours | number | 241-4 | No | Time format used by the date and time selector. Available values are as follows:
- **12**: displayed in 12-hour format and distinguished by a.m. and p.m.
- **24**: displayed in 24-hour format.
Since API version 5, the default value is the most commonly-used hour format in the current locale.| +| hours | number | 241-4
-5+ | No | Time format used by the date and time selector. Available values are as follows:
- **12**: displayed in 12-hour format and distinguished by a.m. and p.m.
- **24**: displayed in 24-hour format.
Since API version 5, the default value is the most commonly-used hour format in the current locale.| | lunar5+ | boolean | false | No | Whether the pop-up window displays the lunar calendar. | | lunarswitch | boolean | false | No | Whether to display the lunar calendar switch in the date and time selector. When this switch is displayed, the user can switch between the lunar calendar and Gregorian calendar. Turn on the switch to display the lunar calendar, and turn off the switch to hide the lunar calendar.| -Multi-column text selector (**type** is **multi-text**) +### Multi-Column Text Selector | Name | Type | Default Value | Mandatory | Description | | -------- | ------- | --------- | ---- | ---------------------------------------- | @@ -77,42 +77,42 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md | selected-font-size | <length> | 20px | No | Font size of the selected item. The value is of the length type, in pixels. | | disappear-color5+ | <color> | \#ffffff | No | Font color of the items that gradually disappear. Disappearing items are the top option and bottom option of a column containing five options in total. | | disappear-font-size5+ | <length> | 14px | No | Font size of the items that gradually disappear. Disappearing items are the top option and bottom option of a column containing five options in total. | -| font-family | string | sans-serif | No | Font family of the selector, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.| +| font-family | string | sans-serif | No | Font family of the selector, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text. | ## Events The following events are supported. -Text selector (**type** is **text**) +### Text Selector | Name | Parameter | Description | | ------ | ---------------------------------------- | --------------- | -| change | { newValue: newValue, newSelected: newSelected } | Triggered when a value is specified for the text selector.| +| change | { newValue: newValue, newSelected: newSelected } | Triggered when a value is specified for the text selector.| -Time selector (**type** is **time**) +### Time Selector | Name | Parameter | Description | | ------ | ---------------------------------------- | ------------------------------- | -| change | { hour: hour, minute: minute, [second:second]} | Triggered when a value is specified for the time selector.
If seconds are contained, the value contains hour, minute, and second.| +| change | { hour: hour, minute: minute, [second:second]} | Triggered when a value is specified for the time selector.
If seconds are contained, the value contains hour, minute, and second.| -Date selector (**type** is **date**) +### Date Selector | Name | Parameter | Description | | ------ | ---------------------------------------- | --------------- | -| change | { year:year, month:month, day:day } | Triggered when a value is specified for the date selector.| +| change | { year:year, month:month, day:day } | Triggered when a value is specified for the date selector.| -Date and time selector (**type** is **datetime**) +### Date and Time Selector | Name | Parameter | Description | | ------ | ---------------------------------------- | ----------------- | -| change | { year:year, month:month, day:day,  hour:hour, minute:minute } | Triggered when a value is specified for the date and time selector.| +| change | { year:year, month:month, day:day, hour:hour, minute:minute } | Triggered when a value is specified for the date and time selector.| -Multi-text selector (**type** is **multi-text**) +### Multi-Column Text Selector | Name | Parameter | Description | | ------------ | ---------------------------------------- | ---------------------------------------- | -| columnchange | { column:column, newValue:newValue, newSelected:newSelected } | Triggered when the value of a column in the multi-column selector changes.
**column**: column whose value has changed.
**newValue**: selected value.
**newSelected**: index of the selected value.| +| columnchange | { column:column, newValue:newValue, newSelected:newSelected } | Triggered when the value of a column in the multi-column selector changes.
**column**: column whose value has changed.
**newValue**: selected value.
**newSelected**: index of the selected value.| ## Methods @@ -121,67 +121,252 @@ Not supported ## Example - -```html - -
- - Selected: {{time}} - - -
-``` - -```css -/* xxx.css */ -.container { - flex-direction: column; - justify-content: center; - align-items: center; - left: 0px; - top: 0px; - width: 454px; - height: 454px; -} -.title { - font-size: 30px; - text-align: center; -} -.time-picker { - width: 500px; - height: 400px; - margin-top: 20px; -} -``` - -```js -/* xxx.js */ -export default { - data: { - defaultTime: "", - time: "", - }, - onInit() { - this.defaultTime = this.now(); - }, - handleChange(data) { - this.time = this.concat(data.hour, data.minute); - }, - now() { - const date = new Date(); - const hours = date.getHours(); - const minutes = date.getMinutes(); - return this.concat(hours, minutes); - }, - - fill(value) { - return (value > 9 ? "" : "0") + value; - }, - - concat(hours, minutes) { - return `${this.fill(hours)}:${this.fill(minutes)}`; - }, -} -``` - -![lite_bar-4](figures/lite_bar-4.png) +1. Text Selector + ```html + +
+ + Selected value: {{value}} Selected index: {{index}} + + +
+ ``` + + ```css + /* xxx.css */ + .container { + flex-direction: column; + justify-content: center; + align-items: center; + left: 0px; + top: 0px; + width: 454px; + height: 454px; + } + .title { + font-size: 30px; + text-align: center; + margin-top: 20px; + } + ``` + + ```js + /* xxx.js */ + export default { + data: { + options: ['Option 1','Option 2','Option 3'], + value: "Option 1", + index: 0 + }, + handleChange(data) { + this.value = data.newValue; + this.index = data.newSelected; + }, + } + ``` + ![](figures/pickerview1.gif) + +2. Time Selector + ```html + +
+ + Selected: {{time}} + + +
+ ``` + + ```css + /* xxx.css */ + .container { + flex-direction: column; + justify-content: center; + align-items: center; + left: 0px; + top: 0px; + width: 454px; + height: 454px; + } + .title { + font-size: 30px; + text-align: center; + } + .time-picker { + width: 500px; + height: 400px; + margin-top: 20px; + } + ``` + + ```js + /* xxx.js */ + export default { + data: { + defaultTime: "", + time: "", + }, + onInit() { + this.defaultTime = this.now(); + }, + handleChange(data) { + this.time = this.concat(data.hour, data.minute); + }, + now() { + const date = new Date(); + const hours = date.getHours(); + const minutes = date.getMinutes(); + return this.concat(hours, minutes); + }, + fill(value) { + return (value > 9 ? "" : "0") + value; + }, + concat(hours, minutes) { + return `${this.fill(hours)}:${this.fill(minutes)}`; + }, + } + ``` + + ![](figures/pickerview2.gif) + +3. Date Selector + ```html + +
+ + Selected: {{time}} + + +
+ ``` + + ```css + /* xxx.css */ + .container { + flex-direction: column; + justify-content: center; + align-items: center; + left: 0px; + top: 0px; + width: 454px; + height: 454px; + } + .title { + font-size: 30px; + text-align: center; + margin-top: 20px; + } + .date-picker { + width: 500px; + height: 400px; + margin-top: 50px; + } + ``` + + ```js + /* xxx.js */ + export default { + data: { + date: "", + }, + handleChange(data) { + this.date = data.year + "" + data.month + "" + data.day + ""; + }, + } + ``` + + +4. Date and Time Selector + ```html + +
+ + Selected: {{datetime}} + + +
+ ``` + + ```css + /* xxx.css */ + .container { + flex-direction: column; + justify-content: center; + align-items: center; + left: 0px; + top: 0px; + width: 500px; + height: 454px; + } + .title { + font-size: 30px; + text-align: center; + margin-top: 20px; + } + .date-picker { + width: 500px; + height: 400px; + margin-top: 50px; + } + ``` + + ```js + /* xxx.js */ + export default { + data: { + datetime: "", + }, + handleChange(data) { + this.datetime = data.year + "" + data.month + "" + data.day + "" + data.hour + "" + data.minute + ""; + }, + } + ``` + + +5. Multi-Column Text Selector + + ```html + +
+ + Selected: {{ value }} + + +
+ ``` + + ```css + /* xxx.css */ + .container { + flex-direction: column; + justify-content: center; + align-items: center; + left: 0px; + top: 0px; + width: 500px; + height: 454px; + } + .title { + font-size: 30px; + text-align: center; + margin-top: 20px; + } + ``` + + ```js + /* xxx.js */ + export default { + data: { + multitext: [ + [1, 2, 3], + [4, 5, 6], + [7, 8, 9], + ], + value: "" + }, + handleChange(data) { + this.value = "Column: " + data.column + "," + "Value: " + data.newValue + ", Index:" + data.newSelected; + }, + } + ``` + ![](figures/pickerview5.gif) diff --git a/en/application-dev/reference/arkui-js/js-components-basic-picker.md b/en/application-dev/reference/arkui-js/js-components-basic-picker.md index f6425d937129086d130562d8454da03bcaef3c87..5a9ace889f60ae6f6c0c891e8d0a8d55b3dadfd1 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-picker.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-picker.md @@ -58,7 +58,7 @@ When **type** is set to **time**, a time selector is used. | Name | Type | Default Value | Mandatory | Description | | ------------- | ------- | ----------------------------------- | ---- | ---------------------------------------- | | containsecond | boolean | false | No | Whether seconds are contained. | -| selected | string | Current time | No | Default value of the time selector, in format of HH:mm. If seconds are contained, the format is HH:mm:ss. | +| selected | string | Current time | No | Default value of the time selector, in format of HH:mm. If seconds are contained, the format is HH:mm:ss.
| | value | string | - | No | Value of the time selector. | | hours | number | 241-4
-5+ | No | Time format used by the time selector. Available values are as follows:
- **12**: displayed in 12-hour format and distinguished by a.m. and p.m.
- **24**: displayed in 24-hour format.
Since API version 5, the default value is the most commonly-used hour format in the current locale.| @@ -166,52 +166,59 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. ```html
- - - - - - - - - - - + + + + + + + + + +
``` ```css /* xxx.css */ -.container { - flex-direction: column; - justify-content: center; - align-items: center; +.container { + flex-direction: column; + justify-content: center; + align-items: center; } - picker{ - width:60%; - height:80px; - border-radius:20px; - text-color:white; - font-size:15px; - background-color:#4747e3; - margin-left:20%; + +picker { + width: 60%; + height: 80px; + border-radius: 20px; + text-color: white; + font-size: 15px; + background-color: #4747e3; + margin-left: 20%; } - select{ - background-color: #efecec; - height: 50px; - width: 60%; - margin-left: 20%; - margin-top: 300px; - margin-bottom: 50px; - font-size: 22px; + +select { + background-color: #efecec; + height: 50px; + width: 60%; + margin-left: 20%; + margin-top: 300px; + margin-bottom: 50px; + font-size: 22px; } ``` @@ -219,72 +226,96 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. // xxx.js import router from '@system.router'; import prompt from '@system.prompt'; + export default { - data: { - selectList:["text","data","time","datetime","multitext"], - rangetext:['15', "20", "25"], - multitext:[["a", "b", "c"], ["e", "f", "g"], ["h", "i"], ["k", "l", "m"]], - textvalue:'default textvalue', - datevalue:'default datevalue', - timevalue:'default timevalue', - datetimevalue:'default datetimevalue', - multitextvalue:'default multitextvalue', - containsecond:true, - multitextselect:[1,2,0], - datetimeselect:'2012-5-6-11-25', - timeselect:'11:22:30', - dateselect:'2021-3-2', - textselect:'2' - }, - selectChange(e){ - for(let i = 0;i** component is used to generate and display a QR code. - > **NOTE** > > This component is supported since API version 5. Updates will be marked with a superscript to indicate their earliest API version. +The **\** component is used to generate and display a QR code. ## Required Permissions @@ -24,7 +23,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri | Name | Type | Default Value | Mandatory | Description | | ----- | ------ | ---- | ---- | ---------------------------------------- | | value | string | - | Yes | Content used to generate the QR code. | -| type | string | rect | No | QR code type. Available values are as follows:
- **rect**: rectangular QR code
- **circle**: round QR code| +| type | string | rect | No | QR code type. Available values are as follows:
- **rect**: rectangular QR code.
- **circle**: round QR code.| ## Styles @@ -60,8 +59,6 @@ The [universal methods](../arkui-js/js-components-common-methods.md) are support
- Value - 123 Type Color @@ -98,7 +95,6 @@ select{ /* index.js */ export default { data: { - qr_value:'', qr_type: 'rect', qr_size: '300px', qr_col: '#87ceeb', @@ -113,9 +109,6 @@ export default { this.qr_type = 'circle' } }, - setvalue(e) { - this.qr_value = e.newValue - }, setcol(e) { this.qr_col = e.newValue }, diff --git a/en/application-dev/reference/arkui-js/js-components-basic-search.md b/en/application-dev/reference/arkui-js/js-components-basic-search.md index 94cfa99cc29d81d779dbd1b901d8a09b71b86369..adf32950c2889e99e88d67e28da1b6bfb110f4ee 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-search.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-search.md @@ -1,10 +1,9 @@ # search > **NOTE** -> > This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -The **\** component provides an input area for users to search. +The **\** component provides an input area for users to search. ## Child Components @@ -42,7 +41,7 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md | font-size | <length> | 16px | No | Font size of the search box. | | allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.
If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.| | placeholder-color | <color> | \#99000000
| No | Color of the hint text. | -| font-weight | number \| string | normal | No | Font weight. For details, see **font-weight** of the **[\](../arkui-js/js-components-basic-text.md#styles)** component.| +| font-weight | number \| string | normal | No | Font weight. For details, see [font-weight](../arkui-js/js-components-basic-text.md#styles) of the **\** component.| | font-family | string | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.| | caret-color6+ | <color> | - | No | Color of the caret. | diff --git a/en/application-dev/reference/arkui-js/js-components-basic-slider.md b/en/application-dev/reference/arkui-js/js-components-basic-slider.md index 08099a0bf8999752bba1fec21d227b5c710bbae0..e4351b95ac820b6acbeb624e83abe60d4fc113fe 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-slider.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-slider.md @@ -2,9 +2,9 @@ > **NOTE** > -> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -The **\** component is used to quickly adjust settings, such as the volume and brightness. +The **\** component is used to quickly adjust settings, such as the volume and brightness. ## Child Components @@ -22,7 +22,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri | max | number | 100 | No| Maximum value of the slider.| | step | number | 1 | No| Step of each slide.| | value | number | 0 | No| Initial value of the slider.| -| mode5+ | string | outset | No| Slider style. Available values are as follows:
- **outset**: The slider is on the sliding bar.
- **inset**: The slider is inside the sliding bar.| +| mode5+ | string | outset | No| Slider style. Available values are as follows:
- **outset**: The slider is on the slider track.
- **inset**: The slider is in the slider track.| | showsteps5+ | boolean | false | No| Whether to display slider scales.| | showtips5+ | boolean | false | No| Whether a tooltip is displayed to show the percentage value on the slider.| @@ -51,7 +51,7 @@ In addition to the [universal events](../arkui-js/js-components-common-events.md | Attribute| Type| Description| | -------- | -------- | -------- | | value5+ | number | Current value of the slider.| -| mode5+ | string | Type of the change event. Available values are as follows:
- **start**: The **value** starts to change.
- **move**: The **value** is changing with users' dragging.
- **end**: The **value** stops changing.| +| mode5+ | string | Type of the change event. Available values are as follows:
- **start**: The **value** starts to change.
- **move**: The **value** is changing with users' dragging.
- **end**: The **value** stops changing.
- **click**: The **value** changes upon a touch on the slider.| ## Example @@ -59,48 +59,23 @@ In addition to the [universal events](../arkui-js/js-components-common-events.md ```html
- slider start value is {{startValue}} - slider current value is {{currentValue}} - slider end value is {{endValue}} - + + +
``` ```css /* xxx.css */ .container { - flex-direction: column; - justify-content: center; - align-items: center; - + flex-direction: column; + justify-content: center; + align-items: center; } -``` - -```js -// xxx.js -export default { - data: { - value: 0, - startValue: 0, - currentValue: 0, - endValue: 0, - }, - setvalue(e) { - if (e.mode == "start") { - this.value = e.value; - this.startValue = e.value; - } else if (e.mode == "move") { - this.value = e.value; - this.currentValue = e.value; - } else if (e.mode == "end") { - this.value = e.value; - this.endValue = e.value; - } else if (e.mode == "click) { - this.value = e.value; - this.currentValue = e.value; - } - } +slider{ + margin-top: 100px; } ``` + ![slider](figures/slider.png) diff --git a/en/application-dev/reference/arkui-js/js-components-basic-switch.md b/en/application-dev/reference/arkui-js/js-components-basic-switch.md index f7cc8ddd86f2762c8b6a7e5e250e95f22e5c74ed..d58e16b10b6357537684c09f519caa537a469f5c 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-switch.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-switch.md @@ -30,18 +30,20 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri ## Styles + + In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported. -| Name | Type | Default Value | Mandatory | Description | -| ------------------- | -------------------------- | ---------- | ---- | ---------------------------------------- | -| texton-color(Rich) | <color> | \#000000 | No | Text color displayed when the component is checked. | -| textoff-color(Rich) | <color> | \#000000 | No | Text color displayed when the component is not checked. | -| text-padding(Rich) | number | 0px | No | Distance between the two sides of the longest text in **texton** and **textoff** and the border of the slider. | -| font-size(Rich) | <length> | - | No | Font size. This attribute is available only when **texton** and **textoff** are set. | -| allow-scale(Rich) | boolean | true | No | Whether the font size changes with the system's font size settings.
If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.| -| font-style(Rich) | string | normal | No | Font style. This attribute is available only when **texton** and **textoff** are set. For details, see **font-style** of the [**\**](../arkui-js/js-components-basic-text.md#styles) component.| -| font-weight(Rich) | number \| string | normal | No | Font weight. This attribute is available only when **texton** and **textoff** are set. For details, see **font-weight** of the [**\**](../arkui-js/js-components-basic-text.md#styles) component.| -| font-family(Rich) | string | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text. This attribute is available only when **texton** and **textoff** are set.| +| Name | Type | Default Value | Mandatory | Description | +| ------------- | -------------------------- | ---------- | ---- | ---------------------------------------- | +| texton-color | <color> | \#000000 | No | Text color displayed when the component is checked. This attribute is available only when **texton** and **textoff** are set. | +| textoff-color | <color> | \#000000 | No | Text color displayed when the component is not checked. This attribute is available only when **texton** and **textoff** are set. | +| text-padding | number | 0px | No | Distance between the two sides of the longest text in **texton** and **textoff** and the border of the slider. | +| font-size | <length> | - | No | Font size. This attribute is available only when **texton** and **textoff** are set. | +| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.
If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.| +| font-style | string | normal | No | Font style. This attribute is available only when **texton** and **textoff** are set. For details, see [font-style](../arkui-js/js-components-basic-text.md#styles) of the **\** component.| +| font-weight | number \| string | normal | No | Font weight. This attribute is available only when **texton** and **textoff** are set. For details, see [font-weight](../arkui-js/js-components-basic-text.md#styles) of the **\** component.| +| font-family | string | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text. This attribute is available only when **texton** and **textoff** are set.| ## Events @@ -61,45 +63,63 @@ The [universal methods](../arkui-js/js-components-common-methods.md) are support ```html
- - + + + + + +
``` ```css /* xxx.css */ .container { - display: flex; - justify-content: center; - align-items: center; + display: flex; + justify-content: center; + align-items: center; +} +.switch { + texton-color: red; + textoff-color: forestgreen; } -switch{ - texton-color:#002aff; - textoff-color:silver; - text-padding:20px; +.text { + text-padding: 20px; + font-size: 30px; + font-weight: 700; } ``` ```js // xxx.js -import prompt from '@system.prompt'; +import promptAction from '@ohos.promptAction'; export default { - data: { - title: 'World' - }, - switchChange(e){ - console.log(e.checked); - if(e.checked){ - prompt.showToast({ - message: "Switch on." - }); - }else{ - prompt.showToast({ - message: "Switch off." - }); + data: { + title: 'World' + }, + switchChange(e) { + if (e.checked) { + promptAction.showToast({ + message: "Switch on." + }); + } else { + promptAction.showToast({ + message: "Switch off." + }); + } + }, + normalswitchChange(e) { + if (e.checked) { + promptAction.showToast({ + message: "switch on" + }); + } else { + promptAction.showToast({ + message: "switch off" + }); + } } - } } ``` -![en-us_image_0000001152862510](figures/en-us_image_0000001152862510.gif) +![en-us_image_0000001152862510](figures/switch.gif) diff --git a/en/application-dev/reference/arkui-js/js-components-basic-text.md b/en/application-dev/reference/arkui-js/js-components-basic-text.md index c9f0227a6b0f5c684557206d36b84ed722c22c2e..2509a3a6bcc556e19d1393ed80acad3d28c91fb4 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-text.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-text.md @@ -15,7 +15,7 @@ None ## Child Components -Only the **[\](../arkui-js/js-components-basic-span.md)** component is supported. +The **[\](../arkui-js/js-components-basic-span.md)** child component is supported. ## Attributes @@ -34,19 +34,19 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md | allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.
For details about how to make the configuration take effect dynamically, see the **config-changes** attribute in the **config.json** file.| | letter-spacing | <length> | 0px | No | Character spacing (px). | | word-spacing7+ | <length> \| <percentage> \| string | normal | No | Spacing between texts. If the input is a string, the options are as follows:
**normal**: default spacing.| -| font-style | string | normal | No | Font style. Available values are as follows:
- **normal**: standard font style
- **italic**: italic font style| -| font-weight | number \| string | normal | No | Font width. For the number type, the value ranges from 100 to 900. The default value is 400. A larger value indicates a larger font width. The value of the number type must be an integer multiple of 100.
The value of the string type can be **lighter**, **normal**, **bold**, or **bolder**.| +| font-style | string | normal | No | Font style. Available values are as follows:
- **normal**: standard font style.
- **italic**: italic font style.| +| font-weight | number \| string | normal | No | Font weight. For the number type, the value ranges from 100 to 900. The default value is 400. A larger value indicates a heavier font weight. The value of the number type must be an integer multiple of 100.
The value of the string type can be **lighter**, **normal**, **bold**, or **bolder**.| | text-decoration | string | none | No | Text decoration. Available values are as follows:
- **underline**: An underline is used.
- **line-through**: A strikethrough is used.
- **none**: The standard text is used.| | text-decoration-color7+ | <color> | - | No | Color of the text decoration. | | text-align | string | start
| No | Text alignment mode. Available values are as follows:
- **left**: The text is left-aligned.
- **center**: The text is center-aligned.
- **right**: The text is right-aligned.
- **start**: The text is aligned with the direction in which the text is written.
- **end**: The text is aligned with the opposite direction in which the text is written.
If the text width is not specified, the alignment effect may not be obvious when the text width is the same as the width of the parent container.| -| line-height | <length> \| <percentage>7+ \| string7+ | 0px1-6
normal7+ | No | Text line height. When this parameter is set to **0px**, the text line height is not limited and the font size is adaptive. The value of the string type is as follows:
**normal**7+: default line height | +| line-height | <length> \| <percentage>7+ \| string7+ | 0px1-6
normal7+ | No | Text line height. When this parameter is set to **0px**, the text line height is not limited and the font size is adaptive. The value of the string type is as follows:
**normal**7+: default line height| | text-overflow | string | clip | No | Display mode when the text is too long. This style takes effect when the maximum number of lines is specified. Available values are as follows:
- **clip**: The text is clipped and displayed based on the size of the parent container.
- **ellipsis**: The text is displayed based on the size of the parent container. The text that cannot be displayed is replaced with ellipsis. This style must be used together with **max-lines**.| | font-family | string | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.| -| max-lines | number \| string7+ | - | No | Maximum number of text lines. The value of the string type is as follows:
- **auto**7+: The number of text lines adapts to the container height. | +| max-lines | number \| string7+ | - | No | Maximum number of text lines. The value of the string type is as follows:
- **auto**7+: The number of text lines adapts to the container height.| | min-font-size | <length> | - | No | Minimum font size in the text. This style must be used together with **max-font-size**. The font size can be changed dynamically. After the maximum and minimum font sizes are set, **font-size** does not take effect.| | max-font-size | <length> | - | No | Maximum font size in the text. This style must be used together with **min-font-size**. The font size can be changed dynamically. After the maximum and minimum font sizes are set, **font-size** does not take effect.| | font-size-step | <length> | 1px | No | Step for dynamically adjusting the font size in the text. The minimum and maximum font sizes must be set. | -| prefer-font-sizes | <array> | - | No | Preset preferred font sizes. For dynamic font size adjustment, the preset sizes are used to match the maximum number of lines in the text. If the preferred font sizes were not set, the font size will be adjusted based on the maximum and minimum font sizes and the step you have set. If the maximum number of lines in the text cannot be met, **text-overflow** is used to truncate the text. If this parameter is set, **font-size**, **max-font-size**, **min-font-size**, and **font-size-step** do not take effect.
Example values: **12px,14px,16px**| +| prefer-font-sizes | <array> | - | No | Preset preferred font sizes. For dynamic font size adjustment, the preset sizes are used to match the maximum number of lines in the text. If the preferred font sizes were not set, the font size will be adjusted based on the maximum and minimum font sizes and the step you have set. If the maximum number of lines in the text cannot be met, **text-overflow** is used to truncate the text. If this parameter is set, **font-size**, **max-font-size**, **min-font-size**, and **font-size-step** do not take effect.
Example: prefer-font-sizes: 12px,14px,16px| | word-break6+ | string | normal | No | Text line breaking mode. The options are as follows:
- **normal**: Allows text line breaks between words as appropriate to the relevant language writing systems. This is the default mode.
- **break-all**: Allows text line breaks between any characters for writing systems other than Chinese, Japanese, and Korean.
- **break-word**: Works in the same way as **break-all**, except that it does not break unbreakable words.| | text-indent7+ | <length> | - | No | Indentation of the first line. | | white-space7+ | string | pre | No | Mode for processing blanks in the component. The options are as follows:
- **normal**: All spaces, carriage returns, and tabs are combined into one space, and the text is automatically wrapped.
- **nowrap**: All spaces, carriage returns, and tabs are combined into one space, and the text is not wrapped.
- **pre**: All contents are output as-is.
- **pre-wrap**: All contents are output as-is with line breaks.
- **pre-line**: All spaces and tabs are combined into one space, the carriage return remains unchanged, and the text is wrapped.| @@ -76,84 +76,65 @@ The [universal methods](../arkui-js/js-components-common-methods.md) are support ## Example - +1. ```html
-
- - Hello {{ title }} - -
+ default text + hello world with color + hello world with font-size + hello world with letter-spacing + hello world with word-spacing + hello world with italic + hello world with font-weight + hello world with underline + hello world with line-through + hello world with text-align:right
``` ```css /* xxx.css */ .container { - display: flex; - justify-content: center; - align-items: center; -} -.content{ - width: 400px; - height: 400px; - border: 20px; + display: flex; + justify-content: center; + align-items: center; + flex-direction: column; } .title { - font-size: 80px; - text-align: center; - width: 400px; - height: 400px; + text-align: center; + width: 800px; + height: 60px; } -``` - -```js -// xxx.js -export default { - data: { - title: 'World' - } +.textcolor { + color: indianred; } -``` - -![3](figures/3.png) - -```html - -
- - This is a passage - - - This is a passage - -
-``` - -```css -/* xxx.css */ -.container { - flex-direction: column; - align-items: center; - background-color: #F1F3F5; - justify-content: center; +.textsize { + font-size: 40px; +} +.textletterspacing { + letter-spacing: -3px; } -.text1{ - word-spacing: 10px; - adapt-height: true; +.textwordspacing { + word-spacing: 20px; } -.text2{ - width: 200px; - max-lines: 1; - text-overflow: ellipsis; - text-valign: middle; - line-height: 40px; - text-decoration: underline; - text-decoration-color: red; - text-indent: 20px; - white-space: pre; +.textstyle { + font-style: italic; +} +.textweight { + font-weight: 700; +} +.textdecoration1 { + text-decoration: underline; +} +.textdecoration2 { + text-decoration: line-through; + text-decoration-color: red; +} +.textalign { + text-align: right; } ``` -![2](figures/2.png) + +![en-us_image_0000001167823076](figures/text.png) diff --git a/en/application-dev/reference/arkui-js/js-components-basic-xcomponent.md b/en/application-dev/reference/arkui-js/js-components-basic-xcomponent.md index bb5389d410eb12c80575d55d0ea74dd4b33efa05..639f9f1d575f6d5f1aa183ad74f6d1d2a666dc27 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-xcomponent.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-xcomponent.md @@ -1,18 +1,18 @@ # xcomponent - > **NOTE** - > - > This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version. +> **NOTE** +> +> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. - The **\** displays the components to which the EGL/OpenGLES or media data is written. +The **\** displays the components to which the EGL/OpenGLES or media data is written. ## Required Permissions - None +None ## Child Components - Not supported +Not supported ## Attributes diff --git a/en/application-dev/reference/arkui-js/js-components-canvas-canvas.md b/en/application-dev/reference/arkui-js/js-components-canvas-canvas.md index edf0d3afa3412cb67b3d97f38036218f46e1de33..ca3a9125a0dba2956d12d15fe7c82322730f40bb 100644 --- a/en/application-dev/reference/arkui-js/js-components-canvas-canvas.md +++ b/en/application-dev/reference/arkui-js/js-components-canvas-canvas.md @@ -11,7 +11,7 @@ The **\** component is used for customizing drawings. None -## Child Component +## Child Components Not supported @@ -38,7 +38,7 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. ### getContext -getContext(type: '2d', options?: ContextAttrOptions): CanvasRendering2dContext +getContext(type: '2d', options?: ContextAttrOptions): CanvasRenderingContext2D Obtains the canvas drawing context. This API cannot be called in **onInit** or **onReady**. @@ -49,7 +49,7 @@ Obtains the canvas drawing context. This API cannot be called in **onInit** or * | type | string | Yes | Object type. The value is set to **'2d'**, indicating that a 2D drawing object is returned. This object can be used to draw rectangles, texts, and images on the canvas component.| | options6+ | ContextAttrOptions | No | Whether to enable anti-aliasing. By default, anti-aliasing is disabled. | -**Table 1** ContextAttrOptions + **Table 1** ContextAttrOptions | Name | Type | Description | | --------- | ------- | ------------------- | @@ -59,7 +59,7 @@ Obtains the canvas drawing context. This API cannot be called in **onInit** or * | Type | Description | | ---------------------------------------- | -------------------- | -| [CanvasRenderingContext2D](../arkui-js/js-components-canvas-canvasrenderingcontext2d.md) | 2D drawing object, which can be used to draw rectangles, images, and texts, on the canvas component. | +| [CanvasRenderingContext2D](../arkui-js/js-components-canvas-canvasrenderingcontext2d.md) | 2D drawing object, which can be used to draw rectangles, images, and texts on the canvas component.| ### toDataURL6+ diff --git a/en/application-dev/reference/arkui-js/js-components-canvas-canvasgradient.md b/en/application-dev/reference/arkui-js/js-components-canvas-canvasgradient.md index 9bc724d26a7610fa4b7fdbd48b21811a2f472cf2..125067139d62be03f2a19995e9181df6010a1f77 100644 --- a/en/application-dev/reference/arkui-js/js-components-canvas-canvasgradient.md +++ b/en/application-dev/reference/arkui-js/js-components-canvas-canvasgradient.md @@ -25,19 +25,21 @@ Adds a color stop for the **CanvasGradient** object based on the specified offse
-
``` ```js // xxx.js export default { - handleClick() { + onShow() { const el =this.$refs.canvas; - const ctx =el.getContext('2d'); - const gradient = ctx.createLinearGradient(0,0,100,0); - gradient.addColorStop(0,'#00ffff'); - gradient.addColorStop(1,'#ffff00'); + const ctx = el.getContext('2d'); + const gradient = ctx.createLinearGradient(50,0,300,100); + gradient.addColorStop(0.0, 'red') + gradient.addColorStop(0.5, 'white') + gradient.addColorStop(1.0, 'green') + ctx.fillStyle = gradient + ctx.fillRect(0, 0, 300, 300) } } ``` diff --git a/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md b/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md index 4100f9429985f1df7dd1e52087c842f128496226..0ebefab7d190de7f8ca8bd76b570444c0a2aa70b 100644 --- a/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md +++ b/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md @@ -2,7 +2,7 @@ > **NOTE** > -> Supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. **CanvasRenderingContext2D** allows you to draw rectangles, text, images, and other objects on a canvas. @@ -426,9 +426,9 @@ export default { } ``` -![en-us_image_0000001213192781](figures/en-us_image_0000001213192781.png) + ![en-us_image_0000001213192781](figures/en-us_image_0000001213192781.png) -In the above example, the blue rectangle represents the new drawing, and the red rectangle represents the existing drawing. + In the above example, the blue rectangle represents the new drawing, and the red rectangle represents the existing drawing. ### shadowBlur @@ -585,7 +585,7 @@ Fills a rectangle on the canvas. ```html
- +
``` @@ -621,7 +621,7 @@ Clears the content in a rectangle on the canvas. ```html
- +
``` @@ -984,7 +984,7 @@ Creates a pattern for image filling based on a specified source image and repeti ```html
- +
``` @@ -998,7 +998,7 @@ Creates a pattern for image filling based on a specified source image and repeti img.src = 'common/images/example.jpg'; var pat = ctx.createPattern(img, 'repeat'); ctx.fillStyle = pat; - ctx.fillRect(0, 0, 20, 20); + ctx.fillRect(0, 0, 500, 500); } } ``` @@ -1429,7 +1429,7 @@ Defines a transformation matrix. To transform a graph, you only need to set para setTransform(scaleX: number, skewX: number, skewY: number, scale: number, translateX: number, translateY: number): void -Resets the existing transformation matrix and creates a new transformation matrix by using the same parameters as the **transform()** function. +Resets the existing transformation matrix and creates a new transformation matrix by using the same parameters as the **transform()** API. **Parameters** @@ -1574,7 +1574,7 @@ Draws an image on the canvas. ```html
- +
``` @@ -1582,11 +1582,11 @@ Draws an image on the canvas. //xxx.js export default { onShow() { - var test = this.$element('drawImage'); + var test = this.$refs.canvas; var ctx = test.getContext('2d'); var img = new Image(); img.src = 'common/image/test.jpg'; - ctx.drawImage(img, 50, 80, 80, 80); + ctx.drawImage(img, 0, 0, 200, 200, 10, 10, 200, 200); } } ``` diff --git a/en/application-dev/reference/arkui-js/js-components-canvas-path2d.md b/en/application-dev/reference/arkui-js/js-components-canvas-path2d.md index f5f4179442862246d1c3171dde95879efbe4c532..c2ca3f82172d1b3a7c7b6a5a2d5423d9ecc3aabd 100644 --- a/en/application-dev/reference/arkui-js/js-components-canvas-path2d.md +++ b/en/application-dev/reference/arkui-js/js-components-canvas-path2d.md @@ -65,7 +65,7 @@ Sets the path transformation matrix. ```html
- +
``` @@ -95,7 +95,7 @@ Moves the current point of the path back to the start point of the path, and dra ```html
- +
``` @@ -223,7 +223,7 @@ Draws a cubic bezier curve on the canvas. ```html
- +
``` @@ -264,7 +264,7 @@ Draws a quadratic curve on the canvas. ```html
- +
``` @@ -307,7 +307,7 @@ Draws an arc on the canvas. ```html
- +
``` @@ -348,7 +348,7 @@ Draws an arc based on the radius and points on the arc. ```html
- +
``` diff --git a/en/application-dev/reference/arkui-js/js-components-common-transition.md b/en/application-dev/reference/arkui-js/js-components-common-transition.md index 19e54ce8bb7cbbf8f417fb3623a0fbe6635f8f67..d75160229929e2cb565ec65604164c89539e8182 100644 --- a/en/application-dev/reference/arkui-js/js-components-common-transition.md +++ b/en/application-dev/reference/arkui-js/js-components-common-transition.md @@ -11,14 +11,14 @@ | Name | Type | Default Value | Description | | ------- | ------ | ---- | ---------------------------------------- | -| shareid | string | - | Used for the transition of shared elements, which takes effect only when this attribute is set. **\**, **\**, **\**, **\
@@ -60,12 +60,12 @@ In the example below, where **PageA** jumps to **PageB**, the shared element is ```js // xxx.js -import router from '@system.router'; +import router from '@ohos.router'; export default { jump() { router.push({ // The path must be the same as that in the config.json file. - uri: 'pages/detailpage', + url: 'pages/detailpage', }); }, } @@ -93,7 +93,7 @@ export default { ```js // xxx.js -import router from '@system.router'; +import router from '@ohos.router'; export default { jumpBack() { router.back(); @@ -117,7 +117,6 @@ export default { ## Widget Transition > **NOTE** -> > Widget transitions are not available when other transitions (including shared element transitions and custom transitions) are used. @@ -125,7 +124,7 @@ export default { | Name | Type | Default Value | Description | | ----------------- | ------ | ---- | ---------------------------------------- | -| transition-effect | string | - | Whether a component on the current page displays the transition effect during a widget transition. Available values are as follows:
- **unfold**: The component will move upwards by one widget height if the component is located above the widget tapped by the user, or move downwards by one widget height if the component is located below the widget.
- **none**: No transition effect is displayed. | +| transition-effect | string | - | Whether a component on the current page displays the transition effect during a widget transition. Available values are as follows:
- **unfold**: The component will move upwards by one widget height if the component is located above the widget tapped by the user, or move downwards by one widget height if the component is located below the widget.
- **none**: No transition effect is displayed.| ### Example @@ -140,7 +139,7 @@ The **source_page** has a title area on the top and a widget list. Users can tap MAIN TITLE
- + {{$item.title}} @@ -149,19 +148,19 @@ The **source_page** has a title area on the top and a widget list. Users can tap ```js // xxx.js -import router from '@system.router' +import router from '@ohos.router' export default { data: { list: [] }, onInit() { for(var i = 0; i < 10; i++) { - var item = { uri: "pages/card_transition/target_page/index", + var item = { url: "pages/card_transition/target_page/index", title: "this is title" + i, id: "item_" + i } this.list.push(item); } }, - jumpPage(id, uri) { + jumpPage(id, url) { var cardId = this.$element(id).ref; - router.push({ uri: uri, params : { ref : cardId } }); + router.push({ url: url, params : { ref : cardId } }); } } ``` @@ -169,6 +168,8 @@ export default { ```css /* xxx.css */ .container { + width: 100%; + height: 100%; flex-direction: column; align-items: center; background-color: #ABDAFF; @@ -199,6 +200,8 @@ export default { ```css /* xxx.css */ .container { + width: 100%; + height: 100%; flex-direction: column; align-items: center; background-color: #EBFFD7; @@ -223,7 +226,7 @@ export default { | -------------------------- | ------ | ------------- | ---------------------------------------- | | transition-enter | string | - | Works with **@keyframes** and supports transform and opacity animations. For details, see [Attributes available for the @keyframes rule](../arkui-js/js-components-common-animation.md).| | transition-exit | string | - | Works with **@keyframes** and supports transform and opacity animations. For details, see [Attributes available for the @keyframes rule](../arkui-js/js-components-common-animation.md).| -| transition-duration | string | Follows the default page transition time of the device | The unit can be s or ms. The default unit is ms. If no value is specified, the default value is used. | +| transition-duration | string | Follows the default page transition time of the device| The unit can be s|or ms. The default unit is ms. If no value is specified, the default value is used.| | transition-timing-function | string | friction | Speed curve of the transition animation, which makes the animation more fluent. For details, see the description of **animation-timing-function **in [Animation Styles](../arkui-js/js-components-common-animation.md).| @@ -255,16 +258,16 @@ export default {
``` - ```css + ```js // xxx.js - import router from '@system.router'; + import router from '@ohos.router'; export default { data: { - + }, jump() { router.push({ - uri:'pages/transition2/transition2' + url:'pages/transition2/transition2' }) } } @@ -288,13 +291,13 @@ export default { transition-duration: 5s; transition-timing-function: friction; } - + @keyframes go_page { from { opacity: 0; transform: translate(0px) rotate(60deg) scale(1.0); } - + to { opacity: 1; transform: translate(100px) rotate(360deg) scale(1.0); @@ -305,7 +308,7 @@ export default { opacity: 1; transform: translate(200px) rotate(60deg) scale(2); } - + to { opacity: 0; transform: translate(200px) rotate(360deg) scale(2); @@ -321,15 +324,15 @@ export default {
transition
-
``` ```js // xxx.js - import router from '@system.router'; + import router from '@ohos.router'; export default { data: { - + }, jumpBack() { router.back() @@ -346,7 +349,7 @@ export default { width: 100%; height: 100%; } - + .move_page { width: 100px; height: 100px; @@ -356,7 +359,7 @@ export default { transition-duration: 5s; transition-timing-function: ease; } - + @keyframes go_page { from { opacity: 0; @@ -367,7 +370,7 @@ export default { transform:translate(100px) rotate(180deg) scale(2.0); } } - + @keyframes exit_page { from { opacity: 1; diff --git a/en/application-dev/reference/arkui-js/js-components-container-list.md b/en/application-dev/reference/arkui-js/js-components-container-list.md index 640c6c420ce81d299b7d12a1b67cca42b543ea1b..793e037c599b70a09ef595d9ee969823f137917e 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-list.md +++ b/en/application-dev/reference/arkui-js/js-components-container-list.md @@ -72,7 +72,7 @@ In addition to the [universal events](../arkui-js/js-components-common-events.md | scrollend | - | Triggered when the list stops scrolling. | | scrolltouchup | - | Triggered when the list continues scrolling after the user lifts their fingers. | | requestitem | - | Triggered for a request to create a list-item.
This event is triggered when the number of cached list-items outside the visible area is less than the value of **cachedcount** during long list loading with delay.| -| rotate7+ | { rotateValue: number } | Triggered to indicate the incremental value of the rotation angle of the watch crown. This parameter is only supported by wearables. | +| rotation7+ | { rotateValue: number } | Triggered to indicate the incremental value of the rotation angle of the watch crown. This parameter is only supported by wearables. | ## Methods @@ -112,22 +112,6 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. ``` - -```js -// index.js -export default { - data: { - todolist: [{ - title: 'Prepare for the interview', - date: '2021-12-31 10:00:00', - }, { - title: 'Watch the movie', - date: '2021-12-31 20:00:00', - }], - }, -} -``` - ```css /* index.css */ .container { @@ -153,4 +137,21 @@ export default { } ``` +```js +// index.js +export default { + data: { + todolist: [{ + title: 'Prepare for the interview', + date: '2021-12-31 10:00:00' + }, { + title: 'Watch the movie', + date: '2021-12-31 20:00:00' + }], + }, +} +``` + + + ![en-us_image_0000001185033226](figures/en-us_image_0000001185033226.png) diff --git a/en/application-dev/reference/arkui-js/js-components-container-panel.md b/en/application-dev/reference/arkui-js/js-components-container-panel.md index 89e23df188c5250d071bfdcf38b30c6af09e1863..9dd11f5afc549a7cd9a0fde7cdc926af5b433292 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-panel.md +++ b/en/application-dev/reference/arkui-js/js-components-container-panel.md @@ -86,58 +86,63 @@ The following methods are supported. ```html
-
- -
- -
-
- Simple panel in {{modeFlag}} mode -
-
- -
+
+
- + +
+
+ Simple panel in {{ modeFlag }} mode +
+
+ +
+
+
``` ```css /* xxx.css */ .doc-page { - flex-direction: column; - justify-content: center; - align-items: center; + flex-direction: column; + justify-content: center; + align-items: center; } + .btn-div { - width: 100%; - height: 200px; - flex-direction: column; - align-items: center; - justify-content: center; + width: 100%; + height: 200px; + flex-direction: column; + align-items: center; + justify-content: center; } + .txt { - color: #000000; - font-weight: bold; - font-size: 39px; + color: #000000; + font-weight: bold; + font-size: 39px; } + .panel-div { - width: 100%; - flex-direction: column; - align-items: center; + width: 100%; + flex-direction: column; + align-items: center; } + .inner-txt { - width: 100%; - height: 160px; - flex-direction: column; - align-items: center; - justify-content: center; + width: 100%; + height: 160px; + flex-direction: column; + align-items: center; + justify-content: center; } + .inner-btn { - width: 100%; - height: 120px; - justify-content: center; - align-items: center; + width: 100%; + height: 120px; + justify-content: center; + align-items: center; } ``` diff --git a/en/application-dev/reference/arkui-js/js-components-container-popup.md b/en/application-dev/reference/arkui-js/js-components-container-popup.md index ef1cf3c658d395c64808eb9a1743c8d67b76bd81..46d661972f887b2ed6601523198618d7a831d380 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-popup.md +++ b/en/application-dev/reference/arkui-js/js-components-container-popup.md @@ -4,7 +4,7 @@ > > This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -Bubble indication. The **\** component is used to display a pop-up to offer instructions after a user clicks a bound control. +The **\** component is used to display a pop-up to offer instructions after a user clicks a bound component. ## Required Permissions @@ -116,7 +116,7 @@ export default { visibilitychange(e) { prompt.showToast({ message: 'visibility change visibility: ' + e.visibility, - duration: 3000, + duration: 3000 }); }, showpopup() { @@ -124,7 +124,7 @@ export default { }, hidepopup() { this.$element("popup").hide(); - }, + } } ``` diff --git a/en/application-dev/reference/arkui-js/js-components-container-refresh.md b/en/application-dev/reference/arkui-js/js-components-container-refresh.md index 8c3d8c5f42dfeb9721e0c00b1b7a7dbb31187241..fb9bf04be32e5c4612afd0a955810bfec050ae8d 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-refresh.md +++ b/en/application-dev/reference/arkui-js/js-components-container-refresh.md @@ -4,7 +4,7 @@ > > This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -The **** component is used to refresh a page through a pull-down gesture. +The **** component is used to refresh a page through a pull-down gesture. ## Required Permissions @@ -22,7 +22,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri | Name| Type| Default Value| Mandatory| Description| | -------- | -------- | -------- | -------- | -------- | -| offset | <length> | - | No| Distance to the top of the parent component from the **** component that comes to rest after a successful pull-down gesture.| +| offset | <length> | - | No| Distance to the top of the parent component from the **** component that comes to rest after a successful pull-down gesture.| | refreshing | boolean | false | No| Whether the **\** component is being used for refreshing.| | type | string | auto | No| Dynamic effect when the component is refreshed. Two options are available and cannot be modified dynamically.
- **auto**: default effect. When the list is pulled to the top, the list does not move. When the list is pulled to the bottom, a circle is displayed.
- **pulldown**: When the list is pulled to the top, users can continue to pull down to trigger a refresh. The rebound effect will appear after the refresh. If the child component contains a list, set **scrolleffect** of the list to **no** to prevent drop-down effect conflicts.| | lasttime | boolean | false | No| Whether to display the last update time. The character string format is **last update time: XXXX**, where **XXXX** is displayed based on the certain time and date formats and cannot be dynamically modified. (It is recommended that this attribute be used when **type** is set to **pulldown**. The fixed distance is at the bottom of the content drop-down area. Pay attention to the **offset** attribute setting to prevent overlapping.)| @@ -36,8 +36,8 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md | Name| Type| Default Value| Mandatory| Description| | -------- | -------- | -------- | -------- | -------- | -| background-color | <color> | white | No| Background color of the **\** component.| -| progress-color | <color> | black | No| Loading color of the **\** component.| +| background-color | <color> | white
| No| Background color of the **\** component.| +| progress-color | <color> | black
| No| Color of the loading icon of the **\** component.| ## Events @@ -107,7 +107,7 @@ The [universal methods](../arkui-js/js-components-common-methods.md) are not sup ```js // xxx.js -import prompt from '@system.prompt'; +import promptAction from '@ohos.promptAction'; export default { data: { list:[], @@ -121,7 +121,7 @@ export default { } }, refresh: function (e) { - prompt.showToast({ + promptAction.showToast({ message: 'Refreshing...' }) var that = this; @@ -130,7 +130,7 @@ export default { that.fresh = false; var addItem ='Refresh element'; that.list.unshift(addItem); - prompt.showToast({ + promptAction.showToast({ message: 'Refreshed.' }) }, 2000) diff --git a/en/application-dev/reference/arkui-js/js-components-container-stepper.md b/en/application-dev/reference/arkui-js/js-components-container-stepper.md index 6a666a454cd424e1b3daf67fcae1c4a4e08f67a6..09bd2f3fce15f326b1d8f06832d3ea0c4319e234 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-stepper.md +++ b/en/application-dev/reference/arkui-js/js-components-container-stepper.md @@ -27,7 +27,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri | Name | Type | Default Value | Description | | ----- | ------ | ---- | ------------------------------ | -| index | number | - | Index of the **\** child component that is currently displayed.| +| index | number | 0 | Index of the **\** child component to display. By default, the first one is displayed.| ## Styles @@ -46,10 +46,10 @@ In addition to the [universal events](../arkui-js/js-components-common-events.md | Name | Parameter | Description | | ------ | ---------------------------------------- | ---------------------------------------- | | finish | - | Triggered when the last step on the navigator is complete. | -| skip | - | Triggered when users click the skip button, which works only if you have called **setNextButtonStatus** method to allow users to skip all steps.| +| skip | - | Triggered when users click the skip button to skip steps.| | change | { prevIndex: prevIndex, index: index} | Triggered when users click the left or right (text) button of the step navigator to switch between steps. **prevIndex** indicates the index of the previous step, and **index** indicates that of the current step.| -| next | { index: index, pendingIndex: pendingIndex } | Triggered when users click the next (text) button. **index** indicates the index of the current step, and **pendingIndex** indicates that of the step to go. The return value is in **{pendingIndex:*** pendingIndex***}** format. You can use **pendingIndex** to specify a **\** child component as the next step to go.| -| back | { index: index, pendingIndex: pendingIndex } | Triggered when users click the previous (text) button. **index** indicates the index of the current step, and **pendingIndex** indicates that of the step to go. The return value is in Object:{ **{pendingIndex:*** pendingIndex***}** format. You can use **pendingIndex** to specify a **\** child component as the previous step.| +| next | { index: index, pendingIndex: pendingIndex } | Triggered when users click the next (text) button. **index** indicates the index of the current step, and **pendingIndex** indicates that of the step to go. The return value is in **{pendingIndex:*** pendingIndex***}** format. You can use **pendingIndex** to specify a **** child component as the next step to go.| +| back | { index: index, pendingIndex: pendingIndex } | Triggered when users click the previous (text) button. **index** indicates the index of the current step, and **pendingIndex** indicates that of the step to go. The return value is in Object:{ **{pendingIndex:*** pendingIndex***}** format. You can use **pendingIndex** to specify a **** child component as the previous step.| ## Methods @@ -58,101 +58,137 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. | Name | Parameter | Description | | ------------------- | ---------------------------------------- | ---------------------------------------- | -| setNextButtonStatus | { status: string, label: label } | Sets the status of the next (text) button in this step navigator. Available **status** values are as follows:
- **normal**: The next button is displayed normally and can navigate users to the next step when it is clicked.
- **disabled**: The next button is grayed out and unavailable.
- **waiting**: The next button is not displayed, and a process bar is displayed instead.
- **skip**: The skip button is displayed to allow users to skip all remaining steps.| +| setNextButtonStatus | { status: string, label: label } | Sets the text and status of the next button in the step navigator. **label** indicates the button text, and **status** indicates the button status. Available **status** values are as follows:
- **normal**: The next button is displayed normally and can navigate users to the next step when it is clicked.
- **disabled**: The next button is grayed out and unavailable.
- **waiting**: The next button is not displayed, and a process bar is displayed instead.
- **skip**: The skip button is displayed to allow users to skip all remaining steps.| ## Example ```html -
- - -
- First screen -
- -
- -
- Second screen -
- -
- -
- Third screen -
- -
-
+
+ + +
+ Page One + +
+
+ +
+ Page Two + +
+
+ +
+ Page Three + +
+
+
``` ```css /* xxx.css */ .container { - margin-top: 20px; - flex-direction: column; - align-items: center; - height: 300px; + flex-direction: column; + align-items: center; + height: 100%; + width: 100%; + background-color: #f7f7f7; } -.stepperItem { - width: 100%; - flex-direction: column; - align-items: center; +.stepper{ + width: 100%; + height: 100%; } -.stepperItemContent { - color: #0000ff; - font-size: 50px; - justify-content: center; +.stepper-item { + width: 100%; + height: 100%; + flex-direction: column; + align-items: center; +} +.item{ + width: 90%; + height: 86%; + margin-top: 80px; + background-color: white; + border-radius: 60px; + flex-direction: column; + align-items: center; + padding-top: 160px; +} +text { + font-size: 78px; + color: #182431; + opacity: 0.4; } .button { - width: 60%; - margin-top: 30px; - justify-content: center; + width: 40%; + margin-top: 100px; + justify-content: center; } ``` ```js // xxx.js +import prompt from '@system.prompt'; + export default { - data: { - label_1: - { - prevLabel: 'BACK', - nextLabel: 'NEXT', - status: 'normal' - }, - label_2: - { - prevLabel: 'BACK', - nextLabel: 'NEXT', - status: 'normal' - }, - label_3: - { - prevLabel: 'BACK', - nextLabel: 'NEXT', - status: 'normal' - }, - }, - setRightButton(e) { - this.$element('mystepper').setNextButtonStatus({status: 'skip', label: 'SKIP'}); - }, - nextclick(e) { - var index = { - pendingIndex: e.pendingIndex - } - return index; - }, - backclick(e) { - var index = { - pendingIndex: e.pendingIndex + data: { + label_1: + { + prevLabel: 'BACK', + nextLabel: 'NEXT', + status: 'normal' + }, + label_2: + { + prevLabel: 'BACK', + nextLabel: 'NEXT', + status: 'normal' + }, + label_3: + { + prevLabel: 'BACK', + nextLabel: 'NEXT', + status: 'normal' + } + }, + setRightButton(e) { + this.$element('mystepper').setNextButtonStatus({ + status: 'waiting', label: 'SKIP' + }); + }, + nextclick(e) { + var index = { + pendingIndex: e.pendingIndex + } + return index; + }, + backclick(e) { + var index = { + pendingIndex: e.pendingIndex + } + return index; + }, + statuschange(e) { + prompt.showToast({ + message: 'Previous step index' + e.prevIndex + 'Current step index' + e.index + }) + }, + finish() { + prompt.showToast({ + message:'Finished.' + }) + }, + skip() { + prompt.showToast({ + message: 'Skip triggered' + }) } - return index; - }, } ``` -![en-us_image_0000001127125114](figures/en-us_image_0000001127125114.gif) +![](figures/stepper.gif) diff --git a/en/application-dev/reference/arkui-js/js-components-container-swiper.md b/en/application-dev/reference/arkui-js/js-components-container-swiper.md index e0edf4c40ffba747e84e1dc84e8999993bca675e..f607139653a52a1e1edbca359ca60d7224ebcc30 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-swiper.md +++ b/en/application-dev/reference/arkui-js/js-components-container-swiper.md @@ -4,7 +4,7 @@ > > This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -The **\** component provides a container that allows users to switch among child components using swipe gestures. +The **\** component provides a container that allows users to switch among child components using swipe gestures. ## Required Permissions diff --git a/en/application-dev/reference/arkui-js/js-components-media-video.md b/en/application-dev/reference/arkui-js/js-components-media-video.md index c024cbe0058093b754c98f04f579b1cd7dac620f..0141e4818d35042cdef8f77362a95bb3d641b4d8 100644 --- a/en/application-dev/reference/arkui-js/js-components-media-video.md +++ b/en/application-dev/reference/arkui-js/js-components-media-video.md @@ -3,17 +3,7 @@ > **NOTE** > -> - This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -> -> - Set **configChanges** under **abilities** in the **config.json** file to **orientation**. -> ``` -> "abilities": [ -> { -> "configChanges": ["orientation"], -> ... -> } -> ] -> ``` +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. The **\